System.register([], (function (exports, module) {
  'use strict';
  return {
    execute: (function () {

      exports({
        $: isEnglishWordPartAtLast,
        E: getBaselineOffset,
        K: isUnicodeCJK,
        N: isUnicodeSpace,
        P: safeMeasureText,
        W: getSymbolLength,
        X: getSymbolAt,
        Y: getSymbolCodeAt,
        Z: isEnglishWordPartAtFirst,
        _: _createForOfIteratorHelperLoose,
        a$: size,
        a0: getEnglishWordPartAtFirst,
        a1: getEnglishWordPartAtLast,
        a2: fragmentText,
        aA: getPathFromRoot,
        aB: getWorldTransformUntilRoot,
        aP: v2$1,
        aR: v3,
        aT: v4,
        aV: quat,
        aY: mat4,
        ax: sampleAnimationCurve,
        ay: computeRatioByType,
        b1: rect,
        b3: color,
        b8: equals$2,
        b9: approx,
        bA: BitMask,
        bB: Enum,
        bC: ccenum,
        bH: setDefaultLogTimes,
        bL: deprecateModuleExportedName,
        bM: __checkObsolete__,
        bN: __checkObsoleteInNamespace__,
        bO: WorldNode3DToLocalNodeUI,
        bP: WorldNode3DToWorldNodeUI,
        bS: CCClass,
        bT: isCCClassOrFastDefined,
        ba: clamp$1,
        bb: clamp01,
        bc: lerp,
        bd: toRadian,
        be: toDegree,
        bf: random,
        bg: setRandGenerator,
        bh: randomRange,
        bi: randomRangeInt,
        bj: pseudoRandom,
        bk: pseudoRandomRange,
        bl: pseudoRandomRangeInt,
        bm: nextPow2,
        bn: repeat$2,
        bo: pingPong,
        bp: inverseLerp,
        bq: absMaxComponent,
        br: absMax,
        bs: enumerableProps,
        bt: floatToHalf,
        bu: halfToFloat,
        c: createCommonjsModule,
        c1: getSerializationMetadata,
        c4: Eventify,
        c6: debug,
        c7: log,
        c8: error,
        c9: warn,
        cC: murmurhash2_32_gc,
        cD: bezier,
        cE: bezierByTime,
        cQ: formerlySerializedAs$4,
        cS: shift,
        cV: setPropertyEnumType,
        cW: setPropertyEnumTypeOnAttrs,
        cZ: isCCObject,
        c_: isValid,
        ca: assert,
        cb: logID,
        cc: errorID,
        cd: warnID,
        ce: assertID,
        cf: isDisplayStats,
        cg: setDisplayStats,
        ch: getError,
        d1: applyMixins,
        d2: _resetDebugSetting,
        d3: binarySearch,
        d4: binarySearchEpsilon,
        d5: binarySearchBy,
        d6: assertIsNonNullable,
        d7: assertIsTrue,
        d8: assertsArrayIndex,
        d9: flattenCodeArray,
        dF: find,
        dg: createDefaultPipeline,
        e8: deserialize,
        ea: instantiate,
        gV: tween,
        gW: tweenUtil
      });

      function _defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
          var descriptor = props[i];
          descriptor.enumerable = descriptor.enumerable || false;
          descriptor.configurable = true;
          if ("value" in descriptor) descriptor.writable = true;
          Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
        }
      }
      function _createClass(Constructor, protoProps, staticProps) {
        if (protoProps) _defineProperties(Constructor.prototype, protoProps);
        if (staticProps) _defineProperties(Constructor, staticProps);
        Object.defineProperty(Constructor, "prototype", {
          writable: false
        });
        return Constructor;
      }
      function _extends() {
        _extends = Object.assign ? Object.assign.bind() : function (target) {
          for (var i = 1; i < arguments.length; i++) {
            var source = arguments[i];
            for (var key in source) {
              if (Object.prototype.hasOwnProperty.call(source, key)) {
                target[key] = source[key];
              }
            }
          }
          return target;
        };
        return _extends.apply(this, arguments);
      }
      function _inheritsLoose(subClass, superClass) {
        subClass.prototype = Object.create(superClass.prototype);
        subClass.prototype.constructor = subClass;
        _setPrototypeOf(subClass, superClass);
      }
      function _getPrototypeOf(o) {
        _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
          return o.__proto__ || Object.getPrototypeOf(o);
        };
        return _getPrototypeOf(o);
      }
      function _setPrototypeOf(o, p) {
        _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
          o.__proto__ = p;
          return o;
        };
        return _setPrototypeOf(o, p);
      }
      function _isNativeReflectConstruct() {
        if (typeof Reflect === "undefined" || !Reflect.construct) return false;
        if (Reflect.construct.sham) return false;
        if (typeof Proxy === "function") return true;
        try {
          Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
          return true;
        } catch (e) {
          return false;
        }
      }
      function _construct(Parent, args, Class) {
        if (_isNativeReflectConstruct()) {
          _construct = Reflect.construct.bind();
        } else {
          _construct = function _construct(Parent, args, Class) {
            var a = [null];
            a.push.apply(a, args);
            var Constructor = Function.bind.apply(Parent, a);
            var instance = new Constructor();
            if (Class) _setPrototypeOf(instance, Class.prototype);
            return instance;
          };
        }
        return _construct.apply(null, arguments);
      }
      function _isNativeFunction(fn) {
        return Function.toString.call(fn).indexOf("[native code]") !== -1;
      }
      function _wrapNativeSuper(Class) {
        var _cache = typeof Map === "function" ? new Map() : undefined;
        _wrapNativeSuper = function _wrapNativeSuper(Class) {
          if (Class === null || !_isNativeFunction(Class)) return Class;
          if (typeof Class !== "function") {
            throw new TypeError("Super expression must either be null or a function");
          }
          if (typeof _cache !== "undefined") {
            if (_cache.has(Class)) return _cache.get(Class);
            _cache.set(Class, Wrapper);
          }
          function Wrapper() {
            return _construct(Class, arguments, _getPrototypeOf(this).constructor);
          }
          Wrapper.prototype = Object.create(Class.prototype, {
            constructor: {
              value: Wrapper,
              enumerable: false,
              writable: true,
              configurable: true
            }
          });
          return _setPrototypeOf(Wrapper, Class);
        };
        return _wrapNativeSuper(Class);
      }
      function _objectWithoutPropertiesLoose(source, excluded) {
        if (source == null) return {};
        var target = {};
        var sourceKeys = Object.keys(source);
        var key, i;
        for (i = 0; i < sourceKeys.length; i++) {
          key = sourceKeys[i];
          if (excluded.indexOf(key) >= 0) continue;
          target[key] = source[key];
        }
        return target;
      }
      function _assertThisInitialized(self) {
        if (self === void 0) {
          throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
        }
        return self;
      }
      function _unsupportedIterableToArray(o, minLen) {
        if (!o) return;
        if (typeof o === "string") return _arrayLikeToArray(o, minLen);
        var n = Object.prototype.toString.call(o).slice(8, -1);
        if (n === "Object" && o.constructor) n = o.constructor.name;
        if (n === "Map" || n === "Set") return Array.from(o);
        if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
      }
      function _arrayLikeToArray(arr, len) {
        if (len == null || len > arr.length) len = arr.length;
        for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
        return arr2;
      }
      function _createForOfIteratorHelperLoose(o, allowArrayLike) {
        var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
        if (it) return (it = it.call(o)).next.bind(it);
        if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
          if (it) o = it;
          var i = 0;
          return function () {
            if (i >= o.length) return {
              done: true
            };
            return {
              done: false,
              value: o[i++]
            };
          };
        }
        throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
      }
      function _toPrimitive(input, hint) {
        if (typeof input !== "object" || input === null) return input;
        var prim = input[Symbol.toPrimitive];
        if (prim !== undefined) {
          var res = prim.call(input, hint || "default");
          if (typeof res !== "object") return res;
          throw new TypeError("@@toPrimitive must return a primitive value.");
        }
        return (hint === "string" ? String : Number)(input);
      }
      function _toPropertyKey(arg) {
        var key = _toPrimitive(arg, "string");
        return typeof key === "symbol" ? key : String(key);
      }
      function _initializerDefineProperty(target, property, descriptor, context) {
        if (!descriptor) return;
        Object.defineProperty(target, property, {
          enumerable: descriptor.enumerable,
          configurable: descriptor.configurable,
          writable: descriptor.writable,
          value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
        });
      }
      function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
        var desc = {};
        Object.keys(descriptor).forEach(function (key) {
          desc[key] = descriptor[key];
        });
        desc.enumerable = !!desc.enumerable;
        desc.configurable = !!desc.configurable;
        if ('value' in desc || desc.initializer) {
          desc.writable = true;
        }
        desc = decorators.slice().reverse().reduce(function (desc, decorator) {
          return decorator(target, property, desc) || desc;
        }, desc);
        if (context && desc.initializer !== void 0) {
          desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
          desc.initializer = undefined;
        }
        if (desc.initializer === void 0) {
          Object.defineProperty(target, property, desc);
          desc = null;
        }
        return desc;
      }

      function tryDefineGlobal (name, value) {
          const _global = typeof window === 'undefined' ? global : window;
          if (typeof _global[name] === 'undefined') {
              return (_global[name] = value);
          } else {
              // eslint-disable-next-line @typescript-eslint/no-unsafe-return
              return _global[name];
          }
      }

      const NATIVE = false;
      tryDefineGlobal('CC_WECHAT', false);

      const WECHAT_MINI_PROGRAM = false;
      tryDefineGlobal('CC_BAIDU', false);

      const XIAOMI = false;
      tryDefineGlobal('CC_XIAOMI', false);
      tryDefineGlobal('CC_ALIPAY', false);
      tryDefineGlobal('CC_BYTEDANCE', false);
      tryDefineGlobal('CC_OPPO', false);
      tryDefineGlobal('CC_VIVO', false);
      tryDefineGlobal('CC_HUAWEI', false);
      tryDefineGlobal('CC_COCOSPLAY', false);
      tryDefineGlobal('CC_QTT', false);
      tryDefineGlobal('CC_LINKSURE', false);

      const EDITOR = false;
      tryDefineGlobal('CC_EDITOR', false);

      const EDITOR_NOT_IN_PREVIEW = false;

      const PREVIEW = false;
      tryDefineGlobal('CC_PREVIEW', false);
      tryDefineGlobal('CC_BUILD', true);

      const TEST = false;
      tryDefineGlobal('CC_TEST', false);
      tryDefineGlobal('CC_DEBUG', true);
      tryDefineGlobal('CC_DEV', false);

      const MINIGAME = false;
      tryDefineGlobal('CC_MINIGAME', false);

      const RUNTIME_BASED = false;
      tryDefineGlobal('CC_RUNTIME_BASED', false);
      tryDefineGlobal('CC_SUPPORT_JIT', true);

      const JSB = false;
      tryDefineGlobal('CC_JSB', false);

      var _global = typeof window === 'undefined' ? global : window;
      var legacyCC = exports('aM', {
        _global: _global
      });
      legacyCC.internal = {};
      var engineVersion = exports('aL', '3.8.3');
      _global.CocosEngine = legacyCC.ENGINE_VERSION = engineVersion;
      _global.cc = legacyCC;
      var ccwindow = typeof globalThis.jsb !== 'undefined' ? typeof jsb.window !== 'undefined' ? jsb.window : globalThis : globalThis;
      _global.ccwindow = ccwindow;

      var INT_BITS = 32;
      var INT_MAX = 0x7fffffff;
      var INT_MIN = -1 << INT_BITS - 1;
      function sign$1(v) {
        return (v > 0) - (v < 0);
      }
      function abs$1(v) {
        var mask = v >> INT_BITS - 1;
        return (v ^ mask) - mask;
      }
      function min$3(x, y) {
        return y ^ (x ^ y) & -(x < y);
      }
      function max$4(x, y) {
        return x ^ (x ^ y) & -(x < y);
      }
      function isPow2(v) {
        return !(v & v - 1) && !!v;
      }
      function log2(v) {
        var r;
        var shift;
        r = (v > 0xFFFF) << 4;
        v >>>= r;
        shift = (v > 0xFF) << 3;
        v >>>= shift;
        r |= shift;
        shift = (v > 0xF) << 2;
        v >>>= shift;
        r |= shift;
        shift = (v > 0x3) << 1;
        v >>>= shift;
        r |= shift;
        return r | v >> 1;
      }
      function log10(v) {
        return v >= 1000000000 ? 9 : v >= 100000000 ? 8 : v >= 10000000 ? 7 : v >= 1000000 ? 6 : v >= 100000 ? 5 : v >= 10000 ? 4 : v >= 1000 ? 3 : v >= 100 ? 2 : v >= 10 ? 1 : 0;
      }
      function popCount(v) {
        v -= v >>> 1 & 0x55555555;
        v = (v & 0x33333333) + (v >>> 2 & 0x33333333);
        return (v + (v >>> 4) & 0xF0F0F0F) * 0x1010101 >>> 24;
      }
      function countTrailingZeros(v) {
        var c = 32;
        v &= -v;
        if (v) {
          c--;
        }
        if (v & 0x0000FFFF) {
          c -= 16;
        }
        if (v & 0x00FF00FF) {
          c -= 8;
        }
        if (v & 0x0F0F0F0F) {
          c -= 4;
        }
        if (v & 0x33333333) {
          c -= 2;
        }
        if (v & 0x55555555) {
          c -= 1;
        }
        return c;
      }
      function nextPow2$1(v) {
        --v;
        v |= v >>> 1;
        v |= v >>> 2;
        v |= v >>> 4;
        v |= v >>> 8;
        v |= v >>> 16;
        return v + 1;
      }
      function prevPow2(v) {
        v |= v >>> 1;
        v |= v >>> 2;
        v |= v >>> 4;
        v |= v >>> 8;
        v |= v >>> 16;
        return v - (v >>> 1);
      }
      function parity(v) {
        v ^= v >>> 16;
        v ^= v >>> 8;
        v ^= v >>> 4;
        v &= 0xf;
        return 0x6996 >>> v & 1;
      }
      var REVERSE_TABLE = new Array(256);
      (function (tab) {
        for (var i = 0; i < 256; ++i) {
          var v = i;
          var r = i;
          var s = 7;
          for (v >>>= 1; v; v >>>= 1) {
            r <<= 1;
            r |= v & 1;
            --s;
          }
          tab[i] = r << s & 0xff;
        }
      })(REVERSE_TABLE);
      function reverse(v) {
        return REVERSE_TABLE[v & 0xff] << 24 | REVERSE_TABLE[v >>> 8 & 0xff] << 16 | REVERSE_TABLE[v >>> 16 & 0xff] << 8 | REVERSE_TABLE[v >>> 24 & 0xff];
      }
      function interleave2(x, y) {
        x &= 0xFFFF;
        x = (x | x << 8) & 0x00FF00FF;
        x = (x | x << 4) & 0x0F0F0F0F;
        x = (x | x << 2) & 0x33333333;
        x = (x | x << 1) & 0x55555555;
        y &= 0xFFFF;
        y = (y | y << 8) & 0x00FF00FF;
        y = (y | y << 4) & 0x0F0F0F0F;
        y = (y | y << 2) & 0x33333333;
        y = (y | y << 1) & 0x55555555;
        return x | y << 1;
      }
      function deinterleave2(v, n) {
        v = v >>> n & 0x55555555;
        v = (v | v >>> 1) & 0x33333333;
        v = (v | v >>> 2) & 0x0F0F0F0F;
        v = (v | v >>> 4) & 0x00FF00FF;
        v = (v | v >>> 16) & 0x000FFFF;
        return v << 16 >> 16;
      }
      function interleave3(x, y, z) {
        x &= 0x3FF;
        x = (x | x << 16) & 4278190335;
        x = (x | x << 8) & 251719695;
        x = (x | x << 4) & 3272356035;
        x = (x | x << 2) & 1227133513;
        y &= 0x3FF;
        y = (y | y << 16) & 4278190335;
        y = (y | y << 8) & 251719695;
        y = (y | y << 4) & 3272356035;
        y = (y | y << 2) & 1227133513;
        x |= y << 1;
        z &= 0x3FF;
        z = (z | z << 16) & 4278190335;
        z = (z | z << 8) & 251719695;
        z = (z | z << 4) & 3272356035;
        z = (z | z << 2) & 1227133513;
        return x | z << 2;
      }
      function deinterleave3(v, n) {
        v = v >>> n & 1227133513;
        v = (v | v >>> 2) & 3272356035;
        v = (v | v >>> 4) & 251719695;
        v = (v | v >>> 8) & 4278190335;
        v = (v | v >>> 16) & 0x3FF;
        return v << 22 >> 22;
      }
      function nextCombination(v) {
        var t = v | v - 1;
        return t + 1 | (~t & -~t) - 1 >>> countTrailingZeros(v) + 1;
      }

      var bits = /*#__PURE__*/Object.freeze({
        __proto__: null,
        INT_BITS: INT_BITS,
        INT_MAX: INT_MAX,
        INT_MIN: INT_MIN,
        sign: sign$1,
        abs: abs$1,
        min: min$3,
        max: max$4,
        isPow2: isPow2,
        log2: log2,
        log10: log10,
        popCount: popCount,
        countTrailingZeros: countTrailingZeros,
        nextPow2: nextPow2$1,
        prevPow2: prevPow2,
        parity: parity,
        reverse: reverse,
        interleave2: interleave2,
        deinterleave2: deinterleave2,
        interleave3: interleave3,
        deinterleave3: deinterleave3,
        nextCombination: nextCombination
      });
      exports('aN', bits);

      var debugInfos = {
      	"1006": "[Action step]. override me",
      	"1007": "[Action update]. override me",
      	"1008": "[Action reverse]. override me",
      	"1100": "Expected 'data' dict, but not found. Config file: %s",
      	"1101": "Please load the resource first : %s",
      	"1102": "Effect settings not found, effects will not be imported.",
      	"1103": "Success to load scene: %s",
      	"1200": "cocos2d: Director: Error in gettimeofday",
      	"1204": "Running scene should not be null",
      	"1205": "The scene should not be null",
      	"1206": "loadScene: The scene index to load (%s) is out of range.",
      	"1207": "loadScene: Unknown name type to load: '%s'",
      	"1208": "loadScene: Failed to load scene '%s' because '%s' is already being loaded.",
      	"1209": "loadScene: Can not load the scene '%s' because it was not in the build settings before playing.",
      	"1210": "Failed to preload '%s', %s",
      	"1211": "loadScene: The scene index to load (%s) is out of range.",
      	"1212": "loadScene: Unknown name type to load: '%s'",
      	"1213": "loadScene: Failed to load scene '%s' because '%s' is already loading",
      	"1214": "loadScene: Can not load the scene '%s' because it was not in the build settings before playing.",
      	"1215": "Failed to preload '%s', %s",
      	"1216": "Director.runSceneImmediate: scene is not valid",
      	"1217": "Director._initOnEngineInitialized: renderer root initialization failed",
      	"1218": "Forward render pipeline initialized.",
      	"1219": "Deferred render pipeline initialized. Note that non-transparent materials with no lighting will not be rendered, such as builtin-unlit.",
      	"1220": "Failed to set shading scale, pipelineSceneData is invalid.",
      	"1221": "Setting orientation is not supported yet.",
      	"1300": "%s is not in the model pool and cannot be destroyed by destroyModel.",
      	"1400": "'%s' is deprecated, please use '%s' instead.",
      	"1404": "cc.spriteFrameCache is removed, please use cc.loader to load and cache sprite frames of atlas format.",
      	"1406": "'%s.%s' is removed",
      	"1408": "'%s' is removed",
      	"1409": "element type is wrong!",
      	"1502": "cc.scheduler.scheduleCallbackForTarget(): target should be non-null.",
      	"1503": "cc.Scheduler.pauseTarget():target should be non-null",
      	"1504": "cc.Scheduler.resumeTarget():target should be non-null",
      	"1505": "cc.Scheduler.isTargetPaused():target should be non-null",
      	"1506": "warning: you CANNOT change update priority in scheduled function",
      	"1507": "scheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f",
      	"1508": "Argument callback must not be empty",
      	"1509": "Argument target must be non-nullptr",
      	"1510": "cc.Scheduler: Illegal target which doesn't have id, you should do Scheduler.enableForTarget(target) before all scheduler API usage on target",
      	"1511": "cc.Scheduler: pause state of the scheduled task doesn't match the element pause state in Scheduler, the given paused state will be ignored.",
      	"1513": "cc.Scheduler: scheduler stopped using `__instanceId` as id since v2.0, you should do Scheduler.enableForTarget(target) before all scheduler API usage on target",
      	"1514": "since v3.8.0, `Scheduler.schedule(target, callback, interval)` is deprecated, please use `Scheduler.schedule(callback, target, interval)` instead.",
      	"1607": "removeFromParentAndCleanup is deprecated. Use removeFromParent instead",
      	"1619": "callback function must be non-null",
      	"1620": "interval must be positive",
      	"1623": "Set '%s' to normal node (not persist root node).",
      	"1624": "Replacing with the same sgNode",
      	"1625": "The replacement sgNode should not contain any child.",
      	"1626": "Should not set alpha via 'color', set 'opacity' please.",
      	"1627": "Not support for asynchronous creating node in SG",
      	"1632": "Node name can not include '/'.",
      	"1633": "Internal error, should not remove unknown node from parent.",
      	"1635": "reorderChild: this child is not in children list.",
      	"1636": "Node's zIndex value can't be greater than cc.macro.MAX_ZINDEX, setting to the maximum value",
      	"1637": "Node's zIndex value can't be smaller than cc.macro.MIN_ZINDEX, setting to the minimum value",
      	"1638": "Private node's zIndex can't be set, it will keep cc.macro.MIN_ZINDEX as its value",
      	"1800": "cc._EventListenerKeyboard.checkAvailable(): Invalid EventListenerKeyboard!",
      	"1801": "cc._EventListenerTouchOneByOne.checkAvailable(): Invalid EventListenerTouchOneByOne!",
      	"1802": "cc._EventListenerTouchAllAtOnce.checkAvailable(): Invalid EventListenerTouchAllAtOnce!",
      	"1803": "cc._EventListenerAcceleration.checkAvailable():_onAccelerationEvent must be non-nil",
      	"1900": "Invalid parameter.",
      	"2104": "Layer collision. The name of layer (%s) is collided with the name or value of some layer",
      	"2200": "Design resolution not valid",
      	"2201": "should set resolutionPolicy",
      	"2300": "The touches is more than MAX_TOUCHES, nUnusedIndex = %s",
      	"2402": "Forward pipeline startup failed!",
      	"3103": "cc.Texture.addImage(): path should be non-null",
      	"3119": "Lazy init texture with image element failed due to image loading failure: %s",
      	"3120": "Loading texture with unsupported type: '%s'. Add '%s' into 'cc.macro.SUPPORT_TEXTURE_FORMATS' please.",
      	"3121": "Can't find a texture format supported by the current platform! Please add a fallback format in the editor.",
      	"3122": "Error Texture in %s.",
      	"3123": "Set same texture %s.",
      	"3124": "Texture: setMipRange failed because base level is larger than max level",
      	"3300": "Rect width exceeds maximum margin: %s",
      	"3301": "Rect height exceeds maximum margin: %s",
      	"3500": "0 priority is forbidden for fixed priority since it's used for scene graph based priority.",
      	"3501": "Invalid listener type!",
      	"3502": "Can't set fixed priority with scene graph based listener.",
      	"3503": "Invalid parameters.",
      	"3504": "listener must be a cc.EventListener object when adding a fixed priority listener",
      	"3505": "The listener has been registered, please don't register it again.",
      	"3506": "Unsupported listener target.",
      	"3507": "Invalid scene graph priority!",
      	"3508": "If program goes here, there should be event in dispatch.",
      	"3509": "_inDispatch should be 1 here.",
      	"3510": "%s's scene graph node not contains in the parent's children",
      	"3511": "event is undefined",
      	"3512": "Event manager only support scene graph priority for ui nodes which contain UIComponent",
      	"3520": "Device Motion Event request permission: %s",
      	"3521": "Device Motion Event request permission failed: %s",
      	"3601": "The editor property 'playOnFocus' should be used with 'executeInEditMode' in class '%s'",
      	"3602": "Unknown editor property '%s' in class '%s'.",
      	"3603": "Use 'cc.Float' or 'cc.Integer' instead of 'cc.Number' please.",
      	"3604": "Can only indicate one type attribute for %s.",
      	"3605": "The default value of %s is not instance of %s.",
      	"3606": "No needs to indicate the '%s' attribute for %s, which its default value is type of %s.",
      	"3607": "The default value of %s must be an empty string.",
      	"3608": "The type of %s must be CCString, not String.",
      	"3609": "The type of %s must be CCBoolean, not Boolean.",
      	"3610": "The type of %s must be CCFloat or CCInteger, not Number.",
      	"3611": "Can not indicate the '%s' attribute for %s, which its default value is type of %s.",
      	"3612": "%s Just set the default value to 'new %s()' and it will be handled properly.",
      	"3613": "'No need to use 'serializable: false' or 'editorOnly: true' for the getter of '%s.%s', every getter is actually non-serialized.",
      	"3614": "Should not define constructor for cc.Component %s.",
      	"3615": "Each script can have at most one Component.",
      	"3616": "Should not specify class name %s for Component which defines in project.",
      	"3618": "ctor of '%s' can not be another CCClass",
      	"3623": "Can not use 'editor' attribute, '%s' not inherits from Components.",
      	"3625": "[isChildClassOf] superclass should be function type, not",
      	"3626": "Can't remove '%s' because '%s' depends on it.",
      	"3627": "Should not add renderer component (%s) to a Canvas node.",
      	"3628": "Should not add %s to a node which size is already used by its other component.",
      	"3633": "Properties function of '%s' should return an object!",
      	"3634": "Disallow to use '.' in property name",
      	"3637": "Can not declare %s.%s, it is already defined in the prototype of %s",
      	"3639": "Can not apply the specified attribute to the getter of '%s.%s', attribute index: %s",
      	"3640": "'%s': the setter of '%s' is already defined!",
      	"3641": "Can not construct %s because it contains object property.",
      	"3644": "Please define 'type' parameter of %s.%s as the actual constructor.",
      	"3645": "Please define 'type' parameter of %s.%s as the constructor of %s.",
      	"3646": "Unknown 'type' parameter of %s.%s：%s",
      	"3647": "The length of range array must be equal or greater than 2",
      	"3648": "Can not declare %s.%s method, it is already defined in the properties of %s.",
      	"3652": "Failed to `new %s()` under the hood, %s\nIt is used for getting default values declared in TypeScript in the first place.\nPlease ensure the constructor can be called during the script's initialization.",
      	"3653": "Please do not specify \"default\" attribute in decorator of \"%s\" property in \"%s\" class.\nDefault value must be initialized at their declaration:\n\n \n// Before:\n@property({\n  type: cc.SpriteFrame\n  default: null  // <--\n})\nmyProp;\n// After:\n@property({\n  type: cc.SpriteFrame\n})\nmyProp = null;   // <--",
      	"3654": "Please specify a default value for \"%s.%s\" property at its declaration:\n\n \n// Before:\n@property(...)\nmyProp;\n// After:\n@property(...)\nmyProp = 0;",
      	"3655": "Can not specify \"get\" or \"set\"  attribute in decorator for \"%s\" property in \"%s\" class.\nPlease use:\n\n \n@property(...)\nget %s () {\n    ...\n}\n@property\nset %s (value) {\n    ...\n}",
      	"3659": "Violation error: extending enumerations shall have non-overlaped member names or member values",
      	"3660": "You are explicitly specifying `undefined` type to cc property \"%s\" of cc class \"%s\".\nIs this intended? If not, this may indicate a circular reference.\nFor example:\n\n \n// foo.ts\nimport { _decorator } from 'cc';\nimport { Bar } from './bar';  // Given that './bar' also reference 'foo.ts'.\n                              // When importing './bar', execution of './bar' is hung on to wait execution of 'foo.ts',\n                              // the `Bar` imported here is `undefined` until './bar' finish its execution.\n                              // It leads to that\n@_decorator.ccclass           //  ↓\nexport class Foo {            //  ↓\n    @_decorator.type(Bar)     //  → is equivalent to `@_decorator.type(undefined)`\n    public bar: Bar;          // To eliminate this error, either:\n                              // - Refactor your module structure(recommended), or\n                              // - specify the type as cc class name: `@_decorator.type('Bar'/* or any name you specified for `Bar` */)`\n}",
      	"3700": "internal error: _prefab is undefined",
      	"3701": "Failed to load prefab asset for node '%s'",
      	"3800": "The target can not be made persist because it's not a cc.Node or it doesn't have _id property.",
      	"3801": "The node can not be made persist because it's not under root node.",
      	"3802": "The node can not be made persist because it's not in current scene.",
      	"3803": "The target can not be made persist because it's not a cc.Node or it doesn't have _id property.",
      	"3804": "getComponent: Type must be non-nil",
      	"3805": "Can't add component '%s' because %s already contains the same component.",
      	"3806": "Can't add component '%s' to %s because it conflicts with the existing '%s' derived component.",
      	"3807": "addComponent: Failed to get class '%s'",
      	"3808": "addComponent: Should not add component ('%s') when the scripts are still loading.",
      	"3809": "addComponent: The component to add must be a constructor",
      	"3810": "addComponent: The component to add must be child class of cc.Component",
      	"3811": "_addComponentAt: The component to add must be a constructor",
      	"3812": "_addComponentAt: Index out of range",
      	"3813": "removeComponent: Component must be non-nil",
      	"3814": "Argument must be non-nil",
      	"3815": "Component not owned by this entity",
      	"3816": "Node '%s' is already activating",
      	"3817": "Sorry, the component of '%s' which with an index of %s is corrupted! It has been removed.",
      	"3818": "Failed to read or parse project.json",
      	"3819": "Warning: target element is not a DIV or CANVAS",
      	"3820": "The renderer doesn't support the renderMode %s",
      	"3821": "Cannot change hierarchy while activating or deactivating the parent.",
      	"3822": "addComponent: Cannot add any component to the scene.",
      	"3823": "The enabled component (id: %s, name: %s) doesn't have a valid node",
      	"3900": "Invalid clip to add",
      	"3901": "Invalid clip to remove",
      	"3902": "clip is defaultClip, set force to true to force remove clip and animation state",
      	"3903": "animation state is playing, set force to true to force stop and remove clip and animation state",
      	"3904": "motion path of target [%s] in prop [%s] frame [%s] is not valid",
      	"3905": "sprite frames must be an Array.",
      	"3906": "Can't find easing type [%s]",
      	"3907": "Animation state is not playing or already removed",
      	"3912": "already-playing",
      	"3920": "Current context does not allow root motion.",
      	"3921": "You provided a ill-formed track path. The last component of track path should be property key, or the setter should not be empty.",
      	"3923": "Root motion is ignored since root bone could not be located in animation.",
      	"3924": "Root motion is ignored since the root bone could not be located in scene.",
      	"3925": "Target of hierarchy path should be of type Node.",
      	"3926": "Node \"%s\" has no path \"%s\".",
      	"3927": "Target of component path should be of type Node.",
      	"3928": "Node \"%s\" has no component \"%s\".",
      	"3929": "Target object has no property \"%s\".",
      	"3930": "Can not decide type for untyped track: runtime binding does not provide a getter.",
      	"3931": "Can not decide type for untyped track: got a unsupported value from runtime binding.",
      	"3932": "Common targets should only target Vectors/`Size`/`Color`.",
      	"3933": "Each curve that has common target should be numeric curve and targets string property.",
      	"3934": "Misconfigured legacy curve: the first keyframe value is number but others aren't.",
      	"3935": "We don't currently support conversion of \\`CubicSplineQuatValue\\`.",
      	"3936": "Instancing/Batching enabled for non-baked skinning model '%s', this may result in unexpected rendering artifacts. Consider turning it off in the material if you do not intend to do this.",
      	"3937": "Previous error occurred when instantiating animation clip %s on node %s.",
      	"3938": "'%s' is not found from '%s'. It's specified as the root node to play animation clip '%s'.",
      	"3940": "Error when animation attempted to bind material uniform target: target %s is not a material.",
      	"3941": "Error when animation attempted to bind material uniform target: material %s has no recorded pass %s.",
      	"3942": "Error when animation attempted to bind material uniform target: material %s at pass %s has no recorded uniform %s.",
      	"3943": "Error when animation attempted to bind material uniform target: material %s at pass %s's uniform %s has no recorded channel %s.",
      	"4003": "Label font size can't be shirnked less than 0!",
      	"4004": "force notify all fonts loaded!",
      	"4011": "Property spriteFrame of Font '%s' is invalid. Using system font instead.",
      	"4012": "The texture of Font '%s' must be already loaded on JSB. Using system font instead.",
      	"4013": "Sorry, lineHeight of system font not supported on JSB.",
      	"4200": "MaskType: IMAGE_STENCIL only support WebGL mode.",
      	"4201": "The alphaThreshold invalid in Canvas Mode.",
      	"4202": "The inverted invalid in Canvas Mode.",
      	"4300": "Can not found the %s page.",
      	"4301": "Can not add a page without UITransform.",
      	"4302": "Can not set the scroll view content when it hasn't UITransform or its parent hasn't UITransform.",
      	"4303": "The %s scrollBar on the '%s' node is not available, please check it.",
      	"4400": "Invalid RichText img tag! The sprite frame name can't be found in the ImageAtlas!",
      	"4500": "Graphics: There is no model in %s.",
      	"4600": "Script attached to '%s' is missing or invalid.",
      	"4601": "Failed to load wasm module, WebAssembly is not supported on this platform, but as a fallback Asm.js module is culled by mistake.",
      	"4700": "The dom control is not created!",
      	"4800": "unknown asset type",
      	"4901": "loadRes: should not specify the extname in %s %s",
      	"4902": "No need to release non-cached asset.",
      	"4914": "Resources url '%s' does not exist.",
      	"4915": "Pack indices and data do not match in size",
      	"4916": "Failed to download package for %s",
      	"4921": "Invalid pipe or invalid index provided!",
      	"4922": "The pipe to be inserted is already in the pipeline!",
      	"4923": "Uuid Loader: Parse asset [ %s ] failed : %s",
      	"4924": "JSON Loader: Input item doesn't contain string content",
      	"4925": "Uuid Loader: Deserialize asset [ %s ] failed : %s",
      	"4926": "Audio Downloader: no web audio context.",
      	"4927": "Audio Downloader: audio not supported on this browser!",
      	"4928": "Load %s failed!",
      	"4929": "Load Webp ( %s ) failed",
      	"4930": "Load image ( %s ) failed",
      	"4932": "Since v1.10, for any atlas (\"%s\") in the \"resources\" directory, it is not possible to find the contained SpriteFrames via `loadRes`, `getRes` or `releaseRes`. Load the SpriteAtlas first and then use `spriteAtlas.getSpriteFrame(name)` instead please.",
      	"4933": "Download Font [ %s ] failed, using Arial or system default font instead",
      	"4934": "Please assure that the full path of sub asset is correct!",
      	"4935": "Failed to skip prefab asset while deserializing PrefabInfo",
      	"5000": "You are trying to destroy a object twice or more.",
      	"5001": "object not yet destroyed",
      	"5100": "Not a plist file!",
      	"5200": "Warning: localStorage isn't enabled. Please confirm browser cookie or privacy option",
      	"5201": "browser don't support web audio",
      	"5202": "This feature supports WebGL render mode only.",
      	"5300": "Type of target to deserialize not matched with data: target is %s, data is %s",
      	"5301": "Can not find script '%s'",
      	"5302": "Can not find class '%s'",
      	"5303": "Failed to deserialize %s, missing _deserialize function.",
      	"5304": "Unable to deserialize version %s data.",
      	"5402": "cc.js.addon called on non-object:",
      	"5403": "cc.js.mixin: arguments must be type object:",
      	"5404": "The base class to extend from must be non-nil",
      	"5405": "The class to extend must be non-nil",
      	"5406": "Class should be extended before assigning any prototype members.",
      	"5500": "'notify' can not be used in 'get/set' !",
      	"5501": "'notify' must be used with 'default' !",
      	"5507": "The 'default' attribute of '%s.%s' must be an array",
      	"5508": "Invalid type of %s.%s",
      	"5510": "The 'type' attribute of '%s.%s' can not be 'Number', use cc.Float or cc.Integer instead please.",
      	"5511": "The 'type' attribute of '%s.%s' is undefined when loading script",
      	"5512": "Can not serialize '%s.%s' because the specified type is anonymous, please provide a class name or set the 'serializable' attribute of '%s.%s' to 'false'.",
      	"5513": "The 'default' value of '%s.%s' should not be used with a 'get' function.",
      	"5514": "The 'default' value of '%s.%s' should not be used with a 'set' function.",
      	"5515": "The 'default' value of '%s.%s' can not be an constructor. Set default to null please.",
      	"5517": "'%s.%s' hides inherited property '%s.%s'. To make the current property override that implementation, add the `override: true` attribute please.",
      	"5601": "Can not get current scene.",
      	"5602": "Scene is destroyed",
      	"5603": "reference node is destroyed",
      	"5700": "no %s or %s on %s",
      	"5800": "%s.lerp not yet implemented.",
      	"5801": "%s.clone not yet implemented.",
      	"5802": "%s.equals not yet implemented.",
      	"5900": "MotionStreak only support WebGL mode.",
      	"5901": "cc.MotionStreak.getOpacity has not been supported.",
      	"5902": "cc.MotionStreak.setOpacity has not been supported.",
      	"6000": "Custom should not be false if file is not specified.",
      	"6001": "The new %s must not be NaN",
      	"6017": "Incomplete or corrupt PNG file",
      	"6018": "Invalid filter algorithm: %s",
      	"6019": "Invalid byte order value.",
      	"6020": "You forgot your towel!",
      	"6021": "Unknown Field Tag: %s",
      	"6022": "Too many bits requested",
      	"6023": "No bits requested",
      	"6024": "Cannot recover from missing StripByteCounts",
      	"6025": "Cannot handle sub-byte bits per sample",
      	"6026": "Cannot handle sub-byte bits per pixel",
      	"6027": "Palette image missing color map",
      	"6028": "Unknown Photometric Interpretation: %s",
      	"6029": "Unkown error",
      	"6030": "cc.ParticleSystem: error decoding or ungzipping textureImageData",
      	"6031": "cc.ParticleSystem: unknown image format with Data",
      	"6032": "cc.ParticleSystem.initWithDictionary() : error loading the texture",
      	"6033": "cc.ParticleSystem: not allowing create to be invoked twice with different particle system",
      	"6034": "cc.ParticleSystem: shouldn't be initialized repetitively, otherwise there will be potential leak",
      	"6035": "cc.ParticleSystem: change material failed, please use proper particle material",
      	"6036": "cc.ParticleSystem: life time should bigger than 1 or buffer will be insufficient",
      	"6400": "asset.url is not usable in core process",
      	"6402": "AssetLibrary has already been initialized!",
      	"6500": "Widget target must be one of the parent nodes of it",
      	"6600": "collider not added or already removed",
      	"6601": "Can't find testFunc for (%s, $s).",
      	"6700": "Can't init canvas '%s' because it conflicts with the existing '%s', the scene should only have one active canvas at the same time.",
      	"6705": "Argument must be non-nil",
      	"6706": "Priority can't be set in RenderRoot2D node",
      	"6800": "Callback of event must be non-nil",
      	"6801": "The message must be provided",
      	"6900": "The thing you want to instantiate must be an object",
      	"6901": "The thing you want to instantiate is nil",
      	"6902": "The thing you want to instantiate is destroyed",
      	"6903": "The instantiate method for given asset do not implemented",
      	"6904": "Can not instantiate array",
      	"6905": "Can not instantiate DOM element",
      	"7100": "%s already defined in Enum.",
      	"7101": "Sorry, 'cc.Enum' not available on this platform, please report this error here: <https://github.com/cocos-creator/engine/issues/new>",
      	"7200": "Method 'initWithTMXFile' is no effect now, please set property 'tmxAsset' instead.",
      	"7201": "Method 'initWithXML' is no effect now, please set property 'tmxAsset' instead.",
      	"7202": "Add component TiledLayer into node failed.",
      	"7203": "Property 'mapLoaded' is unused now. Please write the logic to the callback 'start'.",
      	"7210": "TMX Hexa zOrder not supported",
      	"7211": "TMX invalid value",
      	"7215": "cocos2d: Warning: TMX Layer %s has no tiles",
      	"7216": "cocos2d: TMXFormat: Unsupported TMX version: %s",
      	"7217": "cocos2d: TMXFomat: Unsupported orientation: %s",
      	"7218": "cc.TMXMapInfo.parseXMLFile(): unsupported compression method",
      	"7219": "cc.TMXMapInfo.parseXMLFile(): Only base64 and/or gzip/zlib maps are supported",
      	"7221": "cc.TMXMapInfo.parseXMLFile(): Texture '%s' not found.",
      	"7222": "Parse %s failed.",
      	"7236": "cc.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released",
      	"7237": "cc.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released",
      	"7238": "cc.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released",
      	"7239": "cc.TMXLayer.setTileGID(): invalid gid: %s",
      	"7240": "cc.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released",
      	"7241": "cc.TiledMap.initWithXML(): Map not found. Please check the filename.",
      	"7401": "Failed to set _defaultArmatureIndex for '%s' because the index is out of range.",
      	"7402": "Failed to set _animationIndex for '%s' because the index is out of range.",
      	"7501": "Failed to set _defaultSkinIndex for '%s' because the index is out of range.",
      	"7502": "Failed to set _animationIndex for '%s' because its skeletonData is invalid.",
      	"7503": "Failed to set _animationIndex for '%s' because the index is out of range.",
      	"7504": "Can not render dynamic created SkeletonData",
      	"7506": "Failed to load spine atlas '$s'",
      	"7507": "Please re-import '%s' because its textures is not initialized! (This workflow will be improved in the future.)",
      	"7508": "The atlas asset of '%s' is not exists!",
      	"7509": "Spine: Animation not found: %s",
      	"7510": "Spine: Animation not found: %s",
      	"7511": "Spine: Invalid input!",
      	"7600": "The context of RenderTexture is invalid.",
      	"7601": "cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;",
      	"7602": "Could not attach texture to the framebuffer",
      	"7603": "clearDepth isn't supported on Cocos2d-Html5",
      	"7604": "saveToFile isn't supported on Cocos2d-Html5",
      	"7605": "newCCImage isn't supported on Cocos2d-Html5",
      	"7606": "GFXTexture is null",
      	"7607": "readPixels buffer size smaller than %d",
      	"7700": "On the web is always keep the aspect ratio",
      	"7701": "Can't know status",
      	"7702": "Video player's duration is not ready to get now!",
      	"7703": "Video Downloader: video not supported on this browser!",
      	"7800": "Web does not support loading",
      	"7801": "Web does not support query history",
      	"7802": "Web does not support query history",
      	"7803": "The current browser does not support the GoBack",
      	"7804": "The current browser does not support the GoForward",
      	"7805": "Web does not support zoom",
      	"7900": "cc.math.Matrix3.assign(): current matrix equals matIn",
      	"7901": "cc.math.mat4Assign(): pOut equals pIn",
      	"7902": "cc.mat.Matrix4.assignFrom(): mat4 equals current matrix",
      	"7903": "cc.math.Matrix4 equal: pMat1 and pMat2 are same object.",
      	"7904": "cc.math.Matrix4.extractPlane: Invalid plane index",
      	"7905": "cc.math.mat4Assign(): pOut equals pIn",
      	"7906": "cc.mat.Matrix4.assignFrom(): mat4 equals current matrix",
      	"7907": "cc.math.Matrix4 equals: pMat1 and pMat2 are same object.",
      	"7908": "Invalid matrix mode specified",
      	"7909": "current quaternion is an invalid value",
      	"8000": "Can't handle this field type or size",
      	"8001": "No bytes requested",
      	"8002": "Too many bytes requested",
      	"8003": "Missing StripByteCounts!",
      	"8100": "cocos2d: ERROR: Failed to compile shader:\n %s",
      	"8101": "cocos2d: ERROR: Failed to compile vertex shader",
      	"8102": "cocos2d: ERROR: Failed to compile fragment shader",
      	"8103": "cc.GLProgram.link(): Cannot link invalid program",
      	"8104": "cocos2d: ERROR: Failed to link program: %s",
      	"8105": "cocos2d: cc.shaderCache._loadDefaultShader, error shader type",
      	"8106": "Please load the resource firset : %s",
      	"8107": "cc.GLProgram.getUniformLocationForName(): uniform name should be non-null",
      	"8108": "cc.GLProgram.getUniformLocationForName(): Invalid operation. Cannot get uniform location when program is not initialized",
      	"8109": "modelView matrix is undefined.",
      	"8200": "Please set node's active instead of rigidbody's enabled.",
      	"8300": "Should only one camera exists, please check your project.",
      	"8301": "Camera does not support Canvas Mode.",
      	"8302": "Camera.viewport is deprecated, please use setViewportInOrientedSpace instead.",
      	"8400": "Wrong type arguments, 'filePath' must be a String.",
      	"9000": "Stencil manager does not support level bigger than %d in this device.",
      	"9001": "Stencil manager is already empty, cannot pop any mask",
      	"9002": "Failed to request any buffer from a mesh buffer without accessor",
      	"9003": "The internal state of LinearBufferAccessor have severe issue and irreversible, please check the reason",
      	"9004": "Failed to allocate chunk in StaticVBAccessor, the requested buffer might be too large: %d bytes",
      	"9005": "BATCHER2D_MEM_INCREMENT is too large, the Max value for BATCHER2D_MEM_INCREMENT is 2303KB (smaller than 65536 *9* 4 / 1024 = 2304KB)",
      	"9006": "QuadRenderData is removed, please use MeshRenderData instead.",
      	"9007": "Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation.",
      	"9100": "texture size exceeds current device limits %d/%d",
      	"9101": "The length of the TypedArrayBuffer must be an integer.",
      	"9201": "Cannot access game frame or container.",
      	"9202": "Setting window size is not supported.",
      	"9300": "The current buffer beyond the limit in ui static component, please reduce the amount",
      	"9301": "The UI has not been initialized",
      	"9302": "Can't getGFXSampler with out device",
      	"9600": "[Physics]: please check to see if physics modules are included",
      	"9610": "[Physics]: cannon.js physics system doesn't support capsule collider",
      	"9611": "[Physics]: builtin physics system doesn't support mesh collider",
      	"9612": "[Physics]: builtin physics system doesn't support cylinder collider",
      	"9613": "[Physics]: cannon.js physics system doesn't support hinge drive and angular limit",
      	"9620": "[Physics][Ammo]: changing the mesh is not supported after the initialization is completed",
      	"9630": "[Physics]: A dynamic rigid body can not have the following collider shapes: Terrain, Plane and Non-convex Mesh. Node name: %s",
      	"9640": "[Physics][builtin]: sweep functions are not supported in builtin",
      	"9641": "[Physics][cannon.js]: sweep functions are not supported in cannon.js",
      	"10001": "The sub-mesh contains %d vertices, which beyonds the capability (%d vertices most) of renderer of your platform.",
      	"10002": "Sub-mesh may include at most %d morph targets, but you specified %d.",
      	"11000": "WebGL context lost.",
      	"12001": "BlendFactors are disabled when using custom material, please modify the blend state in the material instead.",
      	"12002": "Can't add renderable component to this node because it already have one.",
      	"12004": "SubModel can only support %d passes.",
      	"12005": "Material already initialized, request aborted.",
      	"12006": "Pass already destroyed.",
      	"12007": "This is old usage, please swap the parameters.",
      	"12008": "GeometryRenderer: too many lines.",
      	"12009": "GeometryRenderer: too many triangles.",
      	"12010": "PassUtils: illegal uniform handle, accessing uniform at offset %d",
      	"12011": "Pass: setUniform is invoked with incompatible uniform data type for binding %d, expected type is %s",
      	"12012": "Can't set a material instance to a sharedMaterial slot",
      	"12100": "The font size is too big to be fitted into texture atlas. Please switch to other label cache modes or choose a smaller font size.",
      	"12101": "The asset %s has been destroyed!",
      	"12102": "Base pass cannot override states, please use pass instance instead.",
      	"12103": "Custom pipeline create shader %s failed. Please restart editor.",
      	"12104": "Create shader %s failed.",
      	"12105": "Pass resources incomplete.",
      	"12106": "Cannot patch non-builtin macros.",
      	"12107": "Custom pipeline invalid render pass, program: %s. Please restart editor.",
      	"12108": "Custom pipeline invalid render phase, program: %s. Please restart editor.",
      	"13100": "Incorrect CCON magic.",
      	"13101": "Unknown CCON version number: %d.",
      	"13102": "CCON Format error.",
      	"13103": "Can not encode CCON binary: lack of text encoder.",
      	"13104": "Can not decode CCON binary: lack of text decoder.",
      	"14000": "State machine matched too many transitions(greater than %s) during this frame: %s.",
      	"14100": "Pool.destroy no longer take a function as parameter, Please specify destruct function in the construction of Pool instead",
      	"14200": "Can not update a static mesh.",
      	"14201": "The primitiveIndex is out of range.",
      	"14202": "meshopt asm decoder initialized",
      	"14203": "meshopt wasm decoder initialized",
      	"14204": "meshopt decoder error: %d",
      	"14300": "Can not keep world transform due to the zero scaling of parent node",
      	"14400": "Spline error: less than 2 knots.",
      	"14401": "Spline error: less than 4 knots or not a multiple of 4.\n\n<!-- Rendering algorithm reserved: 15000 - 16000 -->",
      	"15000": "Can not find corresponding diffuse map for environment lighting, use hemisphere diffuse instead, change environment lighting type to regenerate diffuse map",
      	"15001": "Can not find environment map, disable IBL lighting",
      	"15002": "Diffuse map resource is missing, please change environment lighting type to regenerate resource",
      	"15003": "The shadow visible distance is so small that CSM stratification is not effective, Please change the value of shadowDistance so that it is 10 times greater than 0.1",
      	"15004": "The native folder may be generated from older versions, please refer https://docs.cocos.com/creator/manual/en/release-notes/ to upgrade.",
      	"15100": "Camera '%s' clear flag is skybox, but skybox is disabled,  may cause strange background effect, please set camera clear flag to solid color.",
      	"16000": "'%s' is deprecated since v%s.",
      	"16001": "'%s' is deprecated since v%s, please use '%s' instead.",
      	"16002": "'%s' is removed since v%s.",
      	"16003": "'%s' is removed since v%s, please use '%s' instead.",
      	"16101": "The effect('%s') you are looking for does not exist, please confirm the effect name in the editor. NOTE: Since 3.6, the name of the built-in effect has been changed to its name in the editor, please check it out. More information please refer to https://docs.cocos.com/creator/manual/en/shader/effect-inspector.html",
      	"16201": "The asset replacing failed, can not found override asset('%s') for '%s'",
      	"16301": "node '%s' doesn't have any ModelRenderer component, this component will not work. please add ModelRenderer component first",
      	"16302": "There is no reflection probe in the scene or no probe is near the current object. No reflection probe will take effect on this object. Please create a new reflection probe or move existing ones closer.",
      	"16303": "Skin material needs floating-point render target, please check ENABLE_FLOAT_OUTPUT define in Project Settings--Macro",
      	"16304": "Skin material may need more accurate calculations, please select a head model of standard size, check the isGlobalStandardSkinObject option in the MeshRender component.",
      	"0100": "%s not yet implemented.",
      	"0200": "You should specify a valid DOM canvas element."
      };

      var ccdocument$6 = ccwindow.document;
      var logList = null;
      var ccLog = console.log.bind(console);
      var ccWarn = ccLog;
      var ccError = ccLog;
      var ccAssert = function ccAssert(condition, message) {
        if (!condition) {
          for (var _len = arguments.length, optionalParams = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
            optionalParams[_key - 2] = arguments[_key];
          }
          console.log("ASSERT: " + formatString.apply(void 0, [message].concat(optionalParams)));
        }
      };
      var ccDebug = ccLog;
      function formatString() {
        for (var _len2 = arguments.length, data = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          data[_key2] = arguments[_key2];
        }
        return legacyCC.js.formatStr.apply(null, data);
      }
      function log() {
        return ccLog.apply(void 0, arguments);
      }
      function warn() {
        return ccWarn.apply(void 0, arguments);
      }
      function error() {
        return ccError.apply(void 0, arguments);
      }
      function assert(condition, message) {
        for (var _len3 = arguments.length, optionalParams = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
          optionalParams[_key3 - 2] = arguments[_key3];
        }
        return ccAssert.apply(void 0, [condition, message].concat(optionalParams));
      }
      function debug() {
        return ccDebug.apply(void 0, arguments);
      }
      function _resetDebugSetting(mode) {
        ccLog = ccWarn = ccError = ccAssert = ccDebug = function ccDebug() {};
        if (mode === DebugMode.NONE) {
          return;
        }
        if (mode > DebugMode.ERROR) {
          var logToWebPage = function logToWebPage(msg) {
            if (!legacyCC.game.canvas) {
              return;
            }
            if (!logList) {
              var logDiv = ccdocument$6.createElement('Div');
              logDiv.setAttribute('id', 'logInfoDiv');
              logDiv.setAttribute('width', '200');
              logDiv.setAttribute('height', legacyCC.game.canvas.height);
              var logDivStyle = logDiv.style;
              logDivStyle.zIndex = '99999';
              logDivStyle.position = 'absolute';
              logDivStyle.top = logDivStyle.left = '0';
              logList = ccdocument$6.createElement('textarea');
              logList.setAttribute('rows', '20');
              logList.setAttribute('cols', '30');
              logList.setAttribute('disabled', 'true');
              var logListStyle = logList.style;
              logListStyle.backgroundColor = 'transparent';
              logListStyle.borderBottom = '1px solid #cccccc';
              logListStyle.borderTopWidth = logListStyle.borderLeftWidth = logListStyle.borderRightWidth = '0px';
              logListStyle.borderTopStyle = logListStyle.borderLeftStyle = logListStyle.borderRightStyle = 'none';
              logListStyle.padding = '0px';
              logListStyle.margin = '0px';
              logDiv.appendChild(logList);
              legacyCC.game.canvas.parentNode.appendChild(logDiv);
            }
            logList.value = logList.value + msg + "\r\n";
            logList.scrollTop = logList.scrollHeight;
          };
          ccError = function ccError() {
            logToWebPage("ERROR :  " + formatString.apply(void 0, arguments));
          };
          ccAssert = function ccAssert(condition, message) {
            if (!condition) {
              for (var _len4 = arguments.length, optionalParams = new Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
                optionalParams[_key4 - 2] = arguments[_key4];
              }
              logToWebPage("ASSERT: " + formatString.apply(void 0, [message].concat(optionalParams)));
            }
          };
          if (mode !== DebugMode.ERROR_FOR_WEB_PAGE) {
            ccWarn = function ccWarn() {
              logToWebPage("WARN :  " + formatString.apply(void 0, arguments));
            };
          }
          if (mode === DebugMode.INFO_FOR_WEB_PAGE) {
            ccLog = function ccLog() {
              logToWebPage(formatString.apply(void 0, arguments));
            };
          }
        } else if (console) {
          if (!console.error) {
            console.error = console.log;
          }
          if (!console.warn) {
            console.warn = console.log;
          }
          if (console.error.bind) {
            ccError = console.error.bind(console);
          } else {
            ccError = function () {
              for (var _len5 = arguments.length, data = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
                data[_key5] = arguments[_key5];
              }
              return console.error.apply(console, data);
            };
          }
          ccAssert = function ccAssert(condition, message) {
            if (!condition) {
              for (var _len6 = arguments.length, optionalParams = new Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) {
                optionalParams[_key6 - 2] = arguments[_key6];
              }
              var errorText = formatString.apply(void 0, [message].concat(optionalParams));
              {
                throw new Error(errorText);
              }
            }
          };
        }
        if (mode !== DebugMode.ERROR) {
          if (console.warn.bind) {
            ccWarn = console.warn.bind(console);
          } else {
            ccWarn = function () {
              for (var _len7 = arguments.length, data = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
                data[_key7] = arguments[_key7];
              }
              return console.warn.apply(console, data);
            };
          }
        }
        if (mode <= DebugMode.INFO) {
          if (console.log.bind) {
            ccLog = console.log.bind(console);
          } else {
            ccLog = function ccLog() {
              for (var _len8 = arguments.length, data = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
                data[_key8] = arguments[_key8];
              }
              return console.log.apply(console, data);
            };
          }
        }
        if (mode <= DebugMode.VERBOSE) {
          if (typeof console.debug === 'function') {
            var vendorDebug = console.debug.bind(console);
            ccDebug = function ccDebug() {
              return vendorDebug.apply(void 0, arguments);
            };
          }
        }
      }
      function _throw(error_) {
        {
          var stack = error_.stack;
          if (stack) {
            error(stack);
          } else {
            error(error_);
          }
          return undefined;
        }
      }
      function getTypedFormatter(type) {
        return function (id) {
          var msg = debugInfos[id] || 'unknown id' ;
          for (var _len9 = arguments.length, args = new Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) {
            args[_key9 - 1] = arguments[_key9];
          }
          if (args.length === 0) {
            return msg;
          }
          return formatString.apply(void 0, [msg].concat(args)) ;
        };
      }
      var logFormatter = getTypedFormatter();
      function logID(id) {
        for (var _len10 = arguments.length, optionalParams = new Array(_len10 > 1 ? _len10 - 1 : 0), _key10 = 1; _key10 < _len10; _key10++) {
          optionalParams[_key10 - 1] = arguments[_key10];
        }
        log(logFormatter.apply(void 0, [id].concat(optionalParams)));
      }
      var warnFormatter = getTypedFormatter();
      function warnID(id) {
        for (var _len11 = arguments.length, optionalParams = new Array(_len11 > 1 ? _len11 - 1 : 0), _key11 = 1; _key11 < _len11; _key11++) {
          optionalParams[_key11 - 1] = arguments[_key11];
        }
        warn(warnFormatter.apply(void 0, [id].concat(optionalParams)));
      }
      var errorFormatter = getTypedFormatter();
      function errorID(id) {
        for (var _len12 = arguments.length, optionalParams = new Array(_len12 > 1 ? _len12 - 1 : 0), _key12 = 1; _key12 < _len12; _key12++) {
          optionalParams[_key12 - 1] = arguments[_key12];
        }
        error(errorFormatter.apply(void 0, [id].concat(optionalParams)));
      }
      var assertFormatter = getTypedFormatter();
      function assertID(condition, id) {
        if (condition) {
          return;
        }
        for (var _len13 = arguments.length, optionalParams = new Array(_len13 > 2 ? _len13 - 2 : 0), _key13 = 2; _key13 < _len13; _key13++) {
          optionalParams[_key13 - 2] = arguments[_key13];
        }
        assert(false, assertFormatter.apply(void 0, [id].concat(optionalParams)));
      }
      var DebugMode; exports('ci', DebugMode);
      (function (DebugMode) {
        DebugMode[DebugMode["NONE"] = 0] = "NONE";
        DebugMode[DebugMode["VERBOSE"] = 1] = "VERBOSE";
        DebugMode[DebugMode["INFO"] = 2] = "INFO";
        DebugMode[DebugMode["WARN"] = 3] = "WARN";
        DebugMode[DebugMode["ERROR"] = 4] = "ERROR";
        DebugMode[DebugMode["INFO_FOR_WEB_PAGE"] = 5] = "INFO_FOR_WEB_PAGE";
        DebugMode[DebugMode["WARN_FOR_WEB_PAGE"] = 6] = "WARN_FOR_WEB_PAGE";
        DebugMode[DebugMode["ERROR_FOR_WEB_PAGE"] = 7] = "ERROR_FOR_WEB_PAGE";
      })(DebugMode || (exports('ci', DebugMode = {})));
      function getError(errorId) {
        for (var _len14 = arguments.length, param = new Array(_len14 > 1 ? _len14 - 1 : 0), _key14 = 1; _key14 < _len14; _key14++) {
          param[_key14 - 1] = arguments[_key14];
        }
        return errorFormatter.apply(void 0, [errorId].concat(param));
      }
      function isDisplayStats() {
        return legacyCC.profiler ? legacyCC.profiler.isShowingStats() : false;
      }
      function setDisplayStats(displayStats) {
        if (legacyCC.profiler) {
          displayStats ? legacyCC.profiler.showStats() : legacyCC.profiler.hideStats();
        }
      }

      var debug$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        log: log,
        warn: warn,
        error: error,
        assert: assert,
        debug: debug,
        _resetDebugSetting: _resetDebugSetting,
        _throw: _throw,
        logID: logID,
        warnID: warnID,
        errorID: errorID,
        assertID: assertID,
        get DebugMode () { return DebugMode; },
        getError: getError,
        isDisplayStats: isDisplayStats,
        setDisplayStats: setDisplayStats
      });

      var defaultLogTimes = 10;
      function setDefaultLogTimes(times) {
        if (times > 0) {
          defaultLogTimes = times;
        }
      }
      var replaceProperty; exports('bI', replaceProperty);
      var removeProperty; exports('bJ', removeProperty);
      var markAsWarning; exports('bK', markAsWarning);
      var replacePropertyLog;
      var markAsWarningLog;
      var removePropertyLog;
      var messageID = 0;
      var messageMap = new Map();
      replacePropertyLog = function replacePropertyLog(n, dp, n2, newp, f, id, s) {
        var item = messageMap.get(id);
        if (item && item.logTimes > item.count) {
          f("'%s' is deprecated, please use '%s' instead. " + s, n + "." + dp, n2 + "." + newp);
          item.count++;
        }
      };
      exports('bI', replaceProperty = function replaceProperty(owner, ownerName, properties) {
        if (owner == null) return;
        properties.forEach(function (item) {
          var id = messageID++;
          messageMap.set(id, {
            id: id,
            count: 0,
            logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
          });
          var target = item.target != null ? item.target : owner;
          var newName = item.newName != null ? item.newName : item.name;
          var targetName = item.targetName != null ? item.targetName : ownerName;
          var sameTarget = target === owner;
          var suggest = item.suggest ? "(" + item.suggest + ")" : '';
          if (item.customFunction != null) {
            owner[item.name] = function () {
              var _ref;
              replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
              return (_ref = item.customFunction).call.apply(_ref, [this].concat(Array.prototype.slice.call(arguments)));
            };
          } else if (item.customSetter != null || item.customGetter != null) {
            var hasSetter = item.customSetter != null;
            var hasGetter = item.customGetter != null;
            if (hasSetter && hasGetter) {
              Object.defineProperty(owner, item.name, {
                get: function get() {
                  replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                  return item.customGetter.call(this);
                },
                set: function set(v) {
                  replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                  item.customSetter.call(this, v);
                },
                enumerable: false
              });
            } else if (hasSetter) {
              Object.defineProperty(owner, item.name, {
                set: function set(v) {
                  replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                  item.customSetter.call(this, v);
                },
                enumerable: false
              });
            } else if (hasGetter) {
              Object.defineProperty(owner, item.name, {
                get: function get() {
                  replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                  return item.customGetter.call(this);
                },
                enumerable: false
              });
            }
          } else {
            Object.defineProperty(owner, item.name, {
              get: function get() {
                replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                return sameTarget ? this[newName] : target[newName];
              },
              set: function set(v) {
                replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                if (sameTarget) {
                  this[newName] = v;
                } else {
                  target[newName] = v;
                }
              },
              enumerable: false
            });
          }
        });
      });
      removePropertyLog = function removePropertyLog(n, dp, f, id, s) {
        var item = messageMap.get(id);
        if (item && item.logTimes > item.count) {
          f("'%s' has been removed. " + s, n + "." + dp);
          item.count++;
        }
      };
      exports('bJ', removeProperty = function removeProperty(owner, ownerName, properties) {
        if (owner == null) return;
        properties.forEach(function (item) {
          var id = messageID++;
          messageMap.set(id, {
            id: id,
            count: 0,
            logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
          });
          var suggest = item.suggest ? "(" + item.suggest + ")" : '';
          Object.defineProperty(owner, item.name, {
            get: function get() {
              return removePropertyLog(ownerName, item.name, error, id, suggest);
            },
            set: function set() {
              removePropertyLog(ownerName, item.name, error, id, suggest);
            },
            enumerable: false
          });
        });
      });
      markAsWarningLog = function markAsWarningLog(n, dp, f, id, s) {
        var item = messageMap.get(id);
        if (item && item.logTimes > item.count) {
          f("'%s' is deprecated. " + s, n + "." + dp);
          item.count++;
        }
      };
      exports('bK', markAsWarning = function markAsWarning(owner, ownerName, properties) {
        if (owner == null) return;
        var _defaultGetSet = function _defaultGetSet(d, n, dp, f, id, s) {
          if (d.get) {
            var oldGet = d.get;
            d.get = function () {
              markAsWarningLog(n, dp, f, id, s);
              return oldGet.call(this);
            };
          }
          if (d.set) {
            var oldSet = d.set;
            d.set = function (v) {
              markAsWarningLog(n, dp, f, id, s);
              oldSet.call(this, v);
            };
          }
          Object.defineProperty(owner, dp, d);
        };
        properties.forEach(function (item) {
          var deprecatedProp = item.name;
          var descriptor = Object.getOwnPropertyDescriptor(owner, deprecatedProp);
          if (!descriptor || !descriptor.configurable) {
            return;
          }
          var id = messageID++;
          messageMap.set(id, {
            id: id,
            count: 0,
            logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
          });
          var suggest = item.suggest ? "(" + item.suggest + ")" : '';
          if (typeof descriptor.value !== 'undefined') {
            if (typeof descriptor.value === 'function') {
              var oldValue = descriptor.value;
              owner[deprecatedProp] = function () {
                markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest);
                return oldValue.call.apply(oldValue, [this].concat(Array.prototype.slice.call(arguments)));
              };
            } else {
              var _oldValue = descriptor.value;
              Object.defineProperty(owner, deprecatedProp, {
                configurable: true,
                get: function get() {
                  markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest);
                  return _oldValue;
                }
              });
              if (descriptor.writable) {
                Object.defineProperty(owner, deprecatedProp, {
                  set: function set(value) {
                    markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest);
                    _oldValue = value;
                  }
                });
              }
            }
          } else {
            _defaultGetSet(descriptor, ownerName, deprecatedProp, warn, id, suggest);
          }
          Object.defineProperty(owner, deprecatedProp, {
            enumerable: false
          });
        });
      });
      var topLevelDeprecateList = {};
      function deprecateModuleExportedName(deprecateList) {
        for (var deprecateName in deprecateList) {
          var deprecateInfo = deprecateList[deprecateName];
          topLevelDeprecateList[deprecateName] = deprecateInfo;
        }
      }
      function _checkObsoleteByName(checkName) {
        var deprecateInfo = topLevelDeprecateList[checkName];
        if (!deprecateInfo) {
          return;
        }
        var newName = deprecateInfo.newName,
          since = deprecateInfo.since,
          removed = deprecateInfo.removed;
        if (removed) {
          if (newName) {
            errorID(16003, checkName, since, newName);
          } else {
            errorID(16002, checkName, since);
          }
        } else if (newName) {
          warnID(16001, checkName, since, newName);
        } else {
          warnID(16000, checkName, since);
        }
      }
      function __checkObsolete__(checkList) {
        for (var _iterator = _createForOfIteratorHelperLoose(checkList), _step; !(_step = _iterator()).done;) {
          var checkName = _step.value;
          _checkObsoleteByName(checkName);
        }
      }
      var _cachedProxy;
      function __checkObsoleteInNamespace__(ccNamespace) {
        if (!_cachedProxy) {
          if (typeof Proxy === 'undefined') {
            _cachedProxy = {};
          } else {
            _cachedProxy = new Proxy(ccNamespace, {
              get: function get(target, name, receiver) {
                _checkObsoleteByName(name);
                return Reflect.get(target, name, receiver);
              }
            });
          }
        }
        return _cachedProxy;
      }

      var _class$3O;
      var NonUuidMark = '.';
      var IDGenerator = function () {
        function IDGenerator(category) {
          this.id = void 0;
          this.prefix = void 0;
          this.id = 0 | Math.random() * 998;
          this.prefix = category ? category + NonUuidMark : '';
        }
        var _proto = IDGenerator.prototype;
        _proto.getNewId = function getNewId() {
          return this.prefix + (++this.id).toString();
        };
        return IDGenerator;
      }();
      _class$3O = IDGenerator;
      IDGenerator.global = new _class$3O('global');

      var tempCIDGenerator = new IDGenerator('TmpCId.');
      var aliasesTag = typeof Symbol === 'undefined' ? '__aliases__' : Symbol('[[Aliases]]');
      var classNameTag = '__classname__';
      var classIdTag = '__cid__';
      function isNumber(object) {
        return typeof object === 'number' || object instanceof Number;
      }
      function isString(object) {
        return typeof object === 'string' || object instanceof String;
      }
      function isEmptyObject(obj) {
        for (var key in obj) {
          return false;
        }
        return true;
      }
      var value = function () {
        var descriptor = {
          value: undefined,
          enumerable: false,
          writable: false,
          configurable: true
        };
        return function (object, propertyName, value_, writable, enumerable) {
          descriptor.value = value_;
          descriptor.writable = writable;
          descriptor.enumerable = enumerable;
          Object.defineProperty(object, propertyName, descriptor);
          descriptor.value = undefined;
        };
      }();
      var getset = function () {
        var descriptor = {
          get: undefined,
          set: undefined,
          enumerable: false
        };
        return function (object, propertyName, getter, setter, enumerable, configurable) {
          if (enumerable === void 0) {
            enumerable = false;
          }
          if (configurable === void 0) {
            configurable = false;
          }
          if (typeof setter === 'boolean') {
            console.log('Set `setter` to boolean is deprecated. Please don not use like this again.');
            enumerable = setter;
            setter = undefined;
          }
          descriptor.get = getter;
          descriptor.set = setter;
          descriptor.enumerable = enumerable;
          descriptor.configurable = configurable;
          Object.defineProperty(object, propertyName, descriptor);
          descriptor.get = undefined;
          descriptor.set = undefined;
        };
      }();
      var get = function () {
        var descriptor = {
          get: undefined,
          enumerable: false,
          configurable: false
        };
        return function (object, propertyName, getter, enumerable, configurable) {
          descriptor.get = getter;
          descriptor.enumerable = enumerable;
          descriptor.configurable = configurable;
          Object.defineProperty(object, propertyName, descriptor);
          descriptor.get = undefined;
        };
      }();
      var set = function () {
        var descriptor = {
          set: undefined,
          enumerable: false,
          configurable: false
        };
        return function (object, propertyName, setter, enumerable, configurable) {
          descriptor.set = setter;
          descriptor.enumerable = enumerable;
          descriptor.configurable = configurable;
          Object.defineProperty(object, propertyName, descriptor);
          descriptor.set = undefined;
        };
      }();
      function createMap(forceDictMode) {
        var map = Object.create(null);
        if (forceDictMode) {
          var INVALID_IDENTIFIER_1 = '.';
          var INVALID_IDENTIFIER_2 = '/';
          map[INVALID_IDENTIFIER_1] = 1;
          map[INVALID_IDENTIFIER_2] = 1;
          delete map[INVALID_IDENTIFIER_1];
          delete map[INVALID_IDENTIFIER_2];
        }
        return map;
      }
      function getClassName(objOrCtor) {
        if (typeof objOrCtor === 'function') {
          var prototype = objOrCtor.prototype;
          if (prototype && prototype.hasOwnProperty(classNameTag) && prototype[classNameTag]) {
            return prototype[classNameTag];
          }
          var ret = '';
          if (objOrCtor.name) {
            ret = objOrCtor.name;
          }
          if (objOrCtor.toString) {
            var arr;
            var str = objOrCtor.toString();
            if (str.charAt(0) === '[') {
              arr = /\[\w+\s*(\w+)\]/.exec(str);
            } else {
              arr = /function\s*(\w+)/.exec(str);
            }
            if (arr && arr.length === 2) {
              ret = arr[1];
            }
          }
          return ret !== 'Object' ? ret : '';
        } else if (objOrCtor && objOrCtor.constructor) {
          return getClassName(objOrCtor.constructor);
        }
        return '';
      }
      function obsolete(object, obsoleted, newExpr, writable) {
        var extractPropName = /([^.]+)$/;
        var oldProp = extractPropName.exec(obsoleted)[0];
        var newProp = extractPropName.exec(newExpr)[0];
        function getter() {
          return this[newProp];
        }
        function setter(value_) {
          this[newProp] = value_;
        }
        if (writable) {
          getset(object, oldProp, getter, setter);
        } else {
          get(object, oldProp, getter);
        }
      }
      function obsoletes(obj, objName, props, writable) {
        for (var obsoleted in props) {
          var newName = props[obsoleted];
          obsolete(obj, objName + "." + obsoleted, newName, writable);
        }
      }
      var REGEXP_NUM_OR_STR = /(%d)|(%s)/;
      var REGEXP_STR = /%s/;
      function formatStr(msg) {
        for (var _len = arguments.length, subst = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          subst[_key - 1] = arguments[_key];
        }
        if (arguments.length === 0) {
          return '';
        }
        if (subst.length === 0) {
          return "" + msg;
        }
        var hasSubstitution = typeof msg === 'string' && REGEXP_NUM_OR_STR.test(msg);
        if (hasSubstitution) {
          for (var _iterator = _createForOfIteratorHelperLoose(subst), _step; !(_step = _iterator()).done;) {
            var arg = _step.value;
            var regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR;
            if (regExpToTest.test(msg)) {
              var notReplaceFunction = "" + arg;
              msg = msg.replace(regExpToTest, notReplaceFunction);
            } else {
              msg += " " + arg;
            }
          }
        } else {
          for (var _iterator2 = _createForOfIteratorHelperLoose(subst), _step2; !(_step2 = _iterator2()).done;) {
            var _arg = _step2.value;
            msg += " " + _arg;
          }
        }
        return msg;
      }
      function shiftArguments() {
        var len = arguments.length - 1;
        var args = new Array(len);
        for (var i = 0; i < len; ++i) {
          args[i] = arguments[i + 1];
        }
        return args;
      }
      function getPropertyDescriptor(object, propertyName) {
        while (object) {
          var pd = Object.getOwnPropertyDescriptor(object, propertyName);
          if (pd) {
            return pd;
          }
          object = Object.getPrototypeOf(object);
        }
        return null;
      }
      function _copyProp(name, source, target) {
        var pd = getPropertyDescriptor(source, name);
        if (pd) {
          Object.defineProperty(target, name, pd);
        }
      }
      function copyAllProperties(source, target, excepts) {
        var propertyNames = Object.getOwnPropertyNames(source);
        for (var i = 0, len = propertyNames.length; i < len; ++i) {
          var _propertyName = propertyNames[i];
          if (excepts.indexOf(_propertyName) !== -1) {
            continue;
          }
          _copyProp(_propertyName, source, target);
        }
      }
      function addon(object) {
        object = object || {};
        for (var _len2 = arguments.length, sources = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          sources[_key2 - 1] = arguments[_key2];
        }
        for (var _i = 0, _sources = sources; _i < _sources.length; _i++) {
          var source = _sources[_i];
          if (source) {
            if (typeof source !== 'object') {
              errorID(5402, source);
              continue;
            }
            for (var name in source) {
              if (!(name in object)) {
                _copyProp(name, source, object);
              }
            }
          }
        }
        return object;
      }
      function mixin(object) {
        object = object || {};
        for (var _len3 = arguments.length, sources = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
          sources[_key3 - 1] = arguments[_key3];
        }
        for (var _i2 = 0, _sources2 = sources; _i2 < _sources2.length; _i2++) {
          var source = _sources2[_i2];
          if (source) {
            if (typeof source !== 'object') {
              errorID(5403, source);
              continue;
            }
            for (var name in source) {
              _copyProp(name, source, object);
            }
          }
        }
        return object;
      }
      function extend(cls, base) {
        for (var p in base) {
          if (base.hasOwnProperty(p)) {
            cls[p] = base[p];
          }
        }
        cls.prototype = Object.create(base.prototype, {
          constructor: {
            value: cls,
            writable: true,
            configurable: true
          }
        });
        return cls;
      }
      function getSuper(constructor) {
        var proto = constructor.prototype;
        var dunderProto = proto && Object.getPrototypeOf(proto);
        return dunderProto && dunderProto.constructor;
      }
      function isChildClassOf(subclass, superclass) {
        if (subclass && superclass) {
          if (typeof subclass !== 'function') {
            return false;
          }
          if (typeof superclass !== 'function') {
            return false;
          }
          if (subclass === superclass) {
            return true;
          }
          for (;;) {
            subclass = getSuper(subclass);
            if (!subclass) {
              return false;
            }
            if (subclass === superclass) {
              return true;
            }
          }
        }
        return false;
      }
      function clear$1(object) {
        for (var _i3 = 0, _Object$keys = Object.keys(object); _i3 < _Object$keys.length; _i3++) {
          var key = _Object$keys[_i3];
          delete object[key];
        }
      }
      function isTempClassId(id) {
        return typeof id !== 'string' || id.startsWith(tempCIDGenerator.prefix);
      }
      var _idToClass = createMap(true);
      var _nameToClass = createMap(true);
      function setup(tag, table, allowExist) {
        return function (id, constructor) {
          if (constructor.prototype.hasOwnProperty(tag)) {
            delete table[constructor.prototype[tag]];
          }
          value(constructor.prototype, tag, id);
          if (id) {
            var registered = table[id];
            if (!allowExist && registered && registered !== constructor) {
              var err = "A Class already exists with the same " + tag + " : \"" + id + "\".";
              error(err);
            } else {
              table[id] = constructor;
            }
          }
        };
      }
      var _setClassId = setup('__cid__', _idToClass, false);
      var doSetClassName = setup('__classname__', _nameToClass, true);
      function setClassName(className, constructor) {
        doSetClassName(className, constructor);
        if (!constructor.prototype.hasOwnProperty(classIdTag)) {
          var _id = className || tempCIDGenerator.getNewId();
          if (_id) {
            _setClassId(_id, constructor);
          }
        }
      }
      function setClassAlias(target, alias) {
        var nameRegistry = _nameToClass[alias];
        var idRegistry = _idToClass[alias];
        var ok = true;
        if (nameRegistry && nameRegistry !== target) {
          error("\"" + alias + "\" has already been set as name or alias of another class.");
          ok = false;
        }
        if (idRegistry && idRegistry !== target) {
          error("\"" + alias + "\" has already been set as id or alias of another class.");
          ok = false;
        }
        if (ok) {
          var classAliases = target[aliasesTag];
          if (!classAliases) {
            classAliases = [];
            target[aliasesTag] = classAliases;
          }
          classAliases.push(alias);
          _nameToClass[alias] = target;
          _idToClass[alias] = target;
        }
      }
      function unregisterClass() {
        for (var _len4 = arguments.length, constructors = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
          constructors[_key4] = arguments[_key4];
        }
        for (var _i4 = 0, _constructors = constructors; _i4 < _constructors.length; _i4++) {
          var _constructor = _constructors[_i4];
          var p = _constructor.prototype;
          var classId = p[classIdTag];
          if (classId) {
            delete _idToClass[classId];
          }
          var classname = p[classNameTag];
          if (classname) {
            delete _nameToClass[classname];
          }
          var aliases = p[aliasesTag];
          if (aliases) {
            for (var iAlias = 0; iAlias < aliases.length; ++iAlias) {
              var alias = aliases[iAlias];
              delete _nameToClass[alias];
              delete _idToClass[alias];
            }
          }
        }
      }
      function _getClassById(classId) {
        return getClassById(classId);
      }
      function getClassById(classId) {
        return _idToClass[classId];
      }
      function getClassByName(classname) {
        return _nameToClass[classname];
      }
      function _getClassId(obj, allowTempId) {
        return getClassId(obj, allowTempId);
      }
      function getClassId(obj, allowTempId) {
        allowTempId = typeof allowTempId !== 'undefined' ? allowTempId : true;
        var res;
        if (typeof obj === 'function' && obj.prototype.hasOwnProperty(classIdTag)) {
          res = obj.prototype[classIdTag];
          if (!allowTempId && (EDITOR) && isTempClassId(res)) {
            return '';
          }
          return res;
        }
        if (obj && obj.constructor) {
          var prototype = obj.constructor.prototype;
          if (prototype && prototype.hasOwnProperty(classIdTag)) {
            res = obj[classIdTag];
            if (!allowTempId && (EDITOR) && isTempClassId(res)) {
              return '';
            }
            return res;
          }
        }
        return '';
      }

      var Pool$1 = function () {
        var _proto = Pool.prototype;
        _proto.get = function get() {
          return this._get();
        };
        function Pool(_0, _1) {
          this.count = void 0;
          this._pool = void 0;
          this._cleanup = void 0;
          var size = _1 === undefined ? _0 : _1;
          var cleanupFunc = _1 === undefined ? null : _0;
          this.count = 0;
          this._pool = new Array(size);
          this._cleanup = cleanupFunc;
        }
        _proto._get = function _get() {
          if (this.count > 0) {
            --this.count;
            var cache = this._pool[this.count];
            this._pool[this.count] = null;
            return cache;
          }
          return null;
        };
        _proto.put = function put(obj) {
          var pool = this._pool;
          if (this.count < pool.length) {
            if (this._cleanup && this._cleanup(obj) === false) {
              return;
            }
            pool[this.count] = obj;
            ++this.count;
          }
        };
        _proto.resize = function resize(length) {
          if (length >= 0) {
            this._pool.length = length;
            if (this.count > length) {
              this.count = length;
            }
          }
        };
        return Pool;
      }();

      var MutableForwardIterator = function () {
        function MutableForwardIterator(array) {
          this.i = 0;
          this.array = array;
        }
        var _proto = MutableForwardIterator.prototype;
        _proto.remove = function remove(value) {
          var index = this.array.indexOf(value);
          if (index >= 0) {
            this.removeAt(index);
          }
        };
        _proto.removeAt = function removeAt(i) {
          this.array.splice(i, 1);
          if (i <= this.i) {
            --this.i;
          }
        };
        _proto.fastRemove = function fastRemove(value) {
          var index = this.array.indexOf(value);
          if (index >= 0) {
            this.fastRemoveAt(index);
          }
        };
        _proto.fastRemoveAt = function fastRemoveAt(i) {
          var array = this.array;
          array[i] = array[array.length - 1];
          --array.length;
          if (i <= this.i) {
            --this.i;
          }
        };
        _proto.push = function push(item) {
          this.array.push(item);
        };
        _createClass(MutableForwardIterator, [{
          key: "length",
          get: function get() {
            return this.array.length;
          },
          set: function set(value) {
            this.array.length = value;
            if (this.i >= value) {
              this.i = value - 1;
            }
          }
        }]);
        return MutableForwardIterator;
      }();

      function removeAt(array, index) {
        array.splice(index, 1);
      }
      function fastRemoveAt$2(array, index) {
        var length = array.length;
        if (index < 0 || index >= length) {
          return;
        }
        array[index] = array[length - 1];
        array.length = length - 1;
      }
      function remove(array, value) {
        var index = array.indexOf(value);
        if (index >= 0) {
          removeAt(array, index);
          return true;
        } else {
          return false;
        }
      }
      function fastRemove(array, value) {
        var index = array.indexOf(value);
        if (index >= 0) {
          array[index] = array[array.length - 1];
          --array.length;
        }
      }
      function removeIf(array, predicate) {
        var index = array.findIndex(predicate);
        if (index >= 0) {
          var _value = array[index];
          removeAt(array, index);
          return _value;
        }
      }
      function verifyType(array, type) {
        if (array && array.length > 0) {
          for (var _iterator = _createForOfIteratorHelperLoose(array), _step; !(_step = _iterator()).done;) {
            var item = _step.value;
            if (!(item instanceof type)) {
              logID(1300);
              return false;
            }
          }
        }
        return true;
      }
      function removeArray(array, removals) {
        for (var i = 0, l = removals.length; i < l; i++) {
          remove(array, removals[i]);
        }
      }
      function appendObjectsAt(array, objects, index) {
        array.splice.apply(array, [index, 0].concat(objects));
        return array;
      }
      function contains$2(array, value) {
        return array.indexOf(value) >= 0;
      }
      function copy(array) {
        var len = array.length;
        var cloned = new Array(len);
        for (var i = 0; i < len; i += 1) {
          cloned[i] = array[i];
        }
        return cloned;
      }

      var array = /*#__PURE__*/Object.freeze({
        __proto__: null,
        removeAt: removeAt,
        fastRemoveAt: fastRemoveAt$2,
        remove: remove,
        fastRemove: fastRemove,
        removeIf: removeIf,
        verifyType: verifyType,
        removeArray: removeArray,
        appendObjectsAt: appendObjectsAt,
        contains: contains$2,
        copy: copy,
        MutableForwardIterator: MutableForwardIterator
      });

      var js = {
        IDGenerator: IDGenerator,
        Pool: Pool$1,
        array: array,
        isNumber: isNumber,
        isString: isString,
        isEmptyObject: isEmptyObject,
        getPropertyDescriptor: getPropertyDescriptor,
        addon: addon,
        mixin: mixin,
        extend: extend,
        getSuper: getSuper,
        isChildClassOf: isChildClassOf,
        clear: clear$1,
        value: value,
        getset: getset,
        get: get,
        set: set,
        unregisterClass: unregisterClass,
        getClassName: getClassName,
        setClassName: setClassName,
        setClassAlias: setClassAlias,
        getClassByName: getClassByName,
        getClassById: getClassById,
        get _registeredClassNames() {
          return _extends({}, _nameToClass);
        },
        set _registeredClassNames(value) {
          clear$1(_nameToClass);
          Object.assign(_nameToClass, value);
        },
        get _registeredClassIds() {
          return _extends({}, _idToClass);
        },
        set _registeredClassIds(value) {
          clear$1(_idToClass);
          Object.assign(_idToClass, value);
        },
        _getClassId: _getClassId,
        getClassId: getClassId,
        _setClassId: _setClassId,
        _getClassById: _getClassById,
        obsolete: obsolete,
        obsoletes: obsoletes,
        formatStr: formatStr,
        shiftArguments: shiftArguments,
        createMap: createMap
      };
      legacyCC.js = js;

      var js$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        array: array,
        js: js,
        IDGenerator: IDGenerator,
        Pool: Pool$1,
        isNumber: isNumber,
        isString: isString,
        isEmptyObject: isEmptyObject,
        value: value,
        getset: getset,
        get: get,
        set: set,
        createMap: createMap,
        getClassName: getClassName,
        obsolete: obsolete,
        obsoletes: obsoletes,
        formatStr: formatStr,
        shiftArguments: shiftArguments,
        getPropertyDescriptor: getPropertyDescriptor,
        copyAllProperties: copyAllProperties,
        addon: addon,
        mixin: mixin,
        extend: extend,
        getSuper: getSuper,
        isChildClassOf: isChildClassOf,
        clear: clear$1,
        _idToClass: _idToClass,
        _nameToClass: _nameToClass,
        _setClassId: _setClassId,
        setClassName: setClassName,
        setClassAlias: setClassAlias,
        unregisterClass: unregisterClass,
        _getClassById: _getClassById,
        getClassById: getClassById,
        getClassByName: getClassByName,
        _getClassId: _getClassId,
        getClassId: getClassId
      });
      exports('bE', js$1);

      function BitMask(obj) {
        if ('__bitmask__' in obj) {
          return obj;
        }
        value(obj, '__bitmask__', null, true);
        var lastIndex = -1;
        var keys = Object.keys(obj);
        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];
          var val = obj[key];
          if (val === -1) {
            val = ++lastIndex;
            obj[key] = val;
          } else if (typeof val === 'number') {
            lastIndex = val;
          } else if (typeof val === 'string' && Number.isInteger(parseFloat(key))) {
            continue;
          }
          var reverseKey = "" + val;
          if (key !== reverseKey) {
            value(obj, reverseKey, key);
          }
        }
        return obj;
      }
      BitMask.isBitMask = function (BitMaskType) {
        return BitMaskType && BitMaskType.hasOwnProperty('__bitmask__');
      };
      BitMask.getList = function (BitMaskDef) {
        if (BitMaskDef.__bitmask__) {
          return BitMaskDef.__bitmask__;
        }
        return BitMask.update(BitMaskDef);
      };
      BitMask.update = function (BitMaskDef) {
        if (!Array.isArray(BitMaskDef.__bitmask__)) {
          BitMaskDef.__bitmask__ = [];
        }
        var bitList = BitMaskDef.__bitmask__;
        bitList.length = 0;
        for (var name in BitMaskDef) {
          var v = BitMaskDef[name];
          if (Number.isInteger(v)) {
            bitList.push({
              name: name,
              value: v
            });
          }
        }
        bitList.sort(function (a, b) {
          return a.value - b.value;
        });
        return bitList;
      };
      legacyCC.BitMask = BitMask;

      function assertIsNonNullable(expr, message) {
        assertIsTrue(!(expr === null || expr === undefined), message);
      }
      function assertIsTrue(expr, message) {
        if (!expr) {
          throw new Error("Assertion failed: " + (message !== null && message !== void 0 ? message : '<no-message>'));
        }
      }
      function assertsArrayIndex(array, index) {
        assertIsTrue(index >= 0 && index < array.length, "Array index " + index + " out of bounds: [0, " + array.length + ")");
      }

      function Enum(obj) {
        if ('__enums__' in obj) {
          return obj;
        }
        value(obj, '__enums__', null, true);
        return Enum.update(obj);
      }
      Enum.update = function (obj) {
        var lastIndex = -1;
        var keys = Object.keys(obj);
        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];
          var val = obj[key];
          if (val === -1) {
            val = ++lastIndex;
            obj[key] = val;
          } else if (typeof val === 'number') {
            lastIndex = val;
          } else if (typeof val === 'string' && Number.isInteger(parseFloat(key))) {
            continue;
          }
          var reverseKey = "" + val;
          if (key !== reverseKey) {
            value(obj, reverseKey, key);
          }
        }
        if (Array.isArray(obj.__enums__)) {
          updateList(obj);
        }
        return obj;
      };
      (function (_Enum) {})(Enum || (exports('bB', Enum = {})));
      Enum.isEnum = function (enumType) {
        return enumType && enumType.hasOwnProperty('__enums__');
      };
      function assertIsEnum(enumType) {
        assertIsTrue(enumType.hasOwnProperty('__enums__'));
      }
      Enum.getList = function (enumType) {
        assertIsEnum(enumType);
        if (enumType.__enums__) {
          return enumType.__enums__;
        }
        return updateList(enumType);
      };
      function updateList(enumType) {
        assertIsEnum(enumType);
        var enums = enumType.__enums__ || [];
        enums.length = 0;
        for (var name in enumType) {
          var v = enumType[name];
          if (Number.isInteger(v)) {
            enums.push({
              name: name,
              value: v
            });
          }
        }
        enums.sort(function (a, b) {
          return a.value - b.value;
        });
        enumType.__enums__ = enums;
        return enums;
      }
      Enum.sortList = function (enumType, compareFn) {
        assertIsEnum(enumType);
        if (!Array.isArray(enumType.__enums__)) {
          return;
        }
        enumType.__enums__.sort(compareFn);
      };
      function ccenum(enumType) {
        if (!('__enums__' in enumType)) {
          value(enumType, '__enums__', null, true);
        }
      }
      legacyCC.Enum = Enum;

      var ValueType = exports('bD', function () {
        function ValueType() {}
        var _proto = ValueType.prototype;
        _proto.clone = function clone() {
          errorID(100, getClassName(this) + ".clone");
          return this;
        };
        _proto.equals = function equals(other) {
          return false;
        };
        _proto.set = function set(other) {
          errorID(100, getClassName(this) + ".set");
        };
        _proto.toString = function toString() {
          return "";
        };
        return ValueType;
      }());
      setClassName('cc.ValueType', ValueType);
      legacyCC.ValueType = ValueType;

      var Category;
      (function (Category) {
        Category["PATH"] = "path";
        Category["ENGINE"] = "engine";
        Category["ASSETS"] = "assets";
        Category["SCRIPTING"] = "scripting";
        Category["PHYSICS"] = "physics";
        Category["RENDERING"] = "rendering";
        Category["LAUNCH"] = "launch";
        Category["SCREEN"] = "screen";
        Category["SPLASH_SCREEN"] = "splashScreen";
        Category["ANIMATION"] = "animation";
        Category["PROFILING"] = "profiling";
        Category["PLUGINS"] = "plugins";
        Category["XR"] = "xr";
      })(Category || (Category = {}));
      var Settings = exports('cy', function () {
        function Settings() {
          this._settings = {};
          this._override = {};
        }
        var _proto = Settings.prototype;
        _proto.init = function init(path, overrides) {
          var _this = this;
          if (path === void 0) {
            path = '';
          }
          if (overrides === void 0) {
            overrides = {};
          }
          for (var categoryName in overrides) {
            var category = overrides[categoryName];
            if (category) {
              for (var name in category) {
                this.overrideSettings(categoryName, name, category[name]);
              }
            }
          }
          if (!path) return Promise.resolve();
          return new Promise(function (resolve, reject) {
            {
              var xhr = new XMLHttpRequest();
              xhr.open('GET', path);
              xhr.responseType = 'text';
              xhr.onload = function () {
                _this._settings = JSON.parse(xhr.response);
                resolve();
              };
              xhr.onerror = function () {
                reject(new Error('request settings failed!'));
              };
              xhr.send(null);
            }
          });
        };
        _proto.overrideSettings = function overrideSettings(category, name, value) {
          if (!(category in this._override)) {
            this._override[category] = {};
          }
          this._override[category][name] = value;
        };
        _proto.querySettings = function querySettings(category, name) {
          if (category in this._override) {
            var categorySettings = this._override[category];
            if (categorySettings && name in categorySettings) {
              return categorySettings[name];
            }
          }
          if (category in this._settings) {
            var _categorySettings = this._settings[category];
            if (_categorySettings && name in _categorySettings) {
              return _categorySettings[name];
            }
          }
          return null;
        };
        return Settings;
      }());
      Settings.Category = Category;
      var settings = exports('cz', new Settings());
      legacyCC.settings = settings;

      var _PORTRAIT = 1;
      var _PORTRAIT_UPSIDE_DOWN = _PORTRAIT << 1;
      var _LEFT = _PORTRAIT << 2;
      var _RIGHT = _PORTRAIT << 3;
      var _LANDSCAPE = _LEFT | _RIGHT;
      var _AUTO = _PORTRAIT | _LANDSCAPE;
      var Orientation$1;
      (function (Orientation) {
        Orientation[Orientation["PORTRAIT"] = _PORTRAIT] = "PORTRAIT";
        Orientation[Orientation["PORTRAIT_UPSIDE_DOWN"] = _PORTRAIT_UPSIDE_DOWN] = "PORTRAIT_UPSIDE_DOWN";
        Orientation[Orientation["LANDSCAPE_LEFT"] = _LEFT] = "LANDSCAPE_LEFT";
        Orientation[Orientation["LANDSCAPE_RIGHT"] = _RIGHT] = "LANDSCAPE_RIGHT";
        Orientation[Orientation["LANDSCAPE"] = _LANDSCAPE] = "LANDSCAPE";
        Orientation[Orientation["AUTO"] = _AUTO] = "AUTO";
      })(Orientation$1 || (Orientation$1 = {}));

      var SUPPORT_TEXTURE_FORMATS = ['.astc', '.pkm', '.pvr', '.webp', '.jpg', '.jpeg', '.bmp', '.png'];
      var KEY = {
        none: 0,
        back: 6,
        menu: 18,
        backspace: 8,
        tab: 9,
        enter: 13,
        shift: 16,
        ctrl: 17,
        alt: 18,
        pause: 19,
        capslock: 20,
        escape: 27,
        space: 32,
        pageup: 33,
        pagedown: 34,
        end: 35,
        home: 36,
        left: 37,
        up: 38,
        right: 39,
        down: 40,
        select: 41,
        insert: 45,
        Delete: 46,
        0: 48,
        1: 49,
        2: 50,
        3: 51,
        4: 52,
        5: 53,
        6: 54,
        7: 55,
        8: 56,
        9: 57,
        a: 65,
        b: 66,
        c: 67,
        d: 68,
        e: 69,
        f: 70,
        g: 71,
        h: 72,
        i: 73,
        j: 74,
        k: 75,
        l: 76,
        m: 77,
        n: 78,
        o: 79,
        p: 80,
        q: 81,
        r: 82,
        s: 83,
        t: 84,
        u: 85,
        v: 86,
        w: 87,
        x: 88,
        y: 89,
        z: 90,
        num0: 96,
        num1: 97,
        num2: 98,
        num3: 99,
        num4: 100,
        num5: 101,
        num6: 102,
        num7: 103,
        num8: 104,
        num9: 105,
        '*': 106,
        '+': 107,
        '-': 109,
        numdel: 110,
        '/': 111,
        f1: 112,
        f2: 113,
        f3: 114,
        f4: 115,
        f5: 116,
        f6: 117,
        f7: 118,
        f8: 119,
        f9: 120,
        f10: 121,
        f11: 122,
        f12: 123,
        numlock: 144,
        scrolllock: 145,
        ';': 186,
        semicolon: 186,
        equal: 187,
        '=': 187,
        ',': 188,
        comma: 188,
        dash: 189,
        '.': 190,
        period: 190,
        forwardslash: 191,
        grave: 192,
        '[': 219,
        openbracket: 219,
        backslash: 220,
        ']': 221,
        closebracket: 221,
        quote: 222,
        dpadLeft: 1000,
        dpadRight: 1001,
        dpadUp: 1003,
        dpadDown: 1004,
        dpadCenter: 1005
      };
      var macro = exports('cl', {
        SUPPORT_TEXTURE_FORMATS: SUPPORT_TEXTURE_FORMATS,
        KEY: KEY,
        RAD: Math.PI / 180,
        DEG: 180 / Math.PI,
        REPEAT_FOREVER: Number.MAX_VALUE - 1,
        FLT_EPSILON: 0.0000001192092896,
        ORIENTATION_PORTRAIT: Orientation$1.PORTRAIT,
        ORIENTATION_PORTRAIT_UPSIDE_DOWN: Orientation$1.PORTRAIT_UPSIDE_DOWN,
        ORIENTATION_LANDSCAPE: Orientation$1.LANDSCAPE,
        ORIENTATION_LANDSCAPE_LEFT: Orientation$1.LANDSCAPE_LEFT,
        ORIENTATION_LANDSCAPE_RIGHT: Orientation$1.LANDSCAPE_RIGHT,
        ORIENTATION_AUTO: Orientation$1.AUTO,
        ENABLE_TILEDMAP_CULLING: true,
        TOUCH_TIMEOUT: 5000,
        ENABLE_TRANSPARENT_CANVAS: false,
        ENABLE_WEBGL_ANTIALIAS: true,
        ENABLE_FLOAT_OUTPUT: false,
        CLEANUP_IMAGE_CACHE: false,
        ENABLE_MULTI_TOUCH: true,
        MAX_LABEL_CANVAS_POOL_SIZE: 20,
        ENABLE_WEBGL_HIGHP_STRUCT_VALUES: false,
        BATCHER2D_MEM_INCREMENT: 144,
        CUSTOM_PIPELINE_NAME: '',
        init: function init() {
          var defaultValues = settings.querySettings(Settings.Category.ENGINE, 'macros');
          if (defaultValues) {
            for (var key in defaultValues) {
              macro[key] = defaultValues[key];
            }
          }
        }
      });
      legacyCC.macro = macro;

      function setTimeoutRAF(callback, delay) {
        var _globalThis$__globalX;
        for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
          args[_key - 2] = arguments[_key];
        }
        var start = performance.now();
        var raf = requestAnimationFrame || window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame;
        if (raf === undefined || (_globalThis$__globalX = globalThis.__globalXR) !== null && _globalThis$__globalX !== void 0 && _globalThis$__globalX.isWebXR) {
          return setTimeout.apply(void 0, [callback, delay].concat(args));
        }
        var handleRAF = function handleRAF() {
          if (performance.now() - start < delay) {
            raf(handleRAF);
          } else {
            callback.apply(void 0, args);
          }
        };
        return raf(handleRAF);
      }

      var BUILTIN_CLASSID_RE = /^(?:cc|dragonBones|sp|ccsg)\..+/;
      var BASE64_KEYS$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
      var values = new Array(123);
      for (var i$4 = 0; i$4 < 123; ++i$4) {
        values[i$4] = 64;
      }
      for (var _i$1 = 0; _i$1 < 64; ++_i$1) {
        values[BASE64_KEYS$1.charCodeAt(_i$1)] = _i$1;
      }
      var BASE64_VALUES$1 = values;
      function propertyDefine(ctor, sameNameGetSets, diffNameGetSets) {
        function define(np, propName, getter, setter) {
          var pd = Object.getOwnPropertyDescriptor(np, propName);
          if (pd) {
            if (pd.get) {
              np[getter] = pd.get;
            }
            if (pd.set && setter) {
              np[setter] = pd.set;
            }
          } else {
            var getterFunc = np[getter];
            {
              getset(np, propName, getterFunc, np[setter]);
            }
          }
        }
        var propName;
        var np = ctor.prototype;
        for (var _i2 = 0; _i2 < sameNameGetSets.length; _i2++) {
          propName = sameNameGetSets[_i2];
          var suffix = propName[0].toUpperCase() + propName.slice(1);
          define(np, propName, "get" + suffix, "set" + suffix);
        }
        for (propName in diffNameGetSets) {
          var gs = diffNameGetSets[propName];
          define(np, propName, gs[0], gs[1]);
        }
      }
      function pushToMap(map, key, value, pushFront) {
        var exists = map[key];
        if (exists) {
          if (Array.isArray(exists)) {
            if (pushFront) {
              exists.push(exists[0]);
              exists[0] = value;
            } else {
              exists.push(value);
            }
          } else {
            map[key] = pushFront ? [value, exists] : [exists, value];
          }
        } else {
          map[key] = value;
        }
      }
      function contains$1(refNode, otherNode) {
        if (typeof refNode.contains === 'function') {
          return refNode.contains(otherNode);
        } else if (typeof refNode.compareDocumentPosition === 'function') {
          return !!(refNode.compareDocumentPosition(otherNode) & 16);
        } else {
          var node = otherNode.parentNode;
          if (node) {
            do {
              if (node === refNode) {
                return true;
              } else {
                node = node.parentNode;
              }
            } while (node !== null);
          }
          return false;
        }
      }
      function isDomNode(node) {
        if (typeof window === 'object' && typeof Node === 'function') {
          return node instanceof Node;
        } else {
          return !!node && typeof node === 'object' && typeof node.nodeType === 'number' && typeof node.nodeName === 'string';
        }
      }
      function callInNextTick(callback, p1, p2) {
        if (callback) {
          setTimeoutRAF(function () {
            callback(p1, p2);
          }, 0);
        }
      }
      function tryCatchFunctor_EDITOR(funcName) {
        return Function('target', "" + ('try {\n' + '  target.') + funcName + "();\n" + "}\n" + "catch (e) {\n" + "  cc._throw(e);\n" + "}");
      }
      function isPlainEmptyObj_DEV(obj) {
        if (!obj || obj.constructor !== Object) {
          return false;
        }
        return isEmptyObject(obj);
      }
      function clampf(value, min_inclusive, max_inclusive) {
        if (min_inclusive > max_inclusive) {
          var temp = min_inclusive;
          min_inclusive = max_inclusive;
          max_inclusive = temp;
        }
        return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive;
      }
      function degreesToRadians(angle) {
        return angle * macro.RAD;
      }
      function radiansToDegrees(angle) {
        return angle * macro.DEG;
      }
      legacyCC.misc = {
        BUILTIN_CLASSID_RE: BUILTIN_CLASSID_RE,
        BASE64_VALUES: BASE64_VALUES$1,
        propertyDefine: propertyDefine,
        pushToMap: pushToMap,
        contains: contains$1,
        isDomNode: isDomNode,
        callInNextTick: callInNextTick,
        isPlainEmptyObj_DEV: isPlainEmptyObj_DEV,
        clampf: clampf,
        degreesToRadians: degreesToRadians,
        radiansToDegrees: radiansToDegrees
      };

      var misc = /*#__PURE__*/Object.freeze({
        __proto__: null,
        BUILTIN_CLASSID_RE: BUILTIN_CLASSID_RE,
        BASE64_VALUES: BASE64_VALUES$1,
        propertyDefine: propertyDefine,
        pushToMap: pushToMap,
        contains: contains$1,
        isDomNode: isDomNode,
        callInNextTick: callInNextTick,
        tryCatchFunctor_EDITOR: tryCatchFunctor_EDITOR,
        isPlainEmptyObj_DEV: isPlainEmptyObj_DEV,
        clampf: clampf,
        degreesToRadians: degreesToRadians,
        radiansToDegrees: radiansToDegrees
      });
      exports('bF', misc);

      var DELIMETER$1 = '$_$';
      function createAttrsSingle(owner, superAttrs) {
        var attrs = superAttrs ? Object.create(superAttrs) : {};
        value(owner, '__attrs__', attrs);
        return attrs;
      }
      function createAttrs(subclass) {
        if (typeof subclass !== 'function') {
          var instance = subclass;
          return createAttrsSingle(instance, getClassAttrs(instance.constructor));
        }
        var superClass;
        var chains = legacyCC.Class.getInheritanceChain(subclass);
        for (var i = chains.length - 1; i >= 0; i--) {
          var cls = chains[i];
          var attrs = cls.hasOwnProperty('__attrs__') && cls.__attrs__;
          if (!attrs) {
            superClass = chains[i + 1];
            createAttrsSingle(cls, superClass && superClass.__attrs__);
          }
        }
        superClass = chains[0];
        createAttrsSingle(subclass, superClass && superClass.__attrs__);
        return subclass.__attrs__;
      }
      function attr(constructor, propertyName) {
        var attrs = getClassAttrs(constructor);
        var prefix = propertyName + DELIMETER$1;
        var ret = {};
        for (var key in attrs) {
          if (key.startsWith(prefix)) {
            ret[key.slice(prefix.length)] = attrs[key];
          }
        }
        return ret;
      }
      function getClassAttrs(constructor) {
        return constructor.hasOwnProperty('__attrs__') && constructor.__attrs__ || createAttrs(constructor);
      }
      function setClassAttr$1(ctor, propName, key, value) {
        getClassAttrs(ctor)[propName + DELIMETER$1 + key] = value;
      }
      var PrimitiveType$1 = function () {
        function PrimitiveType(name, defaultValue) {
          this.name = void 0;
          this["default"] = void 0;
          this.name = name;
          this["default"] = defaultValue;
        }
        var _proto = PrimitiveType.prototype;
        _proto.toString = function toString() {
          return this.name;
        };
        return PrimitiveType;
      }();
      var CCInteger = exports('bV', new PrimitiveType$1('Integer', 0));
      legacyCC.Integer = CCInteger;
      legacyCC.CCInteger = CCInteger;
      var CCFloat = exports('bW', new PrimitiveType$1('Float', 0.0));
      legacyCC.Float = CCFloat;
      legacyCC.CCFloat = CCFloat;
      var CCBoolean = exports('bX', new PrimitiveType$1('Boolean', false));
      legacyCC.Boolean = CCBoolean;
      legacyCC.CCBoolean = CCBoolean;
      var CCString = exports('bY', new PrimitiveType$1('String', ''));
      legacyCC.String = CCString;
      legacyCC.CCString = CCString;
      function getTypeChecker_ET(type, attributeName) {
        return function (constructor, mainPropertyName) {
          var propInfo = "\"" + getClassName(constructor) + "." + mainPropertyName + "\"";
          var mainPropAttrs = attr(constructor, mainPropertyName);
          var mainPropAttrsType = mainPropAttrs.type;
          if (mainPropAttrsType === CCInteger || mainPropAttrsType === CCFloat) {
            mainPropAttrsType = 'Number';
          } else if (mainPropAttrsType === CCString || mainPropAttrsType === CCBoolean) {
            mainPropAttrsType = "" + mainPropAttrsType;
          }
          if (mainPropAttrsType !== type) {
            warnID(3604, propInfo);
            return;
          }
          if (!mainPropAttrs.hasOwnProperty('default')) {
            return;
          }
          var defaultVal = mainPropAttrs["default"];
          if (typeof defaultVal === 'undefined') {
            return;
          }
          var isContainer = Array.isArray(defaultVal) || isPlainEmptyObj_DEV(defaultVal);
          if (isContainer) {
            return;
          }
          var defaultType = typeof defaultVal;
          var type_lowerCase = type.toLowerCase();
          if (defaultType === type_lowerCase) {
            if (type_lowerCase === 'object') {
              if (defaultVal && !(defaultVal instanceof mainPropAttrs.ctor)) {
                warnID(3605, propInfo, getClassName(mainPropAttrs.ctor));
              } else {
                return;
              }
            } else if (type !== 'Number') {
              warnID(3606, attributeName, propInfo, type);
            }
          } else if (defaultType !== 'function') {
            if (type === CCString["default"] && defaultVal == null) {
              warnID(3607, propInfo);
            } else {
              warnID(3611, attributeName, propInfo, defaultType);
            }
          } else {
            return;
          }
          delete mainPropAttrs.type;
        };
      }
      function getObjTypeChecker_ET(typeCtor) {
        return function (classCtor, mainPropName) {
          getTypeChecker_ET('Object', 'type')(classCtor, mainPropName);
          var defaultDef = getClassAttrs(classCtor)[mainPropName + DELIMETER$1 + "default"];
          var defaultVal = legacyCC.Class.getDefault(defaultDef);
          if (!Array.isArray(defaultVal) && isChildClassOf(typeCtor, legacyCC.ValueType)) {
            var typename = getClassName(typeCtor);
            var info = formatStr('No need to specify the "type" of "%s.%s" because %s is a child class of ValueType.', getClassName(classCtor), mainPropName, typename);
            if (defaultDef) {
              log(info);
            } else {
              warnID(3612, info, typename, getClassName(classCtor), mainPropName, typename);
            }
          }
        };
      }

      var attributeUtils = /*#__PURE__*/Object.freeze({
        __proto__: null,
        DELIMETER: DELIMETER$1,
        createAttrsSingle: createAttrsSingle,
        createAttrs: createAttrs,
        attr: attr,
        getClassAttrs: getClassAttrs,
        setClassAttr: setClassAttr$1,
        PrimitiveType: PrimitiveType$1,
        CCInteger: CCInteger,
        CCFloat: CCFloat,
        CCBoolean: CCBoolean,
        CCString: CCString,
        getTypeChecker_ET: getTypeChecker_ET,
        getObjTypeChecker_ET: getObjTypeChecker_ET
      });

      var SerializableAttrs = {
        "default": {},
        serializable: {},
        editorOnly: {},
        formerlySerializedAs: {}
      };
      function parseNotify(val, propName, notify, properties) {
        if (val.get || val.set) {
          return;
        }
        if (val.hasOwnProperty('default')) {
          var newKey = "_N$" + propName;
          val.get = function () {
            return this[newKey];
          };
          val.set = function (value) {
            var oldValue = this[newKey];
            this[newKey] = value;
            notify.call(this, oldValue);
          };
          var newValue = {};
          properties[newKey] = newValue;
          for (var attr in SerializableAttrs) {
            var v = SerializableAttrs[attr];
            if (val.hasOwnProperty(attr)) {
              newValue[attr] = val[attr];
              if (!v.canUsedInGet) {
                delete val[attr];
              }
            }
          }
        }
      }
      function parseType(val, type, className, propName) {
        if (Array.isArray(type)) {
          if (type.length > 0) {
            val.type = type = type[0];
          } else {
            return errorID(5508, className, propName);
          }
        }
        if (typeof type === 'function') {
          if (type === String) {
            val.type = legacyCC.String;
          } else if (type === Boolean) {
            val.type = legacyCC.Boolean;
          } else if (type === Number) {
            val.type = legacyCC.Float;
          }
        }
      }
      function _wrapOptions(isGetset, _default, type) {
        var res = isGetset || typeof _default === 'undefined' ? {
          _short: true
        } : {
          _short: true,
          "default": _default
        };
        if (type) {
          res.type = type;
        }
        return res;
      }
      function getFullFormOfProperty(options, isGetset) {
        var isLiteral = options && options.constructor === Object;
        if (!isLiteral) {
          if (Array.isArray(options) && options.length > 0) {
            return _wrapOptions(isGetset, [], options);
          } else if (typeof options === 'function') {
            var type = options;
            return _wrapOptions(isGetset, isChildClassOf(type, legacyCC.ValueType) ? new type() : null, type);
          } else if (options instanceof PrimitiveType$1) {
            return _wrapOptions(isGetset, undefined, options);
          } else {
            return _wrapOptions(isGetset, options);
          }
        }
        return null;
      }
      function preprocessAttrs(properties, className, cls) {
        for (var propName in properties) {
          var val = properties[propName];
          var fullForm = getFullFormOfProperty(val, false);
          if (fullForm) {
            val = properties[propName] = fullForm;
          }
          if (val) {
            var notify = val.notify;
            if (notify) {
              {
                parseNotify(val, propName, notify, properties);
              }
            }
            if ('type' in val) {
              parseType(val, val.type, className, propName);
            }
          }
        }
      }

      var requiringFrames = [];
      function push(module, uuid, script, importMeta) {
        if (script === undefined) {
          script = uuid;
          uuid = '';
        }
        requiringFrames.push({
          uuid: uuid,
          script: script,
          module: module,
          exports: module.exports,
          beh: null,
          importMeta: importMeta
        });
      }
      function pop() {
        var frameInfo = requiringFrames.pop();
        var module = frameInfo.module;
        var exports = module.exports;
        if (exports === frameInfo.exports) {
          for (var anykey in exports) {
            return;
          }
          module.exports = exports = frameInfo.cls;
        }
      }
      function peek() {
        return requiringFrames[requiringFrames.length - 1];
      }
      legacyCC._RF = {
        push: push,
        pop: pop,
        peek: peek
      };

      var PropertyStashInternalFlag;
      (function (PropertyStashInternalFlag) {
        PropertyStashInternalFlag[PropertyStashInternalFlag["STANDALONE"] = 1] = "STANDALONE";
        PropertyStashInternalFlag[PropertyStashInternalFlag["IMPLICIT_VISIBLE"] = 2] = "IMPLICIT_VISIBLE";
        PropertyStashInternalFlag[PropertyStashInternalFlag["IMPLICIT_SERIALIZABLE"] = 4] = "IMPLICIT_SERIALIZABLE";
      })(PropertyStashInternalFlag || (PropertyStashInternalFlag = {}));

      function setPropertyEnumType(objectOrConstructor, propertyName, enumType) {
        setPropertyEnumTypeOnAttrs(getClassAttrs(objectOrConstructor), propertyName, enumType);
      }
      function setPropertyEnumTypeOnAttrs(attrs, propertyName, enumType) {
        attrs["" + propertyName + DELIMETER$1 + "type"] = 'Enum';
        attrs["" + propertyName + DELIMETER$1 + "enumList"] = Enum.getList(enumType);
      }

      var DELIMETER = DELIMETER$1;
      var CCCLASS_TAG = '__ctors__';
      var ENUM_TAG = exports('cX', 'Enum');
      var BITMASK_TAG = exports('cY', 'BitMask');
      function pushUnique(array, item) {
        if (array.indexOf(item) < 0) {
          array.push(item);
        }
      }
      function appendProp(cls, name) {
        pushUnique(cls.__props__, name);
      }
      function defineProp(cls, className, propName, val) {
        appendProp(cls, propName);
        parseAttributes(cls, val, className, propName);
      }
      function defineGetSet(cls, name, propName, val) {
        var getter = val.get;
        val.set;
        if (getter) {
          parseAttributes(cls, val, name, propName);
          setClassAttr$1(cls, propName, 'serializable', false);
        }
      }
      function getDefault(defaultVal) {
        if (typeof defaultVal === 'function') {
          {
            return defaultVal();
          }
        }
        return defaultVal;
      }
      function doDefine(className, baseClass, options) {
        var ctor = options.ctor;
        value(ctor, CCCLASS_TAG, true, true);
        ctor.prototype;
        if (baseClass) {
          ctor.$super = baseClass;
        }
        setClassName(className, ctor);
        return ctor;
      }
      function define$2(className, baseClass, options) {
        var Component = legacyCC.Component;
        var frame = peek();
        if (frame && isChildClassOf(baseClass, Component)) {
          if (isChildClassOf(frame.cls, Component)) {
            errorID(3615);
            return null;
          }
          className = className || frame.script;
        }
        var cls = doDefine(className, baseClass, options);
        if (frame) {
          if (isChildClassOf(baseClass, Component)) {
            var uuid = frame.uuid;
            if (uuid) {
              _setClassId(uuid, cls);
            }
            frame.cls = cls;
          } else if (!isChildClassOf(frame.cls, Component)) {
            frame.cls = cls;
          }
        }
        return cls;
      }
      function getNewValueTypeCodeJit(value) {
        var clsName = getClassName(value);
        var type = value.constructor;
        var res = "new " + clsName + "(";
        for (var i = 0; i < type.__props__.length; i++) {
          var prop = type.__props__[i];
          var propVal = value[prop];
          res += propVal;
          if (i < type.__props__.length - 1) {
            res += ',';
          }
        }
        return res + ")";
      }
      function escapeForJS$1(s) {
        return JSON.stringify(s).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
      }
      var IDENTIFIER_RE$1 = /^[A-Za-z_$][0-9A-Za-z_$]*$/;
      function declareProperties(cls, className, properties, baseClass) {
        cls.__props__ = [];
        if (baseClass && baseClass.__props__) {
          cls.__props__ = baseClass.__props__.slice();
        }
        if (properties) {
          preprocessAttrs(properties, className);
          for (var propName in properties) {
            var val = properties[propName];
            if (!val.get && !val.set) {
              defineProp(cls, className, propName, val);
            } else {
              defineGetSet(cls, className, propName, val);
            }
          }
        }
        var attrs = getClassAttrs(cls);
        cls.__values__ = cls.__props__.filter(function (prop) {
          return attrs["" + prop + DELIMETER + "serializable"] !== false;
        });
      }
      function CCClass(options) {
        var name = options.name;
        var base = options["extends"];
        var cls = define$2(name, base, options);
        if (!name) {
          name = legacyCC.js.getClassName(cls);
        }
        cls._sealed = true;
        if (base) {
          base._sealed = false;
        }
        var properties = options.properties;
        declareProperties(cls, name, properties, base);
        var editor = options.editor;
        if (editor) {
          if (isChildClassOf(base, legacyCC.Component)) {
            legacyCC.Component._registerEditorProps(cls, editor);
          }
        }
        return cls;
      }
      CCClass._isCCClass = function isCCClass(constructor) {
        var _constructor$hasOwnPr;
        return constructor === null || constructor === void 0 ? void 0 : (_constructor$hasOwnPr = constructor.hasOwnProperty) === null || _constructor$hasOwnPr === void 0 ? void 0 : _constructor$hasOwnPr.call(constructor, CCCLASS_TAG);
      };
      CCClass.fastDefine = function (className, constructor, serializableFields) {
        setClassName(className, constructor);
        var props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields);
        var attrs = getClassAttrs(constructor);
        for (var i = 0; i < props.length; i++) {
          var key = props[i];
          attrs[key + DELIMETER + "visible"] = false;
          attrs[key + DELIMETER + "default"] = serializableFields[key];
        }
      };
      CCClass.Attr = attributeUtils;
      CCClass.attr = attr;
      function isCCClassOrFastDefined(constructor) {
        var _constructor$hasOwnPr2;
        return constructor === null || constructor === void 0 ? void 0 : (_constructor$hasOwnPr2 = constructor.hasOwnProperty) === null || _constructor$hasOwnPr2 === void 0 ? void 0 : _constructor$hasOwnPr2.call(constructor, '__values__');
      }
      CCClass.isCCClassOrFastDefined = isCCClassOrFastDefined;
      function getInheritanceChain(constructor) {
        var chain = [];
        for (;;) {
          constructor = getSuper(constructor);
          if (!constructor) {
            break;
          }
          if (constructor !== Object) {
            chain.push(constructor);
          }
        }
        return chain;
      }
      CCClass.getInheritanceChain = getInheritanceChain;
      var PrimitiveTypes = {
        Integer: 'Number',
        Float: 'Number',
        Boolean: 'Boolean',
        String: 'String'
      };
      function parseAttributes(constructor, attributes, className, propertyName, usedInGetter) {
        var attrs = null;
        var propertyNamePrefix = '';
        function initAttrs() {
          propertyNamePrefix = propertyName + DELIMETER;
          return attrs = getClassAttrs(constructor);
        }
        if ('type' in attributes && typeof attributes.type === 'undefined') {
          warnID(3660, propertyName, className);
        }
        var type = attributes.type;
        if (type) {
          var primitiveType = PrimitiveTypes[type];
          if (primitiveType) {
            (attrs || initAttrs())[propertyNamePrefix + "type"] = type;
          } else if (type === 'Object') ; else if (typeof type === 'object') {
            if (Enum.isEnum(type)) {
              setPropertyEnumTypeOnAttrs(attrs || initAttrs(), propertyName, type);
            } else if (BitMask.isBitMask(type)) {
              (attrs || initAttrs())[propertyNamePrefix + "type"] = BITMASK_TAG;
              attrs[propertyNamePrefix + "bitmaskList"] = BitMask.getList(type);
            } else ;
          } else if (typeof type === 'function') {
            (attrs || initAttrs())[propertyNamePrefix + "type"] = 'Object';
            attrs[propertyNamePrefix + "ctor"] = type;
          } else ;
        }
        if ('default' in attributes) {
          (attrs || initAttrs())[propertyNamePrefix + "default"] = attributes["default"];
        }
        var parseSimpleAttribute = function parseSimpleAttribute(attributeName, expectType) {
          if (attributeName in attributes) {
            var val = attributes[attributeName];
            if (typeof val === expectType) {
              (attrs || initAttrs())[propertyNamePrefix + attributeName] = val;
            }
          }
        };
        if (attributes.editorOnly) {
          {
            (attrs || initAttrs())[propertyNamePrefix + "editorOnly"] = true;
          }
        }
        var isStandaloneMode = attributes.__internalFlags & PropertyStashInternalFlag.STANDALONE;
        var normalizedSerializable;
        if (isStandaloneMode) {
          normalizedSerializable = attributes.serializable === true || (attributes.__internalFlags & PropertyStashInternalFlag.IMPLICIT_SERIALIZABLE) !== 0;
        } else if (attributes.serializable === false) {
          normalizedSerializable = false;
        }
        if (typeof normalizedSerializable !== 'undefined') {
          (attrs || initAttrs())[propertyNamePrefix + "serializable"] = normalizedSerializable;
        }
        parseSimpleAttribute('formerlySerializedAs', 'string');
        var range = attributes.range;
        if (range) {
          if (Array.isArray(range)) {
            if (range.length >= 2) {
              (attrs || initAttrs())[propertyNamePrefix + "min"] = range[0];
              attrs[propertyNamePrefix + "max"] = range[1];
              if (range.length > 2) {
                attrs[propertyNamePrefix + "step"] = range[2];
              }
            }
          }
        }
        parseSimpleAttribute('min', 'number');
        parseSimpleAttribute('max', 'number');
        parseSimpleAttribute('step', 'number');
      }
      CCClass.isArray = function (defaultVal) {
        defaultVal = getDefault(defaultVal);
        return Array.isArray(defaultVal);
      };
      CCClass.getDefault = getDefault;
      CCClass.escapeForJS = escapeForJS$1;
      CCClass.IDENTIFIER_RE = IDENTIFIER_RE$1;
      CCClass.getNewValueTypeCode = getNewValueTypeCodeJit;
      legacyCC.Class = CCClass;

      var _d2r = Math.PI / 180.0;
      var _r2d = 180.0 / Math.PI;
      var _random = Math.random;
      var HALF_PI = exports('b5', Math.PI * 0.5);
      var TWO_PI = exports('b6', Math.PI * 2.0);
      var EPSILON$3 = exports('b7', 0.000001);
      function equals$2(a, b) {
        return Math.abs(a - b) <= EPSILON$3 * Math.max(1.0, Math.abs(a), Math.abs(b));
      }
      function approx(a, b, maxDiff) {
        maxDiff = maxDiff || EPSILON$3;
        return Math.abs(a - b) <= maxDiff;
      }
      function clamp$1(val, min, max) {
        if (min > max) {
          var temp = min;
          min = max;
          max = temp;
        }
        return val < min ? min : val > max ? max : val;
      }
      function clamp01(val) {
        return val < 0 ? 0 : val > 1 ? 1 : val;
      }
      function lerp(from, to, ratio) {
        return from + (to - from) * ratio;
      }
      function toRadian(a) {
        return a * _d2r;
      }
      function toDegree(a) {
        return a * _r2d;
      }
      function random() {
        return _random();
      }
      function setRandGenerator(func) {
        _random = func;
      }
      function randomRange(min, max) {
        return random() * (max - min) + min;
      }
      function randomRangeInt(min, max) {
        return Math.floor(randomRange(min, max));
      }
      function pseudoRandom(seed) {
        seed = (seed * 9301 + 49297) % 233280;
        return seed / 233280.0;
      }
      function pseudoRandomRange(seed, min, max) {
        return pseudoRandom(seed) * (max - min) + min;
      }
      function pseudoRandomRangeInt(seed, min, max) {
        return Math.floor(pseudoRandomRange(seed, min, max));
      }
      function nextPow2(val) {
        return nextPow2$1(val);
      }
      function repeat$2(t, length) {
        return t - Math.floor(t / length) * length;
      }
      function pingPong(t, length) {
        t = repeat$2(t, length * 2);
        t = length - Math.abs(t - length);
        return t;
      }
      function inverseLerp(from, to, value) {
        return (value - from) / (to - from);
      }
      function absMaxComponent(v) {
        if (Math.abs(v.x) > Math.abs(v.y)) {
          if (Math.abs(v.x) > Math.abs(v.z)) {
            return v.x;
          } else {
            return v.z;
          }
        } else if (Math.abs(v.y) > Math.abs(v.z)) {
          return v.y;
        } else {
          return v.z;
        }
      }
      function absMax(a, b) {
        if (Math.abs(a) > Math.abs(b)) {
          return a;
        } else {
          return b;
        }
      }
      function enumerableProps(prototype, attrs) {
        attrs.forEach(function (key) {
          Object.defineProperty(prototype, key, {
            enumerable: true
          });
        });
      }
      var toHalf = function () {
        var floatView = new Float32Array(1);
        var int32View = new Int32Array(floatView.buffer);
        return function toHalf(fval) {
          floatView[0] = fval;
          var fbits = int32View[0];
          var s = fbits >> 16 & 0x8000;
          var em = fbits & 0x7fffffff;
          var h = em - (112 << 23) + (1 << 12) >> 13;
          h = em < 113 << 23 ? 0 : h;
          h = em >= 143 << 23 ? 0x7c00 : h;
          h = em > 255 << 23 ? 0x7e00 : h;
          int32View[0] = s | h;
          return int32View[0];
        };
      }();
      var fromHalf = function () {
        var floatView = new Float32Array(1);
        var int32View = new Int32Array(floatView.buffer);
        return function fromHalf(hval) {
          var s = hval >> 15 & 0x00000001;
          var em = hval & 0x00007fff;
          var h = em << 13;
          var fbits = 0;
          if (h !== 0x7c00) {
            h += 112 << 23;
            if (em === 0) {
              h = (h & 0xfffff) >> 1;
            } else if (em === 0x7fff) {
              h = 0x7fffffff;
            }
          } else {
            h = 0x7f800000;
          }
          fbits = s << 31 | h;
          int32View[0] = fbits;
          return floatView[0];
        };
      }();
      function floatToHalf(val) {
        return toHalf(val);
      }
      function halfToFloat(val) {
        return fromHalf(val);
      }

      var _class$3N;
      var Vec4 = exports('aS', function (_ValueType) {
        _inheritsLoose(Vec4, _ValueType);
        Vec4.clone = function clone(a) {
          return new Vec4(a.x, a.y, a.z, a.w);
        };
        Vec4.copy = function copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          out.w = a.w;
          return out;
        };
        Vec4.set = function set(out, x, y, z, w) {
          out.x = x;
          out.y = y;
          out.z = z;
          out.w = w;
          return out;
        };
        Vec4.fromColor = function fromColor(out, color) {
          out.x = color.r;
          out.y = color.g;
          out.z = color.b;
          out.w = color.a;
          return out;
        };
        Vec4.angle = function angle(a, b) {
          var dx = a.y * b.z - a.z * b.y;
          var dy = a.z * b.x - a.x * b.z;
          var dz = a.x * b.y - a.y * b.x;
          var dotVal = a.x * b.x + a.y * b.y + a.z * b.z;
          return Math.atan2(Math.sqrt(dx * dx + dy * dy + dz * dz), dotVal);
        };
        Vec4.add = function add(out, a, b) {
          out.x = a.x + b.x;
          out.y = a.y + b.y;
          out.z = a.z + b.z;
          out.w = a.w + b.w;
          return out;
        };
        Vec4.subtract = function subtract(out, a, b) {
          out.x = a.x - b.x;
          out.y = a.y - b.y;
          out.z = a.z - b.z;
          out.w = a.w - b.w;
          return out;
        };
        Vec4.multiply = function multiply(out, a, b) {
          out.x = a.x * b.x;
          out.y = a.y * b.y;
          out.z = a.z * b.z;
          out.w = a.w * b.w;
          return out;
        };
        Vec4.divide = function divide(out, a, b) {
          out.x = a.x / b.x;
          out.y = a.y / b.y;
          out.z = a.z / b.z;
          out.w = a.w / b.w;
          return out;
        };
        Vec4.ceil = function ceil(out, a) {
          out.x = Math.ceil(a.x);
          out.y = Math.ceil(a.y);
          out.z = Math.ceil(a.z);
          out.w = Math.ceil(a.w);
          return out;
        };
        Vec4.floor = function floor(out, a) {
          out.x = Math.floor(a.x);
          out.y = Math.floor(a.y);
          out.z = Math.floor(a.z);
          out.w = Math.floor(a.w);
          return out;
        };
        Vec4.min = function min(out, a, b) {
          out.x = Math.min(a.x, b.x);
          out.y = Math.min(a.y, b.y);
          out.z = Math.min(a.z, b.z);
          out.w = Math.min(a.w, b.w);
          return out;
        };
        Vec4.max = function max(out, a, b) {
          out.x = Math.max(a.x, b.x);
          out.y = Math.max(a.y, b.y);
          out.z = Math.max(a.z, b.z);
          out.w = Math.max(a.w, b.w);
          return out;
        };
        Vec4.round = function round(out, a) {
          out.x = Math.round(a.x);
          out.y = Math.round(a.y);
          out.z = Math.round(a.z);
          out.w = Math.round(a.w);
          return out;
        };
        Vec4.multiplyScalar = function multiplyScalar(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          out.z = a.z * b;
          out.w = a.w * b;
          return out;
        };
        Vec4.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
          out.x = a.x + b.x * scale;
          out.y = a.y + b.y * scale;
          out.z = a.z + b.z * scale;
          out.w = a.w + b.w * scale;
          return out;
        };
        Vec4.distance = function distance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          var z = b.z - a.z;
          var w = b.w - a.w;
          return Math.sqrt(x * x + y * y + z * z + w * w);
        };
        Vec4.squaredDistance = function squaredDistance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          var z = b.z - a.z;
          var w = b.w - a.w;
          return x * x + y * y + z * z + w * w;
        };
        Vec4.len = function len(a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var w = a.w;
          return Math.sqrt(x * x + y * y + z * z + w * w);
        };
        Vec4.lengthSqr = function lengthSqr(a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var w = a.w;
          return x * x + y * y + z * z + w * w;
        };
        Vec4.negate = function negate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          out.z = -a.z;
          out.w = -a.w;
          return out;
        };
        Vec4.inverse = function inverse(out, a) {
          out.x = 1.0 / a.x;
          out.y = 1.0 / a.y;
          out.z = 1.0 / a.z;
          out.w = 1.0 / a.w;
          return out;
        };
        Vec4.inverseSafe = function inverseSafe(out, a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var w = a.w;
          if (Math.abs(x) < EPSILON$3) {
            out.x = 0;
          } else {
            out.x = 1.0 / x;
          }
          if (Math.abs(y) < EPSILON$3) {
            out.y = 0;
          } else {
            out.y = 1.0 / y;
          }
          if (Math.abs(z) < EPSILON$3) {
            out.z = 0;
          } else {
            out.z = 1.0 / z;
          }
          if (Math.abs(w) < EPSILON$3) {
            out.w = 0;
          } else {
            out.w = 1.0 / w;
          }
          return out;
        };
        Vec4.normalize = function normalize(out, a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var w = a.w;
          var len = x * x + y * y + z * z + w * w;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            out.x = x * len;
            out.y = y * len;
            out.z = z * len;
            out.w = w * len;
          } else {
            out.x = 0;
            out.y = 0;
            out.z = 0;
            out.w = 0;
          }
          return out;
        };
        Vec4.dot = function dot(a, b) {
          return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
        };
        Vec4.lerp = function lerp(out, a, b, t) {
          out.x = a.x + t * (b.x - a.x);
          out.y = a.y + t * (b.y - a.y);
          out.z = a.z + t * (b.z - a.z);
          out.w = a.w + t * (b.w - a.w);
          return out;
        };
        Vec4.scale = function scale(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          out.z = a.z * b;
          out.w = a.w * b;
          return out;
        };
        Vec4.random = function random$1(out, scale) {
          scale = scale || 1.0;
          var phi = random() * 2.0 * Math.PI;
          var cosTheta = random() * 2 - 1;
          var sinTheta = Math.sqrt(1 - cosTheta * cosTheta);
          out.x = sinTheta * Math.cos(phi) * scale;
          out.y = sinTheta * Math.sin(phi) * scale;
          out.z = cosTheta * scale;
          out.w = 0;
          return out;
        };
        Vec4.transformMat4 = function transformMat4(out, a, m) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var w = a.w;
          out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12 * w;
          out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13 * w;
          out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14 * w;
          out.w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15 * w;
          return out;
        };
        Vec4.transformAffine = function transformAffine(out, v, m) {
          var x = v.x;
          var y = v.y;
          var z = v.z;
          var w = v.w;
          out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12 * w;
          out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13 * w;
          out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14 * w;
          out.w = v.w;
          return out;
        };
        Vec4.transformQuat = function transformQuat(out, a, q) {
          var x = a.x,
            y = a.y,
            z = a.z;
          var _x = q.x;
          var _y = q.y;
          var _z = q.z;
          var _w = q.w;
          var ix = _w * x + _y * z - _z * y;
          var iy = _w * y + _z * x - _x * z;
          var iz = _w * z + _x * y - _y * x;
          var iw = -_x * x - _y * y - _z * z;
          out.x = ix * _w + iw * -_x + iy * -_z - iz * -_y;
          out.y = iy * _w + iw * -_y + iz * -_x - ix * -_z;
          out.z = iz * _w + iw * -_z + ix * -_y - iy * -_x;
          out.w = a.w;
          return out;
        };
        Vec4.toArray = function toArray(out, v, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = v.x;
          out[ofs + 1] = v.y;
          out[ofs + 2] = v.z;
          out[ofs + 3] = v.w;
          return out;
        };
        Vec4.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          out.z = arr[ofs + 2];
          out.w = arr[ofs + 3];
          return out;
        };
        Vec4.strictEquals = function strictEquals(a, b) {
          return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
        };
        Vec4.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          var hasInf = Math.abs(a.x) === Infinity || Math.abs(a.y) === Infinity || Math.abs(a.z) === Infinity || Math.abs(a.w) === Infinity || Math.abs(b.x) === Infinity || Math.abs(b.y) === Infinity || Math.abs(b.z) === Infinity || Math.abs(b.w) === Infinity;
          return !hasInf && Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) && Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z)) && Math.abs(a.w - b.w) <= epsilon * Math.max(1.0, Math.abs(a.w), Math.abs(b.w));
        };
        function Vec4(x, y, z, w) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof x === 'object') {
            _this.x = x.x;
            _this.y = x.y;
            _this.z = x.z;
            _this.w = x.w;
          } else {
            _this.x = x || 0;
            _this.y = y || 0;
            _this.z = z || 0;
            _this.w = w || 0;
          }
          return _this;
        }
        var _proto = Vec4.prototype;
        _proto.clone = function clone() {
          return new Vec4(this.x, this.y, this.z, this.w);
        };
        _proto.set = function set(x, y, z, w) {
          if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
            this.z = x.z;
            this.w = x.w;
          } else {
            this.x = x || 0;
            this.y = y || 0;
            this.z = z || 0;
            this.w = w || 0;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) && Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z)) && Math.abs(this.w - other.w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(other.w));
        };
        _proto.equals4f = function equals4f(x, y, z, w, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x)) && Math.abs(this.y - y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(y)) && Math.abs(this.z - z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(z)) && Math.abs(this.w - w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(w));
        };
        _proto.strictEquals = function strictEquals(other) {
          return this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w;
        };
        _proto.strictEquals4f = function strictEquals4f(x, y, z, w) {
          return this.x === x && this.y === y && this.z === z && this.w === w;
        };
        _proto.lerp = function lerp(to, ratio) {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var w = this.w;
          this.x = x + ratio * (to.x - x);
          this.y = y + ratio * (to.y - y);
          this.z = z + ratio * (to.z - z);
          this.w = w + ratio * (to.w - w);
          return this;
        };
        _proto.toString = function toString() {
          return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.z.toFixed(2) + ", " + this.w.toFixed(2) + ")";
        };
        _proto.clampf = function clampf(minInclusive, maxInclusive) {
          this.x = clamp$1(this.x, minInclusive.x, maxInclusive.x);
          this.y = clamp$1(this.y, minInclusive.y, maxInclusive.y);
          this.z = clamp$1(this.z, minInclusive.z, maxInclusive.z);
          this.w = clamp$1(this.w, minInclusive.w, maxInclusive.w);
          return this;
        };
        _proto.add = function add(other) {
          this.x += other.x;
          this.y += other.y;
          this.z += other.z;
          this.w += other.w;
          return this;
        };
        _proto.add4f = function add4f(x, y, z, w) {
          this.x += x;
          this.y += y;
          this.z += z;
          this.w += w;
          return this;
        };
        _proto.subtract = function subtract(other) {
          this.x -= other.x;
          this.y -= other.y;
          this.z -= other.z;
          this.w -= other.w;
          return this;
        };
        _proto.subtract4f = function subtract4f(x, y, z, w) {
          this.x -= x;
          this.y -= y;
          this.z -= z;
          this.w -= w;
          return this;
        };
        _proto.multiplyScalar = function multiplyScalar(scalar) {
          if (typeof scalar === 'object') {
            console.warn('should use Vec4.multiply for vector * vector operation');
          }
          this.x *= scalar;
          this.y *= scalar;
          this.z *= scalar;
          this.w *= scalar;
          return this;
        };
        _proto.multiply = function multiply(other) {
          if (typeof other !== 'object') {
            console.warn('should use Vec4.scale for vector * scalar operation');
          }
          this.x *= other.x;
          this.y *= other.y;
          this.z *= other.z;
          this.w *= other.w;
          return this;
        };
        _proto.multiply4f = function multiply4f(x, y, z, w) {
          this.x *= x;
          this.y *= y;
          this.z *= z;
          this.w *= w;
          return this;
        };
        _proto.divide = function divide(other) {
          this.x /= other.x;
          this.y /= other.y;
          this.z /= other.z;
          this.w /= other.w;
          return this;
        };
        _proto.divide4f = function divide4f(x, y, z, w) {
          this.x /= x;
          this.y /= y;
          this.z /= z;
          this.w /= w;
          return this;
        };
        _proto.negative = function negative() {
          this.x = -this.x;
          this.y = -this.y;
          this.z = -this.z;
          this.w = -this.w;
          return this;
        };
        _proto.dot = function dot(vector) {
          return this.x * vector.x + this.y * vector.y + this.z * vector.z + this.w * vector.w;
        };
        _proto.cross = function cross(vector) {
          var ax = this.x,
            ay = this.y,
            az = this.z;
          var bx = vector.x,
            by = vector.y,
            bz = vector.z;
          this.x = ay * bz - az * by;
          this.y = az * bx - ax * bz;
          this.z = ax * by - ay * bx;
          return this;
        };
        _proto.length = function length() {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var w = this.w;
          return Math.sqrt(x * x + y * y + z * z + w * w);
        };
        _proto.lengthSqr = function lengthSqr() {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var w = this.w;
          return x * x + y * y + z * z + w * w;
        };
        _proto.normalize = function normalize() {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var w = this.w;
          var len = x * x + y * y + z * z + w * w;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            this.x = x * len;
            this.y = y * len;
            this.z = z * len;
            this.w = w * len;
          }
          return this;
        };
        _proto.scale = function scale(scalar) {
          this.x *= scalar;
          this.y *= scalar;
          this.z *= scalar;
          this.w *= scalar;
          return this;
        };
        _proto.transformMat4 = function transformMat4(matrix) {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var w = this.w;
          this.x = matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12 * w;
          this.y = matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13 * w;
          this.z = matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14 * w;
          this.w = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15 * w;
          return this;
        };
        return Vec4;
      }(ValueType));
      _class$3N = Vec4;
      Vec4.ZERO = Object.freeze(new _class$3N(0, 0, 0, 0));
      Vec4.ONE = Object.freeze(new _class$3N(1, 1, 1, 1));
      Vec4.NEG_ONE = Object.freeze(new _class$3N(-1, -1, -1, -1));
      Vec4.UNIT_X = Object.freeze(new _class$3N(1, 0, 0, 0));
      Vec4.UNIT_Y = Object.freeze(new _class$3N(0, 1, 0, 0));
      Vec4.UNIT_Z = Object.freeze(new _class$3N(0, 0, 1, 0));
      Vec4.UNIT_W = Object.freeze(new _class$3N(0, 0, 0, 1));
      CCClass.fastDefine('cc.Vec4', Vec4, {
        x: 0,
        y: 0,
        z: 0,
        w: 0
      });
      legacyCC.Vec4 = Vec4;
      function v4(x, y, z, w) {
        return new Vec4(x, y, z, w);
      }
      legacyCC.v4 = v4;

      var _class$3M;
      var Vec3 = exports('aQ', function (_ValueType) {
        _inheritsLoose(Vec3, _ValueType);
        Vec3.zero = function zero(out) {
          out.x = 0;
          out.y = 0;
          out.z = 0;
          return out;
        };
        Vec3.clone = function clone(a) {
          return new Vec3(a.x, a.y, a.z);
        };
        Vec3.copy = function copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          return out;
        };
        Vec3.set = function set(out, x, y, z) {
          out.x = x;
          out.y = y;
          out.z = z;
          return out;
        };
        Vec3.add = function add(out, a, b) {
          out.x = a.x + b.x;
          out.y = a.y + b.y;
          out.z = a.z + b.z;
          return out;
        };
        Vec3.subtract = function subtract(out, a, b) {
          out.x = a.x - b.x;
          out.y = a.y - b.y;
          out.z = a.z - b.z;
          return out;
        };
        Vec3.multiply = function multiply(out, a, b) {
          out.x = a.x * b.x;
          out.y = a.y * b.y;
          out.z = a.z * b.z;
          return out;
        };
        Vec3.divide = function divide(out, a, b) {
          out.x = a.x / b.x;
          out.y = a.y / b.y;
          out.z = a.z / b.z;
          return out;
        };
        Vec3.ceil = function ceil(out, a) {
          out.x = Math.ceil(a.x);
          out.y = Math.ceil(a.y);
          out.z = Math.ceil(a.z);
          return out;
        };
        Vec3.floor = function floor(out, a) {
          out.x = Math.floor(a.x);
          out.y = Math.floor(a.y);
          out.z = Math.floor(a.z);
          return out;
        };
        Vec3.min = function min(out, a, b) {
          out.x = Math.min(a.x, b.x);
          out.y = Math.min(a.y, b.y);
          out.z = Math.min(a.z, b.z);
          return out;
        };
        Vec3.max = function max(out, a, b) {
          out.x = Math.max(a.x, b.x);
          out.y = Math.max(a.y, b.y);
          out.z = Math.max(a.z, b.z);
          return out;
        };
        Vec3.round = function round(out, a) {
          out.x = Math.round(a.x);
          out.y = Math.round(a.y);
          out.z = Math.round(a.z);
          return out;
        };
        Vec3.multiplyScalar = function multiplyScalar(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          out.z = a.z * b;
          return out;
        };
        Vec3.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
          out.x = a.x + b.x * scale;
          out.y = a.y + b.y * scale;
          out.z = a.z + b.z * scale;
          return out;
        };
        Vec3.distance = function distance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          var z = b.z - a.z;
          return Math.sqrt(x * x + y * y + z * z);
        };
        Vec3.squaredDistance = function squaredDistance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          var z = b.z - a.z;
          return x * x + y * y + z * z;
        };
        Vec3.len = function len(a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          return Math.sqrt(x * x + y * y + z * z);
        };
        Vec3.lengthSqr = function lengthSqr(a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          return x * x + y * y + z * z;
        };
        Vec3.negate = function negate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          out.z = -a.z;
          return out;
        };
        Vec3.invert = function invert(out, a) {
          out.x = 1.0 / a.x;
          out.y = 1.0 / a.y;
          out.z = 1.0 / a.z;
          return out;
        };
        Vec3.invertSafe = function invertSafe(out, a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          if (Math.abs(x) < EPSILON$3) {
            out.x = 0;
          } else {
            out.x = 1.0 / x;
          }
          if (Math.abs(y) < EPSILON$3) {
            out.y = 0;
          } else {
            out.y = 1.0 / y;
          }
          if (Math.abs(z) < EPSILON$3) {
            out.z = 0;
          } else {
            out.z = 1.0 / z;
          }
          return out;
        };
        Vec3.normalize = function normalize(out, a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var len = x * x + y * y + z * z;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            out.x = x * len;
            out.y = y * len;
            out.z = z * len;
          } else {
            out.x = 0;
            out.y = 0;
            out.z = 0;
          }
          return out;
        };
        Vec3.dot = function dot(a, b) {
          return a.x * b.x + a.y * b.y + a.z * b.z;
        };
        Vec3.cross = function cross(out, a, b) {
          var ax = a.x,
            ay = a.y,
            az = a.z;
          var bx = b.x,
            by = b.y,
            bz = b.z;
          out.x = ay * bz - az * by;
          out.y = az * bx - ax * bz;
          out.z = ax * by - ay * bx;
          return out;
        };
        Vec3.lerp = function lerp(out, a, b, t) {
          out.x = a.x + t * (b.x - a.x);
          out.y = a.y + t * (b.y - a.y);
          out.z = a.z + t * (b.z - a.z);
          return out;
        };
        Vec3.random = function random$1(out, scale) {
          scale = scale || 1.0;
          var phi = random() * 2.0 * Math.PI;
          var cosTheta = random() * 2 - 1;
          var sinTheta = Math.sqrt(1 - cosTheta * cosTheta);
          out.x = sinTheta * Math.cos(phi) * scale;
          out.y = sinTheta * Math.sin(phi) * scale;
          out.z = cosTheta * scale;
          return out;
        };
        Vec3.transformMat4 = function transformMat4(out, a, m) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var rhw = m.m03 * x + m.m07 * y + m.m11 * z + m.m15;
          rhw = rhw ? 1 / rhw : 1;
          out.x = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) * rhw;
          out.y = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) * rhw;
          out.z = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) * rhw;
          return out;
        };
        Vec3.transformMat4Normal = function transformMat4Normal(out, a, m) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var rhw = m.m03 * x + m.m07 * y + m.m11 * z;
          rhw = rhw ? 1 / rhw : 1;
          out.x = (m.m00 * x + m.m04 * y + m.m08 * z) * rhw;
          out.y = (m.m01 * x + m.m05 * y + m.m09 * z) * rhw;
          out.z = (m.m02 * x + m.m06 * y + m.m10 * z) * rhw;
          return out;
        };
        Vec3.transformMat3 = function transformMat3(out, a, m) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          out.x = x * m.m00 + y * m.m03 + z * m.m06;
          out.y = x * m.m01 + y * m.m04 + z * m.m07;
          out.z = x * m.m02 + y * m.m05 + z * m.m08;
          return out;
        };
        Vec3.transformAffine = function transformAffine(out, v, m) {
          var x = v.x;
          var y = v.y;
          var z = v.z;
          out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12;
          out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13;
          out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14;
          return out;
        };
        Vec3.transformQuat = function transformQuat(out, a, q) {
          var ix = q.w * a.x + q.y * a.z - q.z * a.y;
          var iy = q.w * a.y + q.z * a.x - q.x * a.z;
          var iz = q.w * a.z + q.x * a.y - q.y * a.x;
          var iw = -q.x * a.x - q.y * a.y - q.z * a.z;
          out.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;
          out.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;
          out.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;
          return out;
        };
        Vec3.transformRTS = function transformRTS(out, a, r, t, s) {
          var x = a.x * s.x;
          var y = a.y * s.y;
          var z = a.z * s.z;
          var ix = r.w * x + r.y * z - r.z * y;
          var iy = r.w * y + r.z * x - r.x * z;
          var iz = r.w * z + r.x * y - r.y * x;
          var iw = -r.x * x - r.y * y - r.z * z;
          out.x = ix * r.w + iw * -r.x + iy * -r.z - iz * -r.y + t.x;
          out.y = iy * r.w + iw * -r.y + iz * -r.x - ix * -r.z + t.y;
          out.z = iz * r.w + iw * -r.z + ix * -r.y - iy * -r.x + t.z;
          return out;
        };
        Vec3.transformInverseRTS = function transformInverseRTS(out, a, r, t, s) {
          var x = a.x - t.x;
          var y = a.y - t.y;
          var z = a.z - t.z;
          var ix = r.w * x - r.y * z + r.z * y;
          var iy = r.w * y - r.z * x + r.x * z;
          var iz = r.w * z - r.x * y + r.y * x;
          var iw = r.x * x + r.y * y + r.z * z;
          out.x = (ix * r.w + iw * r.x + iy * r.z - iz * r.y) / s.x;
          out.y = (iy * r.w + iw * r.y + iz * r.x - ix * r.z) / s.y;
          out.z = (iz * r.w + iw * r.z + ix * r.y - iy * r.x) / s.z;
          return out;
        };
        Vec3.rotateX = function rotateX(out, v, o, a) {
          var x = v.x - o.x;
          var y = v.y - o.y;
          var z = v.z - o.z;
          var cos = Math.cos(a);
          var sin = Math.sin(a);
          var rx = x;
          var ry = y * cos - z * sin;
          var rz = y * sin + z * cos;
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        };
        Vec3.rotateY = function rotateY(out, v, o, a) {
          var x = v.x - o.x;
          var y = v.y - o.y;
          var z = v.z - o.z;
          var cos = Math.cos(a);
          var sin = Math.sin(a);
          var rx = z * sin + x * cos;
          var ry = y;
          var rz = z * cos - x * sin;
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        };
        Vec3.rotateZ = function rotateZ(out, v, o, a) {
          var x = v.x - o.x;
          var y = v.y - o.y;
          var z = v.z - o.z;
          var cos = Math.cos(a);
          var sin = Math.sin(a);
          var rx = x * cos - y * sin;
          var ry = x * sin + y * cos;
          var rz = z;
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        };
        Vec3.rotateN = function rotateN(out, v, o, n, a) {
          var x = v.x - o.x;
          var y = v.y - o.y;
          var z = v.z - o.z;
          var nx = n.x;
          var ny = n.y;
          var nz = n.z;
          var cos = Math.cos(a);
          var sin = Math.sin(a);
          var rx = x * (nx * nx * (1.0 - cos) + cos) + y * (nx * ny * (1.0 - cos) - nz * sin) + z * (nx * nz * (1.0 - cos) + ny * sin);
          var ry = x * (nx * ny * (1.0 - cos) + nz * sin) + y * (ny * ny * (1.0 - cos) + cos) + z * (ny * nz * (1.0 - cos) - nx * sin);
          var rz = x * (nx * nz * (1.0 - cos) - ny * sin) + y * (ny * nz * (1.0 - cos) + nx * sin) + z * (nz * nz * (1.0 - cos) + cos);
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        };
        Vec3.toArray = function toArray(out, v, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = v.x;
          out[ofs + 1] = v.y;
          out[ofs + 2] = v.z;
          return out;
        };
        Vec3.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          out.z = arr[ofs + 2];
          return out;
        };
        Vec3.strictEquals = function strictEquals(a, b) {
          return a.x === b.x && a.y === b.y && a.z === b.z;
        };
        Vec3.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          var a0 = a.x,
            a1 = a.y,
            a2 = a.z;
          var b0 = b.x,
            b1 = b.y,
            b2 = b.z;
          return Math.abs(a0 - b0) <= epsilon * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= epsilon * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= epsilon * Math.max(1.0, Math.abs(a2), Math.abs(b2));
        };
        Vec3.angle = function angle(a, b) {
          var magSqr1 = a.x * a.x + a.y * a.y + a.z * a.z;
          var magSqr2 = b.x * b.x + b.y * b.y + b.z * b.z;
          if (magSqr1 === 0 || magSqr2 === 0) {
            return 0.0;
          }
          var dot = a.x * b.x + a.y * b.y + a.z * b.z;
          var cosine = dot / Math.sqrt(magSqr1 * magSqr2);
          cosine = clamp$1(cosine, -1.0, 1.0);
          return Math.acos(cosine);
        };
        Vec3.projectOnPlane = function projectOnPlane(out, a, n) {
          return Vec3.subtract(out, a, Vec3.project(out, a, n));
        };
        Vec3.project = function project(out, a, b) {
          var sqrLen = Vec3.lengthSqr(b);
          if (sqrLen < 0.000001) {
            return Vec3.set(out, 0, 0, 0);
          } else {
            return Vec3.multiplyScalar(out, b, Vec3.dot(a, b) / sqrLen);
          }
        };
        Vec3.moveTowards = function moveTowards(out, current, target, maxStep) {
          var deltaX = target.x - current.x;
          var deltaY = target.y - current.y;
          var deltaZ = target.z - current.z;
          var distanceSqr = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
          if (distanceSqr === 0 || maxStep >= 0 && distanceSqr < maxStep * maxStep) {
            out.x = target.x;
            out.y = target.y;
            out.z = target.z;
            return out;
          }
          var distance = Math.sqrt(distanceSqr);
          var scale = maxStep / distance;
          out.x = current.x + deltaX * scale;
          out.y = current.y + deltaY * scale;
          out.z = current.z + deltaZ * scale;
          return out;
        };
        Vec3.generateOrthogonal = function generateOrthogonal(out, n) {
          var x = n.x,
            y = n.y,
            z = n.z;
          var absX = Math.abs(x);
          var absY = Math.abs(y);
          var absZ = Math.abs(z);
          if (absX < absY && absX < absZ) {
            Vec3.set(out, 0.0, z, -y);
          } else if (absY < absZ) {
            Vec3.set(out, z, 0.0, -x);
          } else {
            Vec3.set(out, y, -x, 0.0);
          }
          return Vec3.normalize(out, out);
        };
        function Vec3(x, y, z) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof x === 'object') {
            _this.x = x.x;
            _this.y = x.y;
            _this.z = x.z;
          } else {
            _this.x = x || 0;
            _this.y = y || 0;
            _this.z = z || 0;
          }
          return _this;
        }
        var _proto = Vec3.prototype;
        _proto.clone = function clone() {
          return new Vec3(this.x, this.y, this.z);
        };
        _proto.set = function set(x, y, z) {
          if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
            this.z = x.z;
          } else {
            this.x = x || 0;
            this.y = y || 0;
            this.z = z || 0;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - other.x) <= epsilon && Math.abs(this.y - other.y) <= epsilon && Math.abs(this.z - other.z) <= epsilon;
        };
        _proto.equals3f = function equals3f(x, y, z, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - x) <= epsilon && Math.abs(this.y - y) <= epsilon && Math.abs(this.z - z) <= epsilon;
        };
        _proto.strictEquals = function strictEquals(other) {
          return this.x === other.x && this.y === other.y && this.z === other.z;
        };
        _proto.strictEquals3f = function strictEquals3f(x, y, z) {
          return this.x === x && this.y === y && this.z === z;
        };
        _proto.toString = function toString() {
          return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.z.toFixed(2) + ")";
        };
        _proto.lerp = function lerp(to, ratio) {
          this.x += ratio * (to.x - this.x);
          this.y += ratio * (to.y - this.y);
          this.z += ratio * (to.z - this.z);
          return this;
        };
        _proto.add = function add(other) {
          this.x += other.x;
          this.y += other.y;
          this.z += other.z;
          return this;
        };
        _proto.add3f = function add3f(x, y, z) {
          this.x += x;
          this.y += y;
          this.z += z;
          return this;
        };
        _proto.subtract = function subtract(other) {
          this.x -= other.x;
          this.y -= other.y;
          this.z -= other.z;
          return this;
        };
        _proto.subtract3f = function subtract3f(x, y, z) {
          this.x -= x;
          this.y -= y;
          this.z -= z;
          return this;
        };
        _proto.multiplyScalar = function multiplyScalar(scalar) {
          if (typeof scalar === 'object') {
            console.warn('should use Vec3.multiply for vector * vector operation');
          }
          this.x *= scalar;
          this.y *= scalar;
          this.z *= scalar;
          return this;
        };
        _proto.multiply = function multiply(other) {
          if (typeof other !== 'object') {
            console.warn('should use Vec3.scale for vector * scalar operation');
          }
          this.x *= other.x;
          this.y *= other.y;
          this.z *= other.z;
          return this;
        };
        _proto.multiply3f = function multiply3f(x, y, z) {
          this.x *= x;
          this.y *= y;
          this.z *= z;
          return this;
        };
        _proto.divide = function divide(other) {
          this.x /= other.x;
          this.y /= other.y;
          this.z /= other.z;
          return this;
        };
        _proto.divide3f = function divide3f(x, y, z) {
          this.x /= x;
          this.y /= y;
          this.z /= z;
          return this;
        };
        _proto.negative = function negative() {
          this.x = -this.x;
          this.y = -this.y;
          this.z = -this.z;
          return this;
        };
        _proto.clampf = function clampf(minInclusive, maxInclusive) {
          this.x = clamp$1(this.x, minInclusive.x, maxInclusive.x);
          this.y = clamp$1(this.y, minInclusive.y, maxInclusive.y);
          this.z = clamp$1(this.z, minInclusive.z, maxInclusive.z);
          return this;
        };
        _proto.dot = function dot(other) {
          return this.x * other.x + this.y * other.y + this.z * other.z;
        };
        _proto.cross = function cross(other) {
          var ax = this.x,
            ay = this.y,
            az = this.z;
          var bx = other.x,
            by = other.y,
            bz = other.z;
          this.x = ay * bz - az * by;
          this.y = az * bx - ax * bz;
          this.z = ax * by - ay * bx;
          return this;
        };
        _proto.length = function length() {
          return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
        };
        _proto.lengthSqr = function lengthSqr() {
          return this.x * this.x + this.y * this.y + this.z * this.z;
        };
        _proto.normalize = function normalize() {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var len = x * x + y * y + z * z;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            this.x = x * len;
            this.y = y * len;
            this.z = z * len;
          }
          return this;
        };
        _proto.transformMat4 = function transformMat4(matrix) {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var rhw = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15;
          rhw = rhw ? 1 / rhw : 1;
          this.x = (matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12) * rhw;
          this.y = (matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13) * rhw;
          this.z = (matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14) * rhw;
          return this;
        };
        return Vec3;
      }(ValueType));
      _class$3M = Vec3;
      Vec3.UNIT_X = Object.freeze(new _class$3M(1, 0, 0));
      Vec3.UNIT_Y = Object.freeze(new _class$3M(0, 1, 0));
      Vec3.UNIT_Z = Object.freeze(new _class$3M(0, 0, 1));
      Vec3.RIGHT = Object.freeze(new _class$3M(1, 0, 0));
      Vec3.UP = Object.freeze(new _class$3M(0, 1, 0));
      Vec3.FORWARD = Object.freeze(new _class$3M(0, 0, -1));
      Vec3.ZERO = Object.freeze(new _class$3M(0, 0, 0));
      Vec3.ONE = Object.freeze(new _class$3M(1, 1, 1));
      Vec3.NEG_ONE = Object.freeze(new _class$3M(-1, -1, -1));
      Vec3.slerp = function () {
        var cacheV1 = new _class$3M();
        var cacheV2 = new _class$3M();
        var cacheV3 = new _class$3M();
        return function (out, from, to, t) {
          var EPSILON = 1e-5;
          var lenFrom = _class$3M.len(from);
          var lenTo = _class$3M.len(to);
          if (lenFrom < EPSILON || lenTo < EPSILON) {
            return _class$3M.lerp(out, from, to, t);
          }
          var lenLerped = lerp(lenFrom, lenTo, t);
          var dot = _class$3M.dot(from, to) / (lenFrom * lenTo);
          if (dot > 1.0 - EPSILON) {
            return _class$3M.lerp(out, from, to, t);
          } else if (dot < -1.0 + EPSILON) {
            var fromNormalized = _class$3M.multiplyScalar(cacheV1, from, 1.0 / lenFrom);
            var _axis = _class$3M.generateOrthogonal(cacheV2, fromNormalized);
            var _angle = Math.PI * t;
            rotateAxisAngle(cacheV3, fromNormalized, _axis, _angle);
            _class$3M.multiplyScalar(out, cacheV3, lenLerped);
            return out;
          } else {
            var dotClamped = dot;
            var theta = Math.acos(dotClamped) * t;
            var _fromNormalized = _class$3M.multiplyScalar(cacheV1, from, 1.0 / lenFrom);
            var toNormalized = _class$3M.multiplyScalar(cacheV2, to, 1.0 / lenTo);
            _class$3M.scaleAndAdd(cacheV3, toNormalized, _fromNormalized, -dotClamped);
            _class$3M.normalize(cacheV3, cacheV3);
            _class$3M.multiplyScalar(cacheV3, cacheV3, Math.sin(theta));
            _class$3M.scaleAndAdd(cacheV3, cacheV3, _fromNormalized, Math.cos(theta));
            _class$3M.multiplyScalar(out, cacheV3, lenLerped);
            return out;
          }
        };
      }();
      Vec3.signedAngle = function () {
        var cacheCross = new _class$3M();
        return function (a, b, normal) {
          var angle = _class$3M.angle(a, b);
          var cross = _class$3M.cross(cacheCross, a, b);
          var dot = _class$3M.dot(cross, normal);
          return dot < 0 ? -angle : angle;
        };
      }();
      CCClass.fastDefine('cc.Vec3', Vec3, {
        x: 0,
        y: 0,
        z: 0
      });
      legacyCC.Vec3 = Vec3;
      function v3(x, y, z) {
        return new Vec3(x, y, z);
      }
      var rotateAxisAngle = function () {
        var cacheQ = {
          x: 0.0,
          y: 0.0,
          z: 0.0,
          w: 0.0
        };
        return function (out, input, axis, angle) {
          var rad = angle * 0.5;
          var s = Math.sin(rad);
          cacheQ.x = s * axis.x;
          cacheQ.y = s * axis.y;
          cacheQ.z = s * axis.z;
          cacheQ.w = Math.cos(rad);
          Vec3.transformQuat(out, input, cacheQ);
          return out;
        };
      }();
      legacyCC.v3 = v3;

      var _class$3L;
      var toFloat = 1 / 255;
      var Color$1 = exports('b2', function (_ValueType) {
        _inheritsLoose(Color, _ValueType);
        Color.clone = function clone(a) {
          var out = new Color();
          if (a._val) {
            out._val = a._val;
          } else {
            out._val = (a.a << 24 >>> 0) + (a.b << 16) + (a.g << 8) + a.r;
          }
          return out;
        };
        Color.copy = function copy(out, a) {
          out.r = a.r;
          out.g = a.g;
          out.b = a.b;
          out.a = a.a;
          return out;
        };
        Color.set = function set(out, r, g, b, a) {
          out.r = r;
          out.g = g;
          out.b = b;
          out.a = a;
          return out;
        };
        Color.toVec4 = function toVec4(color, out) {
          out = out !== undefined ? out : new Vec4();
          out.x = color.r * toFloat;
          out.y = color.g * toFloat;
          out.z = color.b * toFloat;
          out.w = color.a * toFloat;
          return out;
        };
        Color.fromVec4 = function fromVec4(value, out) {
          out = out === undefined ? new Color() : out;
          out.r = Math.floor(value.x / toFloat);
          out.g = Math.floor(value.y / toFloat);
          out.b = Math.floor(value.z / toFloat);
          out.a = Math.floor(value.w / toFloat);
          return out;
        };
        Color.fromHEX = function fromHEX(out, hex) {
          var hexNumber;
          if (typeof hex === 'string') {
            hex = hex[0] === '#' ? hex.substring(1) : hex;
            if (hex.length === 6) {
              hex += 'FF';
            } else if (hex.length === 3) {
              hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + 'FF';
            } else if (hex.length === 4) {
              hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
            }
            hexNumber = Number('0x' + hex);
          } else {
            if (hex < 0x1000000) {
              hex = (hex << 8) + 0xff;
            }
            hexNumber = hex;
          }
          out.r = hexNumber >>> 24;
          out.g = (hexNumber & 0x00ff0000) >>> 16;
          out.b = (hexNumber & 0x0000ff00) >>> 8;
          out.a = hexNumber & 0x000000ff;
          out._val = (out.a << 24 >>> 0) + (out.b << 16) + (out.g << 8) + out.r;
          return out;
        };
        Color.add = function add(out, a, b) {
          out.r = a.r + b.r;
          out.g = a.g + b.g;
          out.b = a.b + b.b;
          out.a = a.a + b.a;
          return out;
        };
        Color.subtract = function subtract(out, a, b) {
          out.r = a.r - b.r;
          out.g = a.g - b.g;
          out.b = a.b - b.b;
          out.a = a.a - b.a;
          return out;
        };
        Color.multiply = function multiply(out, a, b) {
          out.r = a.r * b.r;
          out.g = a.g * b.g;
          out.b = a.b * b.b;
          out.a = a.a * b.a;
          return out;
        };
        Color.divide = function divide(out, a, b) {
          out.r = a.r / b.r;
          out.g = a.g / b.g;
          out.b = a.b / b.b;
          out.a = a.a / b.a;
          return out;
        };
        Color.scale = function scale(out, a, b) {
          out.r = a.r * b;
          out.g = a.g * b;
          out.b = a.b * b;
          out.a = a.a * b;
          return out;
        };
        Color.lerp = function lerp(out, from, to, ratio) {
          var r = from.r;
          var g = from.g;
          var b = from.b;
          var a = from.a;
          r += (to.r - r) * ratio;
          g += (to.g - g) * ratio;
          b += (to.b - b) * ratio;
          a += (to.a - a) * ratio;
          out._val = Math.floor((a << 24 >>> 0) + (b << 16) + (g << 8) + r);
          return out;
        };
        Color.toArray = function toArray(out, a, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          var scale = a instanceof Color || a.a > 1 ? 1 / 255 : 1;
          out[ofs + 0] = a.r * scale;
          out[ofs + 1] = a.g * scale;
          out[ofs + 2] = a.b * scale;
          out[ofs + 3] = a.a * scale;
          return out;
        };
        Color.fromArray = function fromArray(arr, out, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.r = arr[ofs + 0] * 255;
          out.g = arr[ofs + 1] * 255;
          out.b = arr[ofs + 2] * 255;
          out.a = arr[ofs + 3] * 255;
          return out;
        };
        Color.fromUint32 = function fromUint32(out, uint32) {
          out._val = uint32;
          return out;
        };
        Color.toUint32 = function toUint32(color) {
          return color._val;
        };
        Color.strictEquals = function strictEquals(a, b) {
          return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
        };
        Color.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          var hasInf = Math.abs(a.r) === Infinity || Math.abs(a.g) === Infinity || Math.abs(a.b) === Infinity || Math.abs(a.a) === Infinity;
          return !hasInf && Math.abs(a.r - b.r) <= epsilon * Math.max(1.0, Math.abs(a.r), Math.abs(b.r)) && Math.abs(a.g - b.g) <= epsilon * Math.max(1.0, Math.abs(a.g), Math.abs(b.g)) && Math.abs(a.b - b.b) <= epsilon * Math.max(1.0, Math.abs(a.b), Math.abs(b.b)) && Math.abs(a.a - b.a) <= epsilon * Math.max(1.0, Math.abs(a.a), Math.abs(b.a));
        };
        Color.hex = function hex(a) {
          return (a.r * 255 << 24 | a.g * 255 << 16 | a.b * 255 << 8 | a.a * 255) >>> 0;
        };
        function Color(r, g, b, a) {
          var _this;
          _this = _ValueType.call(this) || this;
          _this._val = 0;
          if (typeof r === 'string') {
            _this.fromHEX(r);
          } else if (g !== undefined) {
            _this.set(r, g, b, a);
          } else {
            _this.set(r);
          }
          return _this;
        }
        var _proto = Color.prototype;
        _proto.clone = function clone() {
          var ret = new Color();
          ret._val = this._val;
          return ret;
        };
        _proto.equals = function equals(other) {
          return other && this._val === other._val;
        };
        _proto.lerp = function lerp(to, ratio) {
          var r = this.r;
          var g = this.g;
          var b = this.b;
          var a = this.a;
          r += (to.r - r) * ratio;
          g += (to.g - g) * ratio;
          b += (to.b - b) * ratio;
          a += (to.a - a) * ratio;
          this._val = Math.floor((a << 24 >>> 0) + (b << 16) + (g << 8) + r);
          return this;
        };
        _proto.toString = function toString() {
          return "rgba(" + this.r.toFixed() + ", " + this.g.toFixed() + ", " + this.b.toFixed() + ", " + this.a.toFixed() + ")";
        };
        _proto.toCSS = function toCSS(opt) {
          if (opt === void 0) {
            opt = 'rgba';
          }
          if (opt === 'rgba') {
            return "rgba(" + this.r + "," + this.g + "," + this.b + "," + (this.a * toFloat).toFixed(2) + ")";
          } else if (opt === 'rgb') {
            return "rgb(" + this.r + "," + this.g + "," + this.b + ")";
          } else {
            return "#" + this.toHEX(opt);
          }
        };
        _proto.fromHEX = function fromHEX(hex) {
          var hexNumber;
          if (typeof hex === 'string') {
            hex = hex[0] === '#' ? hex.substring(1) : hex;
            if (hex.length === 6) {
              hex += 'FF';
            } else if (hex.length === 3) {
              hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + 'FF';
            } else if (hex.length === 4) {
              hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
            }
            hexNumber = Number('0x' + hex);
          } else {
            if (hex < 0x1000000) {
              hex = (hex << 8) + 0xff;
            }
            hexNumber = hex;
          }
          var r = hexNumber >>> 24;
          var g = (hexNumber & 0x00ff0000) >>> 16;
          var b = (hexNumber & 0x0000ff00) >>> 8;
          var a = hexNumber & 0x000000ff;
          this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + r;
          return this;
        };
        _proto.toHEX = function toHEX(fmt) {
          if (fmt === void 0) {
            fmt = '#rrggbb';
          }
          var prefix = '0';
          var hex = [(this.r < 16 ? prefix : '') + this.r.toString(16), (this.g < 16 ? prefix : '') + this.g.toString(16), (this.b < 16 ? prefix : '') + this.b.toString(16)];
          if (fmt === '#rgb') {
            hex[0] = hex[0][0];
            hex[1] = hex[1][0];
            hex[2] = hex[2][0];
          } else if (fmt === '#rrggbbaa') {
            hex.push((this.a < 16 ? prefix : '') + this.a.toString(16));
          }
          return hex.join('');
        };
        _proto.toRGBValue = function toRGBValue() {
          return this._val & 0x00ffffff;
        };
        _proto.fromHSV = function fromHSV(h, s, v) {
          var r = 0;
          var g = 0;
          var b = 0;
          if (s === 0) {
            r = g = b = v;
          } else if (v === 0) {
            r = g = b = 0;
          } else {
            if (h === 1) {
              h = 0;
            }
            h *= 6;
            var i = Math.floor(h);
            var f = h - i;
            var p = v * (1 - s);
            var q = v * (1 - s * f);
            var t = v * (1 - s * (1 - f));
            switch (i) {
              default:
                assertIsTrue(false);
              case 0:
                r = v;
                g = t;
                b = p;
                break;
              case 1:
                r = q;
                g = v;
                b = p;
                break;
              case 2:
                r = p;
                g = v;
                b = t;
                break;
              case 3:
                r = p;
                g = q;
                b = v;
                break;
              case 4:
                r = t;
                g = p;
                b = v;
                break;
              case 5:
                r = v;
                g = p;
                b = q;
                break;
            }
          }
          r *= 255;
          g *= 255;
          b *= 255;
          this._val = (this.a << 24 >>> 0) + (b << 16) + (g << 8) + (r | 0);
          return this;
        };
        _proto.toHSV = function toHSV() {
          var r = this.r * toFloat;
          var g = this.g * toFloat;
          var b = this.b * toFloat;
          var hsv = {
            h: 0,
            s: 0,
            v: 0
          };
          var max = Math.max(r, g, b);
          var min = Math.min(r, g, b);
          var delta = 0;
          hsv.v = max;
          hsv.s = max ? (max - min) / max : 0;
          if (!hsv.s) {
            hsv.h = 0;
          } else {
            delta = max - min;
            if (r === max) {
              hsv.h = (g - b) / delta;
            } else if (g === max) {
              hsv.h = 2 + (b - r) / delta;
            } else {
              hsv.h = 4 + (r - g) / delta;
            }
            hsv.h /= 6;
            if (hsv.h < 0) {
              hsv.h += 1.0;
            }
          }
          return hsv;
        };
        _proto.set = function set(r, g, b, a) {
          if (typeof r === 'object') {
            if (r._val != null) {
              this._val = r._val;
            } else {
              g = r.g || 0;
              b = r.b || 0;
              a = typeof r.a === 'number' ? r.a : 255;
              r = r.r || 0;
              this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + (r | 0);
            }
          } else {
            r = r || 0;
            g = g || 0;
            b = b || 0;
            a = typeof a === 'number' ? a : 255;
            this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + (r | 0);
          }
          return this;
        };
        _proto.multiply = function multiply(other) {
          var r = (this._val & 0x000000ff) * other.r >> 8;
          var g = (this._val & 0x0000ff00) * other.g >> 8;
          var b = (this._val & 0x00ff0000) * other.b >> 8;
          var a = ((this._val & 0xff000000) >>> 8) * other.a;
          this._val = a & 0xff000000 | b & 0x00ff0000 | g & 0x0000ff00 | r & 0x000000ff;
          return this;
        };
        _proto._set_r_unsafe = function _set_r_unsafe(red) {
          this._val = (this._val & 0xffffff00 | red) >>> 0;
          return this;
        };
        _proto._set_g_unsafe = function _set_g_unsafe(green) {
          this._val = (this._val & 0xffff00ff | green << 8) >>> 0;
          return this;
        };
        _proto._set_b_unsafe = function _set_b_unsafe(blue) {
          this._val = (this._val & 0xff00ffff | blue << 16) >>> 0;
          return this;
        };
        _proto._set_a_unsafe = function _set_a_unsafe(alpha) {
          this._val = (this._val & 0x00ffffff | alpha << 24) >>> 0;
          return this;
        };
        _createClass(Color, [{
          key: "r",
          get: function get() {
            return this._val & 0x000000ff;
          },
          set: function set(red) {
            red = ~~clamp$1(red, 0, 255);
            this._val = (this._val & 0xffffff00 | red) >>> 0;
          }
        }, {
          key: "g",
          get: function get() {
            return (this._val & 0x0000ff00) >> 8;
          },
          set: function set(green) {
            green = ~~clamp$1(green, 0, 255);
            this._val = (this._val & 0xffff00ff | green << 8) >>> 0;
          }
        }, {
          key: "b",
          get: function get() {
            return (this._val & 0x00ff0000) >> 16;
          },
          set: function set(blue) {
            blue = ~~clamp$1(blue, 0, 255);
            this._val = (this._val & 0xff00ffff | blue << 16) >>> 0;
          }
        }, {
          key: "a",
          get: function get() {
            return (this._val & 0xff000000) >>> 24;
          },
          set: function set(alpha) {
            alpha = ~~clamp$1(alpha, 0, 255);
            this._val = (this._val & 0x00ffffff | alpha << 24) >>> 0;
          }
        }, {
          key: "x",
          get: function get() {
            return this.r * toFloat;
          },
          set: function set(value) {
            this.r = value * 255;
          }
        }, {
          key: "y",
          get: function get() {
            return this.g * toFloat;
          },
          set: function set(value) {
            this.g = value * 255;
          }
        }, {
          key: "z",
          get: function get() {
            return this.b * toFloat;
          },
          set: function set(value) {
            this.b = value * 255;
          }
        }, {
          key: "w",
          get: function get() {
            return this.a * toFloat;
          },
          set: function set(value) {
            this.a = value * 255;
          }
        }]);
        return Color;
      }(ValueType));
      _class$3L = Color$1;
      Color$1.WHITE = Object.freeze(new _class$3L(255, 255, 255, 255));
      Color$1.GRAY = Object.freeze(new _class$3L(127, 127, 127, 255));
      Color$1.BLACK = Object.freeze(new _class$3L(0, 0, 0, 255));
      Color$1.TRANSPARENT = Object.freeze(new _class$3L(0, 0, 0, 0));
      Color$1.RED = Object.freeze(new _class$3L(255, 0, 0, 255));
      Color$1.GREEN = Object.freeze(new _class$3L(0, 255, 0, 255));
      Color$1.BLUE = Object.freeze(new _class$3L(0, 0, 255, 255));
      Color$1.CYAN = Object.freeze(new _class$3L(0, 255, 255, 255));
      Color$1.MAGENTA = Object.freeze(new _class$3L(255, 0, 255, 255));
      Color$1.YELLOW = Object.freeze(new _class$3L(255, 255, 0, 255));
      CCClass.fastDefine('cc.Color', Color$1, {
        r: 0,
        g: 0,
        b: 0,
        a: 255
      });
      legacyCC.Color = Color$1;
      function color(r, g, b, a) {
        return new Color$1(r, g, b, a);
      }
      legacyCC.color = color;
      function clampVec3(val, min, max) {
        if (min > max) {
          var temp = min;
          min = max;
          max = temp;
        }
        return val < min ? min : val > max ? max : val;
      }
      function floorVec3(val) {
        var temp = val.clone();
        temp.x = Math.floor(val.x);
        temp.y = Math.floor(val.y);
        temp.z = Math.floor(val.z);
        return temp;
      }
      function stepVec3(a, b) {
        if (a < b) {
          return b;
        } else {
          return a;
        }
      }
      function packRGBE(rgb) {
        var maxComp = Math.max(Math.max(rgb.x, rgb.y), rgb.z);
        var e = 128.0;
        if (maxComp > 0.0001) {
          e = Math.log(maxComp) / Math.log(1.1);
          e = Math.ceil(e);
          e = clamp$1(e + 128.0, 0.0, 255.0);
        }
        var sc = 1.0 / Math.pow(1.1, e - 128.0);
        var encode = clampVec3(rgb.multiplyScalar(sc), new Vec3(0.0, 0.0, 0.0), new Vec3(1.0, 1.0, 1.0));
        encode.multiplyScalar(255.0);
        var encode_rounded = floorVec3(encode).add(stepVec3(encode.subtract(floorVec3(encode)), new Vec3(0.5, 0.5, 0.5)));
        return new Vec4(encode_rounded.x / 255.0, encode_rounded.y / 255.0, encode_rounded.z / 255.0, e / 255.0);
      }

      var _class$3K;
      var Mat3 = exports('aW', function (_ValueType) {
        _inheritsLoose(Mat3, _ValueType);
        Mat3.clone = function clone(a) {
          return new Mat3(a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, a.m08);
        };
        Mat3.copy = function copy(out, a) {
          out.m00 = a.m00;
          out.m01 = a.m01;
          out.m02 = a.m02;
          out.m03 = a.m03;
          out.m04 = a.m04;
          out.m05 = a.m05;
          out.m06 = a.m06;
          out.m07 = a.m07;
          out.m08 = a.m08;
          return out;
        };
        Mat3.set = function set(out, m00, m01, m02, m03, m04, m05, m06, m07, m08) {
          out.m00 = m00;
          out.m01 = m01;
          out.m02 = m02;
          out.m03 = m03;
          out.m04 = m04;
          out.m05 = m05;
          out.m06 = m06;
          out.m07 = m07;
          out.m08 = m08;
          return out;
        };
        Mat3.identity = function identity(out) {
          out.m00 = 1;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 1;
          out.m05 = 0;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 1;
          return out;
        };
        Mat3.transpose = function transpose(out, a) {
          if (out === a) {
            var a01 = a.m01;
            var a02 = a.m02;
            var a12 = a.m05;
            out.m01 = a.m03;
            out.m02 = a.m06;
            out.m03 = a01;
            out.m05 = a.m07;
            out.m06 = a02;
            out.m07 = a12;
          } else {
            out.m00 = a.m00;
            out.m01 = a.m03;
            out.m02 = a.m06;
            out.m03 = a.m01;
            out.m04 = a.m04;
            out.m05 = a.m07;
            out.m06 = a.m02;
            out.m07 = a.m05;
            out.m08 = a.m08;
          }
          return out;
        };
        Mat3.invert = function invert(out, a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          var b01 = a22 * a11 - a12 * a21;
          var b11 = -a22 * a10 + a12 * a20;
          var b21 = a21 * a10 - a11 * a20;
          var det = a00 * b01 + a01 * b11 + a02 * b21;
          if (det === 0) {
            out.m00 = 0;
            out.m01 = 0;
            out.m02 = 0;
            out.m03 = 0;
            out.m04 = 0;
            out.m05 = 0;
            out.m06 = 0;
            out.m07 = 0;
            out.m08 = 0;
            return out;
          }
          det = 1.0 / det;
          out.m00 = b01 * det;
          out.m01 = (-a22 * a01 + a02 * a21) * det;
          out.m02 = (a12 * a01 - a02 * a11) * det;
          out.m03 = b11 * det;
          out.m04 = (a22 * a00 - a02 * a20) * det;
          out.m05 = (-a12 * a00 + a02 * a10) * det;
          out.m06 = b21 * det;
          out.m07 = (-a21 * a00 + a01 * a20) * det;
          out.m08 = (a11 * a00 - a01 * a10) * det;
          return out;
        };
        Mat3.determinant = function determinant(a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
        };
        Mat3.multiply = function multiply(out, a, b) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          var b00 = b.m00;
          var b01 = b.m01;
          var b02 = b.m02;
          var b10 = b.m03;
          var b11 = b.m04;
          var b12 = b.m05;
          var b20 = b.m06;
          var b21 = b.m07;
          var b22 = b.m08;
          out.m00 = b00 * a00 + b01 * a10 + b02 * a20;
          out.m01 = b00 * a01 + b01 * a11 + b02 * a21;
          out.m02 = b00 * a02 + b01 * a12 + b02 * a22;
          out.m03 = b10 * a00 + b11 * a10 + b12 * a20;
          out.m04 = b10 * a01 + b11 * a11 + b12 * a21;
          out.m05 = b10 * a02 + b11 * a12 + b12 * a22;
          out.m06 = b20 * a00 + b21 * a10 + b22 * a20;
          out.m07 = b20 * a01 + b21 * a11 + b22 * a21;
          out.m08 = b20 * a02 + b21 * a12 + b22 * a22;
          return out;
        };
        Mat3.multiplyMat4 = function multiplyMat4(out, a, b) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          var b00 = b.m00;
          var b01 = b.m01;
          var b02 = b.m02;
          var b10 = b.m04;
          var b11 = b.m05;
          var b12 = b.m06;
          var b20 = b.m08;
          var b21 = b.m09;
          var b22 = b.m10;
          out.m00 = b00 * a00 + b01 * a10 + b02 * a20;
          out.m01 = b00 * a01 + b01 * a11 + b02 * a21;
          out.m02 = b00 * a02 + b01 * a12 + b02 * a22;
          out.m03 = b10 * a00 + b11 * a10 + b12 * a20;
          out.m04 = b10 * a01 + b11 * a11 + b12 * a21;
          out.m05 = b10 * a02 + b11 * a12 + b12 * a22;
          out.m06 = b20 * a00 + b21 * a10 + b22 * a20;
          out.m07 = b20 * a01 + b21 * a11 + b22 * a21;
          out.m08 = b20 * a02 + b21 * a12 + b22 * a22;
          return out;
        };
        Mat3.transform = function transform(out, a, v) {
          this.translate(out, a, v);
        };
        Mat3.translate = function translate(out, a, v) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          var x = v.x;
          var y = v.y;
          out.m00 = a00;
          out.m01 = a01;
          out.m02 = a02;
          out.m03 = a10;
          out.m04 = a11;
          out.m05 = a12;
          out.m06 = x * a00 + y * a10 + a20;
          out.m07 = x * a01 + y * a11 + a21;
          out.m08 = x * a02 + y * a12 + a22;
          return out;
        };
        Mat3.scale = function scale(out, a, v) {
          var x = v.x;
          var y = v.y;
          out.m00 = x * a.m00;
          out.m01 = x * a.m01;
          out.m02 = x * a.m02;
          out.m03 = y * a.m03;
          out.m04 = y * a.m04;
          out.m05 = y * a.m05;
          out.m06 = a.m06;
          out.m07 = a.m07;
          out.m08 = a.m08;
          return out;
        };
        Mat3.rotate = function rotate(out, a, rad) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          out.m00 = c * a00 + s * a10;
          out.m01 = c * a01 + s * a11;
          out.m02 = c * a02 + s * a12;
          out.m03 = c * a10 - s * a00;
          out.m04 = c * a11 - s * a01;
          out.m05 = c * a12 - s * a02;
          out.m06 = a20;
          out.m07 = a21;
          out.m08 = a22;
          return out;
        };
        Mat3.fromMat4 = function fromMat4(out, a) {
          out.m00 = a.m00;
          out.m01 = a.m01;
          out.m02 = a.m02;
          out.m03 = a.m04;
          out.m04 = a.m05;
          out.m05 = a.m06;
          out.m06 = a.m08;
          out.m07 = a.m09;
          out.m08 = a.m10;
          return out;
        };
        Mat3.fromViewUp = function fromViewUp(out, view, up) {
          if (Vec3.lengthSqr(view) < EPSILON$3 * EPSILON$3) {
            Mat3.identity(out);
            return out;
          }
          up = up || Vec3.UNIT_Y;
          Vec3.normalize(v3_1$9, Vec3.cross(v3_1$9, up, view));
          if (Vec3.lengthSqr(v3_1$9) < EPSILON$3 * EPSILON$3) {
            Mat3.identity(out);
            return out;
          }
          Vec3.cross(v3_2$3, view, v3_1$9);
          Mat3.set(out, v3_1$9.x, v3_1$9.y, v3_1$9.z, v3_2$3.x, v3_2$3.y, v3_2$3.z, view.x, view.y, view.z);
          return out;
        };
        Mat3.fromTranslation = function fromTranslation(out, v) {
          out.m00 = 1;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 1;
          out.m05 = 0;
          out.m06 = v.x;
          out.m07 = v.y;
          out.m08 = 1;
          return out;
        };
        Mat3.fromScaling = function fromScaling(out, v) {
          out.m00 = v.x;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = v.y;
          out.m05 = 0;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 1;
          return out;
        };
        Mat3.fromRotation = function fromRotation(out, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          out.m00 = c;
          out.m01 = s;
          out.m02 = 0;
          out.m03 = -s;
          out.m04 = c;
          out.m05 = 0;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 1;
          return out;
        };
        Mat3.fromQuat = function fromQuat(out, q) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var yx = y * x2;
          var yy = y * y2;
          var zx = z * x2;
          var zy = z * y2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          out.m00 = 1 - yy - zz;
          out.m03 = yx - wz;
          out.m06 = zx + wy;
          out.m01 = yx + wz;
          out.m04 = 1 - xx - zz;
          out.m07 = zy - wx;
          out.m02 = zx - wy;
          out.m05 = zy + wx;
          out.m08 = 1 - xx - yy;
          return out;
        };
        Mat3.inverseTransposeMat4 = function inverseTransposeMat4(out, a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var a30 = a.m12;
          var a31 = a.m13;
          var a32 = a.m14;
          var a33 = a.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
          if (!det) {
            return null;
          }
          det = 1.0 / det;
          out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
          out.m01 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
          out.m02 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
          out.m03 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
          out.m04 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
          out.m05 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
          out.m06 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
          out.m07 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
          out.m08 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
          return out;
        };
        Mat3.toArray = function toArray(out, m, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = m.m00;
          out[ofs + 1] = m.m01;
          out[ofs + 2] = m.m02;
          out[ofs + 3] = m.m03;
          out[ofs + 4] = m.m04;
          out[ofs + 5] = m.m05;
          out[ofs + 6] = m.m06;
          out[ofs + 7] = m.m07;
          out[ofs + 8] = m.m08;
          return out;
        };
        Mat3.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.m00 = arr[ofs + 0];
          out.m01 = arr[ofs + 1];
          out.m02 = arr[ofs + 2];
          out.m03 = arr[ofs + 3];
          out.m04 = arr[ofs + 4];
          out.m05 = arr[ofs + 5];
          out.m06 = arr[ofs + 6];
          out.m07 = arr[ofs + 7];
          out.m08 = arr[ofs + 8];
          return out;
        };
        Mat3.add = function add(out, a, b) {
          out.m00 = a.m00 + b.m00;
          out.m01 = a.m01 + b.m01;
          out.m02 = a.m02 + b.m02;
          out.m03 = a.m03 + b.m03;
          out.m04 = a.m04 + b.m04;
          out.m05 = a.m05 + b.m05;
          out.m06 = a.m06 + b.m06;
          out.m07 = a.m07 + b.m07;
          out.m08 = a.m08 + b.m08;
          return out;
        };
        Mat3.subtract = function subtract(out, a, b) {
          out.m00 = a.m00 - b.m00;
          out.m01 = a.m01 - b.m01;
          out.m02 = a.m02 - b.m02;
          out.m03 = a.m03 - b.m03;
          out.m04 = a.m04 - b.m04;
          out.m05 = a.m05 - b.m05;
          out.m06 = a.m06 - b.m06;
          out.m07 = a.m07 - b.m07;
          out.m08 = a.m08 - b.m08;
          return out;
        };
        Mat3.multiplyScalar = function multiplyScalar(out, a, b) {
          out.m00 = a.m00 * b;
          out.m01 = a.m01 * b;
          out.m02 = a.m02 * b;
          out.m03 = a.m03 * b;
          out.m04 = a.m04 * b;
          out.m05 = a.m05 * b;
          out.m06 = a.m06 * b;
          out.m07 = a.m07 * b;
          out.m08 = a.m08 * b;
          return out;
        };
        Mat3.multiplyScalarAndAdd = function multiplyScalarAndAdd(out, a, b, scale) {
          out.m00 = b.m00 * scale + a.m00;
          out.m01 = b.m01 * scale + a.m01;
          out.m02 = b.m02 * scale + a.m02;
          out.m03 = b.m03 * scale + a.m03;
          out.m04 = b.m04 * scale + a.m04;
          out.m05 = b.m05 * scale + a.m05;
          out.m06 = b.m06 * scale + a.m06;
          out.m07 = b.m07 * scale + a.m07;
          out.m08 = b.m08 * scale + a.m08;
          return out;
        };
        Mat3.strictEquals = function strictEquals(a, b) {
          return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08;
        };
        Mat3.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(a.m00 - b.m00) <= epsilon * Math.max(1.0, Math.abs(a.m00), Math.abs(b.m00)) && Math.abs(a.m01 - b.m01) <= epsilon * Math.max(1.0, Math.abs(a.m01), Math.abs(b.m01)) && Math.abs(a.m02 - b.m02) <= epsilon * Math.max(1.0, Math.abs(a.m02), Math.abs(b.m02)) && Math.abs(a.m03 - b.m03) <= epsilon * Math.max(1.0, Math.abs(a.m03), Math.abs(b.m03)) && Math.abs(a.m04 - b.m04) <= epsilon * Math.max(1.0, Math.abs(a.m04), Math.abs(b.m04)) && Math.abs(a.m05 - b.m05) <= epsilon * Math.max(1.0, Math.abs(a.m05), Math.abs(b.m05)) && Math.abs(a.m06 - b.m06) <= epsilon * Math.max(1.0, Math.abs(a.m06), Math.abs(b.m06)) && Math.abs(a.m07 - b.m07) <= epsilon * Math.max(1.0, Math.abs(a.m07), Math.abs(b.m07)) && Math.abs(a.m08 - b.m08) <= epsilon * Math.max(1.0, Math.abs(a.m08), Math.abs(b.m08));
        };
        Mat3.toEuler = function toEuler(matrix, v) {
          var a00 = matrix.m00;
          var a01 = matrix.m01;
          matrix.m02;
          var a10 = matrix.m03;
          var a11 = matrix.m04;
          matrix.m05;
          var a20 = matrix.m06;
          var a21 = matrix.m07;
          var a22 = matrix.m08;
          if (a21 < 0.999) {
            if (a21 > -0.999) {
              v.x = Math.asin(-a21);
              v.y = Math.atan2(a20, a22);
              v.z = Math.atan2(a01, a11);
              return true;
            } else {
              v.x = HALF_PI;
              v.y = Math.atan2(a10, a00);
              v.z = 0.0;
              return false;
            }
          } else {
            v.x = -HALF_PI;
            v.y = Math.atan2(-a10, a00);
            v.z = 0.0;
            return false;
          }
        };
        function Mat3(m00, m01, m02, m03, m04, m05, m06, m07, m08) {
          var _this;
          if (m00 === void 0) {
            m00 = 1;
          }
          if (m01 === void 0) {
            m01 = 0;
          }
          if (m02 === void 0) {
            m02 = 0;
          }
          if (m03 === void 0) {
            m03 = 0;
          }
          if (m04 === void 0) {
            m04 = 1;
          }
          if (m05 === void 0) {
            m05 = 0;
          }
          if (m06 === void 0) {
            m06 = 0;
          }
          if (m07 === void 0) {
            m07 = 0;
          }
          if (m08 === void 0) {
            m08 = 1;
          }
          _this = _ValueType.call(this) || this;
          if (typeof m00 === 'object') {
            _this.m00 = m00.m00;
            _this.m01 = m00.m01;
            _this.m02 = m00.m02;
            _this.m03 = m00.m03;
            _this.m04 = m00.m04;
            _this.m05 = m00.m05;
            _this.m06 = m00.m06;
            _this.m07 = m00.m07;
            _this.m08 = m00.m08;
          } else {
            _this.m00 = m00;
            _this.m01 = m01;
            _this.m02 = m02;
            _this.m03 = m03;
            _this.m04 = m04;
            _this.m05 = m05;
            _this.m06 = m06;
            _this.m07 = m07;
            _this.m08 = m08;
          }
          return _this;
        }
        var _proto = Mat3.prototype;
        _proto.clone = function clone() {
          var t = this;
          return new Mat3(t.m00, t.m01, t.m02, t.m03, t.m04, t.m05, t.m06, t.m07, t.m08);
        };
        _proto.set = function set(m00, m01, m02, m03, m04, m05, m06, m07, m08) {
          if (m00 === void 0) {
            m00 = 1;
          }
          if (m01 === void 0) {
            m01 = 0;
          }
          if (m02 === void 0) {
            m02 = 0;
          }
          if (m03 === void 0) {
            m03 = 0;
          }
          if (m04 === void 0) {
            m04 = 1;
          }
          if (m05 === void 0) {
            m05 = 0;
          }
          if (m06 === void 0) {
            m06 = 0;
          }
          if (m07 === void 0) {
            m07 = 0;
          }
          if (m08 === void 0) {
            m08 = 1;
          }
          if (typeof m00 === 'object') {
            this.m00 = m00.m00;
            this.m01 = m00.m01;
            this.m02 = m00.m02;
            this.m03 = m00.m03;
            this.m04 = m00.m04;
            this.m05 = m00.m05;
            this.m06 = m00.m06;
            this.m07 = m00.m07;
            this.m08 = m00.m08;
          } else {
            this.m00 = m00;
            this.m01 = m01;
            this.m02 = m02;
            this.m03 = m03;
            this.m04 = m04;
            this.m05 = m05;
            this.m06 = m06;
            this.m07 = m07;
            this.m08 = m08;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.m00 - other.m00) <= epsilon * Math.max(1.0, Math.abs(this.m00), Math.abs(other.m00)) && Math.abs(this.m01 - other.m01) <= epsilon * Math.max(1.0, Math.abs(this.m01), Math.abs(other.m01)) && Math.abs(this.m02 - other.m02) <= epsilon * Math.max(1.0, Math.abs(this.m02), Math.abs(other.m02)) && Math.abs(this.m03 - other.m03) <= epsilon * Math.max(1.0, Math.abs(this.m03), Math.abs(other.m03)) && Math.abs(this.m04 - other.m04) <= epsilon * Math.max(1.0, Math.abs(this.m04), Math.abs(other.m04)) && Math.abs(this.m05 - other.m05) <= epsilon * Math.max(1.0, Math.abs(this.m05), Math.abs(other.m05)) && Math.abs(this.m06 - other.m06) <= epsilon * Math.max(1.0, Math.abs(this.m06), Math.abs(other.m06)) && Math.abs(this.m07 - other.m07) <= epsilon * Math.max(1.0, Math.abs(this.m07), Math.abs(other.m07)) && Math.abs(this.m08 - other.m08) <= epsilon * Math.max(1.0, Math.abs(this.m08), Math.abs(other.m08));
        };
        _proto.strictEquals = function strictEquals(other) {
          return this.m00 === other.m00 && this.m01 === other.m01 && this.m02 === other.m02 && this.m03 === other.m03 && this.m04 === other.m04 && this.m05 === other.m05 && this.m06 === other.m06 && this.m07 === other.m07 && this.m08 === other.m08;
        };
        _proto.toString = function toString() {
          var t = this;
          return "[\n" + t.m00 + ", " + t.m01 + ", " + t.m02 + ",\n" + t.m03 + ",\n" + t.m04 + ", " + t.m05 + ",\n" + t.m06 + ", " + t.m07 + ",\n" + t.m08 + "\n" + "]";
        };
        _proto.identity = function identity() {
          this.m00 = 1;
          this.m01 = 0;
          this.m02 = 0;
          this.m03 = 0;
          this.m04 = 1;
          this.m05 = 0;
          this.m06 = 0;
          this.m07 = 0;
          this.m08 = 1;
          return this;
        };
        _proto.transpose = function transpose() {
          var a01 = this.m01;
          var a02 = this.m02;
          var a12 = this.m05;
          this.m01 = this.m03;
          this.m02 = this.m06;
          this.m03 = a01;
          this.m05 = this.m07;
          this.m06 = a02;
          this.m07 = a12;
          return this;
        };
        _proto.invert = function invert() {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a10 = this.m03;
          var a11 = this.m04;
          var a12 = this.m05;
          var a20 = this.m06;
          var a21 = this.m07;
          var a22 = this.m08;
          var b01 = a22 * a11 - a12 * a21;
          var b11 = -a22 * a10 + a12 * a20;
          var b21 = a21 * a10 - a11 * a20;
          var det = a00 * b01 + a01 * b11 + a02 * b21;
          if (det === 0) {
            this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
            return this;
          }
          det = 1.0 / det;
          this.m00 = b01 * det;
          this.m01 = (-a22 * a01 + a02 * a21) * det;
          this.m02 = (a12 * a01 - a02 * a11) * det;
          this.m03 = b11 * det;
          this.m04 = (a22 * a00 - a02 * a20) * det;
          this.m05 = (-a12 * a00 + a02 * a10) * det;
          this.m06 = b21 * det;
          this.m07 = (-a21 * a00 + a01 * a20) * det;
          this.m08 = (a11 * a00 - a01 * a10) * det;
          return this;
        };
        _proto.determinant = function determinant() {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a10 = this.m03;
          var a11 = this.m04;
          var a12 = this.m05;
          var a20 = this.m06;
          var a21 = this.m07;
          var a22 = this.m08;
          return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
        };
        _proto.add = function add(mat) {
          this.m00 += mat.m00;
          this.m01 += mat.m01;
          this.m02 += mat.m02;
          this.m03 += mat.m03;
          this.m04 += mat.m04;
          this.m05 += mat.m05;
          this.m06 += mat.m06;
          this.m07 += mat.m07;
          this.m08 += mat.m08;
          return this;
        };
        _proto.subtract = function subtract(mat) {
          this.m00 -= mat.m00;
          this.m01 -= mat.m01;
          this.m02 -= mat.m02;
          this.m03 -= mat.m03;
          this.m04 -= mat.m04;
          this.m05 -= mat.m05;
          this.m06 -= mat.m06;
          this.m07 -= mat.m07;
          this.m08 -= mat.m08;
          return this;
        };
        _proto.multiply = function multiply(mat) {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a10 = this.m03;
          var a11 = this.m04;
          var a12 = this.m05;
          var a20 = this.m06;
          var a21 = this.m07;
          var a22 = this.m08;
          var b00 = mat.m00;
          var b01 = mat.m01;
          var b02 = mat.m02;
          var b10 = mat.m03;
          var b11 = mat.m04;
          var b12 = mat.m05;
          var b20 = mat.m06;
          var b21 = mat.m07;
          var b22 = mat.m08;
          this.m00 = b00 * a00 + b01 * a10 + b02 * a20;
          this.m01 = b00 * a01 + b01 * a11 + b02 * a21;
          this.m02 = b00 * a02 + b01 * a12 + b02 * a22;
          this.m03 = b10 * a00 + b11 * a10 + b12 * a20;
          this.m04 = b10 * a01 + b11 * a11 + b12 * a21;
          this.m05 = b10 * a02 + b11 * a12 + b12 * a22;
          this.m06 = b20 * a00 + b21 * a10 + b22 * a20;
          this.m07 = b20 * a01 + b21 * a11 + b22 * a21;
          this.m08 = b20 * a02 + b21 * a12 + b22 * a22;
          return this;
        };
        _proto.multiplyScalar = function multiplyScalar(scalar) {
          this.m00 *= scalar;
          this.m01 *= scalar;
          this.m02 *= scalar;
          this.m03 *= scalar;
          this.m04 *= scalar;
          this.m05 *= scalar;
          this.m06 *= scalar;
          this.m07 *= scalar;
          this.m08 *= scalar;
          return this;
        };
        _proto.scale = function scale(vec) {
          var x = vec.x;
          var y = vec.y;
          this.m00 = x * this.m00;
          this.m01 = x * this.m01;
          this.m02 = x * this.m02;
          this.m03 = y * this.m03;
          this.m04 = y * this.m04;
          this.m05 = y * this.m05;
          this.m06 = this.m06;
          this.m07 = this.m07;
          this.m08 = this.m08;
          return this;
        };
        _proto.rotate = function rotate(rad) {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a10 = this.m03;
          var a11 = this.m04;
          var a12 = this.m05;
          var a20 = this.m06;
          var a21 = this.m07;
          var a22 = this.m08;
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          this.m00 = c * a00 + s * a10;
          this.m01 = c * a01 + s * a11;
          this.m02 = c * a02 + s * a12;
          this.m03 = c * a10 - s * a00;
          this.m04 = c * a11 - s * a01;
          this.m05 = c * a12 - s * a02;
          this.m06 = a20;
          this.m07 = a21;
          this.m08 = a22;
          return this;
        };
        _proto.fromQuat = function fromQuat(q) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var yx = y * x2;
          var yy = y * y2;
          var zx = z * x2;
          var zy = z * y2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          this.m00 = 1 - yy - zz;
          this.m03 = yx - wz;
          this.m06 = zx + wy;
          this.m01 = yx + wz;
          this.m04 = 1 - xx - zz;
          this.m07 = zy - wx;
          this.m02 = zx - wy;
          this.m05 = zy + wx;
          this.m08 = 1 - xx - yy;
          return this;
        };
        return Mat3;
      }(ValueType));
      _class$3K = Mat3;
      Mat3.IDENTITY = Object.freeze(new _class$3K());
      var v3_1$9 = new Vec3();
      var v3_2$3 = new Vec3();
      CCClass.fastDefine('cc.Mat3', Mat3, {
        m00: 1,
        m01: 0,
        m02: 0,
        m03: 0,
        m04: 1,
        m05: 0,
        m06: 0,
        m07: 0,
        m08: 1
      });
      legacyCC.Mat3 = Mat3;

      var _class$3J;
      var Quat = exports('aU', function (_ValueType) {
        _inheritsLoose(Quat, _ValueType);
        Quat.clone = function clone(a) {
          return new Quat(a.x, a.y, a.z, a.w);
        };
        Quat.copy = function copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          out.w = a.w;
          return out;
        };
        Quat.set = function set(out, x, y, z, w) {
          out.x = x;
          out.y = y;
          out.z = z;
          out.w = w;
          return out;
        };
        Quat.identity = function identity(out) {
          out.x = 0;
          out.y = 0;
          out.z = 0;
          out.w = 1;
          return out;
        };
        Quat.rotationTo = function rotationTo(out, a, b) {
          var dot = Vec3.dot(a, b);
          if (dot < -0.999999) {
            Vec3.cross(v3_1$8, Vec3.UNIT_X, a);
            if (v3_1$8.length() < 0.000001) {
              Vec3.cross(v3_1$8, Vec3.UNIT_Y, a);
            }
            Vec3.normalize(v3_1$8, v3_1$8);
            Quat.fromAxisAngle(out, v3_1$8, Math.PI);
            return out;
          } else if (dot > 0.999999) {
            out.x = 0;
            out.y = 0;
            out.z = 0;
            out.w = 1;
            return out;
          } else {
            Vec3.cross(v3_1$8, a, b);
            out.x = v3_1$8.x;
            out.y = v3_1$8.y;
            out.z = v3_1$8.z;
            out.w = 1 + dot;
            return Quat.normalize(out, out);
          }
        };
        Quat.getAxisAngle = function getAxisAngle(outAxis, q) {
          var rad = Math.acos(q.w) * 2.0;
          var s = Math.sin(rad / 2.0);
          if (s !== 0.0) {
            outAxis.x = q.x / s;
            outAxis.y = q.y / s;
            outAxis.z = q.z / s;
          } else {
            outAxis.x = 1;
            outAxis.y = 0;
            outAxis.z = 0;
          }
          return rad;
        };
        Quat.multiply = function multiply(out, a, b) {
          var x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;
          var y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;
          var z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;
          var w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;
          out.x = x;
          out.y = y;
          out.z = z;
          out.w = w;
          return out;
        };
        Quat.multiplyScalar = function multiplyScalar(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          out.z = a.z * b;
          out.w = a.w * b;
          return out;
        };
        Quat.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
          out.x = a.x + b.x * scale;
          out.y = a.y + b.y * scale;
          out.z = a.z + b.z * scale;
          out.w = a.w + b.w * scale;
          return out;
        };
        Quat.rotateX = function rotateX(out, a, rad) {
          rad *= 0.5;
          var bx = Math.sin(rad);
          var bw = Math.cos(rad);
          var x = a.x,
            y = a.y,
            z = a.z,
            w = a.w;
          out.x = x * bw + w * bx;
          out.y = y * bw + z * bx;
          out.z = z * bw - y * bx;
          out.w = w * bw - x * bx;
          return out;
        };
        Quat.rotateY = function rotateY(out, a, rad) {
          rad *= 0.5;
          var by = Math.sin(rad);
          var bw = Math.cos(rad);
          var x = a.x,
            y = a.y,
            z = a.z,
            w = a.w;
          out.x = x * bw - z * by;
          out.y = y * bw + w * by;
          out.z = z * bw + x * by;
          out.w = w * bw - y * by;
          return out;
        };
        Quat.rotateZ = function rotateZ(out, a, rad) {
          rad *= 0.5;
          var bz = Math.sin(rad);
          var bw = Math.cos(rad);
          var x = a.x,
            y = a.y,
            z = a.z,
            w = a.w;
          out.x = x * bw + y * bz;
          out.y = y * bw - x * bz;
          out.z = z * bw + w * bz;
          out.w = w * bw - z * bz;
          return out;
        };
        Quat.rotateAround = function rotateAround(out, rot, axis, rad) {
          Quat.invert(qt_1$1, rot);
          Vec3.transformQuat(v3_1$8, axis, qt_1$1);
          Quat.fromAxisAngle(qt_1$1, v3_1$8, rad);
          Quat.multiply(out, rot, qt_1$1);
          return out;
        };
        Quat.rotateAroundLocal = function rotateAroundLocal(out, rot, axis, rad) {
          Quat.fromAxisAngle(qt_1$1, axis, rad);
          Quat.multiply(out, rot, qt_1$1);
          return out;
        };
        Quat.calculateW = function calculateW(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          out.w = Math.sqrt(Math.abs(1.0 - a.x * a.x - a.y * a.y - a.z * a.z));
          return out;
        };
        Quat.dot = function dot(a, b) {
          return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
        };
        Quat.lerp = function lerp(out, a, b, t) {
          out.x = a.x + t * (b.x - a.x);
          out.y = a.y + t * (b.y - a.y);
          out.z = a.z + t * (b.z - a.z);
          out.w = a.w + t * (b.w - a.w);
          return out;
        };
        Quat.slerp = function slerp(out, a, b, t) {
          var scale0 = 0;
          var scale1 = 0;
          var bx = b.x;
          var by = b.y;
          var bz = b.z;
          var bw = b.w;
          var cosom = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
          if (cosom < 0.0) {
            cosom = -cosom;
            bx = -bx;
            by = -by;
            bz = -bz;
            bw = -bw;
          }
          if (1.0 - cosom > 0.000001) {
            var omega = Math.acos(cosom);
            var sinom = Math.sin(omega);
            scale0 = Math.sin((1.0 - t) * omega) / sinom;
            scale1 = Math.sin(t * omega) / sinom;
          } else {
            scale0 = 1.0 - t;
            scale1 = t;
          }
          out.x = scale0 * a.x + scale1 * bx;
          out.y = scale0 * a.y + scale1 * by;
          out.z = scale0 * a.z + scale1 * bz;
          out.w = scale0 * a.w + scale1 * bw;
          return out;
        };
        Quat.sqlerp = function sqlerp(out, a, b, c, d, t) {
          Quat.slerp(qt_1$1, a, d, t);
          Quat.slerp(qt_2, b, c, t);
          Quat.slerp(out, qt_1$1, qt_2, 2 * t * (1 - t));
          return out;
        };
        Quat.invert = function invert(out, a) {
          var dot = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
          var invDot = dot ? 1.0 / dot : 0;
          out.x = -a.x * invDot;
          out.y = -a.y * invDot;
          out.z = -a.z * invDot;
          out.w = a.w * invDot;
          return out;
        };
        Quat.conjugate = function conjugate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          out.z = -a.z;
          out.w = a.w;
          return out;
        };
        Quat.len = function len(a) {
          return Math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w);
        };
        Quat.lengthSqr = function lengthSqr(a) {
          return a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
        };
        Quat.normalize = function normalize(out, a) {
          var len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            out.x = a.x * len;
            out.y = a.y * len;
            out.z = a.z * len;
            out.w = a.w * len;
          } else {
            out.x = 0;
            out.y = 0;
            out.z = 0;
            out.w = 0;
          }
          return out;
        };
        Quat.fromAxes = function fromAxes(out, xAxis, yAxis, zAxis) {
          Mat3.set(m3_1$2, xAxis.x, xAxis.y, xAxis.z, yAxis.x, yAxis.y, yAxis.z, zAxis.x, zAxis.y, zAxis.z);
          return Quat.normalize(out, Quat.fromMat3(out, m3_1$2));
        };
        Quat.fromViewUp = function fromViewUp(out, view, up) {
          Mat3.fromViewUp(m3_1$2, view, up);
          return Quat.normalize(out, Quat.fromMat3(out, m3_1$2));
        };
        Quat.fromAxisAngle = function fromAxisAngle(out, axis, rad) {
          rad *= 0.5;
          var s = Math.sin(rad);
          out.x = s * axis.x;
          out.y = s * axis.y;
          out.z = s * axis.z;
          out.w = Math.cos(rad);
          return out;
        };
        Quat.fromMat3 = function fromMat3(out, m) {
          var m00 = m.m00,
            m01 = m.m01,
            m02 = m.m02,
            m10 = m.m03,
            m11 = m.m04,
            m12 = m.m05,
            m20 = m.m06,
            m21 = m.m07,
            m22 = m.m08;
          var fourXSquaredMinus1 = m00 - m11 - m22;
          var fourYSquaredMinus1 = m11 - m00 - m22;
          var fourZSquaredMinus1 = m22 - m00 - m11;
          var fourWSquaredMinus1 = m00 + m11 + m22;
          var biggestIndex = 0;
          var fourBiggestSquaredMinus1 = fourWSquaredMinus1;
          if (fourXSquaredMinus1 > fourBiggestSquaredMinus1) {
            fourBiggestSquaredMinus1 = fourXSquaredMinus1;
            biggestIndex = 1;
          }
          if (fourYSquaredMinus1 > fourBiggestSquaredMinus1) {
            fourBiggestSquaredMinus1 = fourYSquaredMinus1;
            biggestIndex = 2;
          }
          if (fourZSquaredMinus1 > fourBiggestSquaredMinus1) {
            fourBiggestSquaredMinus1 = fourZSquaredMinus1;
            biggestIndex = 3;
          }
          var biggestVal = Math.sqrt(fourBiggestSquaredMinus1 + 1) * 0.5;
          var mult = 0.25 / biggestVal;
          switch (biggestIndex) {
            case 0:
              out.w = biggestVal;
              out.x = (m12 - m21) * mult;
              out.y = (m20 - m02) * mult;
              out.z = (m01 - m10) * mult;
              break;
            case 1:
              out.w = (m12 - m21) * mult;
              out.x = biggestVal;
              out.y = (m01 + m10) * mult;
              out.z = (m20 + m02) * mult;
              break;
            case 2:
              out.w = (m20 - m02) * mult;
              out.x = (m01 + m10) * mult;
              out.y = biggestVal;
              out.z = (m12 + m21) * mult;
              break;
            case 3:
              out.w = (m01 - m10) * mult;
              out.x = (m20 + m02) * mult;
              out.y = (m12 + m21) * mult;
              out.z = biggestVal;
              break;
            default:
              out.w = 1;
              out.x = 0;
              out.y = 0;
              out.z = 0;
              break;
          }
          return out;
        };
        Quat.fromEuler = function fromEuler(out, x, y, z) {
          x *= halfToRad;
          y *= halfToRad;
          z *= halfToRad;
          var sx = Math.sin(x);
          var cx = Math.cos(x);
          var sy = Math.sin(y);
          var cy = Math.cos(y);
          var sz = Math.sin(z);
          var cz = Math.cos(z);
          out.x = sx * cy * cz + cx * sy * sz;
          out.y = cx * sy * cz + sx * cy * sz;
          out.z = cx * cy * sz - sx * sy * cz;
          out.w = cx * cy * cz - sx * sy * sz;
          return out;
        };
        Quat.fromAngleZ = function fromAngleZ(out, z) {
          z *= halfToRad;
          out.x = out.y = 0;
          out.z = Math.sin(z);
          out.w = Math.cos(z);
          return out;
        };
        Quat.toAxisX = function toAxisX(out, q) {
          var fy = 2.0 * q.y;
          var fz = 2.0 * q.z;
          out.x = 1.0 - fy * q.y - fz * q.z;
          out.y = fy * q.x + fz * q.w;
          out.z = fz * q.x - fy * q.w;
          return out;
        };
        Quat.toAxisY = function toAxisY(out, q) {
          var fx = 2.0 * q.x;
          var fy = 2.0 * q.y;
          var fz = 2.0 * q.z;
          out.x = fy * q.x - fz * q.w;
          out.y = 1.0 - fx * q.x - fz * q.z;
          out.z = fz * q.y + fx * q.w;
          return out;
        };
        Quat.toAxisZ = function toAxisZ(out, q) {
          var fx = 2.0 * q.x;
          var fy = 2.0 * q.y;
          var fz = 2.0 * q.z;
          out.x = fz * q.x + fy * q.w;
          out.y = fz * q.y - fx * q.w;
          out.z = 1.0 - fx * q.x - fy * q.y;
          return out;
        };
        Quat.toEuler = function toEuler(out, q, outerZ) {
          var x = q.x,
            y = q.y,
            z = q.z,
            w = q.w;
          var bank = 0;
          var heading = 0;
          var attitude = 0;
          var test = x * y + z * w;
          if (test > 0.499999) {
            bank = 0;
            heading = toDegree(2 * Math.atan2(x, w));
            attitude = 90;
          } else if (test < -0.499999) {
            bank = 0;
            heading = -toDegree(2 * Math.atan2(x, w));
            attitude = -90;
          } else {
            var sqx = x * x;
            var sqy = y * y;
            var sqz = z * z;
            bank = toDegree(Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz));
            heading = toDegree(Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz));
            attitude = toDegree(Math.asin(2 * test));
            if (outerZ) {
              bank = -180 * Math.sign(bank + 1e-6) + bank;
              heading = -180 * Math.sign(heading + 1e-6) + heading;
              attitude = 180 * Math.sign(attitude + 1e-6) - attitude;
            }
          }
          out.x = bank;
          out.y = heading;
          out.z = attitude;
          return out;
        };
        Quat.toEulerInYXZOrder = function toEulerInYXZOrder(out, q) {
          Mat3.fromQuat(m3_1$2, q);
          Mat3.toEuler(m3_1$2, out);
          out.x = toDegree(out.x);
          out.y = toDegree(out.y);
          out.z = toDegree(out.z);
        };
        Quat.toArray = function toArray(out, q, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = q.x;
          out[ofs + 1] = q.y;
          out[ofs + 2] = q.z;
          out[ofs + 3] = q.w;
          return out;
        };
        Quat.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          out.z = arr[ofs + 2];
          out.w = arr[ofs + 3];
          return out;
        };
        Quat.strictEquals = function strictEquals(a, b) {
          return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
        };
        Quat.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) && Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z)) && Math.abs(a.w - b.w) <= epsilon * Math.max(1.0, Math.abs(a.w), Math.abs(b.w));
        };
        Quat.angle = function angle(a, b) {
          var dot = Math.min(Math.abs(Quat.dot(a, b)), 1.0);
          return Math.acos(dot) * 2.0;
        };
        Quat.rotateTowards = function rotateTowards(out, from, to, maxStep) {
          var angle = Quat.angle(from, to);
          if (angle === 0) {
            out.x = to.x;
            out.y = to.y;
            out.z = to.z;
            out.w = to.w;
            return out;
          }
          var t = Math.min(maxStep / toDegree(angle), 1.0);
          return Quat.slerp(out, from, to, t);
        };
        function Quat(x, y, z, w) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof x === 'object') {
            _this.x = x.x;
            _this.y = x.y;
            _this.z = x.z;
            _this.w = x.w;
          } else {
            _this.x = x || 0;
            _this.y = y || 0;
            _this.z = z || 0;
            _this.w = w !== null && w !== void 0 ? w : 1;
          }
          return _this;
        }
        var _proto = Quat.prototype;
        _proto.clone = function clone() {
          return new Quat(this.x, this.y, this.z, this.w);
        };
        _proto.set = function set(x, y, z, w) {
          if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
            this.z = x.z;
            this.w = x.w;
          } else {
            this.x = x || 0;
            this.y = y || 0;
            this.z = z || 0;
            this.w = w !== null && w !== void 0 ? w : 1;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) && Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z)) && Math.abs(this.w - other.w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(other.w));
        };
        _proto.strictEquals = function strictEquals(other) {
          return other && this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w;
        };
        _proto.getEulerAngles = function getEulerAngles(out) {
          return Quat.toEuler(out, this);
        };
        _proto.lerp = function lerp(to, ratio) {
          this.x += ratio * (to.x - this.x);
          this.y += ratio * (to.y - this.y);
          this.z += ratio * (to.z - this.z);
          this.w += ratio * (to.w - this.w);
          return this;
        };
        _proto.slerp = function slerp(to, ratio) {
          return Quat.slerp(this, this, to, ratio);
        };
        _proto.length = function length() {
          return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
        };
        _proto.lengthSqr = function lengthSqr() {
          return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
        };
        return Quat;
      }(ValueType));
      _class$3J = Quat;
      Quat.IDENTITY = Object.freeze(new _class$3J());
      var qt_1$1 = new Quat();
      var qt_2 = new Quat();
      var v3_1$8 = new Vec3();
      var m3_1$2 = new Mat3();
      var halfToRad = 0.5 * Math.PI / 180.0;
      CCClass.fastDefine('cc.Quat', Quat, {
        x: 0,
        y: 0,
        z: 0,
        w: 1
      });
      legacyCC.Quat = Quat;
      function quat(x, y, z, w) {
        if (x === void 0) {
          x = 0;
        }
        if (y === void 0) {
          y = 0;
        }
        if (z === void 0) {
          z = 0;
        }
        if (w === void 0) {
          w = 1;
        }
        return new Quat(x, y, z, w);
      }
      legacyCC.quat = quat;

      var _class$3I;
      var preTransforms = exports('b4', Object.freeze([Object.freeze([1, 0, 0, 1]), Object.freeze([0, 1, -1, 0]), Object.freeze([-1, 0, 0, -1]), Object.freeze([0, -1, 1, 0])]));
      var Mat4 = exports('aX', function (_ValueType) {
        _inheritsLoose(Mat4, _ValueType);
        Mat4.clone = function clone(a) {
          return new Mat4(a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, a.m08, a.m09, a.m10, a.m11, a.m12, a.m13, a.m14, a.m15);
        };
        Mat4.copy = function copy(out, a) {
          out.m00 = a.m00;
          out.m01 = a.m01;
          out.m02 = a.m02;
          out.m03 = a.m03;
          out.m04 = a.m04;
          out.m05 = a.m05;
          out.m06 = a.m06;
          out.m07 = a.m07;
          out.m08 = a.m08;
          out.m09 = a.m09;
          out.m10 = a.m10;
          out.m11 = a.m11;
          out.m12 = a.m12;
          out.m13 = a.m13;
          out.m14 = a.m14;
          out.m15 = a.m15;
          return out;
        };
        Mat4.set = function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
          out.m00 = m00;
          out.m01 = m01;
          out.m02 = m02;
          out.m03 = m03;
          out.m04 = m10;
          out.m05 = m11;
          out.m06 = m12;
          out.m07 = m13;
          out.m08 = m20;
          out.m09 = m21;
          out.m10 = m22;
          out.m11 = m23;
          out.m12 = m30;
          out.m13 = m31;
          out.m14 = m32;
          out.m15 = m33;
          return out;
        };
        Mat4.identity = function identity(out) {
          out.m00 = 1;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = 1;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = 1;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.transpose = function transpose(out, a) {
          if (out === a) {
            var a01 = a.m01;
            var a02 = a.m02;
            var a03 = a.m03;
            var a12 = a.m06;
            var a13 = a.m07;
            var a23 = a.m11;
            out.m01 = a.m04;
            out.m02 = a.m08;
            out.m03 = a.m12;
            out.m04 = a01;
            out.m06 = a.m09;
            out.m07 = a.m13;
            out.m08 = a02;
            out.m09 = a12;
            out.m11 = a.m14;
            out.m12 = a03;
            out.m13 = a13;
            out.m14 = a23;
          } else {
            out.m00 = a.m00;
            out.m01 = a.m04;
            out.m02 = a.m08;
            out.m03 = a.m12;
            out.m04 = a.m01;
            out.m05 = a.m05;
            out.m06 = a.m09;
            out.m07 = a.m13;
            out.m08 = a.m02;
            out.m09 = a.m06;
            out.m10 = a.m10;
            out.m11 = a.m14;
            out.m12 = a.m03;
            out.m13 = a.m07;
            out.m14 = a.m11;
            out.m15 = a.m15;
          }
          return out;
        };
        Mat4.invert = function invert(out, a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var a30 = a.m12;
          var a31 = a.m13;
          var a32 = a.m14;
          var a33 = a.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
          if (det === 0) {
            out.m00 = 0;
            out.m01 = 0;
            out.m02 = 0;
            out.m03 = 0;
            out.m04 = 0;
            out.m05 = 0;
            out.m06 = 0;
            out.m07 = 0;
            out.m08 = 0;
            out.m09 = 0;
            out.m10 = 0;
            out.m11 = 0;
            out.m12 = 0;
            out.m13 = 0;
            out.m14 = 0;
            out.m15 = 0;
            return out;
          }
          det = 1.0 / det;
          out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
          out.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
          out.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
          out.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det;
          out.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
          out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
          out.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
          out.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det;
          out.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
          out.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
          out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
          out.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det;
          out.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det;
          out.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det;
          out.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det;
          out.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det;
          return out;
        };
        Mat4.determinant = function determinant(a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var a30 = a.m12;
          var a31 = a.m13;
          var a32 = a.m14;
          var a33 = a.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
        };
        Mat4.multiply = function multiply(out, a, b) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var a30 = a.m12;
          var a31 = a.m13;
          var a32 = a.m14;
          var a33 = a.m15;
          var b0 = b.m00;
          var b1 = b.m01;
          var b2 = b.m02;
          var b3 = b.m03;
          out.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          out.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          out.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          out.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = b.m04;
          b1 = b.m05;
          b2 = b.m06;
          b3 = b.m07;
          out.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          out.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          out.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          out.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = b.m08;
          b1 = b.m09;
          b2 = b.m10;
          b3 = b.m11;
          out.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          out.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          out.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          out.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = b.m12;
          b1 = b.m13;
          b2 = b.m14;
          b3 = b.m15;
          out.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          out.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          out.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          out.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          return out;
        };
        Mat4.transform = function transform(out, a, v) {
          var x = v.x;
          var y = v.y;
          var z = v.z;
          if (a === out) {
            out.m12 = a.m00 * x + a.m04 * y + a.m08 * z + a.m12;
            out.m13 = a.m01 * x + a.m05 * y + a.m09 * z + a.m13;
            out.m14 = a.m02 * x + a.m06 * y + a.m10 * z + a.m14;
            out.m15 = a.m03 * x + a.m07 * y + a.m11 * z + a.m15;
          } else {
            var a00 = a.m00;
            var a01 = a.m01;
            var a02 = a.m02;
            var a03 = a.m03;
            var a10 = a.m04;
            var a11 = a.m05;
            var a12 = a.m06;
            var a13 = a.m07;
            var a20 = a.m08;
            var a21 = a.m09;
            var a22 = a.m10;
            var a23 = a.m11;
            out.m00 = a00;
            out.m01 = a01;
            out.m02 = a02;
            out.m03 = a03;
            out.m04 = a10;
            out.m05 = a11;
            out.m06 = a12;
            out.m07 = a13;
            out.m08 = a20;
            out.m09 = a21;
            out.m10 = a22;
            out.m11 = a23;
            out.m12 = a00 * x + a10 * y + a20 * z + a.m12;
            out.m13 = a01 * x + a11 * y + a21 * z + a.m13;
            out.m14 = a02 * x + a12 * y + a22 * z + a.m14;
            out.m15 = a03 * x + a13 * y + a23 * z + a.m15;
          }
          return out;
        };
        Mat4.translate = function translate(out, a, v) {
          if (a === out) {
            out.m12 += v.x;
            out.m13 += v.y;
            out.m14 += v.z;
          } else {
            out.m00 = a.m00;
            out.m01 = a.m01;
            out.m02 = a.m02;
            out.m03 = a.m03;
            out.m04 = a.m04;
            out.m05 = a.m05;
            out.m06 = a.m06;
            out.m07 = a.m07;
            out.m08 = a.m08;
            out.m09 = a.m09;
            out.m10 = a.m10;
            out.m11 = a.m11;
            out.m12 = a.m12 + v.x;
            out.m13 = a.m13 + v.y;
            out.m14 = a.m14 + v.z;
            out.m15 = a.m15;
          }
          return out;
        };
        Mat4.scale = function scale(out, a, v) {
          var x = v.x;
          var y = v.y;
          var z = v.z;
          out.m00 = a.m00 * x;
          out.m01 = a.m01 * x;
          out.m02 = a.m02 * x;
          out.m03 = a.m03 * x;
          out.m04 = a.m04 * y;
          out.m05 = a.m05 * y;
          out.m06 = a.m06 * y;
          out.m07 = a.m07 * y;
          out.m08 = a.m08 * z;
          out.m09 = a.m09 * z;
          out.m10 = a.m10 * z;
          out.m11 = a.m11 * z;
          out.m12 = a.m12;
          out.m13 = a.m13;
          out.m14 = a.m14;
          out.m15 = a.m15;
          return out;
        };
        Mat4.rotate = function rotate(out, a, rad, axis) {
          var x = axis.x;
          var y = axis.y;
          var z = axis.z;
          var len = Math.sqrt(x * x + y * y + z * z);
          if (Math.abs(len) < EPSILON$3) {
            return null;
          }
          len = 1 / len;
          x *= len;
          y *= len;
          z *= len;
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var t = 1 - c;
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var b00 = x * x * t + c;
          var b01 = y * x * t + z * s;
          var b02 = z * x * t - y * s;
          var b10 = x * y * t - z * s;
          var b11 = y * y * t + c;
          var b12 = z * y * t + x * s;
          var b20 = x * z * t + y * s;
          var b21 = y * z * t - x * s;
          var b22 = z * z * t + c;
          out.m00 = a00 * b00 + a10 * b01 + a20 * b02;
          out.m01 = a01 * b00 + a11 * b01 + a21 * b02;
          out.m02 = a02 * b00 + a12 * b01 + a22 * b02;
          out.m03 = a03 * b00 + a13 * b01 + a23 * b02;
          out.m04 = a00 * b10 + a10 * b11 + a20 * b12;
          out.m05 = a01 * b10 + a11 * b11 + a21 * b12;
          out.m06 = a02 * b10 + a12 * b11 + a22 * b12;
          out.m07 = a03 * b10 + a13 * b11 + a23 * b12;
          out.m08 = a00 * b20 + a10 * b21 + a20 * b22;
          out.m09 = a01 * b20 + a11 * b21 + a21 * b22;
          out.m10 = a02 * b20 + a12 * b21 + a22 * b22;
          out.m11 = a03 * b20 + a13 * b21 + a23 * b22;
          if (a !== out) {
            out.m12 = a.m12;
            out.m13 = a.m13;
            out.m14 = a.m14;
            out.m15 = a.m15;
          }
          return out;
        };
        Mat4.rotateX = function rotateX(out, a, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          if (a !== out) {
            out.m00 = a.m00;
            out.m01 = a.m01;
            out.m02 = a.m02;
            out.m03 = a.m03;
            out.m12 = a.m12;
            out.m13 = a.m13;
            out.m14 = a.m14;
            out.m15 = a.m15;
          }
          out.m04 = a10 * c + a20 * s;
          out.m05 = a11 * c + a21 * s;
          out.m06 = a12 * c + a22 * s;
          out.m07 = a13 * c + a23 * s;
          out.m08 = a20 * c - a10 * s;
          out.m09 = a21 * c - a11 * s;
          out.m10 = a22 * c - a12 * s;
          out.m11 = a23 * c - a13 * s;
          return out;
        };
        Mat4.rotateY = function rotateY(out, a, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          if (a !== out) {
            out.m04 = a.m04;
            out.m05 = a.m05;
            out.m06 = a.m06;
            out.m07 = a.m07;
            out.m12 = a.m12;
            out.m13 = a.m13;
            out.m14 = a.m14;
            out.m15 = a.m15;
          }
          out.m00 = a00 * c - a20 * s;
          out.m01 = a01 * c - a21 * s;
          out.m02 = a02 * c - a22 * s;
          out.m03 = a03 * c - a23 * s;
          out.m08 = a00 * s + a20 * c;
          out.m09 = a01 * s + a21 * c;
          out.m10 = a02 * s + a22 * c;
          out.m11 = a03 * s + a23 * c;
          return out;
        };
        Mat4.rotateZ = function rotateZ(out, a, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          if (a !== out) {
            out.m08 = a.m08;
            out.m09 = a.m09;
            out.m10 = a.m10;
            out.m11 = a.m11;
            out.m12 = a.m12;
            out.m13 = a.m13;
            out.m14 = a.m14;
            out.m15 = a.m15;
          }
          out.m00 = a00 * c + a10 * s;
          out.m01 = a01 * c + a11 * s;
          out.m02 = a02 * c + a12 * s;
          out.m03 = a03 * c + a13 * s;
          out.m04 = a10 * c - a00 * s;
          out.m05 = a11 * c - a01 * s;
          out.m06 = a12 * c - a02 * s;
          out.m07 = a13 * c - a03 * s;
          return out;
        };
        Mat4.fromTranslation = function fromTranslation(out, v) {
          out.m00 = 1;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = 1;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = 1;
          out.m11 = 0;
          out.m12 = v.x;
          out.m13 = v.y;
          out.m14 = v.z;
          out.m15 = 1;
          return out;
        };
        Mat4.fromScaling = function fromScaling(out, v) {
          out.m00 = v.x;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = v.y;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = v.z;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.fromRotation = function fromRotation(out, rad, axis) {
          var x = axis.x;
          var y = axis.y;
          var z = axis.z;
          var len = Math.sqrt(x * x + y * y + z * z);
          if (Math.abs(len) < EPSILON$3) {
            return null;
          }
          len = 1 / len;
          x *= len;
          y *= len;
          z *= len;
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var t = 1 - c;
          out.m00 = x * x * t + c;
          out.m01 = y * x * t + z * s;
          out.m02 = z * x * t - y * s;
          out.m03 = 0;
          out.m04 = x * y * t - z * s;
          out.m05 = y * y * t + c;
          out.m06 = z * y * t + x * s;
          out.m07 = 0;
          out.m08 = x * z * t + y * s;
          out.m09 = y * z * t - x * s;
          out.m10 = z * z * t + c;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.fromXRotation = function fromXRotation(out, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          out.m00 = 1;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = c;
          out.m06 = s;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = -s;
          out.m10 = c;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.fromYRotation = function fromYRotation(out, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          out.m00 = c;
          out.m01 = 0;
          out.m02 = -s;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = 1;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = s;
          out.m09 = 0;
          out.m10 = c;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.fromZRotation = function fromZRotation(out, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          out.m00 = c;
          out.m01 = s;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = -s;
          out.m05 = c;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = 1;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.fromRT = function fromRT(out, q, v) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          out.m00 = 1 - (yy + zz);
          out.m01 = xy + wz;
          out.m02 = xz - wy;
          out.m03 = 0;
          out.m04 = xy - wz;
          out.m05 = 1 - (xx + zz);
          out.m06 = yz + wx;
          out.m07 = 0;
          out.m08 = xz + wy;
          out.m09 = yz - wx;
          out.m10 = 1 - (xx + yy);
          out.m11 = 0;
          out.m12 = v.x;
          out.m13 = v.y;
          out.m14 = v.z;
          out.m15 = 1;
          return out;
        };
        Mat4.getTranslation = function getTranslation(out, mat) {
          out.x = mat.m12;
          out.y = mat.m13;
          out.z = mat.m14;
          return out;
        };
        Mat4.getScaling = function getScaling(out, mat) {
          var m00 = m3_1$1.m00 = mat.m00;
          var m01 = m3_1$1.m01 = mat.m01;
          var m02 = m3_1$1.m02 = mat.m02;
          var m04 = m3_1$1.m03 = mat.m04;
          var m05 = m3_1$1.m04 = mat.m05;
          var m06 = m3_1$1.m05 = mat.m06;
          var m08 = m3_1$1.m06 = mat.m08;
          var m09 = m3_1$1.m07 = mat.m09;
          var m10 = m3_1$1.m08 = mat.m10;
          out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02);
          out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06);
          out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10);
          if (Mat3.determinant(m3_1$1) < 0) {
            out.x *= -1;
          }
          return out;
        };
        Mat4.getRotation = function getRotation(out, mat) {
          var trace = mat.m00 + mat.m05 + mat.m10;
          var S = 0;
          if (trace > 0) {
            S = Math.sqrt(trace + 1.0) * 2;
            out.w = 0.25 * S;
            out.x = (mat.m06 - mat.m09) / S;
            out.y = (mat.m08 - mat.m02) / S;
            out.z = (mat.m01 - mat.m04) / S;
          } else if (mat.m00 > mat.m05 && mat.m00 > mat.m10) {
            S = Math.sqrt(1.0 + mat.m00 - mat.m05 - mat.m10) * 2;
            out.w = (mat.m06 - mat.m09) / S;
            out.x = 0.25 * S;
            out.y = (mat.m01 + mat.m04) / S;
            out.z = (mat.m08 + mat.m02) / S;
          } else if (mat.m05 > mat.m10) {
            S = Math.sqrt(1.0 + mat.m05 - mat.m00 - mat.m10) * 2;
            out.w = (mat.m08 - mat.m02) / S;
            out.x = (mat.m01 + mat.m04) / S;
            out.y = 0.25 * S;
            out.z = (mat.m06 + mat.m09) / S;
          } else {
            S = Math.sqrt(1.0 + mat.m10 - mat.m00 - mat.m05) * 2;
            out.w = (mat.m01 - mat.m04) / S;
            out.x = (mat.m08 + mat.m02) / S;
            out.y = (mat.m06 + mat.m09) / S;
            out.z = 0.25 * S;
          }
          return out;
        };
        Mat4.toRTS = function toRTS(m, q, v, s) {
          var sx = Vec3.set(v3_1$7, m.m00, m.m01, m.m02).length();
          var sy = Vec3.set(v3_1$7, m.m04, m.m05, m.m06).length();
          var sz = Vec3.set(v3_1$7, m.m08, m.m09, m.m10).length();
          m3_1$1.m00 = m.m00 / sx;
          m3_1$1.m01 = m.m01 / sx;
          m3_1$1.m02 = m.m02 / sx;
          m3_1$1.m03 = m.m04 / sy;
          m3_1$1.m04 = m.m05 / sy;
          m3_1$1.m05 = m.m06 / sy;
          m3_1$1.m06 = m.m08 / sz;
          m3_1$1.m07 = m.m09 / sz;
          m3_1$1.m08 = m.m10 / sz;
          var det = Mat3.determinant(m3_1$1);
          if (s) {
            Vec3.set(s, sx, sy, sz);
            if (det < 0) {
              s.x *= -1;
            }
          }
          if (v) {
            Vec3.set(v, m.m12, m.m13, m.m14);
          }
          if (q) {
            if (det < 0) {
              m3_1$1.m00 *= -1;
              m3_1$1.m01 *= -1;
              m3_1$1.m02 *= -1;
            }
            Quat.fromMat3(q, m3_1$1);
          }
        };
        Mat4.toSRT = function toSRT(m, q, v, s) {
          var sx = Vec3.set(v3_1$7, m.m00, m.m01, m.m02).length();
          var sy = Vec3.set(v3_1$7, m.m04, m.m05, m.m06).length();
          var sz = Vec3.set(v3_1$7, m.m08, m.m09, m.m10).length();
          if (s) {
            s.x = sx;
            s.y = sy;
            s.z = sz;
          }
          if (v) {
            Vec3.set(v, m.m12, m.m13, m.m14);
          }
          if (q) {
            m3_1$1.m00 = m.m00 / sx;
            m3_1$1.m01 = m.m01 / sx;
            m3_1$1.m02 = m.m02 / sx;
            m3_1$1.m03 = m.m04 / sy;
            m3_1$1.m04 = m.m05 / sy;
            m3_1$1.m05 = m.m06 / sy;
            m3_1$1.m06 = m.m08 / sz;
            m3_1$1.m07 = m.m09 / sz;
            m3_1$1.m08 = m.m10 / sz;
            var det = Mat3.determinant(m3_1$1);
            if (det < 0) {
              if (s) s.x *= -1;
              m3_1$1.m00 *= -1;
              m3_1$1.m01 *= -1;
              m3_1$1.m02 *= -1;
            }
            Quat.fromMat3(q, m3_1$1);
          }
        };
        Mat4.toEuler = function toEuler(m, v) {
          Mat3.set(m3_1$1, m.m00, m.m01, m.m02, m.m04, m.m05, m.m06, m.m08, m.m09, m.m10);
          return Mat3.toEuler(m3_1$1, v);
        };
        Mat4.fromRTS = function fromRTS(out, q, v, s) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          out.m00 = (1 - (yy + zz)) * sx;
          out.m01 = (xy + wz) * sx;
          out.m02 = (xz - wy) * sx;
          out.m03 = 0;
          out.m04 = (xy - wz) * sy;
          out.m05 = (1 - (xx + zz)) * sy;
          out.m06 = (yz + wx) * sy;
          out.m07 = 0;
          out.m08 = (xz + wy) * sz;
          out.m09 = (yz - wx) * sz;
          out.m10 = (1 - (xx + yy)) * sz;
          out.m11 = 0;
          out.m12 = v.x;
          out.m13 = v.y;
          out.m14 = v.z;
          out.m15 = 1;
          return out;
        };
        Mat4.fromSRT = function fromSRT(out, q, v, s) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          out.m00 = (1 - (yy + zz)) * sx;
          out.m01 = (xy + wz) * sx;
          out.m02 = (xz - wy) * sx;
          out.m03 = 0;
          out.m04 = (xy - wz) * sy;
          out.m05 = (1 - (xx + zz)) * sy;
          out.m06 = (yz + wx) * sy;
          out.m07 = 0;
          out.m08 = (xz + wy) * sz;
          out.m09 = (yz - wx) * sz;
          out.m10 = (1 - (xx + yy)) * sz;
          out.m11 = 0;
          out.m12 = v.x;
          out.m13 = v.y;
          out.m14 = v.z;
          out.m15 = 1;
          return out;
        };
        Mat4.fromRTSOrigin = function fromRTSOrigin(out, q, v, s, o) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          var ox = o.x;
          var oy = o.y;
          var oz = o.z;
          out.m00 = (1 - (yy + zz)) * sx;
          out.m01 = (xy + wz) * sx;
          out.m02 = (xz - wy) * sx;
          out.m03 = 0;
          out.m04 = (xy - wz) * sy;
          out.m05 = (1 - (xx + zz)) * sy;
          out.m06 = (yz + wx) * sy;
          out.m07 = 0;
          out.m08 = (xz + wy) * sz;
          out.m09 = (yz - wx) * sz;
          out.m10 = (1 - (xx + yy)) * sz;
          out.m11 = 0;
          out.m12 = v.x + ox - (out.m00 * ox + out.m04 * oy + out.m08 * oz);
          out.m13 = v.y + oy - (out.m01 * ox + out.m05 * oy + out.m09 * oz);
          out.m14 = v.z + oz - (out.m02 * ox + out.m06 * oy + out.m10 * oz);
          out.m15 = 1;
          return out;
        };
        Mat4.fromSRTOrigin = function fromSRTOrigin(out, q, v, s, o) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          var ox = o.x;
          var oy = o.y;
          var oz = o.z;
          out.m00 = (1 - (yy + zz)) * sx;
          out.m01 = (xy + wz) * sx;
          out.m02 = (xz - wy) * sx;
          out.m03 = 0;
          out.m04 = (xy - wz) * sy;
          out.m05 = (1 - (xx + zz)) * sy;
          out.m06 = (yz + wx) * sy;
          out.m07 = 0;
          out.m08 = (xz + wy) * sz;
          out.m09 = (yz - wx) * sz;
          out.m10 = (1 - (xx + yy)) * sz;
          out.m11 = 0;
          out.m12 = v.x + ox - (out.m00 * ox + out.m04 * oy + out.m08 * oz);
          out.m13 = v.y + oy - (out.m01 * ox + out.m05 * oy + out.m09 * oz);
          out.m14 = v.z + oz - (out.m02 * ox + out.m06 * oy + out.m10 * oz);
          out.m15 = 1;
          return out;
        };
        Mat4.fromQuat = function fromQuat(out, q) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var yx = y * x2;
          var yy = y * y2;
          var zx = z * x2;
          var zy = z * y2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          out.m00 = 1 - yy - zz;
          out.m01 = yx + wz;
          out.m02 = zx - wy;
          out.m03 = 0;
          out.m04 = yx - wz;
          out.m05 = 1 - xx - zz;
          out.m06 = zy + wx;
          out.m07 = 0;
          out.m08 = zx + wy;
          out.m09 = zy - wx;
          out.m10 = 1 - xx - yy;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.frustum = function frustum(out, left, right, bottom, top, near, far) {
          var rl = 1 / (right - left);
          var tb = 1 / (top - bottom);
          var nf = 1 / (near - far);
          out.m00 = near * 2 * rl;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = near * 2 * tb;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = (right + left) * rl;
          out.m09 = (top + bottom) * tb;
          out.m10 = (far + near) * nf;
          out.m11 = -1;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = far * near * 2 * nf;
          out.m15 = 0;
          return out;
        };
        Mat4.perspective = function perspective(out, fov, aspect, near, far, isFOVY, minClipZ, projectionSignY, orientation) {
          if (isFOVY === void 0) {
            isFOVY = true;
          }
          if (minClipZ === void 0) {
            minClipZ = -1;
          }
          if (projectionSignY === void 0) {
            projectionSignY = 1;
          }
          if (orientation === void 0) {
            orientation = 0;
          }
          var f = 1.0 / Math.tan(fov / 2);
          var nf = 1 / (near - far);
          var x = isFOVY ? f / aspect : f;
          var y = (isFOVY ? f : f * aspect) * projectionSignY;
          var preTransform = preTransforms[orientation];
          out.m00 = x * preTransform[0];
          out.m01 = x * preTransform[1];
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = y * preTransform[2];
          out.m05 = y * preTransform[3];
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = (far - minClipZ * near) * nf;
          out.m11 = -1;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = far * near * nf * (1 - minClipZ);
          out.m15 = 0;
          return out;
        };
        Mat4.ortho = function ortho(out, left, right, bottom, top, near, far, minClipZ, projectionSignY, orientation) {
          if (minClipZ === void 0) {
            minClipZ = -1;
          }
          if (projectionSignY === void 0) {
            projectionSignY = 1;
          }
          if (orientation === void 0) {
            orientation = 0;
          }
          var lr = 1 / (left - right);
          var bt = 1 / (bottom - top) * projectionSignY;
          var nf = 1 / (near - far);
          var x = -2 * lr;
          var y = -2 * bt;
          var dx = (left + right) * lr;
          var dy = (top + bottom) * bt;
          var preTransform = preTransforms[orientation];
          out.m00 = x * preTransform[0];
          out.m01 = x * preTransform[1];
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = y * preTransform[2];
          out.m05 = y * preTransform[3];
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = nf * (1 - minClipZ);
          out.m11 = 0;
          out.m12 = dx * preTransform[0] + dy * preTransform[2];
          out.m13 = dx * preTransform[1] + dy * preTransform[3];
          out.m14 = (near - minClipZ * far) * nf;
          out.m15 = 1;
          return out;
        };
        Mat4.lookAt = function lookAt(out, eye, center, up) {
          var eyex = eye.x;
          var eyey = eye.y;
          var eyez = eye.z;
          var upx = up.x;
          var upy = up.y;
          var upz = up.z;
          var centerx = center.x;
          var centery = center.y;
          var centerz = center.z;
          var z0 = eyex - centerx;
          var z1 = eyey - centery;
          var z2 = eyez - centerz;
          var len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
          z0 *= len;
          z1 *= len;
          z2 *= len;
          var x0 = upy * z2 - upz * z1;
          var x1 = upz * z0 - upx * z2;
          var x2 = upx * z1 - upy * z0;
          len = 1 / Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
          x0 *= len;
          x1 *= len;
          x2 *= len;
          var y0 = z1 * x2 - z2 * x1;
          var y1 = z2 * x0 - z0 * x2;
          var y2 = z0 * x1 - z1 * x0;
          out.m00 = x0;
          out.m01 = y0;
          out.m02 = z0;
          out.m03 = 0;
          out.m04 = x1;
          out.m05 = y1;
          out.m06 = z1;
          out.m07 = 0;
          out.m08 = x2;
          out.m09 = y2;
          out.m10 = z2;
          out.m11 = 0;
          out.m12 = -(x0 * eyex + x1 * eyey + x2 * eyez);
          out.m13 = -(y0 * eyex + y1 * eyey + y2 * eyez);
          out.m14 = -(z0 * eyex + z1 * eyey + z2 * eyez);
          out.m15 = 1;
          return out;
        };
        Mat4.inverseTranspose = function inverseTranspose(out, a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var a30 = a.m12;
          var a31 = a.m13;
          var a32 = a.m14;
          var a33 = a.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
          if (!det) {
            return null;
          }
          det = 1.0 / det;
          out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
          out.m01 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
          out.m02 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
          out.m03 = 0;
          out.m04 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
          out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
          out.m06 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
          out.m07 = 0;
          out.m08 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
          out.m09 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
          out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.toArray = function toArray(out, m, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = m.m00;
          out[ofs + 1] = m.m01;
          out[ofs + 2] = m.m02;
          out[ofs + 3] = m.m03;
          out[ofs + 4] = m.m04;
          out[ofs + 5] = m.m05;
          out[ofs + 6] = m.m06;
          out[ofs + 7] = m.m07;
          out[ofs + 8] = m.m08;
          out[ofs + 9] = m.m09;
          out[ofs + 10] = m.m10;
          out[ofs + 11] = m.m11;
          out[ofs + 12] = m.m12;
          out[ofs + 13] = m.m13;
          out[ofs + 14] = m.m14;
          out[ofs + 15] = m.m15;
          return out;
        };
        Mat4.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.m00 = arr[ofs + 0];
          out.m01 = arr[ofs + 1];
          out.m02 = arr[ofs + 2];
          out.m03 = arr[ofs + 3];
          out.m04 = arr[ofs + 4];
          out.m05 = arr[ofs + 5];
          out.m06 = arr[ofs + 6];
          out.m07 = arr[ofs + 7];
          out.m08 = arr[ofs + 8];
          out.m09 = arr[ofs + 9];
          out.m10 = arr[ofs + 10];
          out.m11 = arr[ofs + 11];
          out.m12 = arr[ofs + 12];
          out.m13 = arr[ofs + 13];
          out.m14 = arr[ofs + 14];
          out.m15 = arr[ofs + 15];
          return out;
        };
        Mat4.add = function add(out, a, b) {
          out.m00 = a.m00 + b.m00;
          out.m01 = a.m01 + b.m01;
          out.m02 = a.m02 + b.m02;
          out.m03 = a.m03 + b.m03;
          out.m04 = a.m04 + b.m04;
          out.m05 = a.m05 + b.m05;
          out.m06 = a.m06 + b.m06;
          out.m07 = a.m07 + b.m07;
          out.m08 = a.m08 + b.m08;
          out.m09 = a.m09 + b.m09;
          out.m10 = a.m10 + b.m10;
          out.m11 = a.m11 + b.m11;
          out.m12 = a.m12 + b.m12;
          out.m13 = a.m13 + b.m13;
          out.m14 = a.m14 + b.m14;
          out.m15 = a.m15 + b.m15;
          return out;
        };
        Mat4.subtract = function subtract(out, a, b) {
          out.m00 = a.m00 - b.m00;
          out.m01 = a.m01 - b.m01;
          out.m02 = a.m02 - b.m02;
          out.m03 = a.m03 - b.m03;
          out.m04 = a.m04 - b.m04;
          out.m05 = a.m05 - b.m05;
          out.m06 = a.m06 - b.m06;
          out.m07 = a.m07 - b.m07;
          out.m08 = a.m08 - b.m08;
          out.m09 = a.m09 - b.m09;
          out.m10 = a.m10 - b.m10;
          out.m11 = a.m11 - b.m11;
          out.m12 = a.m12 - b.m12;
          out.m13 = a.m13 - b.m13;
          out.m14 = a.m14 - b.m14;
          out.m15 = a.m15 - b.m15;
          return out;
        };
        Mat4.multiplyScalar = function multiplyScalar(out, a, b) {
          out.m00 = a.m00 * b;
          out.m01 = a.m01 * b;
          out.m02 = a.m02 * b;
          out.m03 = a.m03 * b;
          out.m04 = a.m04 * b;
          out.m05 = a.m05 * b;
          out.m06 = a.m06 * b;
          out.m07 = a.m07 * b;
          out.m08 = a.m08 * b;
          out.m09 = a.m09 * b;
          out.m10 = a.m10 * b;
          out.m11 = a.m11 * b;
          out.m12 = a.m12 * b;
          out.m13 = a.m13 * b;
          out.m14 = a.m14 * b;
          out.m15 = a.m15 * b;
          return out;
        };
        Mat4.multiplyScalarAndAdd = function multiplyScalarAndAdd(out, a, b, scale) {
          out.m00 = a.m00 + b.m00 * scale;
          out.m01 = a.m01 + b.m01 * scale;
          out.m02 = a.m02 + b.m02 * scale;
          out.m03 = a.m03 + b.m03 * scale;
          out.m04 = a.m04 + b.m04 * scale;
          out.m05 = a.m05 + b.m05 * scale;
          out.m06 = a.m06 + b.m06 * scale;
          out.m07 = a.m07 + b.m07 * scale;
          out.m08 = a.m08 + b.m08 * scale;
          out.m09 = a.m09 + b.m09 * scale;
          out.m10 = a.m10 + b.m10 * scale;
          out.m11 = a.m11 + b.m11 * scale;
          out.m12 = a.m12 + b.m12 * scale;
          out.m13 = a.m13 + b.m13 * scale;
          out.m14 = a.m14 + b.m14 * scale;
          out.m15 = a.m15 + b.m15 * scale;
          return out;
        };
        Mat4.strictEquals = function strictEquals(a, b) {
          return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08 && a.m09 === b.m09 && a.m10 === b.m10 && a.m11 === b.m11 && a.m12 === b.m12 && a.m13 === b.m13 && a.m14 === b.m14 && a.m15 === b.m15;
        };
        Mat4.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(a.m00 - b.m00) <= epsilon * Math.max(1.0, Math.abs(a.m00), Math.abs(b.m00)) && Math.abs(a.m01 - b.m01) <= epsilon * Math.max(1.0, Math.abs(a.m01), Math.abs(b.m01)) && Math.abs(a.m02 - b.m02) <= epsilon * Math.max(1.0, Math.abs(a.m02), Math.abs(b.m02)) && Math.abs(a.m03 - b.m03) <= epsilon * Math.max(1.0, Math.abs(a.m03), Math.abs(b.m03)) && Math.abs(a.m04 - b.m04) <= epsilon * Math.max(1.0, Math.abs(a.m04), Math.abs(b.m04)) && Math.abs(a.m05 - b.m05) <= epsilon * Math.max(1.0, Math.abs(a.m05), Math.abs(b.m05)) && Math.abs(a.m06 - b.m06) <= epsilon * Math.max(1.0, Math.abs(a.m06), Math.abs(b.m06)) && Math.abs(a.m07 - b.m07) <= epsilon * Math.max(1.0, Math.abs(a.m07), Math.abs(b.m07)) && Math.abs(a.m08 - b.m08) <= epsilon * Math.max(1.0, Math.abs(a.m08), Math.abs(b.m08)) && Math.abs(a.m09 - b.m09) <= epsilon * Math.max(1.0, Math.abs(a.m09), Math.abs(b.m09)) && Math.abs(a.m10 - b.m10) <= epsilon * Math.max(1.0, Math.abs(a.m10), Math.abs(b.m10)) && Math.abs(a.m11 - b.m11) <= epsilon * Math.max(1.0, Math.abs(a.m11), Math.abs(b.m11)) && Math.abs(a.m12 - b.m12) <= epsilon * Math.max(1.0, Math.abs(a.m12), Math.abs(b.m12)) && Math.abs(a.m13 - b.m13) <= epsilon * Math.max(1.0, Math.abs(a.m13), Math.abs(b.m13)) && Math.abs(a.m14 - b.m14) <= epsilon * Math.max(1.0, Math.abs(a.m14), Math.abs(b.m14)) && Math.abs(a.m15 - b.m15) <= epsilon * Math.max(1.0, Math.abs(a.m15), Math.abs(b.m15));
        };
        function Mat4(m00, m01, m02, m03, m04, m05, m06, m07, m08, m09, m10, m11, m12, m13, m14, m15) {
          var _this;
          if (m00 === void 0) {
            m00 = 1;
          }
          if (m01 === void 0) {
            m01 = 0;
          }
          if (m02 === void 0) {
            m02 = 0;
          }
          if (m03 === void 0) {
            m03 = 0;
          }
          if (m04 === void 0) {
            m04 = 0;
          }
          if (m05 === void 0) {
            m05 = 1;
          }
          if (m06 === void 0) {
            m06 = 0;
          }
          if (m07 === void 0) {
            m07 = 0;
          }
          if (m08 === void 0) {
            m08 = 0;
          }
          if (m09 === void 0) {
            m09 = 0;
          }
          if (m10 === void 0) {
            m10 = 1;
          }
          if (m11 === void 0) {
            m11 = 0;
          }
          if (m12 === void 0) {
            m12 = 0;
          }
          if (m13 === void 0) {
            m13 = 0;
          }
          if (m14 === void 0) {
            m14 = 0;
          }
          if (m15 === void 0) {
            m15 = 1;
          }
          _this = _ValueType.call(this) || this;
          if (typeof m00 === 'object') {
            _this.m00 = m00.m00;
            _this.m01 = m00.m01;
            _this.m02 = m00.m02;
            _this.m03 = m00.m03;
            _this.m04 = m00.m04;
            _this.m05 = m00.m05;
            _this.m06 = m00.m06;
            _this.m07 = m00.m07;
            _this.m08 = m00.m08;
            _this.m09 = m00.m09;
            _this.m10 = m00.m10;
            _this.m11 = m00.m11;
            _this.m12 = m00.m12;
            _this.m13 = m00.m13;
            _this.m14 = m00.m14;
            _this.m15 = m00.m15;
          } else {
            _this.m00 = m00;
            _this.m01 = m01;
            _this.m02 = m02;
            _this.m03 = m03;
            _this.m04 = m04;
            _this.m05 = m05;
            _this.m06 = m06;
            _this.m07 = m07;
            _this.m08 = m08;
            _this.m09 = m09;
            _this.m10 = m10;
            _this.m11 = m11;
            _this.m12 = m12;
            _this.m13 = m13;
            _this.m14 = m14;
            _this.m15 = m15;
          }
          return _this;
        }
        var _proto = Mat4.prototype;
        _proto.clone = function clone() {
          return new Mat4(this.m00, this.m01, this.m02, this.m03, this.m04, this.m05, this.m06, this.m07, this.m08, this.m09, this.m10, this.m11, this.m12, this.m13, this.m14, this.m15);
        };
        _proto.set = function set(m00, m01, m02, m03, m04, m05, m06, m07, m08, m09, m10, m11, m12, m13, m14, m15) {
          if (m00 === void 0) {
            m00 = 1;
          }
          if (m01 === void 0) {
            m01 = 0;
          }
          if (m02 === void 0) {
            m02 = 0;
          }
          if (m03 === void 0) {
            m03 = 0;
          }
          if (m04 === void 0) {
            m04 = 0;
          }
          if (m05 === void 0) {
            m05 = 1;
          }
          if (m06 === void 0) {
            m06 = 0;
          }
          if (m07 === void 0) {
            m07 = 0;
          }
          if (m08 === void 0) {
            m08 = 0;
          }
          if (m09 === void 0) {
            m09 = 0;
          }
          if (m10 === void 0) {
            m10 = 1;
          }
          if (m11 === void 0) {
            m11 = 0;
          }
          if (m12 === void 0) {
            m12 = 0;
          }
          if (m13 === void 0) {
            m13 = 0;
          }
          if (m14 === void 0) {
            m14 = 0;
          }
          if (m15 === void 0) {
            m15 = 1;
          }
          if (typeof m00 === 'object') {
            this.m01 = m00.m01;
            this.m02 = m00.m02;
            this.m03 = m00.m03;
            this.m04 = m00.m04;
            this.m05 = m00.m05;
            this.m06 = m00.m06;
            this.m07 = m00.m07;
            this.m08 = m00.m08;
            this.m09 = m00.m09;
            this.m10 = m00.m10;
            this.m11 = m00.m11;
            this.m12 = m00.m12;
            this.m13 = m00.m13;
            this.m14 = m00.m14;
            this.m15 = m00.m15;
            this.m00 = m00.m00;
          } else {
            this.m01 = m01;
            this.m02 = m02;
            this.m03 = m03;
            this.m04 = m04;
            this.m05 = m05;
            this.m06 = m06;
            this.m07 = m07;
            this.m08 = m08;
            this.m09 = m09;
            this.m10 = m10;
            this.m11 = m11;
            this.m12 = m12;
            this.m13 = m13;
            this.m14 = m14;
            this.m15 = m15;
            this.m00 = m00;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          var hasInf = Math.abs(this.m00) === Infinity || Math.abs(this.m01) === Infinity || Math.abs(this.m02) === Infinity || Math.abs(this.m03) === Infinity || Math.abs(this.m04) === Infinity || Math.abs(this.m05) === Infinity || Math.abs(this.m06) === Infinity || Math.abs(this.m07) === Infinity || Math.abs(this.m08) === Infinity || Math.abs(this.m09) === Infinity || Math.abs(this.m10) === Infinity || Math.abs(this.m11) === Infinity || Math.abs(this.m12) === Infinity || Math.abs(this.m13) === Infinity || Math.abs(this.m14) === Infinity || Math.abs(this.m15) === Infinity;
          return !hasInf && Math.abs(this.m00 - other.m00) <= epsilon * Math.max(1.0, Math.abs(this.m00), Math.abs(other.m00)) && Math.abs(this.m01 - other.m01) <= epsilon * Math.max(1.0, Math.abs(this.m01), Math.abs(other.m01)) && Math.abs(this.m02 - other.m02) <= epsilon * Math.max(1.0, Math.abs(this.m02), Math.abs(other.m02)) && Math.abs(this.m03 - other.m03) <= epsilon * Math.max(1.0, Math.abs(this.m03), Math.abs(other.m03)) && Math.abs(this.m04 - other.m04) <= epsilon * Math.max(1.0, Math.abs(this.m04), Math.abs(other.m04)) && Math.abs(this.m05 - other.m05) <= epsilon * Math.max(1.0, Math.abs(this.m05), Math.abs(other.m05)) && Math.abs(this.m06 - other.m06) <= epsilon * Math.max(1.0, Math.abs(this.m06), Math.abs(other.m06)) && Math.abs(this.m07 - other.m07) <= epsilon * Math.max(1.0, Math.abs(this.m07), Math.abs(other.m07)) && Math.abs(this.m08 - other.m08) <= epsilon * Math.max(1.0, Math.abs(this.m08), Math.abs(other.m08)) && Math.abs(this.m09 - other.m09) <= epsilon * Math.max(1.0, Math.abs(this.m09), Math.abs(other.m09)) && Math.abs(this.m10 - other.m10) <= epsilon * Math.max(1.0, Math.abs(this.m10), Math.abs(other.m10)) && Math.abs(this.m11 - other.m11) <= epsilon * Math.max(1.0, Math.abs(this.m11), Math.abs(other.m11)) && Math.abs(this.m12 - other.m12) <= epsilon * Math.max(1.0, Math.abs(this.m12), Math.abs(other.m12)) && Math.abs(this.m13 - other.m13) <= epsilon * Math.max(1.0, Math.abs(this.m13), Math.abs(other.m13)) && Math.abs(this.m14 - other.m14) <= epsilon * Math.max(1.0, Math.abs(this.m14), Math.abs(other.m14)) && Math.abs(this.m15 - other.m15) <= epsilon * Math.max(1.0, Math.abs(this.m15), Math.abs(other.m15));
        };
        _proto.strictEquals = function strictEquals(other) {
          return this.m00 === other.m00 && this.m01 === other.m01 && this.m02 === other.m02 && this.m03 === other.m03 && this.m04 === other.m04 && this.m05 === other.m05 && this.m06 === other.m06 && this.m07 === other.m07 && this.m08 === other.m08 && this.m09 === other.m09 && this.m10 === other.m10 && this.m11 === other.m11 && this.m12 === other.m12 && this.m13 === other.m13 && this.m14 === other.m14 && this.m15 === other.m15;
        };
        _proto.toString = function toString() {
          return "[\n" + this.m00 + ", " + this.m01 + ", " + this.m02 + ", " + this.m03 + ",\n" + this.m04 + ", " + this.m05 + ", " + this.m06 + ", " + this.m07 + ",\n" + this.m08 + ", " + this.m09 + ", " + this.m10 + ", " + this.m11 + ",\n" + this.m12 + ", " + this.m13 + ", " + this.m14 + ", " + this.m15 + "\n" + ']';
        };
        _proto.identity = function identity() {
          this.m00 = 1;
          this.m01 = 0;
          this.m02 = 0;
          this.m03 = 0;
          this.m04 = 0;
          this.m05 = 1;
          this.m06 = 0;
          this.m07 = 0;
          this.m08 = 0;
          this.m09 = 0;
          this.m10 = 1;
          this.m11 = 0;
          this.m12 = 0;
          this.m13 = 0;
          this.m14 = 0;
          this.m15 = 1;
          return this;
        };
        _proto.zero = function zero() {
          this.m00 = 0;
          this.m01 = 0;
          this.m02 = 0;
          this.m03 = 0;
          this.m04 = 0;
          this.m05 = 0;
          this.m06 = 0;
          this.m07 = 0;
          this.m08 = 0;
          this.m09 = 0;
          this.m10 = 0;
          this.m11 = 0;
          this.m12 = 0;
          this.m13 = 0;
          this.m14 = 0;
          this.m15 = 0;
          return this;
        };
        _proto.transpose = function transpose() {
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a12 = this.m06;
          var a13 = this.m07;
          var a23 = this.m11;
          this.m01 = this.m04;
          this.m02 = this.m08;
          this.m03 = this.m12;
          this.m04 = a01;
          this.m06 = this.m09;
          this.m07 = this.m13;
          this.m08 = a02;
          this.m09 = a12;
          this.m11 = this.m14;
          this.m12 = a03;
          this.m13 = a13;
          this.m14 = a23;
          return this;
        };
        _proto.invert = function invert() {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a10 = this.m04;
          var a11 = this.m05;
          var a12 = this.m06;
          var a13 = this.m07;
          var a20 = this.m08;
          var a21 = this.m09;
          var a22 = this.m10;
          var a23 = this.m11;
          var a30 = this.m12;
          var a31 = this.m13;
          var a32 = this.m14;
          var a33 = this.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
          if (det === 0) {
            this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
            return this;
          }
          det = 1.0 / det;
          this.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
          this.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
          this.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
          this.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det;
          this.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
          this.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
          this.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
          this.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det;
          this.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
          this.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
          this.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
          this.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det;
          this.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det;
          this.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det;
          this.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det;
          this.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det;
          return this;
        };
        _proto.determinant = function determinant() {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a10 = this.m04;
          var a11 = this.m05;
          var a12 = this.m06;
          var a13 = this.m07;
          var a20 = this.m08;
          var a21 = this.m09;
          var a22 = this.m10;
          var a23 = this.m11;
          var a30 = this.m12;
          var a31 = this.m13;
          var a32 = this.m14;
          var a33 = this.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
        };
        _proto.add = function add(mat) {
          this.m00 += mat.m00;
          this.m01 += mat.m01;
          this.m02 += mat.m02;
          this.m03 += mat.m03;
          this.m04 += mat.m04;
          this.m05 += mat.m05;
          this.m06 += mat.m06;
          this.m07 += mat.m07;
          this.m08 += mat.m08;
          this.m09 += mat.m09;
          this.m10 += mat.m10;
          this.m11 += mat.m11;
          this.m12 += mat.m12;
          this.m13 += mat.m13;
          this.m14 += mat.m14;
          this.m15 += mat.m15;
          return this;
        };
        _proto.subtract = function subtract(mat) {
          this.m00 -= mat.m00;
          this.m01 -= mat.m01;
          this.m02 -= mat.m02;
          this.m03 -= mat.m03;
          this.m04 -= mat.m04;
          this.m05 -= mat.m05;
          this.m06 -= mat.m06;
          this.m07 -= mat.m07;
          this.m08 -= mat.m08;
          this.m09 -= mat.m09;
          this.m10 -= mat.m10;
          this.m11 -= mat.m11;
          this.m12 -= mat.m12;
          this.m13 -= mat.m13;
          this.m14 -= mat.m14;
          this.m15 -= mat.m15;
          return this;
        };
        _proto.multiply = function multiply(mat) {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a10 = this.m04;
          var a11 = this.m05;
          var a12 = this.m06;
          var a13 = this.m07;
          var a20 = this.m08;
          var a21 = this.m09;
          var a22 = this.m10;
          var a23 = this.m11;
          var a30 = this.m12;
          var a31 = this.m13;
          var a32 = this.m14;
          var a33 = this.m15;
          var b0 = mat.m00;
          var b1 = mat.m01;
          var b2 = mat.m02;
          var b3 = mat.m03;
          this.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          this.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          this.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          this.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = mat.m04;
          b1 = mat.m05;
          b2 = mat.m06;
          b3 = mat.m07;
          this.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          this.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          this.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          this.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = mat.m08;
          b1 = mat.m09;
          b2 = mat.m10;
          b3 = mat.m11;
          this.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          this.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          this.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          this.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = mat.m12;
          b1 = mat.m13;
          b2 = mat.m14;
          b3 = mat.m15;
          this.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          this.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          this.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          this.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          return this;
        };
        _proto.multiplyScalar = function multiplyScalar(scalar) {
          this.m00 *= scalar;
          this.m01 *= scalar;
          this.m02 *= scalar;
          this.m03 *= scalar;
          this.m04 *= scalar;
          this.m05 *= scalar;
          this.m06 *= scalar;
          this.m07 *= scalar;
          this.m08 *= scalar;
          this.m09 *= scalar;
          this.m10 *= scalar;
          this.m11 *= scalar;
          this.m12 *= scalar;
          this.m13 *= scalar;
          this.m14 *= scalar;
          this.m15 *= scalar;
          return this;
        };
        _proto.translate = function translate(vec) {
          this.m12 += vec.x;
          this.m13 += vec.y;
          this.m14 += vec.z;
          return this;
        };
        _proto.transform = function transform(vec) {
          var x = vec.x,
            y = vec.y,
            z = vec.z;
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a10 = this.m04;
          var a11 = this.m05;
          var a12 = this.m06;
          var a13 = this.m07;
          var a20 = this.m08;
          var a21 = this.m09;
          var a22 = this.m10;
          var a23 = this.m11;
          this.m12 = a00 * x + a10 * y + a20 * z + this.m12;
          this.m13 = a01 * x + a11 * y + a21 * z + this.m13;
          this.m14 = a02 * x + a12 * y + a22 * z + this.m14;
          this.m15 = a03 * x + a13 * y + a23 * z + this.m15;
          return this;
        };
        _proto.scale = function scale(vec) {
          var x = vec.x;
          var y = vec.y;
          var z = vec.z;
          this.m00 *= x;
          this.m01 *= x;
          this.m02 *= x;
          this.m03 *= x;
          this.m04 *= y;
          this.m05 *= y;
          this.m06 *= y;
          this.m07 *= y;
          this.m08 *= z;
          this.m09 *= z;
          this.m10 *= z;
          this.m11 *= z;
          return this;
        };
        _proto.rotate = function rotate(rad, axis) {
          var x = axis.x;
          var y = axis.y;
          var z = axis.z;
          var len = Math.sqrt(x * x + y * y + z * z);
          if (Math.abs(len) < EPSILON$3) {
            return null;
          }
          len = 1 / len;
          x *= len;
          y *= len;
          z *= len;
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var t = 1 - c;
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a10 = this.m04;
          var a11 = this.m05;
          var a12 = this.m06;
          var a13 = this.m07;
          var a20 = this.m08;
          var a21 = this.m09;
          var a22 = this.m10;
          var a23 = this.m11;
          var b00 = x * x * t + c;
          var b01 = y * x * t + z * s;
          var b02 = z * x * t - y * s;
          var b10 = x * y * t - z * s;
          var b11 = y * y * t + c;
          var b12 = z * y * t + x * s;
          var b20 = x * z * t + y * s;
          var b21 = y * z * t - x * s;
          var b22 = z * z * t + c;
          this.m00 = a00 * b00 + a10 * b01 + a20 * b02;
          this.m01 = a01 * b00 + a11 * b01 + a21 * b02;
          this.m02 = a02 * b00 + a12 * b01 + a22 * b02;
          this.m03 = a03 * b00 + a13 * b01 + a23 * b02;
          this.m04 = a00 * b10 + a10 * b11 + a20 * b12;
          this.m05 = a01 * b10 + a11 * b11 + a21 * b12;
          this.m06 = a02 * b10 + a12 * b11 + a22 * b12;
          this.m07 = a03 * b10 + a13 * b11 + a23 * b12;
          this.m08 = a00 * b20 + a10 * b21 + a20 * b22;
          this.m09 = a01 * b20 + a11 * b21 + a21 * b22;
          this.m10 = a02 * b20 + a12 * b21 + a22 * b22;
          this.m11 = a03 * b20 + a13 * b21 + a23 * b22;
          return this;
        };
        _proto.getTranslation = function getTranslation(out) {
          out.x = this.m12;
          out.y = this.m13;
          out.z = this.m14;
          return out;
        };
        _proto.getScale = function getScale(out) {
          var m00 = m3_1$1.m00 = this.m00;
          var m01 = m3_1$1.m01 = this.m01;
          var m02 = m3_1$1.m02 = this.m02;
          var m04 = m3_1$1.m03 = this.m04;
          var m05 = m3_1$1.m04 = this.m05;
          var m06 = m3_1$1.m05 = this.m06;
          var m08 = m3_1$1.m06 = this.m08;
          var m09 = m3_1$1.m07 = this.m09;
          var m10 = m3_1$1.m08 = this.m10;
          out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02);
          out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06);
          out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10);
          if (Mat3.determinant(m3_1$1) < 0) {
            out.x *= -1;
          }
          return out;
        };
        _proto.getRotation = function getRotation(out) {
          var sx = Vec3.set(v3_1$7, this.m00, this.m01, this.m02).length();
          var sy = Vec3.set(v3_1$7, this.m04, this.m05, this.m06).length();
          var sz = Vec3.set(v3_1$7, this.m08, this.m09, this.m10).length();
          m3_1$1.m00 = this.m00 / sx;
          m3_1$1.m01 = this.m01 / sx;
          m3_1$1.m02 = this.m02 / sx;
          m3_1$1.m03 = this.m04 / sy;
          m3_1$1.m04 = this.m05 / sy;
          m3_1$1.m05 = this.m06 / sy;
          m3_1$1.m06 = this.m08 / sz;
          m3_1$1.m07 = this.m09 / sz;
          m3_1$1.m08 = this.m10 / sz;
          var det = Mat3.determinant(m3_1$1);
          if (det < 0) {
            m3_1$1.m00 *= -1;
            m3_1$1.m01 *= -1;
            m3_1$1.m02 *= -1;
          }
          return Quat.fromMat3(out, m3_1$1);
        };
        _proto.fromRTS = function fromRTS(q, v, s) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          this.m00 = (1 - (yy + zz)) * sx;
          this.m01 = (xy + wz) * sx;
          this.m02 = (xz - wy) * sx;
          this.m03 = 0;
          this.m04 = (xy - wz) * sy;
          this.m05 = (1 - (xx + zz)) * sy;
          this.m06 = (yz + wx) * sy;
          this.m07 = 0;
          this.m08 = (xz + wy) * sz;
          this.m09 = (yz - wx) * sz;
          this.m10 = (1 - (xx + yy)) * sz;
          this.m11 = 0;
          this.m12 = v.x;
          this.m13 = v.y;
          this.m14 = v.z;
          this.m15 = 1;
          return this;
        };
        _proto.fromSRT = function fromSRT(q, v, s) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          this.m00 = (1 - (yy + zz)) * sx;
          this.m01 = (xy + wz) * sx;
          this.m02 = (xz - wy) * sx;
          this.m03 = 0;
          this.m04 = (xy - wz) * sy;
          this.m05 = (1 - (xx + zz)) * sy;
          this.m06 = (yz + wx) * sy;
          this.m07 = 0;
          this.m08 = (xz + wy) * sz;
          this.m09 = (yz - wx) * sz;
          this.m10 = (1 - (xx + yy)) * sz;
          this.m11 = 0;
          this.m12 = v.x;
          this.m13 = v.y;
          this.m14 = v.z;
          this.m15 = 1;
          return this;
        };
        _proto.fromQuat = function fromQuat(q) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var yx = y * x2;
          var yy = y * y2;
          var zx = z * x2;
          var zy = z * y2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          this.m00 = 1 - yy - zz;
          this.m01 = yx + wz;
          this.m02 = zx - wy;
          this.m03 = 0;
          this.m04 = yx - wz;
          this.m05 = 1 - xx - zz;
          this.m06 = zy + wx;
          this.m07 = 0;
          this.m08 = zx + wy;
          this.m09 = zy - wx;
          this.m10 = 1 - xx - yy;
          this.m11 = 0;
          this.m12 = 0;
          this.m13 = 0;
          this.m14 = 0;
          this.m15 = 1;
          return this;
        };
        return Mat4;
      }(ValueType));
      _class$3I = Mat4;
      Mat4.IDENTITY = Object.freeze(new _class$3I());
      var v3_1$7 = new Vec3();
      var m3_1$1 = new Mat3();
      CCClass.fastDefine('cc.Mat4', Mat4, {
        m00: 1,
        m01: 0,
        m02: 0,
        m03: 0,
        m04: 0,
        m05: 1,
        m06: 0,
        m07: 0,
        m08: 0,
        m09: 0,
        m10: 1,
        m11: 0,
        m12: 0,
        m13: 0,
        m14: 0,
        m15: 1
      });
      legacyCC.Mat4 = Mat4;
      function mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
        return new Mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33);
      }
      legacyCC.mat4 = mat4;

      var _class$3H;
      var Vec2 = exports('aO', function (_ValueType) {
        _inheritsLoose(Vec2, _ValueType);
        Vec2.clone = function clone(a) {
          return new Vec2(a.x, a.y);
        };
        Vec2.copy = function copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          return out;
        };
        Vec2.set = function set(out, x, y) {
          out.x = x;
          out.y = y;
          return out;
        };
        Vec2.add = function add(out, a, b) {
          out.x = a.x + b.x;
          out.y = a.y + b.y;
          return out;
        };
        Vec2.subtract = function subtract(out, a, b) {
          out.x = a.x - b.x;
          out.y = a.y - b.y;
          return out;
        };
        Vec2.multiply = function multiply(out, a, b) {
          out.x = a.x * b.x;
          out.y = a.y * b.y;
          return out;
        };
        Vec2.divide = function divide(out, a, b) {
          out.x = a.x / b.x;
          out.y = a.y / b.y;
          return out;
        };
        Vec2.ceil = function ceil(out, a) {
          out.x = Math.ceil(a.x);
          out.y = Math.ceil(a.y);
          return out;
        };
        Vec2.floor = function floor(out, a) {
          out.x = Math.floor(a.x);
          out.y = Math.floor(a.y);
          return out;
        };
        Vec2.min = function min(out, a, b) {
          out.x = Math.min(a.x, b.x);
          out.y = Math.min(a.y, b.y);
          return out;
        };
        Vec2.max = function max(out, a, b) {
          out.x = Math.max(a.x, b.x);
          out.y = Math.max(a.y, b.y);
          return out;
        };
        Vec2.round = function round(out, a) {
          out.x = Math.round(a.x);
          out.y = Math.round(a.y);
          return out;
        };
        Vec2.multiplyScalar = function multiplyScalar(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          return out;
        };
        Vec2.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
          out.x = a.x + b.x * scale;
          out.y = a.y + b.y * scale;
          return out;
        };
        Vec2.distance = function distance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          return Math.sqrt(x * x + y * y);
        };
        Vec2.squaredDistance = function squaredDistance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          return x * x + y * y;
        };
        Vec2.len = function len(a) {
          var x = a.x;
          var y = a.y;
          return Math.sqrt(x * x + y * y);
        };
        Vec2.lengthSqr = function lengthSqr(a) {
          var x = a.x;
          var y = a.y;
          return x * x + y * y;
        };
        Vec2.negate = function negate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          return out;
        };
        Vec2.inverse = function inverse(out, a) {
          out.x = 1.0 / a.x;
          out.y = 1.0 / a.y;
          return out;
        };
        Vec2.inverseSafe = function inverseSafe(out, a) {
          var x = a.x;
          var y = a.y;
          if (Math.abs(x) < EPSILON$3) {
            out.x = 0;
          } else {
            out.x = 1.0 / x;
          }
          if (Math.abs(y) < EPSILON$3) {
            out.y = 0;
          } else {
            out.y = 1.0 / y;
          }
          return out;
        };
        Vec2.normalize = function normalize(out, a) {
          var x = a.x;
          var y = a.y;
          var len = x * x + y * y;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            out.x = x * len;
            out.y = y * len;
          } else {
            out.x = 0;
            out.y = 0;
          }
          return out;
        };
        Vec2.dot = function dot(a, b) {
          return a.x * b.x + a.y * b.y;
        };
        Vec2.cross = function cross(out, a, b) {
          if (out instanceof Vec3) {
            out.x = out.y = 0;
            out.z = a.x * b.y - a.y * b.x;
            return out;
          } else {
            return out.x * a.y - out.y * a.x;
          }
        };
        Vec2.lerp = function lerp(out, a, b, t) {
          var x = a.x;
          var y = a.y;
          out.x = x + t * (b.x - x);
          out.y = y + t * (b.y - y);
          return out;
        };
        Vec2.random = function random$1(out, scale) {
          scale = scale || 1.0;
          var r = random() * 2.0 * Math.PI;
          out.x = Math.cos(r) * scale;
          out.y = Math.sin(r) * scale;
          return out;
        };
        Vec2.transformMat3 = function transformMat3(out, a, m) {
          var x = a.x;
          var y = a.y;
          out.x = m.m00 * x + m.m03 * y + m.m06;
          out.y = m.m01 * x + m.m04 * y + m.m07;
          return out;
        };
        Vec2.transformMat4 = function transformMat4(out, a, m) {
          var x = a.x;
          var y = a.y;
          out.x = m.m00 * x + m.m04 * y + m.m12;
          out.y = m.m01 * x + m.m05 * y + m.m13;
          return out;
        };
        Vec2.str = function str(a) {
          return "Vec2(" + a.x + ", " + a.y + ")";
        };
        Vec2.toArray = function toArray(out, v, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = v.x;
          out[ofs + 1] = v.y;
          return out;
        };
        Vec2.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          return out;
        };
        Vec2.strictEquals = function strictEquals(a, b) {
          return a.x === b.x && a.y === b.y;
        };
        Vec2.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y));
        };
        Vec2.angle = function angle(a, b) {
          var magSqr1 = a.x * a.x + a.y * a.y;
          var magSqr2 = b.x * b.x + b.y * b.y;
          if (magSqr1 === 0 || magSqr2 === 0) {
            return 0.0;
          }
          var dot = a.x * b.x + a.y * b.y;
          var cosine = dot / Math.sqrt(magSqr1 * magSqr2);
          cosine = clamp$1(cosine, -1.0, 1.0);
          return Math.acos(cosine);
        };
        function Vec2(x, y) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof x === 'object') {
            _this.x = x.x;
            _this.y = x.y;
          } else {
            _this.x = x || 0;
            _this.y = y || 0;
          }
          return _this;
        }
        var _proto = Vec2.prototype;
        _proto.clone = function clone() {
          return new Vec2(this.x, this.y);
        };
        _proto.set = function set(x, y) {
          if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
          } else {
            this.x = x || 0;
            this.y = y || 0;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y));
        };
        _proto.equals2f = function equals2f(x, y, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x)) && Math.abs(this.y - y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(y));
        };
        _proto.strictEquals = function strictEquals(other) {
          return other && this.x === other.x && this.y === other.y;
        };
        _proto.strictEquals2f = function strictEquals2f(x, y) {
          return this.x === x && this.y === y;
        };
        _proto.toString = function toString() {
          return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ")";
        };
        _proto.lerp = function lerp(to, ratio) {
          var x = this.x;
          var y = this.y;
          this.x = x + ratio * (to.x - x);
          this.y = y + ratio * (to.y - y);
          return this;
        };
        _proto.clampf = function clampf(minInclusive, maxInclusive) {
          this.x = clamp$1(this.x, minInclusive.x, maxInclusive.x);
          this.y = clamp$1(this.y, minInclusive.y, maxInclusive.y);
          return this;
        };
        _proto.add = function add(other) {
          this.x += other.x;
          this.y += other.y;
          return this;
        };
        _proto.add2f = function add2f(x, y) {
          this.x += x;
          this.y += y;
          return this;
        };
        _proto.subtract = function subtract(other) {
          this.x -= other.x;
          this.y -= other.y;
          return this;
        };
        _proto.subtract2f = function subtract2f(x, y) {
          this.x -= x;
          this.y -= y;
          return this;
        };
        _proto.multiplyScalar = function multiplyScalar(scalar) {
          if (typeof scalar === 'object') {
            console.warn('should use Vec2.multiply for vector * vector operation');
          }
          this.x *= scalar;
          this.y *= scalar;
          return this;
        };
        _proto.multiply = function multiply(other) {
          if (typeof other !== 'object') {
            console.warn('should use Vec2.scale for vector * scalar operation');
          }
          this.x *= other.x;
          this.y *= other.y;
          return this;
        };
        _proto.multiply2f = function multiply2f(x, y) {
          this.x *= x;
          this.y *= y;
          return this;
        };
        _proto.divide = function divide(other) {
          this.x /= other.x;
          this.y /= other.y;
          return this;
        };
        _proto.divide2f = function divide2f(x, y) {
          this.x /= x;
          this.y /= y;
          return this;
        };
        _proto.negative = function negative() {
          this.x = -this.x;
          this.y = -this.y;
          return this;
        };
        _proto.dot = function dot(other) {
          return this.x * other.x + this.y * other.y;
        };
        _proto.cross = function cross(other) {
          return this.x * other.y - this.y * other.x;
        };
        _proto.length = function length() {
          return Math.sqrt(this.x * this.x + this.y * this.y);
        };
        _proto.lengthSqr = function lengthSqr() {
          return this.x * this.x + this.y * this.y;
        };
        _proto.normalize = function normalize() {
          var x = this.x;
          var y = this.y;
          var len = x * x + y * y;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            this.x *= len;
            this.y *= len;
          }
          return this;
        };
        _proto.angle = function angle(other) {
          var magSqr1 = this.lengthSqr();
          var magSqr2 = other.lengthSqr();
          if (magSqr1 === 0 || magSqr2 === 0) {
            return 0.0;
          }
          var dot = this.dot(other);
          var cosine = dot / Math.sqrt(magSqr1 * magSqr2);
          cosine = clamp$1(cosine, -1.0, 1.0);
          return Math.acos(cosine);
        };
        _proto.signAngle = function signAngle(other) {
          var cross = this.cross(other);
          var dot = this.dot(other);
          return Math.atan2(cross, dot);
        };
        _proto.rotate = function rotate(radians) {
          var x = this.x;
          var y = this.y;
          var sin = Math.sin(radians);
          var cos = Math.cos(radians);
          this.x = cos * x - sin * y;
          this.y = sin * x + cos * y;
          return this;
        };
        _proto.project = function project(other) {
          var scalar = this.dot(other) / other.dot(other);
          this.x = other.x * scalar;
          this.y = other.y * scalar;
          return this;
        };
        _proto.transformMat4 = function transformMat4(matrix) {
          var x = this.x;
          var y = this.y;
          this.x = matrix.m00 * x + matrix.m04 * y + matrix.m12;
          this.y = matrix.m01 * x + matrix.m05 * y + matrix.m13;
          return this;
        };
        return Vec2;
      }(ValueType));
      _class$3H = Vec2;
      Vec2.ZERO = Object.freeze(new _class$3H(0, 0));
      Vec2.ONE = Object.freeze(new _class$3H(1, 1));
      Vec2.NEG_ONE = Object.freeze(new _class$3H(-1, -1));
      Vec2.UNIT_X = Object.freeze(new _class$3H(1, 0));
      Vec2.UNIT_Y = Object.freeze(new _class$3H(0, 1));
      CCClass.fastDefine('cc.Vec2', Vec2, {
        x: 0,
        y: 0
      });
      legacyCC.Vec2 = Vec2;
      function v2$1(x, y) {
        return new Vec2(x, y);
      }
      legacyCC.v2 = v2$1;

      replaceProperty(Vec2, 'Vec2', [{
        name: 'sub',
        newName: 'subtract',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'div',
        newName: 'divide',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'dist',
        newName: 'distance',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'sqrDist',
        newName: 'squaredDistance',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'mag',
        newName: 'len',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'sqrMag',
        newName: 'lengthSqr',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec2,
        targetName: 'Vec2'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec2,
        targetName: 'Vec2'
      }]);
      replaceProperty(Vec2.prototype, 'Vec2', [{
        name: 'mag',
        newName: 'length',
        target: Vec2.prototype,
        targetName: 'Vec2'
      }, {
        name: 'magSqr',
        newName: 'lengthSqr',
        target: Vec2.prototype,
        targetName: 'Vec2'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec2.prototype,
        targetName: 'Vec2'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec2.prototype,
        targetName: 'Vec2'
      }]);
      replaceProperty(Vec3, 'Vec3', [{
        name: 'sub',
        newName: 'subtract',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'div',
        newName: 'divide',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'dist',
        newName: 'distance',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'sqrDist',
        newName: 'squaredDistance',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'mag',
        newName: 'len',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'sqrMag',
        newName: 'lengthSqr',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec3,
        targetName: 'Vec3'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec3,
        targetName: 'Vec3'
      }]);
      replaceProperty(Vec3.prototype, 'Vec3', [{
        name: 'mag',
        newName: 'length',
        target: Vec3.prototype,
        targetName: 'Vec3'
      }, {
        name: 'magSqr',
        newName: 'lengthSqr',
        target: Vec3.prototype,
        targetName: 'Vec3'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec3.prototype,
        targetName: 'Vec3'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec3.prototype,
        targetName: 'Vec3'
      }]);
      replaceProperty(Vec4, 'Vec4', [{
        name: 'sub',
        newName: 'subtract',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'div',
        newName: 'divide',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'dist',
        newName: 'distance',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'sqrDist',
        newName: 'squaredDistance',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'mag',
        newName: 'len',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'sqrMag',
        newName: 'lengthSqr',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec4,
        targetName: 'Vec4'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec4,
        targetName: 'Vec4'
      }]);
      replaceProperty(Vec4.prototype, 'Vec4', [{
        name: 'mag',
        newName: 'length',
        target: Vec4.prototype,
        targetName: 'Vec4'
      }, {
        name: 'magSqr',
        newName: 'lengthSqr',
        target: Vec4.prototype,
        targetName: 'Vec4'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Vec4.prototype,
        targetName: 'Vec4'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Vec4.prototype,
        targetName: 'Vec4'
      }]);
      replaceProperty(Quat, 'Quat', [{
        name: 'mag',
        newName: 'len',
        target: Quat,
        targetName: 'Quat'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Quat,
        targetName: 'Quat'
      }, {
        name: 'sqrMag',
        newName: 'lengthSqr',
        target: Quat,
        targetName: 'Quat'
      }, {
        name: 'scale',
        newName: 'multiplyScalar',
        target: Quat,
        targetName: 'Quat'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Quat,
        targetName: 'Quat'
      }]);
      replaceProperty(Quat.prototype, 'Quat', [{
        name: 'scale',
        newName: 'multiplyScalar',
        target: Quat.prototype,
        targetName: 'Quat'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Quat.prototype,
        targetName: 'Quat'
      }]);
      replaceProperty(Color$1, 'Color', [{
        name: 'sub',
        newName: 'subtract',
        target: Color$1,
        targetName: 'Color'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Color$1,
        targetName: 'Color'
      }, {
        name: 'div',
        newName: 'divide',
        target: Color$1,
        targetName: 'Color'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Color$1,
        targetName: 'Color'
      }, {
        name: 'fromHex',
        newName: 'fromHEX',
        customFunction: function customFunction() {
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          var arg1 = args[1].toString(16);
          return legacyCC.Color.fromHEX(args[0], arg1);
        }
      }]);
      replaceProperty(Mat3, 'Mat3', [{
        name: 'sub',
        newName: 'subtract',
        target: Mat3,
        targetName: 'Mat3'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Mat3,
        targetName: 'Mat3'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Mat3,
        targetName: 'Mat3'
      }, {
        name: 'transfrom',
        newName: 'transform',
        target: Mat3,
        targetName: 'Mat3'
      }]);
      replaceProperty(Mat3.prototype, 'Mat3', [{
        name: 'sub',
        newName: 'subtract',
        target: Mat3.prototype,
        targetName: 'Mat3'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Mat3.prototype,
        targetName: 'Mat3'
      }, {
        name: 'mulScalar',
        newName: 'multiplyScalar',
        target: Mat3.prototype,
        targetName: 'Mat3'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Mat3.prototype,
        targetName: 'Mat3'
      }]);
      replaceProperty(Mat4, 'Mat4', [{
        name: 'sub',
        newName: 'subtract',
        target: Mat4,
        targetName: 'Mat4'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Mat4,
        targetName: 'Mat4'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Mat4,
        targetName: 'Mat4'
      }]);
      replaceProperty(Mat4.prototype, 'Mat4', [{
        name: 'sub',
        newName: 'subtract',
        target: Mat4.prototype,
        targetName: 'Mat4'
      }, {
        name: 'mul',
        newName: 'multiply',
        target: Mat4.prototype,
        targetName: 'Mat4'
      }, {
        name: 'mulScalar',
        newName: 'multiplyScalar',
        target: Mat4.prototype,
        targetName: 'Mat4'
      }, {
        name: 'exactEquals',
        newName: 'strictEquals',
        target: Mat4.prototype,
        targetName: 'Mat4'
      }]);

      var MathType;
      (function (MathType) {
        MathType[MathType["VEC2"] = 0] = "VEC2";
        MathType[MathType["VEC3"] = 1] = "VEC3";
        MathType[MathType["VEC4"] = 2] = "VEC4";
        MathType[MathType["QUATERNION"] = 3] = "QUATERNION";
        MathType[MathType["MAT3"] = 4] = "MAT3";
        MathType[MathType["MAT4"] = 5] = "MAT4";
        MathType[MathType["SIZE"] = 6] = "SIZE";
        MathType[MathType["RECT"] = 7] = "RECT";
        MathType[MathType["COLOR"] = 8] = "COLOR";
      })(MathType || (MathType = {}));

      var AffineTransform = exports('aZ', function () {
        AffineTransform.identity = function identity() {
          return new AffineTransform();
        };
        AffineTransform.clone = function clone(affineTransform) {
          return new AffineTransform(affineTransform.a, affineTransform.b, affineTransform.c, affineTransform.d, affineTransform.tx, affineTransform.ty);
        };
        AffineTransform.concat = function concat(out, t1, t2) {
          var a = t1.a;
          var b = t1.b;
          var c = t1.c;
          var d = t1.d;
          var tx = t1.tx;
          var ty = t1.ty;
          out.a = a * t2.a + b * t2.c;
          out.b = a * t2.b + b * t2.d;
          out.c = c * t2.a + d * t2.c;
          out.d = c * t2.b + d * t2.d;
          out.tx = tx * t2.a + ty * t2.c + t2.tx;
          out.ty = tx * t2.b + ty * t2.d + t2.ty;
        };
        AffineTransform.invert = function invert(out, t) {
          var determinant = 1 / (t.a * t.d - t.b * t.c);
          out.a = determinant * t.d;
          out.b = -determinant * t.b;
          out.c = -determinant * t.c;
          out.d = determinant * t.a;
          out.tx = determinant * (t.c * t.ty - t.d * t.tx);
          out.ty = determinant * (t.b * t.tx - t.a * t.ty);
        };
        AffineTransform.fromMat4 = function fromMat4(out, mat) {
          out.a = mat.m00;
          out.b = mat.m01;
          out.c = mat.m04;
          out.d = mat.m05;
          out.tx = mat.m12;
          out.ty = mat.m13;
        };
        AffineTransform.transformVec2 = function transformVec2(out, point, transOrY, t) {
          var x;
          var y;
          if (!t) {
            t = transOrY;
            x = point.x;
            y = point.y;
          } else {
            x = point;
            y = transOrY;
          }
          out.x = t.a * x + t.c * y + t.tx;
          out.y = t.b * x + t.d * y + t.ty;
        };
        AffineTransform.transformSize = function transformSize(out, size, t) {
          out.width = t.a * size.width + t.c * size.height;
          out.height = t.b * size.width + t.d * size.height;
        };
        AffineTransform.transformRect = function transformRect(out, rect, t) {
          var or = rect.x + rect.width;
          var ot = rect.y + rect.height;
          var lbx = t.a * rect.x + t.c * rect.y + t.tx;
          var lby = t.b * rect.x + t.d * rect.y + t.ty;
          var rbx = t.a * or + t.c * rect.y + t.tx;
          var rby = t.b * or + t.d * rect.y + t.ty;
          var ltx = t.a * rect.x + t.c * ot + t.tx;
          var lty = t.b * rect.x + t.d * ot + t.ty;
          var rtx = t.a * or + t.c * ot + t.tx;
          var rty = t.b * or + t.d * ot + t.ty;
          var minX = Math.min(lbx, rbx, ltx, rtx);
          var maxX = Math.max(lbx, rbx, ltx, rtx);
          var minY = Math.min(lby, rby, lty, rty);
          var maxY = Math.max(lby, rby, lty, rty);
          out.x = minX;
          out.y = minY;
          out.width = maxX - minX;
          out.height = maxY - minY;
        };
        AffineTransform.transformObb = function transformObb(out_bl, out_tl, out_tr, out_br, rect, anAffineTransform, flipY) {
          if (flipY === void 0) {
            flipY = true;
          }
          var tx = anAffineTransform.a * rect.x + anAffineTransform.c * rect.y + anAffineTransform.tx;
          var ty = anAffineTransform.b * rect.x + anAffineTransform.d * rect.y + anAffineTransform.ty;
          var xa = anAffineTransform.a * rect.width;
          var xb = anAffineTransform.b * rect.width;
          var yc = anAffineTransform.c * rect.height;
          var yd = anAffineTransform.d * rect.height;
          if (flipY) {
            out_tl.x = tx;
            out_tl.y = ty;
            out_tr.x = xa + tx;
            out_tr.y = xb + ty;
            out_bl.x = yc + tx;
            out_bl.y = yd + ty;
            out_br.x = xa + yc + tx;
            out_br.y = xb + yd + ty;
          } else {
            out_bl.x = tx;
            out_bl.y = ty;
            out_br.x = xa + tx;
            out_br.y = xb + ty;
            out_tl.x = yc + tx;
            out_tl.y = yd + ty;
            out_tr.x = xa + yc + tx;
            out_tr.y = xb + yd + ty;
          }
        };
        function AffineTransform(a, b, c, d, tx, ty) {
          if (a === void 0) {
            a = 1;
          }
          if (b === void 0) {
            b = 0;
          }
          if (c === void 0) {
            c = 0;
          }
          if (d === void 0) {
            d = 1;
          }
          if (tx === void 0) {
            tx = 0;
          }
          if (ty === void 0) {
            ty = 0;
          }
          this.a = a;
          this.b = b;
          this.c = c;
          this.d = d;
          this.tx = tx;
          this.ty = ty;
        }
        return AffineTransform;
      }());
      legacyCC.AffineTransform = AffineTransform;

      var _class$3G;
      var Size$1 = exports('a_', function (_ValueType) {
        _inheritsLoose(Size, _ValueType);
        Size.lerp = function lerp(out, from, to, ratio) {
          out.width = from.width + (to.width - from.width) * ratio;
          out.height = from.height + (to.height - from.height) * ratio;
          return out;
        };
        Size.equals = function equals(a, b) {
          return a.width === b.width && a.height === b.height;
        };
        function Size(width, height) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof width === 'object') {
            _this.width = width.width;
            _this.height = width.height;
          } else {
            _this.width = width || 0;
            _this.height = height || 0;
          }
          return _this;
        }
        var _proto = Size.prototype;
        _proto.clone = function clone() {
          return new Size(this.width, this.height);
        };
        _proto.set = function set(width, height) {
          if (typeof width === 'object') {
            this.height = width.height;
            this.width = width.width;
          } else {
            this.width = width || 0;
            this.height = height || 0;
          }
          return this;
        };
        _proto.equals = function equals(other) {
          return this.width === other.width && this.height === other.height;
        };
        _proto.lerp = function lerp(to, ratio) {
          this.width += (to.width - this.width) * ratio;
          this.height += (to.height - this.height) * ratio;
          return this;
        };
        _proto.toString = function toString() {
          return "(" + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")";
        };
        _createClass(Size, [{
          key: "x",
          get: function get() {
            return this.width;
          },
          set: function set(val) {
            this.width = val;
          }
        }, {
          key: "y",
          get: function get() {
            return this.height;
          },
          set: function set(val) {
            this.height = val;
          }
        }]);
        return Size;
      }(ValueType));
      _class$3G = Size$1;
      Size$1.ZERO = Object.freeze(new _class$3G(0, 0));
      Size$1.ONE = Object.freeze(new _class$3G(1, 1));
      CCClass.fastDefine('cc.Size', Size$1, {
        width: 0,
        height: 0
      });
      function size(width, height) {
        if (width === void 0) {
          width = 0;
        }
        if (height === void 0) {
          height = 0;
        }
        return new Size$1(width, height);
      }
      legacyCC.size = size;
      legacyCC.Size = Size$1;

      var Rect$1 = exports('b0', function (_ValueType) {
        _inheritsLoose(Rect, _ValueType);
        Rect.fromMinMax = function fromMinMax(out, v1, v2) {
          var minX = Math.min(v1.x, v2.x);
          var minY = Math.min(v1.y, v2.y);
          var maxX = Math.max(v1.x, v2.x);
          var maxY = Math.max(v1.y, v2.y);
          out.x = minX;
          out.y = minY;
          out.width = maxX - minX;
          out.height = maxY - minY;
          return out;
        };
        Rect.lerp = function lerp(out, from, to, ratio) {
          var x = from.x;
          var y = from.y;
          var w = from.width;
          var h = from.height;
          out.x = x + (to.x - x) * ratio;
          out.y = y + (to.y - y) * ratio;
          out.width = w + (to.width - w) * ratio;
          out.height = h + (to.height - h) * ratio;
          return out;
        };
        Rect.intersection = function intersection(out, one, other) {
          var axMin = one.x;
          var ayMin = one.y;
          var axMax = one.x + one.width;
          var ayMax = one.y + one.height;
          var bxMin = other.x;
          var byMin = other.y;
          var bxMax = other.x + other.width;
          var byMax = other.y + other.height;
          out.x = Math.max(axMin, bxMin);
          out.y = Math.max(ayMin, byMin);
          out.width = Math.min(axMax, bxMax) - out.x;
          out.height = Math.min(ayMax, byMax) - out.y;
          return out;
        };
        Rect.union = function union(out, one, other) {
          var x = one.x;
          var y = one.y;
          var w = one.width;
          var h = one.height;
          var bx = other.x;
          var by = other.y;
          var bw = other.width;
          var bh = other.height;
          out.x = Math.min(x, bx);
          out.y = Math.min(y, by);
          out.width = Math.max(x + w, bx + bw) - out.x;
          out.height = Math.max(y + h, by + bh) - out.y;
          return out;
        };
        Rect.equals = function equals(a, b) {
          return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
        };
        function Rect(x, y, width, height) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof x === 'object') {
            _this.x = x.x;
            _this.y = x.y;
            _this.width = x.width;
            _this.height = x.height;
          } else {
            _this.x = x || 0;
            _this.y = y || 0;
            _this.width = width || 0;
            _this.height = height || 0;
          }
          return _this;
        }
        var _proto = Rect.prototype;
        _proto.clone = function clone() {
          return new Rect(this.x, this.y, this.width, this.height);
        };
        _proto.set = function set(x, y, width, height) {
          if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
            this.width = x.width;
            this.height = x.height;
          } else {
            this.x = x || 0;
            this.y = y || 0;
            this.width = width || 0;
            this.height = height || 0;
          }
          return this;
        };
        _proto.equals = function equals(other) {
          return this.x === other.x && this.y === other.y && this.width === other.width && this.height === other.height;
        };
        _proto.lerp = function lerp(to, ratio) {
          var x = this.x;
          var y = this.y;
          var w = this.width;
          var h = this.height;
          this.x = x + (to.x - x) * ratio;
          this.y = y + (to.y - y) * ratio;
          this.width = w + (to.width - w) * ratio;
          this.height = h + (to.height - h) * ratio;
          return this;
        };
        _proto.toString = function toString() {
          return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")";
        };
        _proto.intersects = function intersects(other) {
          var maxax = this.x + this.width;
          var maxay = this.y + this.height;
          var maxbx = other.x + other.width;
          var maxby = other.y + other.height;
          return !(maxax < other.x || maxbx < this.x || maxay < other.y || maxby < this.y);
        };
        _proto.contains = function contains(point) {
          return this.x <= point.x && this.x + this.width >= point.x && this.y <= point.y && this.y + this.height >= point.y;
        };
        _proto.containsRect = function containsRect(other) {
          return this.x <= other.x && this.x + this.width >= other.x + other.width && this.y <= other.y && this.y + this.height >= other.y + other.height;
        };
        _proto.transformMat4 = function transformMat4(mat) {
          var ol = this.x;
          var ob = this.y;
          var or = ol + this.width;
          var ot = ob + this.height;
          var lbx = mat.m00 * ol + mat.m04 * ob + mat.m12;
          var lby = mat.m01 * ol + mat.m05 * ob + mat.m13;
          var rbx = mat.m00 * or + mat.m04 * ob + mat.m12;
          var rby = mat.m01 * or + mat.m05 * ob + mat.m13;
          var ltx = mat.m00 * ol + mat.m04 * ot + mat.m12;
          var lty = mat.m01 * ol + mat.m05 * ot + mat.m13;
          var rtx = mat.m00 * or + mat.m04 * ot + mat.m12;
          var rty = mat.m01 * or + mat.m05 * ot + mat.m13;
          var minX = Math.min(lbx, rbx, ltx, rtx);
          var maxX = Math.max(lbx, rbx, ltx, rtx);
          var minY = Math.min(lby, rby, lty, rty);
          var maxY = Math.max(lby, rby, lty, rty);
          this.x = minX;
          this.y = minY;
          this.width = maxX - minX;
          this.height = maxY - minY;
          return this;
        };
        _proto.transformMat4ToPoints = function transformMat4ToPoints(mat, out_lb, out_lt, out_rt, out_rb) {
          var ol = this.x;
          var ob = this.y;
          var or = ol + this.width;
          var ot = ob + this.height;
          out_lb.x = mat.m00 * ol + mat.m04 * ob + mat.m12;
          out_lb.y = mat.m01 * ol + mat.m05 * ob + mat.m13;
          out_rb.x = mat.m00 * or + mat.m04 * ob + mat.m12;
          out_rb.y = mat.m01 * or + mat.m05 * ob + mat.m13;
          out_lt.x = mat.m00 * ol + mat.m04 * ot + mat.m12;
          out_lt.y = mat.m01 * ol + mat.m05 * ot + mat.m13;
          out_rt.x = mat.m00 * or + mat.m04 * ot + mat.m12;
          out_rt.y = mat.m01 * or + mat.m05 * ot + mat.m13;
        };
        _createClass(Rect, [{
          key: "xMin",
          get: function get() {
            return this.x;
          },
          set: function set(value) {
            this.width += this.x - value;
            this.x = value;
          }
        }, {
          key: "yMin",
          get: function get() {
            return this.y;
          },
          set: function set(value) {
            this.height += this.y - value;
            this.y = value;
          }
        }, {
          key: "xMax",
          get: function get() {
            return this.x + this.width;
          },
          set: function set(value) {
            this.width = value - this.x;
          }
        }, {
          key: "yMax",
          get: function get() {
            return this.y + this.height;
          },
          set: function set(value) {
            this.height = value - this.y;
          }
        }, {
          key: "center",
          get: function get() {
            return new Vec2(this.x + this.width * 0.5, this.y + this.height * 0.5);
          },
          set: function set(value) {
            this.x = value.x - this.width * 0.5;
            this.y = value.y - this.height * 0.5;
          }
        }, {
          key: "origin",
          get: function get() {
            return new Vec2(this.x, this.y);
          },
          set: function set(value) {
            this.x = value.x;
            this.y = value.y;
          }
        }, {
          key: "size",
          get: function get() {
            return new Size$1(this.width, this.height);
          },
          set: function set(value) {
            this.width = value.width;
            this.height = value.height;
          }
        }, {
          key: "z",
          get: function get() {
            return this.width;
          },
          set: function set(val) {
            this.width = val;
          }
        }, {
          key: "w",
          get: function get() {
            return this.height;
          },
          set: function set(val) {
            this.height = val;
          }
        }]);
        return Rect;
      }(ValueType));
      CCClass.fastDefine('cc.Rect', Rect$1, {
        x: 0,
        y: 0,
        width: 0,
        height: 0
      });
      legacyCC.Rect = Rect$1;
      function rect(x, y, width, height) {
        if (x === void 0) {
          x = 0;
        }
        if (y === void 0) {
          y = 0;
        }
        if (width === void 0) {
          width = 0;
        }
        if (height === void 0) {
          height = 0;
        }
        return new Rect$1(x, y, width, height);
      }
      legacyCC.rect = rect;

      var MATH_FLOAT_ARRAY = exports('bv', Float64Array);
      var MathBase = exports('bw', function (_ValueType) {
        _inheritsLoose(MathBase, _ValueType);
        function MathBase() {
          return _ValueType.apply(this, arguments) || this;
        }
        MathBase.createFloatArray = function createFloatArray(size) {
          return new MATH_FLOAT_ARRAY(size);
        };
        _createClass(MathBase, [{
          key: "array",
          get: function get() {
            return this._array;
          }
        }]);
        return MathBase;
      }(ValueType));

      var math = /*#__PURE__*/Object.freeze({
        __proto__: null,
        bits: bits,
        Vec2: Vec2,
        v2: v2$1,
        Vec3: Vec3,
        v3: v3,
        Vec4: Vec4,
        v4: v4,
        Quat: Quat,
        quat: quat,
        Mat3: Mat3,
        Mat4: Mat4,
        mat4: mat4,
        AffineTransform: AffineTransform,
        Size: Size$1,
        size: size,
        Rect: Rect$1,
        rect: rect,
        Color: Color$1,
        color: color,
        preTransforms: preTransforms,
        HALF_PI: HALF_PI,
        TWO_PI: TWO_PI,
        EPSILON: EPSILON$3,
        equals: equals$2,
        approx: approx,
        clamp: clamp$1,
        clamp01: clamp01,
        lerp: lerp,
        toRadian: toRadian,
        toDegree: toDegree,
        random: random,
        setRandGenerator: setRandGenerator,
        randomRange: randomRange,
        randomRangeInt: randomRangeInt,
        pseudoRandom: pseudoRandom,
        pseudoRandomRange: pseudoRandomRange,
        pseudoRandomRangeInt: pseudoRandomRangeInt,
        nextPow2: nextPow2,
        repeat: repeat$2,
        pingPong: pingPong,
        inverseLerp: inverseLerp,
        absMaxComponent: absMaxComponent,
        absMax: absMax,
        enumerableProps: enumerableProps,
        floatToHalf: floatToHalf,
        halfToFloat: halfToFloat,
        MATH_FLOAT_ARRAY: MATH_FLOAT_ARRAY,
        MathBase: MathBase
      });
      exports('aI', math);

      var X = new Vec3();
      var Y = new Vec3();
      var Z = new Vec3();
      var d = new Vec3();
      var min$2 = new Vec3();
      var max$3 = new Vec3();
      var u = new Array(3);
      var e = new Array(3);
      function point_plane(point, plane_) {
        return Vec3.dot(plane_.n, point) - plane_.d;
      }
      function pt_point_plane(out, point, plane_) {
        var t = point_plane(point, plane_);
        return Vec3.subtract(out, point, Vec3.multiplyScalar(out, plane_.n, t));
      }
      function pt_point_aabb(out, point, aabb_) {
        Vec3.copy(out, point);
        Vec3.subtract(min$2, aabb_.center, aabb_.halfExtents);
        Vec3.add(max$3, aabb_.center, aabb_.halfExtents);
        out.x = out.x < min$2.x ? min$2.x : out.x;
        out.y = out.y < min$2.y ? min$2.y : out.y;
        out.z = out.z < min$2.z ? min$2.z : out.z;
        out.x = out.x > max$3.x ? max$3.x : out.x;
        out.y = out.y > max$3.y ? max$3.y : out.y;
        out.z = out.z > max$3.z ? max$3.z : out.z;
        return out;
      }
      function pt_point_obb(out, point, obb_) {
        Vec3.set(X, obb_.orientation.m00, obb_.orientation.m01, obb_.orientation.m02);
        Vec3.set(Y, obb_.orientation.m03, obb_.orientation.m04, obb_.orientation.m05);
        Vec3.set(Z, obb_.orientation.m06, obb_.orientation.m07, obb_.orientation.m08);
        u[0] = X;
        u[1] = Y;
        u[2] = Z;
        e[0] = obb_.halfExtents.x;
        e[1] = obb_.halfExtents.y;
        e[2] = obb_.halfExtents.z;
        Vec3.subtract(d, point, obb_.center);
        Vec3.set(out, obb_.center.x, obb_.center.y, obb_.center.z);
        for (var i = 0; i < 3; i++) {
          var dist = Vec3.dot(d, u[i]);
          if (dist > e[i]) {
            dist = e[i];
          }
          if (dist < -e[i]) {
            dist = -e[i];
          }
          out.x += dist * u[i].x;
          out.y += dist * u[i].y;
          out.z += dist * u[i].z;
        }
        return out;
      }
      function pt_point_line(out, point, linePointA, linePointB) {
        Vec3.subtract(X, linePointA, linePointB);
        var dir = X.clone();
        var dirSquaredLength = Vec3.lengthSqr(dir);
        if (dirSquaredLength === 0) {
          Vec3.copy(out, linePointA);
        } else {
          Vec3.subtract(X, point, linePointA);
          var t = Vec3.dot(X, dir) / dirSquaredLength;
          if (t < 0) {
            Vec3.copy(out, linePointA);
          } else if (t > 1) {
            Vec3.copy(out, linePointB);
          } else {
            Vec3.scaleAndAdd(out, linePointA, dir, t);
          }
        }
      }

      var distance = /*#__PURE__*/Object.freeze({
        __proto__: null,
        point_plane: point_plane,
        pt_point_plane: pt_point_plane,
        pt_point_aabb: pt_point_aabb,
        pt_point_obb: pt_point_obb,
        pt_point_line: pt_point_line
      });

      var enums = {
        SHAPE_RAY: 1 << 0,
        SHAPE_LINE: 1 << 1,
        SHAPE_SPHERE: 1 << 2,
        SHAPE_AABB: 1 << 3,
        SHAPE_OBB: 1 << 4,
        SHAPE_PLANE: 1 << 5,
        SHAPE_TRIANGLE: 1 << 6,
        SHAPE_FRUSTUM: 1 << 7,
        SHAPE_FRUSTUM_ACCURATE: 1 << 8,
        SHAPE_CAPSULE: 1 << 9,
        SHAPE_SPLINE: 1 << 10
      };

      var Line$1 = function () {
        Line.create = function create(sx, sy, sz, ex, ey, ez) {
          return new Line(sx, sy, sz, ex, ey, ez);
        };
        Line.clone = function clone(a) {
          return new Line(a.s.x, a.s.y, a.s.z, a.e.x, a.e.y, a.e.z);
        };
        Line.copy = function copy(out, a) {
          Vec3.copy(out.s, a.s);
          Vec3.copy(out.e, a.e);
          return out;
        };
        Line.fromPoints = function fromPoints(out, start, end) {
          Vec3.copy(out.s, start);
          Vec3.copy(out.e, end);
          return out;
        };
        Line.set = function set(out, sx, sy, sz, ex, ey, ez) {
          out.s.x = sx;
          out.s.y = sy;
          out.s.z = sz;
          out.e.x = ex;
          out.e.y = ey;
          out.e.z = ez;
          return out;
        };
        Line.len = function len(a) {
          return Vec3.distance(a.s, a.e);
        };
        function Line(sx, sy, sz, ex, ey, ez) {
          if (sx === void 0) {
            sx = 0;
          }
          if (sy === void 0) {
            sy = 0;
          }
          if (sz === void 0) {
            sz = 0;
          }
          if (ex === void 0) {
            ex = 0;
          }
          if (ey === void 0) {
            ey = 0;
          }
          if (ez === void 0) {
            ez = -1;
          }
          this.s = void 0;
          this.e = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_LINE;
          this.s = new Vec3(sx, sy, sz);
          this.e = new Vec3(ex, ey, ez);
        }
        var _proto = Line.prototype;
        _proto.length = function length() {
          return Vec3.distance(this.s, this.e);
        };
        _createClass(Line, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Line;
      }();

      var Ray = function () {
        Ray.create = function create(ox, oy, oz, dx, dy, dz) {
          if (ox === void 0) {
            ox = 0;
          }
          if (oy === void 0) {
            oy = 0;
          }
          if (oz === void 0) {
            oz = 0;
          }
          if (dx === void 0) {
            dx = 0;
          }
          if (dy === void 0) {
            dy = 0;
          }
          if (dz === void 0) {
            dz = 1;
          }
          return new Ray(ox, oy, oz, dx, dy, dz);
        };
        Ray.clone = function clone(a) {
          return new Ray(a.o.x, a.o.y, a.o.z, a.d.x, a.d.y, a.d.z);
        };
        Ray.copy = function copy(out, a) {
          Vec3.copy(out.o, a.o);
          Vec3.copy(out.d, a.d);
          return out;
        };
        Ray.fromPoints = function fromPoints(out, origin, target) {
          Vec3.copy(out.o, origin);
          Vec3.normalize(out.d, Vec3.subtract(out.d, target, origin));
          return out;
        };
        Ray.set = function set(out, ox, oy, oz, dx, dy, dz) {
          out.o.x = ox;
          out.o.y = oy;
          out.o.z = oz;
          out.d.x = dx;
          out.d.y = dy;
          out.d.z = dz;
          return out;
        };
        function Ray(ox, oy, oz, dx, dy, dz) {
          if (ox === void 0) {
            ox = 0;
          }
          if (oy === void 0) {
            oy = 0;
          }
          if (oz === void 0) {
            oz = 0;
          }
          if (dx === void 0) {
            dx = 0;
          }
          if (dy === void 0) {
            dy = 0;
          }
          if (dz === void 0) {
            dz = -1;
          }
          this.o = void 0;
          this.d = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_RAY;
          this.o = new Vec3(ox, oy, oz);
          this.d = new Vec3(dx, dy, dz);
        }
        var _proto = Ray.prototype;
        _proto.computeHit = function computeHit(out, distance) {
          Vec3.normalize(out, this.d);
          Vec3.scaleAndAdd(out, this.o, out, distance);
        };
        _createClass(Ray, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Ray;
      }();

      var _v3_tmp$2 = new Vec3();
      var _offset = new Vec3();
      var _min = new Vec3();
      var _max = new Vec3();
      function maxComponent$1(v) {
        return Math.max(Math.max(v.x, v.y), v.z);
      }
      var Sphere = function () {
        Sphere.create = function create(cx, cy, cz, r) {
          return new Sphere(cx, cy, cz, r);
        };
        Sphere.clone = function clone(p) {
          return new Sphere(p.center.x, p.center.y, p.center.z, p.radius);
        };
        Sphere.copy = function copy(out, p) {
          Vec3.copy(out.center, p.center);
          out.radius = p.radius;
          return out;
        };
        Sphere.fromPoints = function fromPoints(out, minPos, maxPos) {
          Vec3.multiplyScalar(out.center, Vec3.add(_v3_tmp$2, minPos, maxPos), 0.5);
          out.radius = Vec3.subtract(_v3_tmp$2, maxPos, minPos).length() * 0.5;
          return out;
        };
        Sphere.set = function set(out, cx, cy, cz, r) {
          out.center.x = cx;
          out.center.y = cy;
          out.center.z = cz;
          out.radius = r;
          return out;
        };
        function Sphere(cx, cy, cz, r) {
          if (cx === void 0) {
            cx = 0;
          }
          if (cy === void 0) {
            cy = 0;
          }
          if (cz === void 0) {
            cz = 0;
          }
          if (r === void 0) {
            r = 1;
          }
          this._center = new Vec3(0, 0, 0);
          this._radius = 0;
          this._type = void 0;
          this._type = enums.SHAPE_SPHERE;
          this._center = new Vec3(cx, cy, cz);
          this._radius = r;
        }
        var _proto = Sphere.prototype;
        _proto.destroy = function destroy() {};
        _proto.clone = function clone() {
          return Sphere.clone(this);
        };
        _proto.copy = function copy(a) {
          return Sphere.copy(this, a);
        };
        _proto.getBoundary = function getBoundary(minPos, maxPos) {
          Vec3.set(minPos, this.center.x - this.radius, this.center.y - this.radius, this.center.z - this.radius);
          Vec3.set(maxPos, this.center.x + this.radius, this.center.y + this.radius, this.center.z + this.radius);
        };
        _proto.transform = function transform(m, pos, rot, scale, out) {
          Vec3.transformMat4(out.center, this.center, m);
          out.radius = this.radius * maxComponent$1(scale);
        };
        _proto.translateAndRotate = function translateAndRotate(m, rot, out) {
          Vec3.transformMat4(out.center, this.center, m);
        };
        _proto.setScale = function setScale(scale, out) {
          out.radius = this.radius * maxComponent$1(scale);
        };
        _proto.mergePoint = function mergePoint(point) {
          if (this.radius < 0.0) {
            this.center.set(point);
            this.radius = 0.0;
          }
          Vec3.subtract(_offset, point, this.center);
          var dist = _offset.length();
          if (dist > this.radius) {
            var half = (dist - this.radius) * 0.5;
            this.radius += half;
            Vec3.multiplyScalar(_offset, _offset, half / dist);
            Vec3.add(this.center, this.center, _offset);
          }
        };
        _proto.mergePoints = function mergePoints(points) {
          var length = points.length;
          if (length < 1) return;
          this.radius = -1.0;
          for (var i = 0; i < length; i++) {
            this.mergePoint(points[i]);
          }
        };
        _proto.mergeAABB = function mergeAABB(a) {
          a.getBoundary(_min, _max);
          this.mergePoint(_min);
          this.mergePoint(_max);
        };
        _createClass(Sphere, [{
          key: "center",
          get: function get() {
            return this._center;
          },
          set: function set(val) {
            this._center = val;
          }
        }, {
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(val) {
            this._radius = val;
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Sphere;
      }();

      var rayPlane = function () {
        return function (ray, plane) {
          var denom = Vec3.dot(ray.d, plane.n);
          if (Math.abs(denom) < Number.EPSILON) {
            return 0;
          }
          var d = point_plane(ray.o, plane);
          var t = -d / denom;
          if (t < 0) {
            return 0;
          }
          return t;
        };
      }();
      var rayTriangle = function () {
        var ab = new Vec3(0, 0, 0);
        var ac = new Vec3(0, 0, 0);
        var pvec = new Vec3(0, 0, 0);
        var tvec = new Vec3(0, 0, 0);
        var qvec = new Vec3(0, 0, 0);
        return function (ray, triangle, doubleSided) {
          Vec3.subtract(ab, triangle.b, triangle.a);
          Vec3.subtract(ac, triangle.c, triangle.a);
          Vec3.cross(pvec, ray.d, ac);
          var det = Vec3.dot(ab, pvec);
          if (det < Number.EPSILON && (!doubleSided || det > -Number.EPSILON)) {
            return 0;
          }
          var inv_det = 1 / det;
          Vec3.subtract(tvec, ray.o, triangle.a);
          var u = Vec3.dot(tvec, pvec) * inv_det;
          if (u < 0 || u > 1) {
            return 0;
          }
          Vec3.cross(qvec, tvec, ab);
          var v = Vec3.dot(ray.d, qvec) * inv_det;
          if (v < 0 || u + v > 1) {
            return 0;
          }
          var t = Vec3.dot(ac, qvec) * inv_det;
          return t < 0 ? 0 : t;
        };
      }();
      var raySphere = function () {
        var e = new Vec3(0, 0, 0);
        return function (ray, sphere) {
          var r = sphere.radius;
          var c = sphere.center;
          var o = ray.o;
          var d = ray.d;
          var rSq = r * r;
          Vec3.subtract(e, c, o);
          var eSq = e.lengthSqr();
          var aLength = Vec3.dot(e, d);
          var fSq = rSq - (eSq - aLength * aLength);
          if (fSq < 0) {
            return 0;
          }
          var f = Math.sqrt(fSq);
          var t = eSq < rSq ? aLength + f : aLength - f;
          if (t < 0) {
            return 0;
          }
          return t;
        };
      }();
      var rayAABB = function () {
        var min = new Vec3();
        var max = new Vec3();
        return function (ray, aabb) {
          Vec3.subtract(min, aabb.center, aabb.halfExtents);
          Vec3.add(max, aabb.center, aabb.halfExtents);
          return rayAABB2$1(ray, min, max);
        };
      }();
      function rayAABB2$1(ray, min, max) {
        var o = ray.o;
        var d = ray.d;
        var ix = 1 / d.x;
        var iy = 1 / d.y;
        var iz = 1 / d.z;
        var t1 = (min.x - o.x) * ix;
        var t2 = (max.x - o.x) * ix;
        var t3 = (min.y - o.y) * iy;
        var t4 = (max.y - o.y) * iy;
        var t5 = (min.z - o.z) * iz;
        var t6 = (max.z - o.z) * iz;
        var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
        var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6));
        if (tmax < 0 || tmin > tmax) {
          return 0;
        }
        return tmin > 0 ? tmin : tmax;
      }
      var rayOBB = function () {
        var center = new Vec3();
        var o = new Vec3();
        var d = new Vec3();
        var X = new Vec3();
        var Y = new Vec3();
        var Z = new Vec3();
        var p = new Vec3();
        var size = new Array(3);
        var f = new Array(3);
        var e = new Array(3);
        var t = new Array(6);
        return function (ray, obb) {
          size[0] = obb.halfExtents.x;
          size[1] = obb.halfExtents.y;
          size[2] = obb.halfExtents.z;
          center = obb.center;
          o = ray.o;
          d = ray.d;
          Vec3.set(X, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
          Vec3.set(Y, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
          Vec3.set(Z, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
          Vec3.subtract(p, center, o);
          f[0] = Vec3.dot(X, d);
          f[1] = Vec3.dot(Y, d);
          f[2] = Vec3.dot(Z, d);
          e[0] = Vec3.dot(X, p);
          e[1] = Vec3.dot(Y, p);
          e[2] = Vec3.dot(Z, p);
          for (var i = 0; i < 3; ++i) {
            if (f[i] === 0) {
              if (-e[i] - size[i] > 0 || -e[i] + size[i] < 0) {
                return 0;
              }
              f[i] = 0.0000001;
            }
            t[i * 2 + 0] = (e[i] + size[i]) / f[i];
            t[i * 2 + 1] = (e[i] - size[i]) / f[i];
          }
          var tmin = Math.max(Math.max(Math.min(t[0], t[1]), Math.min(t[2], t[3])), Math.min(t[4], t[5]));
          var tmax = Math.min(Math.min(Math.max(t[0], t[1]), Math.max(t[2], t[3])), Math.max(t[4], t[5]));
          if (tmax < 0 || tmin > tmax) {
            return 0;
          }
          return tmin > 0 ? tmin : tmax;
        };
      }();
      var rayCapsule = function () {
        var v3_0 = new Vec3();
        var v3_1 = new Vec3();
        var v3_2 = new Vec3();
        var v3_3 = new Vec3();
        var v3_4 = new Vec3();
        var v3_5 = new Vec3();
        var v3_6 = new Vec3();
        var sphere_0 = new Sphere();
        return function (ray, capsule) {
          var A = capsule.ellipseCenter0;
          var B = capsule.ellipseCenter1;
          var BA = Vec3.subtract(v3_1, B, A);
          if (BA.length() < EPSILON$3) {
            sphere_0.radius = capsule.radius;
            sphere_0.center.set(capsule.ellipseCenter0);
            return intersect.raySphere(ray, sphere_0);
          }
          var O = ray.o;
          var OA = Vec3.subtract(v3_2, O, A);
          var vRayNorm = Vec3.normalize(v3_0, ray.d);
          var VxBA = Vec3.cross(v3_3, vRayNorm, BA);
          var a = VxBA.lengthSqr();
          if (a === 0) {
            sphere_0.radius = capsule.radius;
            var BO = Vec3.subtract(v3_4, B, O);
            if (OA.lengthSqr() < BO.lengthSqr()) {
              sphere_0.center.set(A);
            } else {
              sphere_0.center.set(B);
            }
            return intersect.raySphere(ray, sphere_0);
          }
          var OAxBA = Vec3.cross(v3_4, OA, BA);
          var ab2 = BA.lengthSqr();
          var b = 2 * Vec3.dot(VxBA, OAxBA);
          var radiusSqr = capsule.radius * capsule.radius;
          var c = OAxBA.lengthSqr() - radiusSqr * ab2;
          var d = b * b - 4 * a * c;
          if (d < 0) {
            return 0;
          }
          var t = (-b - Math.sqrt(d)) / (2 * a);
          if (t < 0) {
            sphere_0.radius = capsule.radius;
            var _BO = Vec3.subtract(v3_5, B, O);
            if (OA.lengthSqr() < _BO.lengthSqr()) {
              sphere_0.center.set(capsule.ellipseCenter0);
            } else {
              sphere_0.center.set(capsule.ellipseCenter1);
            }
            return intersect.raySphere(ray, sphere_0);
          } else {
            var iPos = Vec3.scaleAndAdd(v3_5, ray.o, vRayNorm, t);
            var iPosLen = Vec3.subtract(v3_6, iPos, A);
            var tLimit = Vec3.dot(iPosLen, BA) / ab2;
            if (tLimit >= 0 && tLimit <= 1) {
              return t;
            } else if (tLimit < 0) {
              sphere_0.radius = capsule.radius;
              sphere_0.center.set(capsule.ellipseCenter0);
              return intersect.raySphere(ray, sphere_0);
            } else if (tLimit > 1) {
              sphere_0.radius = capsule.radius;
              sphere_0.center.set(capsule.ellipseCenter1);
              return intersect.raySphere(ray, sphere_0);
            } else {
              return 0;
            }
          }
        };
      }();
      var linePlane = function () {
        var ab = new Vec3(0, 0, 0);
        return function (line, plane) {
          Vec3.subtract(ab, line.e, line.s);
          var t = -point_plane(line.s, plane) / Vec3.dot(ab, plane.n);
          if (t < 0 || t > 1) {
            return 0;
          }
          return t;
        };
      }();
      var lineTriangle = function () {
        var ab = new Vec3(0, 0, 0);
        var ac = new Vec3(0, 0, 0);
        var qp = new Vec3(0, 0, 0);
        var ap = new Vec3(0, 0, 0);
        var n = new Vec3(0, 0, 0);
        var e = new Vec3(0, 0, 0);
        return function (line, triangle, outPt) {
          Vec3.subtract(ab, triangle.b, triangle.a);
          Vec3.subtract(ac, triangle.c, triangle.a);
          Vec3.subtract(qp, line.s, line.e);
          Vec3.cross(n, ab, ac);
          var det = Vec3.dot(qp, n);
          if (det <= 0.0) {
            return 0;
          }
          Vec3.subtract(ap, line.s, triangle.a);
          var t = Vec3.dot(ap, n);
          if (t < 0 || t > det) {
            return 0;
          }
          Vec3.cross(e, qp, ap);
          var v = Vec3.dot(ac, e);
          if (v < 0 || v > det) {
            return 0;
          }
          var w = -Vec3.dot(ab, e);
          if (w < 0.0 || v + w > det) {
            return 0;
          }
          if (outPt) {
            var invDet = 1.0 / det;
            v *= invDet;
            w *= invDet;
            var u = 1.0 - v - w;
            Vec3.set(outPt, triangle.a.x * u + triangle.b.x * v + triangle.c.x * w, triangle.a.y * u + triangle.b.y * v + triangle.c.y * w, triangle.a.z * u + triangle.b.z * v + triangle.c.z * w);
          }
          return 1;
        };
      }();
      var r_t = new Ray();
      function lineAABB(line, aabb) {
        r_t.o.set(line.s);
        Vec3.subtract(r_t.d, line.e, line.s);
        r_t.d.normalize();
        var min = rayAABB(r_t, aabb);
        var len = line.length();
        if (min <= len) {
          return min;
        } else {
          return 0;
        }
      }
      function lineOBB(line, obb) {
        r_t.o.set(line.s);
        Vec3.subtract(r_t.d, line.e, line.s);
        r_t.d.normalize();
        var min = rayOBB(r_t, obb);
        var len = line.length();
        if (min <= len) {
          return min;
        } else {
          return 0;
        }
      }
      function lineSphere(line, sphere) {
        r_t.o.set(line.s);
        Vec3.subtract(r_t.d, line.e, line.s);
        r_t.d.normalize();
        var min = raySphere(r_t, sphere);
        var len = line.length();
        if (min <= len) {
          return min;
        } else {
          return 0;
        }
      }
      var aabbWithAABB = function () {
        var aMin = new Vec3();
        var aMax = new Vec3();
        var bMin = new Vec3();
        var bMax = new Vec3();
        return function (aabb1, aabb2) {
          Vec3.subtract(aMin, aabb1.center, aabb1.halfExtents);
          Vec3.add(aMax, aabb1.center, aabb1.halfExtents);
          Vec3.subtract(bMin, aabb2.center, aabb2.halfExtents);
          Vec3.add(bMax, aabb2.center, aabb2.halfExtents);
          return aMin.x <= bMax.x && aMax.x >= bMin.x && aMin.y <= bMax.y && aMax.y >= bMin.y && aMin.z <= bMax.z && aMax.z >= bMin.z;
        };
      }();
      function getAABBVertices(min, max, out) {
        Vec3.set(out[0], min.x, max.y, max.z);
        Vec3.set(out[1], min.x, max.y, min.z);
        Vec3.set(out[2], min.x, min.y, max.z);
        Vec3.set(out[3], min.x, min.y, min.z);
        Vec3.set(out[4], max.x, max.y, max.z);
        Vec3.set(out[5], max.x, max.y, min.z);
        Vec3.set(out[6], max.x, min.y, max.z);
        Vec3.set(out[7], max.x, min.y, min.z);
      }
      function getOBBVertices(c, e, a1, a2, a3, out) {
        Vec3.set(out[0], c.x + a1.x * e.x + a2.x * e.y + a3.x * e.z, c.y + a1.y * e.x + a2.y * e.y + a3.y * e.z, c.z + a1.z * e.x + a2.z * e.y + a3.z * e.z);
        Vec3.set(out[1], c.x - a1.x * e.x + a2.x * e.y + a3.x * e.z, c.y - a1.y * e.x + a2.y * e.y + a3.y * e.z, c.z - a1.z * e.x + a2.z * e.y + a3.z * e.z);
        Vec3.set(out[2], c.x + a1.x * e.x - a2.x * e.y + a3.x * e.z, c.y + a1.y * e.x - a2.y * e.y + a3.y * e.z, c.z + a1.z * e.x - a2.z * e.y + a3.z * e.z);
        Vec3.set(out[3], c.x + a1.x * e.x + a2.x * e.y - a3.x * e.z, c.y + a1.y * e.x + a2.y * e.y - a3.y * e.z, c.z + a1.z * e.x + a2.z * e.y - a3.z * e.z);
        Vec3.set(out[4], c.x - a1.x * e.x - a2.x * e.y - a3.x * e.z, c.y - a1.y * e.x - a2.y * e.y - a3.y * e.z, c.z - a1.z * e.x - a2.z * e.y - a3.z * e.z);
        Vec3.set(out[5], c.x + a1.x * e.x - a2.x * e.y - a3.x * e.z, c.y + a1.y * e.x - a2.y * e.y - a3.y * e.z, c.z + a1.z * e.x - a2.z * e.y - a3.z * e.z);
        Vec3.set(out[6], c.x - a1.x * e.x + a2.x * e.y - a3.x * e.z, c.y - a1.y * e.x + a2.y * e.y - a3.y * e.z, c.z - a1.z * e.x + a2.z * e.y - a3.z * e.z);
        Vec3.set(out[7], c.x - a1.x * e.x - a2.x * e.y + a3.x * e.z, c.y - a1.y * e.x - a2.y * e.y + a3.y * e.z, c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z);
      }
      function getInterval(vertices, axis) {
        var min = Vec3.dot(axis, vertices[0]);
        var max = min;
        for (var i = 1; i < 8; ++i) {
          var projection = Vec3.dot(axis, vertices[i]);
          min = projection < min ? projection : min;
          max = projection > max ? projection : max;
        }
        return [min, max];
      }
      var aabbWithOBB = function () {
        var test = new Array(15);
        for (var i = 0; i < 15; i++) {
          test[i] = new Vec3(0, 0, 0);
        }
        var vertices = new Array(8);
        var vertices2 = new Array(8);
        for (var _i = 0; _i < 8; _i++) {
          vertices[_i] = new Vec3(0, 0, 0);
          vertices2[_i] = new Vec3(0, 0, 0);
        }
        var min = new Vec3();
        var max = new Vec3();
        return function (aabb, obb) {
          Vec3.set(test[0], 1, 0, 0);
          Vec3.set(test[1], 0, 1, 0);
          Vec3.set(test[2], 0, 0, 1);
          Vec3.set(test[3], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
          Vec3.set(test[4], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
          Vec3.set(test[5], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
          for (var _i2 = 0; _i2 < 3; ++_i2) {
            Vec3.cross(test[6 + _i2 * 3 + 0], test[_i2], test[3]);
            Vec3.cross(test[6 + _i2 * 3 + 1], test[_i2], test[4]);
            Vec3.cross(test[6 + _i2 * 3 + 1], test[_i2], test[5]);
          }
          Vec3.subtract(min, aabb.center, aabb.halfExtents);
          Vec3.add(max, aabb.center, aabb.halfExtents);
          getAABBVertices(min, max, vertices);
          getOBBVertices(obb.center, obb.halfExtents, test[3], test[4], test[5], vertices2);
          for (var j = 0; j < 15; ++j) {
            var a = getInterval(vertices, test[j]);
            var b = getInterval(vertices2, test[j]);
            if (b[0] > a[1] || a[0] > b[1]) {
              return 0;
            }
          }
          return 1;
        };
      }();
      var aabbPlane = function aabbPlane(aabb, plane) {
        var r = aabb.halfExtents.x * Math.abs(plane.n.x) + aabb.halfExtents.y * Math.abs(plane.n.y) + aabb.halfExtents.z * Math.abs(plane.n.z);
        var dot = Vec3.dot(plane.n, aabb.center);
        if (dot + r < plane.d) {
          return -1;
        } else if (dot - r > plane.d) {
          return 0;
        }
        return 1;
      };
      var aabbFrustum = function aabbFrustum(aabb, frustum) {
        for (var i = 0; i < frustum.planes.length; i++) {
          if (aabbPlane(aabb, frustum.planes[i]) === -1) {
            return 0;
          }
        }
        return 1;
      };
      var aabbFrustumCompletelyInside = function aabbFrustumCompletelyInside(aabb, frustum) {
        for (var i = 0; i < frustum.planes.length; i++) {
          if (aabbPlane(aabb, frustum.planes[i]) !== 0) {
            return 0;
          }
        }
        return 1;
      };
      var aabbFrustumAccurate = function () {
        var tmp = new Array(8);
        var out1 = 0;
        var out2 = 0;
        for (var i = 0; i < tmp.length; i++) {
          tmp[i] = new Vec3(0, 0, 0);
        }
        return function (aabb, frustum) {
          var result = 0;
          var intersects = false;
          for (var _i3 = 0; _i3 < frustum.planes.length; _i3++) {
            result = aabbPlane(aabb, frustum.planes[_i3]);
            if (result === -1) return 0;else if (result === 1) {
              intersects = true;
            }
          }
          if (!intersects) {
            return 1;
          }
          for (var _i4 = 0; _i4 < frustum.vertices.length; _i4++) {
            Vec3.subtract(tmp[_i4], frustum.vertices[_i4], aabb.center);
          }
          out1 = 0, out2 = 0;
          for (var _i5 = 0; _i5 < frustum.vertices.length; _i5++) {
            if (tmp[_i5].x > aabb.halfExtents.x) {
              out1++;
            } else if (tmp[_i5].x < -aabb.halfExtents.x) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          out1 = 0;
          out2 = 0;
          for (var _i6 = 0; _i6 < frustum.vertices.length; _i6++) {
            if (tmp[_i6].y > aabb.halfExtents.y) {
              out1++;
            } else if (tmp[_i6].y < -aabb.halfExtents.y) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          out1 = 0;
          out2 = 0;
          for (var _i7 = 0; _i7 < frustum.vertices.length; _i7++) {
            if (tmp[_i7].z > aabb.halfExtents.z) {
              out1++;
            } else if (tmp[_i7].z < -aabb.halfExtents.z) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          return 1;
        };
      }();
      var obbPoint = function () {
        var tmp = new Vec3(0, 0, 0);
        var m3 = new Mat3();
        var lessThan = function lessThan(a, b) {
          return Math.abs(a.x) < b.x && Math.abs(a.y) < b.y && Math.abs(a.z) < b.z;
        };
        return function (obb, point) {
          Vec3.subtract(tmp, point, obb.center);
          Vec3.transformMat3(tmp, tmp, Mat3.transpose(m3, obb.orientation));
          return lessThan(tmp, obb.halfExtents);
        };
      }();
      var obbPlane = function () {
        var absDot = function absDot(n, x, y, z) {
          return Math.abs(n.x * x + n.y * y + n.z * z);
        };
        return function (obb, plane) {
          var r = obb.halfExtents.x * absDot(plane.n, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02) + obb.halfExtents.y * absDot(plane.n, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05) + obb.halfExtents.z * absDot(plane.n, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
          var dot = Vec3.dot(plane.n, obb.center);
          if (dot + r < plane.d) {
            return -1;
          } else if (dot - r > plane.d) {
            return 0;
          }
          return 1;
        };
      }();
      var obbFrustum = function obbFrustum(obb, frustum) {
        for (var i = 0; i < frustum.planes.length; i++) {
          if (obbPlane(obb, frustum.planes[i]) === -1) {
            return 0;
          }
        }
        return 1;
      };
      var obbFrustumAccurate = function () {
        var tmp = new Array(8);
        var dist = 0;
        var out1 = 0;
        var out2 = 0;
        for (var i = 0; i < tmp.length; i++) {
          tmp[i] = new Vec3(0, 0, 0);
        }
        var dot = function dot(n, x, y, z) {
          return n.x * x + n.y * y + n.z * z;
        };
        return function (obb, frustum) {
          var result = 0;
          var intersects = false;
          for (var _i8 = 0; _i8 < frustum.planes.length; _i8++) {
            result = obbPlane(obb, frustum.planes[_i8]);
            if (result === -1) return 0;else if (result === 1) {
              intersects = true;
            }
          }
          if (!intersects) {
            return 1;
          }
          for (var _i9 = 0; _i9 < frustum.vertices.length; _i9++) {
            Vec3.subtract(tmp[_i9], frustum.vertices[_i9], obb.center);
          }
          out1 = 0, out2 = 0;
          for (var _i10 = 0; _i10 < frustum.vertices.length; _i10++) {
            dist = dot(tmp[_i10], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
            if (dist > obb.halfExtents.x) {
              out1++;
            } else if (dist < -obb.halfExtents.x) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          out1 = 0;
          out2 = 0;
          for (var _i11 = 0; _i11 < frustum.vertices.length; _i11++) {
            dist = dot(tmp[_i11], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
            if (dist > obb.halfExtents.y) {
              out1++;
            } else if (dist < -obb.halfExtents.y) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          out1 = 0;
          out2 = 0;
          for (var _i12 = 0; _i12 < frustum.vertices.length; _i12++) {
            dist = dot(tmp[_i12], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
            if (dist > obb.halfExtents.z) {
              out1++;
            } else if (dist < -obb.halfExtents.z) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          return 1;
        };
      }();
      var obbWithOBB = function () {
        var test = new Array(15);
        for (var i = 0; i < 15; i++) {
          test[i] = new Vec3(0, 0, 0);
        }
        var vertices = new Array(8);
        var vertices2 = new Array(8);
        for (var _i13 = 0; _i13 < 8; _i13++) {
          vertices[_i13] = new Vec3(0, 0, 0);
          vertices2[_i13] = new Vec3(0, 0, 0);
        }
        return function (obb1, obb2) {
          Vec3.set(test[0], obb1.orientation.m00, obb1.orientation.m01, obb1.orientation.m02);
          Vec3.set(test[1], obb1.orientation.m03, obb1.orientation.m04, obb1.orientation.m05);
          Vec3.set(test[2], obb1.orientation.m06, obb1.orientation.m07, obb1.orientation.m08);
          Vec3.set(test[3], obb2.orientation.m00, obb2.orientation.m01, obb2.orientation.m02);
          Vec3.set(test[4], obb2.orientation.m03, obb2.orientation.m04, obb2.orientation.m05);
          Vec3.set(test[5], obb2.orientation.m06, obb2.orientation.m07, obb2.orientation.m08);
          for (var _i14 = 0; _i14 < 3; ++_i14) {
            Vec3.cross(test[6 + _i14 * 3 + 0], test[_i14], test[3]);
            Vec3.cross(test[6 + _i14 * 3 + 1], test[_i14], test[4]);
            Vec3.cross(test[6 + _i14 * 3 + 2], test[_i14], test[5]);
          }
          getOBBVertices(obb1.center, obb1.halfExtents, test[0], test[1], test[2], vertices);
          getOBBVertices(obb2.center, obb2.halfExtents, test[3], test[4], test[5], vertices2);
          for (var _i15 = 0; _i15 < 15; ++_i15) {
            var a = getInterval(vertices, test[_i15]);
            var b = getInterval(vertices2, test[_i15]);
            if (b[0] > a[1] || a[0] > b[1]) {
              return 0;
            }
          }
          return 1;
        };
      }();
      var obbCapsule = function () {
        var sphere_0 = new Sphere();
        var v3_0 = new Vec3();
        var v3_1 = new Vec3();
        var v3_2 = new Vec3();
        var v3_verts8 = new Array(8);
        for (var i = 0; i < 8; i++) {
          v3_verts8[i] = new Vec3();
        }
        var v3_axis8 = new Array(8);
        for (var _i16 = 0; _i16 < 8; _i16++) {
          v3_axis8[_i16] = new Vec3();
        }
        return function (obb, capsule) {
          var h = Vec3.squaredDistance(capsule.ellipseCenter0, capsule.ellipseCenter1);
          if (h === 0) {
            sphere_0.radius = capsule.radius;
            sphere_0.center.set(capsule.ellipseCenter0);
            return intersect.sphereOBB(sphere_0, obb);
          } else {
            v3_0.x = obb.orientation.m00;
            v3_0.y = obb.orientation.m01;
            v3_0.z = obb.orientation.m02;
            v3_1.x = obb.orientation.m03;
            v3_1.y = obb.orientation.m04;
            v3_1.z = obb.orientation.m05;
            v3_2.x = obb.orientation.m06;
            v3_2.y = obb.orientation.m07;
            v3_2.z = obb.orientation.m08;
            getOBBVertices(obb.center, obb.halfExtents, v3_0, v3_1, v3_2, v3_verts8);
            var axes = v3_axis8;
            var a0 = Vec3.copy(axes[0], v3_0);
            var a1 = Vec3.copy(axes[1], v3_1);
            var a2 = Vec3.copy(axes[2], v3_2);
            var C = Vec3.subtract(axes[3], capsule.center, obb.center);
            C.normalize();
            var B = Vec3.subtract(axes[4], capsule.ellipseCenter0, capsule.ellipseCenter1);
            B.normalize();
            Vec3.cross(axes[5], a0, B);
            Vec3.cross(axes[6], a1, B);
            Vec3.cross(axes[7], a2, B);
            for (var _i17 = 0; _i17 < 8; ++_i17) {
              var a = getInterval(v3_verts8, axes[_i17]);
              var d0 = Vec3.dot(axes[_i17], capsule.ellipseCenter0);
              var d1 = Vec3.dot(axes[_i17], capsule.ellipseCenter1);
              var max_d = Math.max(d0, d1);
              var min_d = Math.min(d0, d1);
              var d_min = min_d - capsule.radius;
              var d_max = max_d + capsule.radius;
              if (d_min > a[1] || a[0] > d_max) {
                return 0;
              }
            }
            return 1;
          }
        };
      }();
      var spherePlane = function spherePlane(sphere, plane) {
        var dot = Vec3.dot(plane.n, sphere.center);
        var r = sphere.radius * plane.n.length();
        if (dot + r < plane.d) {
          return -1;
        } else if (dot - r > plane.d) {
          return 0;
        }
        return 1;
      };
      var sphereFrustum = function sphereFrustum(sphere, frustum) {
        for (var i = 0; i < frustum.planes.length; i++) {
          if (spherePlane(sphere, frustum.planes[i]) === -1) {
            return 0;
          }
        }
        return 1;
      };
      var sphereFrustumAccurate = function () {
        var pt = new Vec3(0, 0, 0);
        var map = [1, -1, 1, -1, 1, -1];
        return function (sphere, frustum) {
          for (var i = 0; i < 6; i++) {
            var _plane = frustum.planes[i];
            var _r = sphere.radius;
            var c = sphere.center;
            var n = _plane.n;
            var d = _plane.d;
            var dot = Vec3.dot(n, c);
            if (dot + _r < d) return 0;else if (dot - _r > d) {
              continue;
            }
            Vec3.add(pt, c, Vec3.multiplyScalar(pt, n, _r));
            for (var j = 0; j < 6; j++) {
              if (j === i || j === i + map[i]) {
                continue;
              }
              var test = frustum.planes[j];
              if (Vec3.dot(test.n, pt) < test.d) {
                return 0;
              }
            }
          }
          return 1;
        };
      }();
      var sphereWithSphere = function sphereWithSphere(sphere0, sphere1) {
        var r = sphere0.radius + sphere1.radius;
        return Vec3.squaredDistance(sphere0.center, sphere1.center) < r * r;
      };
      var sphereAABB = function () {
        var pt = new Vec3();
        return function (sphere, aabb) {
          pt_point_aabb(pt, sphere.center, aabb);
          return Vec3.squaredDistance(sphere.center, pt) < sphere.radius * sphere.radius;
        };
      }();
      var sphereOBB = function () {
        var pt = new Vec3();
        return function (sphere, obb) {
          pt_point_obb(pt, sphere.center, obb);
          return Vec3.squaredDistance(sphere.center, pt) < sphere.radius * sphere.radius;
        };
      }();
      var sphereCapsule = function () {
        var v3_0 = new Vec3();
        var v3_1 = new Vec3();
        return function (sphere, capsule) {
          var r = sphere.radius + capsule.radius;
          var squaredR = r * r;
          var h = Vec3.squaredDistance(capsule.ellipseCenter0, capsule.ellipseCenter1);
          if (h === 0) {
            return Vec3.squaredDistance(sphere.center, capsule.center) < squaredR;
          } else {
            Vec3.subtract(v3_0, sphere.center, capsule.ellipseCenter0);
            Vec3.subtract(v3_1, capsule.ellipseCenter1, capsule.ellipseCenter0);
            var t = Vec3.dot(v3_0, v3_1) / h;
            if (t < 0) {
              return Vec3.squaredDistance(sphere.center, capsule.ellipseCenter0) < squaredR;
            } else if (t > 1) {
              return Vec3.squaredDistance(sphere.center, capsule.ellipseCenter1) < squaredR;
            } else {
              Vec3.scaleAndAdd(v3_0, capsule.ellipseCenter0, v3_1, t);
              return Vec3.squaredDistance(sphere.center, v3_0) < squaredR;
            }
          }
        };
      }();
      var capsuleWithCapsule = function () {
        var v3_0 = new Vec3();
        var v3_1 = new Vec3();
        var v3_2 = new Vec3();
        var v3_3 = new Vec3();
        var v3_4 = new Vec3();
        var v3_5 = new Vec3();
        return function capsuleWithCapsule(capsuleA, capsuleB) {
          var u = Vec3.subtract(v3_0, capsuleA.ellipseCenter1, capsuleA.ellipseCenter0);
          var v = Vec3.subtract(v3_1, capsuleB.ellipseCenter1, capsuleB.ellipseCenter0);
          var w = Vec3.subtract(v3_2, capsuleA.ellipseCenter0, capsuleB.ellipseCenter0);
          var a = Vec3.dot(u, u);
          var b = Vec3.dot(u, v);
          var c = Vec3.dot(v, v);
          var d = Vec3.dot(u, w);
          var e = Vec3.dot(v, w);
          var D = a * c - b * b;
          var sN;
          var sD = D;
          var tN;
          var tD = D;
          if (D < EPSILON$3) {
            sN = 0.0;
            sD = 1.0;
            tN = e;
            tD = c;
          } else {
            sN = b * e - c * d;
            tN = a * e - b * d;
            if (sN < 0.0) {
              sN = 0.0;
              tN = e;
              tD = c;
            } else if (sN > sD) {
              sN = sD;
              tN = e + b;
              tD = c;
            }
          }
          if (tN < 0.0) {
            tN = 0.0;
            if (-d < 0.0) {
              sN = 0.0;
            } else if (-d > a) {
              sN = sD;
            } else {
              sN = -d;
              sD = a;
            }
          } else if (tN > tD) {
            tN = tD;
            if (-d + b < 0.0) {
              sN = 0;
            } else if (-d + b > a) {
              sN = sD;
            } else {
              sN = -d + b;
              sD = a;
            }
          }
          var sc = Math.abs(sN) < EPSILON$3 ? 0.0 : sN / sD;
          var tc = Math.abs(tN) < EPSILON$3 ? 0.0 : tN / tD;
          var dP = v3_3;
          dP.set(w);
          dP.add(Vec3.multiplyScalar(v3_4, u, sc));
          dP.subtract(Vec3.multiplyScalar(v3_5, v, tc));
          var radius = capsuleA.radius + capsuleB.radius;
          return dP.lengthSqr() < radius * radius;
        };
      }();
      var intersect = {
        raySphere: raySphere,
        rayAABB: rayAABB,
        rayOBB: rayOBB,
        rayPlane: rayPlane,
        rayTriangle: rayTriangle,
        rayCapsule: rayCapsule,
        raySubMesh: null,
        rayMesh: null,
        rayModel: null,
        lineSphere: lineSphere,
        lineAABB: lineAABB,
        lineOBB: lineOBB,
        linePlane: linePlane,
        lineTriangle: lineTriangle,
        sphereWithSphere: sphereWithSphere,
        sphereAABB: sphereAABB,
        sphereOBB: sphereOBB,
        spherePlane: spherePlane,
        sphereFrustum: sphereFrustum,
        sphereFrustumAccurate: sphereFrustumAccurate,
        sphereCapsule: sphereCapsule,
        aabbWithAABB: aabbWithAABB,
        aabbWithOBB: aabbWithOBB,
        aabbPlane: aabbPlane,
        aabbFrustum: aabbFrustum,
        aabbFrustumAccurate: aabbFrustumAccurate,
        obbWithOBB: obbWithOBB,
        obbPlane: obbPlane,
        obbFrustum: obbFrustum,
        obbFrustumAccurate: obbFrustumAccurate,
        obbPoint: obbPoint,
        obbCapsule: obbCapsule,
        aabbFrustumCompletelyInside: aabbFrustumCompletelyInside,
        capsuleWithCapsule: capsuleWithCapsule,
        resolve: function resolve(g1, g2, outPt) {
          if (outPt === void 0) {
            outPt = null;
          }
          var type1 = g1._type;
          var type2 = g2._type;
          var resolver = this[type1 | type2];
          return type1 < type2 ? resolver(g1, g2, outPt) : resolver(g2, g1, outPt);
        }
      };
      intersect[enums.SHAPE_RAY | enums.SHAPE_SPHERE] = raySphere;
      intersect[enums.SHAPE_RAY | enums.SHAPE_AABB] = rayAABB;
      intersect[enums.SHAPE_RAY | enums.SHAPE_OBB] = rayOBB;
      intersect[enums.SHAPE_RAY | enums.SHAPE_PLANE] = rayPlane;
      intersect[enums.SHAPE_RAY | enums.SHAPE_TRIANGLE] = rayTriangle;
      intersect[enums.SHAPE_RAY | enums.SHAPE_CAPSULE] = rayCapsule;
      intersect[enums.SHAPE_LINE | enums.SHAPE_SPHERE] = lineSphere;
      intersect[enums.SHAPE_LINE | enums.SHAPE_AABB] = lineAABB;
      intersect[enums.SHAPE_LINE | enums.SHAPE_OBB] = lineOBB;
      intersect[enums.SHAPE_LINE | enums.SHAPE_PLANE] = linePlane;
      intersect[enums.SHAPE_LINE | enums.SHAPE_TRIANGLE] = lineTriangle;
      intersect[enums.SHAPE_SPHERE] = sphereWithSphere;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_AABB] = sphereAABB;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_OBB] = sphereOBB;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_PLANE] = spherePlane;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM] = sphereFrustum;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM_ACCURATE] = sphereFrustumAccurate;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_CAPSULE] = sphereCapsule;
      intersect[enums.SHAPE_AABB] = aabbWithAABB;
      intersect[enums.SHAPE_AABB | enums.SHAPE_OBB] = aabbWithOBB;
      intersect[enums.SHAPE_AABB | enums.SHAPE_PLANE] = aabbPlane;
      intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM] = aabbFrustum;
      intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM_ACCURATE] = aabbFrustumAccurate;
      intersect[enums.SHAPE_OBB] = obbWithOBB;
      intersect[enums.SHAPE_OBB | enums.SHAPE_PLANE] = obbPlane;
      intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM] = obbFrustum;
      intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM_ACCURATE] = obbFrustumAccurate;
      intersect[enums.SHAPE_OBB | enums.SHAPE_CAPSULE] = obbCapsule;
      intersect[enums.SHAPE_CAPSULE] = capsuleWithCapsule;

      replaceProperty(Line$1.prototype, 'line', [{
        name: 'mag',
        newName: 'len'
      }, {
        name: 'magnitude',
        newName: 'len'
      }]);
      removeProperty(intersect, 'intersect', [{
        name: 'line_quad'
      }]);

      var v1 = new Vec3(0, 0, 0);
      var v2 = new Vec3(0, 0, 0);
      var temp_mat = legacyCC.mat4();
      var temp_vec4 = legacyCC.v4();
      var Plane = function () {
        Plane.create = function create(nx, ny, nz, d) {
          return new Plane(nx, ny, nz, d);
        };
        Plane.clone = function clone(p) {
          return new Plane(p.n.x, p.n.y, p.n.z, p.d);
        };
        Plane.copy = function copy(out, p) {
          Vec3.copy(out.n, p.n);
          out.d = p.d;
          return out;
        };
        Plane.fromPoints = function fromPoints(out, a, b, c) {
          Vec3.subtract(v1, b, a);
          Vec3.subtract(v2, c, a);
          Vec3.normalize(out.n, Vec3.cross(out.n, v1, v2));
          out.d = Vec3.dot(out.n, a);
          return out;
        };
        Plane.set = function set(out, nx, ny, nz, d) {
          out.n.x = nx;
          out.n.y = ny;
          out.n.z = nz;
          out.d = d;
          return out;
        };
        Plane.fromNormalAndPoint = function fromNormalAndPoint(out, normal, point) {
          Vec3.copy(out.n, normal);
          out.d = Vec3.dot(normal, point);
          return out;
        };
        Plane.normalize = function normalize(out, a) {
          var len = a.n.length();
          Vec3.normalize(out.n, a.n);
          if (len > 0) {
            out.d = a.d / len;
          }
          return out;
        };
        function Plane(nx, ny, nz, d) {
          if (nx === void 0) {
            nx = 0;
          }
          if (ny === void 0) {
            ny = 1;
          }
          if (nz === void 0) {
            nz = 0;
          }
          if (d === void 0) {
            d = 0;
          }
          this.n = void 0;
          this._type = enums.SHAPE_PLANE;
          this.n = new Vec3(nx, ny, nz);
          this.d = d;
        }
        var _proto = Plane.prototype;
        _proto.transform = function transform(mat) {
          Mat4.invert(temp_mat, mat);
          Mat4.transpose(temp_mat, temp_mat);
          Vec4.set(temp_vec4, this.n.x, this.n.y, this.n.z, -this.d);
          Vec4.transformMat4(temp_vec4, temp_vec4, temp_mat);
          Vec3.set(this.n, temp_vec4.x, temp_vec4.y, temp_vec4.z);
          this.d = -temp_vec4.w;
        };
        _createClass(Plane, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "x",
          get: function get() {
            return this.n.x;
          },
          set: function set(val) {
            this.n.x = val;
          }
        }, {
          key: "y",
          get: function get() {
            return this.n.y;
          },
          set: function set(val) {
            this.n.y = val;
          }
        }, {
          key: "z",
          get: function get() {
            return this.n.z;
          },
          set: function set(val) {
            this.n.z = val;
          }
        }, {
          key: "w",
          get: function get() {
            return this.d;
          },
          set: function set(val) {
            this.d = val;
          }
        }]);
        return Plane;
      }();

      var Triangle$1 = function () {
        Triangle.create = function create(ax, ay, az, bx, by, bz, cx, cy, cz) {
          if (ax === void 0) {
            ax = 1;
          }
          if (ay === void 0) {
            ay = 0;
          }
          if (az === void 0) {
            az = 0;
          }
          if (bx === void 0) {
            bx = 0;
          }
          if (by === void 0) {
            by = 0;
          }
          if (bz === void 0) {
            bz = 0;
          }
          if (cx === void 0) {
            cx = 0;
          }
          if (cy === void 0) {
            cy = 0;
          }
          if (cz === void 0) {
            cz = 1;
          }
          return new Triangle(ax, ay, az, bx, by, bz, cx, cy, cz);
        };
        Triangle.clone = function clone(t) {
          return new Triangle(t.a.x, t.a.y, t.a.z, t.b.x, t.b.y, t.b.z, t.c.x, t.c.y, t.c.z);
        };
        Triangle.copy = function copy(out, t) {
          Vec3.copy(out.a, t.a);
          Vec3.copy(out.b, t.b);
          Vec3.copy(out.c, t.c);
          return out;
        };
        Triangle.fromPoints = function fromPoints(out, a, b, c) {
          Vec3.copy(out.a, a);
          Vec3.copy(out.b, b);
          Vec3.copy(out.c, c);
          return out;
        };
        Triangle.set = function set(out, ax, ay, az, bx, by, bz, cx, cy, cz) {
          out.a.x = ax;
          out.a.y = ay;
          out.a.z = az;
          out.b.x = bx;
          out.b.y = by;
          out.b.z = bz;
          out.c.x = cx;
          out.c.y = cy;
          out.c.z = cz;
          return out;
        };
        function Triangle(ax, ay, az, bx, by, bz, cx, cy, cz) {
          if (ax === void 0) {
            ax = 0;
          }
          if (ay === void 0) {
            ay = 0;
          }
          if (az === void 0) {
            az = 0;
          }
          if (bx === void 0) {
            bx = 1;
          }
          if (by === void 0) {
            by = 0;
          }
          if (bz === void 0) {
            bz = 0;
          }
          if (cx === void 0) {
            cx = 0;
          }
          if (cy === void 0) {
            cy = 1;
          }
          if (cz === void 0) {
            cz = 0;
          }
          this.a = void 0;
          this.b = void 0;
          this.c = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_TRIANGLE;
          this.a = new Vec3(ax, ay, az);
          this.b = new Vec3(bx, by, bz);
          this.c = new Vec3(cx, cy, cz);
        }
        _createClass(Triangle, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Triangle;
      }();

      var _v3_tmp$1 = new Vec3();
      var _v3_tmp2$1 = new Vec3();
      var _v3_tmp3 = new Vec3();
      var _v3_tmp4 = new Vec3();
      var _m3_tmp$1 = new Mat3();
      var transform_extent_m4 = function transform_extent_m4(out, extent, m4) {
        _m3_tmp$1.m00 = Math.abs(m4.m00);
        _m3_tmp$1.m01 = Math.abs(m4.m01);
        _m3_tmp$1.m02 = Math.abs(m4.m02);
        _m3_tmp$1.m03 = Math.abs(m4.m04);
        _m3_tmp$1.m04 = Math.abs(m4.m05);
        _m3_tmp$1.m05 = Math.abs(m4.m06);
        _m3_tmp$1.m06 = Math.abs(m4.m08);
        _m3_tmp$1.m07 = Math.abs(m4.m09);
        _m3_tmp$1.m08 = Math.abs(m4.m10);
        Vec3.transformMat3(out, extent, _m3_tmp$1);
      };
      var AABB = function () {
        AABB.create = function create(px, py, pz, hw, hh, hl) {
          return new AABB(px, py, pz, hw, hh, hl);
        };
        AABB.clone = function clone(a) {
          return new AABB(a.center.x, a.center.y, a.center.z, a.halfExtents.x, a.halfExtents.y, a.halfExtents.z);
        };
        AABB.copy = function copy(out, a) {
          Vec3.copy(out.center, a.center);
          Vec3.copy(out.halfExtents, a.halfExtents);
          return out;
        };
        AABB.fromPoints = function fromPoints(out, minPos, maxPos) {
          Vec3.add(_v3_tmp$1, maxPos, minPos);
          Vec3.subtract(_v3_tmp2$1, maxPos, minPos);
          Vec3.multiplyScalar(out.center, _v3_tmp$1, 0.5);
          Vec3.multiplyScalar(out.halfExtents, _v3_tmp2$1, 0.5);
          return out;
        };
        AABB.set = function set(out, px, py, pz, hw, hh, hl) {
          out.center.set(px, py, pz);
          out.halfExtents.set(hw, hh, hl);
          return out;
        };
        AABB.merge = function merge(out, a, b) {
          Vec3.subtract(_v3_tmp$1, a.center, a.halfExtents);
          Vec3.subtract(_v3_tmp2$1, b.center, b.halfExtents);
          Vec3.add(_v3_tmp3, a.center, a.halfExtents);
          Vec3.add(_v3_tmp4, b.center, b.halfExtents);
          Vec3.max(_v3_tmp4, _v3_tmp3, _v3_tmp4);
          Vec3.min(_v3_tmp3, _v3_tmp$1, _v3_tmp2$1);
          return AABB.fromPoints(out, _v3_tmp3, _v3_tmp4);
        };
        AABB.toBoundingSphere = function toBoundingSphere(out, a) {
          out.center.set(a.center);
          out.radius = a.halfExtents.length();
          return out;
        };
        AABB.transform = function transform(out, a, matrix) {
          Vec3.transformMat4(out.center, a.center, matrix);
          transform_extent_m4(out.halfExtents, a.halfExtents, matrix);
          return out;
        };
        function AABB(px, py, pz, hw, hh, hl) {
          if (px === void 0) {
            px = 0;
          }
          if (py === void 0) {
            py = 0;
          }
          if (pz === void 0) {
            pz = 0;
          }
          if (hw === void 0) {
            hw = 1;
          }
          if (hh === void 0) {
            hh = 1;
          }
          if (hl === void 0) {
            hl = 1;
          }
          this.center = void 0;
          this.halfExtents = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_AABB;
          this.center = new Vec3(px, py, pz);
          this.halfExtents = new Vec3(hw, hh, hl);
        }
        var _proto = AABB.prototype;
        _proto.getBoundary = function getBoundary(minPos, maxPos) {
          Vec3.subtract(minPos, this.center, this.halfExtents);
          Vec3.add(maxPos, this.center, this.halfExtents);
        };
        _proto.transform = function transform(m, pos, rot, scale, out) {
          Vec3.transformMat4(out.center, this.center, m);
          transform_extent_m4(out.halfExtents, this.halfExtents, m);
        };
        _proto.clone = function clone() {
          return AABB.clone(this);
        };
        _proto.copy = function copy(a) {
          return AABB.copy(this, a);
        };
        _proto.mergePoint = function mergePoint(point) {
          this.getBoundary(_v3_tmp$1, _v3_tmp2$1);
          if (point.x < _v3_tmp$1.x) {
            _v3_tmp$1.x = point.x;
          }
          if (point.y < _v3_tmp$1.y) {
            _v3_tmp$1.y = point.y;
          }
          if (point.z < _v3_tmp$1.z) {
            _v3_tmp$1.z = point.z;
          }
          if (point.x > _v3_tmp2$1.x) {
            _v3_tmp2$1.x = point.x;
          }
          if (point.y > _v3_tmp2$1.y) {
            _v3_tmp2$1.y = point.y;
          }
          if (point.z > _v3_tmp2$1.z) {
            _v3_tmp2$1.z = point.z;
          }
          Vec3.add(_v3_tmp3, _v3_tmp$1, _v3_tmp2$1);
          this.center.set(Vec3.multiplyScalar(_v3_tmp3, _v3_tmp3, 0.5));
          this.halfExtents.set(_v3_tmp2$1.x - _v3_tmp3.x, _v3_tmp2$1.y - _v3_tmp3.y, _v3_tmp2$1.z - _v3_tmp3.z);
        };
        _proto.mergePoints = function mergePoints(points) {
          if (points.length < 1) {
            return;
          }
          for (var i = 0; i < points.length; i++) {
            this.mergePoint(points[i]);
          }
        };
        _proto.mergeFrustum = function mergeFrustum(frustum) {
          this.mergePoints(frustum.vertices);
        };
        _createClass(AABB, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return AABB;
      }();

      var Capsule = function () {
        function Capsule(radius, halfHeight, axis) {
          if (radius === void 0) {
            radius = 0.5;
          }
          if (halfHeight === void 0) {
            halfHeight = 0.5;
          }
          if (axis === void 0) {
            axis = 1;
          }
          this._type = void 0;
          this.radius = void 0;
          this.halfHeight = void 0;
          this.axis = void 0;
          this.center = void 0;
          this.rotation = void 0;
          this.ellipseCenter0 = void 0;
          this.ellipseCenter1 = void 0;
          this._type = enums.SHAPE_CAPSULE;
          this.radius = radius;
          this.halfHeight = halfHeight;
          this.axis = axis;
          this.center = new Vec3();
          this.rotation = new Quat();
          this.ellipseCenter0 = new Vec3(0, halfHeight, 0);
          this.ellipseCenter1 = new Vec3(0, -halfHeight, 0);
          this.updateCache();
        }
        var _proto = Capsule.prototype;
        _proto.transform = function transform(m, pos, rot, scale, out) {
          var ws = scale;
          var s = absMaxComponent(ws);
          out.radius = this.radius * Math.abs(s);
          var halfTotalWorldHeight = (this.halfHeight + this.radius) * Math.abs(ws.y);
          var halfWorldHeight = halfTotalWorldHeight - out.radius;
          if (halfWorldHeight < 0) halfWorldHeight = 0;
          out.halfHeight = halfWorldHeight;
          Vec3.transformMat4(out.center, this.center, m);
          Quat.multiply(out.rotation, this.rotation, rot);
          out.updateCache();
        };
        _proto.updateCache = function updateCache() {
          this.updateLocalCenter();
          Vec3.transformQuat(this.ellipseCenter0, this.ellipseCenter0, this.rotation);
          Vec3.transformQuat(this.ellipseCenter1, this.ellipseCenter1, this.rotation);
          this.ellipseCenter0.add(this.center);
          this.ellipseCenter1.add(this.center);
        };
        _proto.updateLocalCenter = function updateLocalCenter() {
          var halfHeight = this.halfHeight;
          var axis = this.axis;
          switch (axis) {
            case 0:
              this.ellipseCenter0.set(halfHeight, 0, 0);
              this.ellipseCenter1.set(-halfHeight, 0, 0);
              break;
            case 1:
              this.ellipseCenter0.set(0, halfHeight, 0);
              this.ellipseCenter1.set(0, -halfHeight, 0);
              break;
            case 2:
              this.ellipseCenter0.set(0, 0, halfHeight);
              this.ellipseCenter1.set(0, 0, -halfHeight);
              break;
          }
        };
        _createClass(Capsule, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Capsule;
      }();

      var _v$1 = new Array(8);
      _v$1[0] = new Vec3(1, 1, 1);
      _v$1[1] = new Vec3(-1, 1, 1);
      _v$1[2] = new Vec3(-1, -1, 1);
      _v$1[3] = new Vec3(1, -1, 1);
      _v$1[4] = new Vec3(1, 1, -1);
      _v$1[5] = new Vec3(-1, 1, -1);
      _v$1[6] = new Vec3(-1, -1, -1);
      _v$1[7] = new Vec3(1, -1, -1);
      var _nearTemp = new Vec3();
      var _farTemp = new Vec3();
      var _temp_v3$3 = new Vec3();
      var Frustum = function () {
        Frustum.createOrthographic = function createOrthographic(out, width, height, near, far, transform) {
          var halfWidth = width / 2;
          var halfHeight = height / 2;
          Vec3.set(_temp_v3$3, halfWidth, halfHeight, -near);
          Vec3.transformMat4(out.vertices[0], _temp_v3$3, transform);
          Vec3.set(_temp_v3$3, -halfWidth, halfHeight, -near);
          Vec3.transformMat4(out.vertices[1], _temp_v3$3, transform);
          Vec3.set(_temp_v3$3, -halfWidth, -halfHeight, -near);
          Vec3.transformMat4(out.vertices[2], _temp_v3$3, transform);
          Vec3.set(_temp_v3$3, halfWidth, -halfHeight, -near);
          Vec3.transformMat4(out.vertices[3], _temp_v3$3, transform);
          Vec3.set(_temp_v3$3, halfWidth, halfHeight, -far);
          Vec3.transformMat4(out.vertices[4], _temp_v3$3, transform);
          Vec3.set(_temp_v3$3, -halfWidth, halfHeight, -far);
          Vec3.transformMat4(out.vertices[5], _temp_v3$3, transform);
          Vec3.set(_temp_v3$3, -halfWidth, -halfHeight, -far);
          Vec3.transformMat4(out.vertices[6], _temp_v3$3, transform);
          Vec3.set(_temp_v3$3, halfWidth, -halfHeight, -far);
          Vec3.transformMat4(out.vertices[7], _temp_v3$3, transform);
          out.updatePlanes();
        };
        Frustum.createOrtho = function createOrtho(out, width, height, near, far, transform) {
          return Frustum.createOrthographic(out, width, height, near, far, transform);
        };
        Frustum.createPerspective = function createPerspective(out, aspect, fov, near, far, transform) {
          var h = Math.tan(fov * 0.5);
          var w = h * aspect;
          _nearTemp.set(near * w, near * h, near);
          _farTemp.set(far * w, far * h, far);
          var vertexes = out.vertices;
          _temp_v3$3.set(_nearTemp.x, _nearTemp.y, -_nearTemp.z);
          Vec3.transformMat4(vertexes[0], _temp_v3$3, transform);
          _temp_v3$3.set(-_nearTemp.x, _nearTemp.y, -_nearTemp.z);
          Vec3.transformMat4(vertexes[1], _temp_v3$3, transform);
          _temp_v3$3.set(-_nearTemp.x, -_nearTemp.y, -_nearTemp.z);
          Vec3.transformMat4(vertexes[2], _temp_v3$3, transform);
          _temp_v3$3.set(_nearTemp.x, -_nearTemp.y, -_nearTemp.z);
          Vec3.transformMat4(vertexes[3], _temp_v3$3, transform);
          _temp_v3$3.set(_farTemp.x, _farTemp.y, -_farTemp.z);
          Vec3.transformMat4(vertexes[4], _temp_v3$3, transform);
          _temp_v3$3.set(-_farTemp.x, _farTemp.y, -_farTemp.z);
          Vec3.transformMat4(vertexes[5], _temp_v3$3, transform);
          _temp_v3$3.set(-_farTemp.x, -_farTemp.y, -_farTemp.z);
          Vec3.transformMat4(vertexes[6], _temp_v3$3, transform);
          _temp_v3$3.set(_farTemp.x, -_farTemp.y, -_farTemp.z);
          Vec3.transformMat4(vertexes[7], _temp_v3$3, transform);
          out.updatePlanes();
        };
        Frustum.createFromAABB = function createFromAABB(out, aabb) {
          var vec3_min = new Vec3();
          var vec3_max = new Vec3();
          Vec3.subtract(vec3_min, aabb.center, aabb.halfExtents);
          Vec3.add(vec3_max, aabb.center, aabb.halfExtents);
          out.vertices[0].set(vec3_max.x, vec3_max.y, -vec3_min.z);
          out.vertices[1].set(vec3_min.x, vec3_max.y, -vec3_min.z);
          out.vertices[2].set(vec3_min.x, vec3_min.y, -vec3_min.z);
          out.vertices[3].set(vec3_max.x, vec3_min.y, -vec3_min.z);
          out.vertices[4].set(vec3_max.x, vec3_max.y, -vec3_max.z);
          out.vertices[5].set(vec3_min.x, vec3_max.y, -vec3_max.z);
          out.vertices[6].set(vec3_min.x, vec3_min.y, -vec3_max.z);
          out.vertices[7].set(vec3_max.x, vec3_min.y, -vec3_max.z);
          out.updatePlanes();
          return out;
        };
        var _proto = Frustum.prototype;
        _proto.split = function split(start, end, aspect, fov, m) {
          return Frustum.createPerspective(this, aspect, fov, start, end, m);
        };
        Frustum.create = function create() {
          return new Frustum();
        };
        Frustum.clone = function clone(f) {
          return Frustum.copy(new Frustum(), f);
        };
        Frustum.copy = function copy(out, f) {
          out._type = f.type;
          for (var i = 0; i < 6; ++i) {
            Plane.copy(out.planes[i], f.planes[i]);
          }
          for (var _i = 0; _i < 8; ++_i) {
            Vec3.copy(out.vertices[_i], f.vertices[_i]);
          }
          return out;
        };
        function Frustum() {
          this.planes = void 0;
          this.vertices = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_FRUSTUM;
          this.planes = new Array(6);
          for (var i = 0; i < 6; ++i) {
            this.planes[i] = Plane.create(0, 0, 0, 0);
          }
          this.vertices = new Array(8);
          for (var _i2 = 0; _i2 < 8; ++_i2) {
            this.vertices[_i2] = new Vec3();
          }
        }
        _proto.update = function update(m, inv) {
          Vec3.set(this.planes[0].n, m.m03 + m.m00, m.m07 + m.m04, m.m11 + m.m08);
          this.planes[0].d = -(m.m15 + m.m12);
          Vec3.set(this.planes[1].n, m.m03 - m.m00, m.m07 - m.m04, m.m11 - m.m08);
          this.planes[1].d = -(m.m15 - m.m12);
          Vec3.set(this.planes[2].n, m.m03 + m.m01, m.m07 + m.m05, m.m11 + m.m09);
          this.planes[2].d = -(m.m15 + m.m13);
          Vec3.set(this.planes[3].n, m.m03 - m.m01, m.m07 - m.m05, m.m11 - m.m09);
          this.planes[3].d = -(m.m15 - m.m13);
          Vec3.set(this.planes[4].n, m.m03 + m.m02, m.m07 + m.m06, m.m11 + m.m10);
          this.planes[4].d = -(m.m15 + m.m14);
          Vec3.set(this.planes[5].n, m.m03 - m.m02, m.m07 - m.m06, m.m11 - m.m10);
          this.planes[5].d = -(m.m15 - m.m14);
          for (var i = 0; i < 6; i++) {
            var pl = this.planes[i];
            var invDist = 1 / pl.n.length();
            Vec3.multiplyScalar(pl.n, pl.n, invDist);
            pl.d *= invDist;
          }
          for (var _i3 = 0; _i3 < 8; _i3++) {
            Vec3.transformMat4(this.vertices[_i3], _v$1[_i3], inv);
          }
        };
        _proto.transform = function transform(mat) {
          for (var i = 0; i < 8; i++) {
            Vec3.transformMat4(this.vertices[i], this.vertices[i], mat);
          }
          this.updatePlanes();
        };
        _proto.zero = function zero() {
          for (var i = 0; i < 8; i++) {
            this.vertices[i].set(0.0, 0.0, 0.0);
          }
          for (var _i4 = 0; _i4 < 6; _i4++) {
            Plane.set(this.planes[_i4], 0, 0, 0, 0);
          }
        };
        _proto.updatePlanes = function updatePlanes() {
          Plane.fromPoints(this.planes[0], this.vertices[1], this.vertices[6], this.vertices[5]);
          Plane.fromPoints(this.planes[1], this.vertices[3], this.vertices[4], this.vertices[7]);
          Plane.fromPoints(this.planes[2], this.vertices[6], this.vertices[3], this.vertices[7]);
          Plane.fromPoints(this.planes[3], this.vertices[0], this.vertices[5], this.vertices[4]);
          Plane.fromPoints(this.planes[4], this.vertices[2], this.vertices[0], this.vertices[3]);
          Plane.fromPoints(this.planes[5], this.vertices[7], this.vertices[5], this.vertices[6]);
        };
        _createClass(Frustum, [{
          key: "accurate",
          set: function set(b) {
            this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM;
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Frustum;
      }();

      var _v3_tmp = new Vec3();
      var _v3_tmp2 = new Vec3();
      var _m3_tmp = new Mat3();
      var transform_extent_m3 = function transform_extent_m3(out, extent, m3) {
        _m3_tmp.m00 = Math.abs(m3.m00);
        _m3_tmp.m01 = Math.abs(m3.m01);
        _m3_tmp.m02 = Math.abs(m3.m02);
        _m3_tmp.m03 = Math.abs(m3.m03);
        _m3_tmp.m04 = Math.abs(m3.m04);
        _m3_tmp.m05 = Math.abs(m3.m05);
        _m3_tmp.m06 = Math.abs(m3.m06);
        _m3_tmp.m07 = Math.abs(m3.m07);
        _m3_tmp.m08 = Math.abs(m3.m08);
        Vec3.transformMat3(out, extent, _m3_tmp);
      };
      var OBB = function () {
        OBB.create = function create(cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
          return new OBB(cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
        };
        OBB.clone = function clone(a) {
          return new OBB(a.center.x, a.center.y, a.center.z, a.halfExtents.x, a.halfExtents.y, a.halfExtents.z, a.orientation.m00, a.orientation.m01, a.orientation.m02, a.orientation.m03, a.orientation.m04, a.orientation.m05, a.orientation.m06, a.orientation.m07, a.orientation.m08);
        };
        OBB.copy = function copy(out, a) {
          Vec3.copy(out.center, a.center);
          Vec3.copy(out.halfExtents, a.halfExtents);
          Mat3.copy(out.orientation, a.orientation);
          return out;
        };
        OBB.fromPoints = function fromPoints(out, minPos, maxPos) {
          Vec3.multiplyScalar(out.center, Vec3.add(_v3_tmp, minPos, maxPos), 0.5);
          Vec3.multiplyScalar(out.halfExtents, Vec3.subtract(_v3_tmp2, maxPos, minPos), 0.5);
          Mat3.identity(out.orientation);
          return out;
        };
        OBB.set = function set(out, cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
          Vec3.set(out.center, cx, cy, cz);
          Vec3.set(out.halfExtents, hw, hh, hl);
          Mat3.set(out.orientation, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
          return out;
        };
        function OBB(cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
          if (cx === void 0) {
            cx = 0;
          }
          if (cy === void 0) {
            cy = 0;
          }
          if (cz === void 0) {
            cz = 0;
          }
          if (hw === void 0) {
            hw = 1;
          }
          if (hh === void 0) {
            hh = 1;
          }
          if (hl === void 0) {
            hl = 1;
          }
          if (ox_1 === void 0) {
            ox_1 = 1;
          }
          if (ox_2 === void 0) {
            ox_2 = 0;
          }
          if (ox_3 === void 0) {
            ox_3 = 0;
          }
          if (oy_1 === void 0) {
            oy_1 = 0;
          }
          if (oy_2 === void 0) {
            oy_2 = 1;
          }
          if (oy_3 === void 0) {
            oy_3 = 0;
          }
          if (oz_1 === void 0) {
            oz_1 = 0;
          }
          if (oz_2 === void 0) {
            oz_2 = 0;
          }
          if (oz_3 === void 0) {
            oz_3 = 1;
          }
          this.center = void 0;
          this.halfExtents = void 0;
          this.orientation = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_OBB;
          this.center = new Vec3(cx, cy, cz);
          this.halfExtents = new Vec3(hw, hh, hl);
          this.orientation = new Mat3(ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
        }
        var _proto = OBB.prototype;
        _proto.getBoundary = function getBoundary(minPos, maxPos) {
          transform_extent_m3(_v3_tmp, this.halfExtents, this.orientation);
          Vec3.subtract(minPos, this.center, _v3_tmp);
          Vec3.add(maxPos, this.center, _v3_tmp);
        };
        _proto.transform = function transform(m, pos, rot, scale, out) {
          Vec3.transformMat4(out.center, this.center, m);
          Mat3.fromQuat(out.orientation, rot);
          Vec3.multiply(out.halfExtents, this.halfExtents, scale);
        };
        _proto.translateAndRotate = function translateAndRotate(m, rot, out) {
          Vec3.transformMat4(out.center, this.center, m);
          Mat3.fromQuat(out.orientation, rot);
        };
        _proto.setScale = function setScale(scale, out) {
          Vec3.multiply(out.halfExtents, this.halfExtents, scale);
        };
        _createClass(OBB, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return OBB;
      }();

      function binarySearch(array, value) {
        return binarySearchEpsilon(array, value, 0);
      }
      function binarySearchEpsilon(array, value, EPSILON) {
        if (EPSILON === void 0) {
          EPSILON = 1e-6;
        }
        var low = 0;
        var high = array.length - 1;
        var middle = high >>> 1;
        for (; low <= high; middle = low + high >>> 1) {
          var test = array[middle];
          if (test > value + EPSILON) {
            high = middle - 1;
          } else if (test < value - EPSILON) {
            low = middle + 1;
          } else {
            return middle;
          }
        }
        return ~low;
      }
      function binarySearchBy(array, value, lessThan) {
        var low = 0;
        var high = array.length - 1;
        var middle = high >>> 1;
        for (; low <= high; middle = low + high >>> 1) {
          var test = array[middle];
          if (lessThan(test, value) < 0) {
            high = middle - 1;
          } else if (lessThan(test, value) > 0) {
            low = middle + 1;
          } else {
            return middle;
          }
        }
        return ~low;
      }

      var _Symbol$iterator$1;
      _Symbol$iterator$1 = Symbol.iterator;
      var KeyframeCurve = function () {
        function KeyframeCurve() {
          this._times = [];
          this._values = [];
        }
        var _proto = KeyframeCurve.prototype;
        _proto[_Symbol$iterator$1] = function () {
          var _this = this;
          var index = 0;
          return {
            next: function next() {
              if (index >= _this._times.length) {
                return {
                  done: true,
                  value: undefined
                };
              } else {
                var value = [_this._times[index], _this._values[index]];
                ++index;
                return {
                  done: false,
                  value: value
                };
              }
            }
          };
        };
        _proto.keyframes = function keyframes() {
          return this;
        };
        _proto.times = function times() {
          return this._times;
        };
        _proto.values = function values() {
          return this._values;
        };
        _proto.getKeyframeTime = function getKeyframeTime(index) {
          return this._times[index];
        };
        _proto.getKeyframeValue = function getKeyframeValue(index) {
          return this._values[index];
        };
        _proto.addKeyFrame = function addKeyFrame(time, keyframeValue) {
          return this._insertNewKeyframe(time, keyframeValue);
        };
        _proto.removeKeyframe = function removeKeyframe(index) {
          this._times.splice(index, 1);
          this._values.splice(index, 1);
        };
        _proto.indexOfKeyframe = function indexOfKeyframe(time) {
          return binarySearchEpsilon(this._times, time);
        };
        _proto.updateTime = function updateTime(index, time) {
          var value = this._values[index];
          this.removeKeyframe(index);
          this._insertNewKeyframe(time, value);
        };
        _proto.assignSorted = function assignSorted(times, values) {
          if (values !== undefined) {
            assertIsTrue(Array.isArray(times));
            this.setKeyframes(times.slice(), values.slice());
          } else {
            var _keyframes = Array.from(times);
            this.setKeyframes(_keyframes.map(function (_ref) {
              var time = _ref[0];
              return time;
            }), _keyframes.map(function (_ref2) {
              var value = _ref2[1];
              return value;
            }));
          }
        };
        _proto.clear = function clear() {
          this._times.length = 0;
          this._values.length = 0;
        };
        _proto.searchKeyframe = function searchKeyframe(time) {
          return binarySearchEpsilon(this._times, time);
        };
        _proto.setKeyframes = function setKeyframes(times, values) {
          assertIsTrue(times.length === values.length);
          assertIsTrue(isSorted(times));
          this._times = times;
          this._values = values;
        };
        _proto._insertNewKeyframe = function _insertNewKeyframe(time, value) {
          var times = this._times;
          var values = this._values;
          var nFrames = times.length;
          var index = binarySearchEpsilon(times, time);
          if (index >= 0) {
            return index;
          }
          var iNext = ~index;
          if (iNext === 0) {
            times.unshift(time);
            values.unshift(value);
          } else if (iNext === nFrames) {
            times.push(time);
            values.push(value);
          } else {
            assertIsTrue(nFrames > 1);
            times.splice(iNext - 1, 0, time);
            values.splice(iNext - 1, 0, value);
          }
          return iNext;
        };
        _createClass(KeyframeCurve, [{
          key: "keyFramesCount",
          get: function get() {
            return this._times.length;
          }
        }, {
          key: "rangeMin",
          get: function get() {
            return this._times[0];
          }
        }, {
          key: "rangeMax",
          get: function get() {
            return this._times[this._values.length - 1];
          }
        }]);
        return KeyframeCurve;
      }();
      CCClass.fastDefine('cc.KeyframeCurve', KeyframeCurve, {
        _times: [],
        _values: []
      });
      function isSorted(values) {
        return values.every(function (value, index, array) {
          return index === 0 || value > array[index - 1] || approx(value, array[index - 1], 1e-6);
        });
      }

      var RealInterpolationMode; exports('cp', RealInterpolationMode);
      (function (RealInterpolationMode) {
        RealInterpolationMode[RealInterpolationMode["LINEAR"] = 0] = "LINEAR";
        RealInterpolationMode[RealInterpolationMode["CONSTANT"] = 1] = "CONSTANT";
        RealInterpolationMode[RealInterpolationMode["CUBIC"] = 2] = "CUBIC";
      })(RealInterpolationMode || (exports('cp', RealInterpolationMode = {})));
      var ExtrapolationMode; exports('cq', ExtrapolationMode);
      (function (ExtrapolationMode) {
        ExtrapolationMode[ExtrapolationMode["LINEAR"] = 0] = "LINEAR";
        ExtrapolationMode[ExtrapolationMode["CLAMP"] = 1] = "CLAMP";
        ExtrapolationMode[ExtrapolationMode["LOOP"] = 2] = "LOOP";
        ExtrapolationMode[ExtrapolationMode["PING_PONG"] = 3] = "PING_PONG";
      })(ExtrapolationMode || (exports('cq', ExtrapolationMode = {})));
      var TangentWeightMode; exports('cr', TangentWeightMode);
      (function (TangentWeightMode) {
        TangentWeightMode[TangentWeightMode["NONE"] = 0] = "NONE";
        TangentWeightMode[TangentWeightMode["LEFT"] = 1] = "LEFT";
        TangentWeightMode[TangentWeightMode["RIGHT"] = 2] = "RIGHT";
        TangentWeightMode[TangentWeightMode["BOTH"] = 3] = "BOTH";
      })(TangentWeightMode || (exports('cr', TangentWeightMode = {})));

      function solveCubic(coeff0, coeff1, coeff2, coeff3, solutions) {
        var a = coeff2 / coeff3;
        var b = coeff1 / coeff3;
        var c = coeff0 / coeff3;
        var sqrA = a * a;
        var p = 1.0 / 3.0 * (-1.0 / 3 * sqrA + b);
        var q = 1.0 / 2.0 * (2.0 / 27.0 * a * sqrA - 1.0 / 3 * a * b + c);
        var cubicP = p * p * p;
        var d = q * q + cubicP;
        var nSolutions = 0;
        if (isZero(d)) {
          if (isZero(q)) {
            solutions[0] = 0;
            return 1;
          } else {
            var u = Math.cbrt(-q);
            solutions[0] = 2 * u;
            solutions[1] = -u;
            return 2;
          }
        } else if (d < 0) {
          var phi = 1.0 / 3 * Math.acos(-q / Math.sqrt(-cubicP));
          var t = 2 * Math.sqrt(-p);
          solutions[0] = t * Math.cos(phi);
          solutions[1] = -t * Math.cos(phi + Math.PI / 3);
          solutions[2] = -t * Math.cos(phi - Math.PI / 3);
          nSolutions = 3;
        } else {
          var sqrtD = Math.sqrt(d);
          var _u = Math.cbrt(sqrtD - q);
          var v = -Math.cbrt(sqrtD + q);
          solutions[0] = _u + v;
          nSolutions = 1;
        }
        var sub = 1.0 / 3 * a;
        for (var i = 0; i < nSolutions; ++i) {
          solutions[i] -= sub;
        }
        return nSolutions;
      }
      var EQN_EPS = 1e-9;
      function isZero(x) {
        return x > -EQN_EPS && x < EQN_EPS;
      }

      function applyDecoratedInitializer(target, property, decorators, initializer) {
        return decorators.slice().reverse().reduce(function (decoratedInitializer, decorator) {
          return decorator(target, property, decoratedInitializer) || decoratedInitializer;
        }, initializer);
      }

      var emptyDecorator = function emptyDecorator() {};
      var emptyDecoratorFn = function emptyDecoratorFn() {
        return emptyDecorator;
      };
      var emptySmartClassDecorator = makeSmartClassDecorator(function () {});
      function makeSmartClassDecorator(decorate) {
        return proxyFn;
        function proxyFn(target) {
          if (typeof target === 'function') {
            return decorate(target);
          } else {
            return function (constructor) {
              return decorate(constructor, target);
            };
          }
        }
      }
      function writeEditorClassProperty(constructor, propertyName, value) {
        var cache = getClassCache(constructor);
        if (cache) {
          var proto = getSubDict(cache, 'proto');
          getSubDict(proto, 'editor')[propertyName] = value;
        }
      }
      function makeEditorClassDecoratorFn(propertyName) {
        return function (value) {
          return function (constructor) {
            writeEditorClassProperty(constructor, propertyName, value);
          };
        };
      }
      var CACHE_KEY = '__ccclassCache__';
      function getClassCache(ctor, decoratorName) {
        return getSubDict(ctor, CACHE_KEY);
      }
      function getSubDict(obj, key) {
        return obj[key] || (obj[key] = {});
      }

      var ccclass$M = makeSmartClassDecorator(function (constructor, name) {
        var base = getSuper(constructor);
        if (base === Object) {
          base = null;
        }
        var proto = {
          name: name,
          "extends": base,
          ctor: constructor
        };
        var cache = constructor[CACHE_KEY];
        if (cache) {
          var decoratedProto = cache.proto;
          if (decoratedProto) {
            mixin(proto, decoratedProto);
          }
          constructor[CACHE_KEY] = undefined;
        }
        var res = CCClass(proto);
        return res;
      });

      var requireComponent = makeEditorClassDecoratorFn('requireComponent');
      var executionOrder$1 = makeEditorClassDecoratorFn('executionOrder');
      var disallowMultiple$1 = emptySmartClassDecorator;

      function property$3(target, propertyKey, descriptorOrInitializer) {
        var options = null;
        function normalized(target, propertyKey, descriptorOrInitializer) {
          var classStash = getOrCreateClassStash(target);
          var propertyStash = getOrCreateEmptyPropertyStash(target, propertyKey);
          var classConstructor = target.constructor;
          mergePropertyOptions(classStash, propertyStash, classConstructor, propertyKey, options, descriptorOrInitializer);
        }
        if (target === undefined) {
          return property$3({
            type: undefined
          });
        } else if (typeof propertyKey === 'undefined') {
          options = target;
          return normalized;
        } else {
          normalized(target, propertyKey, descriptorOrInitializer);
          return undefined;
        }
      }
      function getDefaultFromInitializer(initializer) {
        var value;
        try {
          value = initializer();
        } catch (e) {
          return initializer;
        }
        if (typeof value !== 'object' || value === null) {
          return value;
        } else {
          return initializer;
        }
      }
      function extractActualDefaultValues(classConstructor) {
        var dummyObj;
        try {
          dummyObj = new classConstructor();
        } catch (e) {
          return {};
        }
        return dummyObj;
      }
      function getOrCreateClassStash(target) {
        var cache = getClassCache(target.constructor);
        return cache;
      }
      function getOrCreateEmptyPropertyStash(target, propertyKey) {
        var _ref, _properties$_ref;
        var classStash = getClassCache(target.constructor);
        var ccclassProto = getSubDict(classStash, 'proto');
        var properties = getSubDict(ccclassProto, 'properties');
        var propertyStash = (_properties$_ref = properties[_ref = propertyKey]) !== null && _properties$_ref !== void 0 ? _properties$_ref : properties[_ref] = {};
        return propertyStash;
      }
      function getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer) {
        var _ref2, _properties$_ref2;
        var classStash = getClassCache(target.constructor);
        var ccclassProto = getSubDict(classStash, 'proto');
        var properties = getSubDict(ccclassProto, 'properties');
        var propertyStash = (_properties$_ref2 = properties[_ref2 = propertyKey]) !== null && _properties$_ref2 !== void 0 ? _properties$_ref2 : properties[_ref2] = {};
        propertyStash.__internalFlags |= PropertyStashInternalFlag.STANDALONE;
        if (descriptorOrInitializer && typeof descriptorOrInitializer !== 'function' && (descriptorOrInitializer.get || descriptorOrInitializer.set)) {
          if (descriptorOrInitializer.get) {
            propertyStash.get = descriptorOrInitializer.get;
          }
          if (descriptorOrInitializer.set) {
            propertyStash.set = descriptorOrInitializer.set;
          }
        } else {
          setDefaultValue(classStash, propertyStash, target.constructor, propertyKey, descriptorOrInitializer);
        }
        return propertyStash;
      }
      function mergePropertyOptions(cache, propertyStash, ctor, propertyKey, options, descriptorOrInitializer) {
        var fullOptions;
        var isGetset = descriptorOrInitializer && typeof descriptorOrInitializer !== 'function' && (descriptorOrInitializer.get || descriptorOrInitializer.set);
        if (options) {
          fullOptions = getFullFormOfProperty(options, isGetset);
        }
        var propertyRecord = mixin(propertyStash, fullOptions || options || {});
        if (isGetset) {
          if (descriptorOrInitializer.get) {
            propertyRecord.get = descriptorOrInitializer.get;
          }
          if (descriptorOrInitializer.set) {
            propertyRecord.set = descriptorOrInitializer.set;
          }
        } else {
          setDefaultValue(cache, propertyRecord, ctor, propertyKey, descriptorOrInitializer);
        }
      }
      function setDefaultValue(classStash, propertyStash, classConstructor, propertyKey, descriptorOrInitializer) {
        if (descriptorOrInitializer !== undefined) {
          if (typeof descriptorOrInitializer === 'function') {
            propertyStash["default"] = getDefaultFromInitializer(descriptorOrInitializer);
          } else if (descriptorOrInitializer === null) ; else if (descriptorOrInitializer.initializer) {
            propertyStash["default"] = getDefaultFromInitializer(descriptorOrInitializer.initializer);
          }
        } else {
          var actualDefaultValues = classStash["default"] || (classStash["default"] = extractActualDefaultValues(classConstructor));
          if (actualDefaultValues.hasOwnProperty(propertyKey)) {
            propertyStash["default"] = actualDefaultValues[propertyKey];
          }
        }
      }

      var sMetadataTag = Symbol('cc:SerializationMetadata');
      function getSerializationMetadata(constructor) {
        return constructor[sMetadataTag];
      }
      function getOrCreateSerializationMetadata(constructor) {
        var _ref, _ref$sMetadataTag;
        return (_ref$sMetadataTag = (_ref = constructor)[sMetadataTag]) !== null && _ref$sMetadataTag !== void 0 ? _ref$sMetadataTag : _ref[sMetadataTag] = {};
      }

      var serializable$p = exports('cR', function serializable(target, propertyKey, descriptorOrInitializer) {
        var propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
        setImplicitSerializable(propertyStash);
      });
      function formerlySerializedAs$4(name) {
        return function (target, propertyKey, descriptorOrInitializer) {
          var propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
          propertyStash.formerlySerializedAs = name;
          setImplicitSerializable(propertyStash);
        };
      }
      var editorOnly = function editorOnly(target, propertyKey, descriptorOrInitializer) {
        var propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
        propertyStash.editorOnly = true;
        setImplicitSerializable(propertyStash);
      };
      function setImplicitSerializable(propertyStash) {
        propertyStash.__internalFlags |= PropertyStashInternalFlag.IMPLICIT_SERIALIZABLE;
      }
      var uniquelyReferenced = emptyDecorator ;

      var executeInEditMode = emptySmartClassDecorator;
      var menu = emptyDecoratorFn;
      var playOnFocus = emptySmartClassDecorator;
      var inspector = emptyDecoratorFn;
      var icon = emptyDecoratorFn;
      var help = emptyDecoratorFn;
      var editable = exports('cG', emptyDecorator );
      var visible = exports('cI', emptyDecoratorFn );
      var displayName = exports('cJ', emptyDecoratorFn );
      var tooltip = exports('cH', emptyDecoratorFn );
      var range = exports('cL', emptyDecoratorFn );
      var rangeStep = exports('cM', emptyDecoratorFn );
      var slide = exports('cN', emptyDecorator );
      var displayOrder = exports('cK', emptyDecoratorFn );
      var disallowAnimation = exports('cO', emptyDecorator );

      var integer = type$d(CCInteger);
      var _float = type$d(CCFloat);
      var _boolean = type$d(CCBoolean);
      var string = type$d(CCString);
      function type$d(type) {
        return property$3({
          type: type
        });
      }

      var override$1 = exports('cP', function override(target, propertyKey, descriptorOrInitializer) {
        var propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
        propertyStash.override = true;
      });

      var editorExtrasTag = exports('b_', '__editorExtras__');

      var Empty$1 = function Empty() {};
      var EditorExtendable = exports('c2', editorExtendableInternal());
      assertIsTrue(editorExtrasTag === '__editorExtras__', 'editorExtrasTag needs to be updated.');
      function editorExtendableInternal(Base, className) {
        {
          return Base !== null && Base !== void 0 ? Base : Empty$1;
        }
      }

      var _decorator = /*#__PURE__*/Object.freeze({
        __proto__: null,
        uniquelyReferenced: uniquelyReferenced,
        ccclass: ccclass$M,
        property: property$3,
        requireComponent: requireComponent,
        executionOrder: executionOrder$1,
        disallowMultiple: disallowMultiple$1,
        executeInEditMode: executeInEditMode,
        menu: menu,
        playOnFocus: playOnFocus,
        inspector: inspector,
        icon: icon,
        help: help,
        type: type$d,
        integer: integer,
        float: _float,
        boolean: _boolean,
        string: string,
        editable: editable,
        tooltip: tooltip,
        visible: visible,
        displayName: displayName,
        displayOrder: displayOrder,
        range: range,
        rangeStep: rangeStep,
        slide: slide,
        disallowAnimation: disallowAnimation,
        override: override$1,
        formerlySerializedAs: formerlySerializedAs$4,
        serializable: serializable$p
      });
      exports('bR', _decorator);

      var Destroyed$2 = 1 << 0;
      var ToDestroy = 1 << 2;
      var DontSave$1 = 1 << 3;
      var EditorOnly = 1 << 4;
      var Dirty = 1 << 5;
      var DontDestroy$1 = 1 << 6;
      var Destroying$1 = 1 << 7;
      var Deactivating$2 = 1 << 8;
      var LockedInEditor = 1 << 9;
      var HideInHierarchy$1 = 1 << 10;
      var IsOnEnableCalled$2 = 1 << 11;
      var IsEditorOnEnableCalled = 1 << 12;
      var IsPreloadStarted$1 = 1 << 13;
      var IsOnLoadCalled$2 = 1 << 14;
      var IsOnLoadStarted$1 = 1 << 15;
      var IsStartCalled$1 = 1 << 16;
      var IsRotationLocked = 1 << 17;
      var IsScaleLocked = 1 << 18;
      var IsAnchorLocked = 1 << 19;
      var IsSizeLocked = 1 << 20;
      var IsPositionLocked = 1 << 21;
      var PersistentMask$2 = ~(ToDestroy | Dirty | Destroying$1 | DontDestroy$1 | Deactivating$2 | IsPreloadStarted$1 | IsOnLoadStarted$1 | IsOnLoadCalled$2 | IsStartCalled$1 | IsOnEnableCalled$2 | IsEditorOnEnableCalled | IsRotationLocked | IsScaleLocked | IsAnchorLocked | IsSizeLocked | IsPositionLocked);
      var AllHideMasks = DontSave$1 | EditorOnly | LockedInEditor | HideInHierarchy$1;
      var objectsToDestroy = [];
      function compileDestruct(obj, ctor) {
        var shouldSkipId = obj instanceof legacyCC.Node || obj instanceof legacyCC.Component;
        var idToSkip = shouldSkipId ? '_id' : null;
        var key;
        var propsToReset = {};
        for (key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (key === idToSkip) {
              continue;
            }
            switch (typeof obj[key]) {
              case 'string':
                propsToReset[key] = '';
                break;
              case 'object':
              case 'function':
                propsToReset[key] = null;
                break;
            }
          }
        }
        if (CCClass._isCCClass(ctor)) {
          var attrs = legacyCC.Class.Attr.getClassAttrs(ctor);
          var propList = ctor.__props__;
          for (var i = 0; i < propList.length; i++) {
            key = propList[i];
            var attrKey = "" + key;
            if (attrKey in attrs) {
              if (shouldSkipId && key === '_id') {
                continue;
              }
              switch (typeof attrs[attrKey]) {
                case 'string':
                  propsToReset[key] = '';
                  break;
                case 'object':
                case 'function':
                  propsToReset[key] = null;
                  break;
                case 'undefined':
                  propsToReset[key] = undefined;
                  break;
              }
            }
          }
        }
        {
          var func = '';
          for (key in propsToReset) {
            var statement = void 0;
            if (CCClass.IDENTIFIER_RE.test(key)) {
              statement = "o." + key + "=";
            } else {
              statement = "o[" + CCClass.escapeForJS(key) + "]=";
            }
            var val = propsToReset[key];
            if (val === '') {
              val = '""';
            }
            func += statement + val + ";\n";
          }
          return Function('o', func);
        }
      }
      var CCObject = exports('bU', function () {
        CCObject._deferredDestroy = function _deferredDestroy() {
          var deleteCount = objectsToDestroy.length;
          for (var i = 0; i < deleteCount; ++i) {
            var obj = objectsToDestroy[i];
            if (!(obj._objFlags & Destroyed$2)) {
              obj._destroyImmediate();
            }
          }
          if (deleteCount === objectsToDestroy.length) {
            objectsToDestroy.length = 0;
          } else {
            objectsToDestroy.splice(0, deleteCount);
          }
        };
        function CCObject(name) {
          if (name === void 0) {
            name = '';
          }
          this._objFlags = void 0;
          this._name = void 0;
          this._name = name;
          this._objFlags = 0;
        }
        var _proto = CCObject.prototype;
        _proto.destroy = function destroy() {
          if (this._objFlags & Destroyed$2) {
            warnID(5000);
            return false;
          }
          if (this._objFlags & ToDestroy) {
            return false;
          }
          this._objFlags |= ToDestroy;
          objectsToDestroy.push(this);
          return true;
        };
        _proto._destruct = function _destruct() {
          var ctor = this.constructor;
          var destruct;
          if (Object.prototype.hasOwnProperty.call(ctor, '__destruct__')) {
            destruct = ctor.__destruct__;
          } else {
            destruct = compileDestruct(this, ctor);
            value(ctor, '__destruct__', destruct, true);
          }
          destruct(this);
        };
        _proto._destroyImmediate = function _destroyImmediate() {
          var _onPreDestroy, _ref;
          if (this._objFlags & Destroyed$2) {
            errorID(5000);
            return;
          }
          (_onPreDestroy = (_ref = this)._onPreDestroy) === null || _onPreDestroy === void 0 ? void 0 : _onPreDestroy.call(_ref);
          {
            this._destruct();
          }
          this._objFlags |= Destroyed$2;
        };
        _createClass(CCObject, [{
          key: "name",
          get: function get() {
            return this._name;
          },
          set: function set(value) {
            this._name = value;
          }
        }, {
          key: "hideFlags",
          get: function get() {
            return this._objFlags & CCObject.Flags.AllHideMasks;
          },
          set: function set(hideFlags) {
            var flags = hideFlags & CCObject.Flags.AllHideMasks;
            this._objFlags = this._objFlags & ~CCObject.Flags.AllHideMasks | flags;
          }
        }, {
          key: "isValid",
          get: function get() {
            return !(this._objFlags & Destroyed$2);
          }
        }]);
        return CCObject;
      }());
      var prototype = CCObject.prototype;
      prototype._deserialize = null;
      {
        CCClass.fastDefine('cc.Object', CCObject, {
          _name: '',
          _objFlags: 0
        });
      }
      value(CCObject, 'Flags', {
        Destroyed: Destroyed$2,
        DontSave: DontSave$1,
        EditorOnly: EditorOnly,
        Dirty: Dirty,
        DontDestroy: DontDestroy$1,
        PersistentMask: PersistentMask$2,
        Destroying: Destroying$1,
        Deactivating: Deactivating$2,
        LockedInEditor: LockedInEditor,
        HideInHierarchy: HideInHierarchy$1,
        AllHideMasks: AllHideMasks,
        IsPreloadStarted: IsPreloadStarted$1,
        IsOnLoadStarted: IsOnLoadStarted$1,
        IsOnLoadCalled: IsOnLoadCalled$2,
        IsOnEnableCalled: IsOnEnableCalled$2,
        IsStartCalled: IsStartCalled$1,
        IsEditorOnEnableCalled: IsEditorOnEnableCalled,
        IsPositionLocked: IsPositionLocked,
        IsRotationLocked: IsRotationLocked,
        IsScaleLocked: IsScaleLocked,
        IsAnchorLocked: IsAnchorLocked,
        IsSizeLocked: IsSizeLocked
      });
      function isCCObject(object) {
        return object instanceof CCObject;
      }
      function isValid(value, strictMode) {
        if (typeof value === 'object') {
          return !!value && !(value._objFlags & (strictMode ? Destroyed$2 | ToDestroy : Destroyed$2));
        } else {
          return typeof value !== 'undefined';
        }
      }
      legacyCC.isValid = isValid;
      legacyCC.Object = CCObject;

      var _dec$3J, _class$3F, _class2$3i, _initializer$2$, _initializer2$2o, _initializer3$1N, _initializer4$1w, _class3$10, _BuiltinElementTypeTr;
      var StorageUnit;
      (function (StorageUnit) {
        StorageUnit[StorageUnit["Uint8"] = 0] = "Uint8";
        StorageUnit[StorageUnit["Uint16"] = 1] = "Uint16";
        StorageUnit[StorageUnit["Uint32"] = 2] = "Uint32";
        StorageUnit[StorageUnit["Int8"] = 3] = "Int8";
        StorageUnit[StorageUnit["Int16"] = 4] = "Int16";
        StorageUnit[StorageUnit["Int32"] = 5] = "Int32";
        StorageUnit[StorageUnit["Float32"] = 6] = "Float32";
        StorageUnit[StorageUnit["Float64"] = 7] = "Float64";
      })(StorageUnit || (StorageUnit = {}));
      var ElementType;
      (function (ElementType) {
        ElementType[ElementType["Scalar"] = 0] = "Scalar";
        ElementType[ElementType["Vec2"] = 1] = "Vec2";
        ElementType[ElementType["Vec3"] = 2] = "Vec3";
        ElementType[ElementType["Vec4"] = 3] = "Vec4";
        ElementType[ElementType["Quat"] = 4] = "Quat";
        ElementType[ElementType["Mat4"] = 5] = "Mat4";
      })(ElementType || (ElementType = {}));
      var elementTypeBits = 3;
      function combineStorageUnitElementType(unit, elementType) {
        return (elementType << elementTypeBits) + unit;
      }
      function extractStorageUnitElementType(combined) {
        return {
          storageUnit: ~(-1 << elementTypeBits) & combined,
          elementType: combined >> elementTypeBits
        };
      }
      var CompactValueTypeArray = exports('bZ', (_dec$3J = ccclass$M('cc.CompactValueTypeArray'), _dec$3J(_class$3F = (_class2$3i = (_class3$10 = function () {
        function CompactValueTypeArray() {
          this._byteOffset = _initializer$2$ && _initializer$2$();
          this._unitCount = _initializer2$2o && _initializer2$2o();
          this._unitElement = _initializer3$1N && _initializer3$1N();
          this._length = _initializer4$1w && _initializer4$1w();
        }
        CompactValueTypeArray.lengthFor = function lengthFor(values, elementType, unit) {
          var elementTraits = getElementTraits(elementType);
          return elementTraits.requiredUnits * values.length * getStorageConstructor(unit).BYTES_PER_ELEMENT;
        };
        CompactValueTypeArray.compress = function compress(values, elementType, unit, arrayBuffer, byteOffset, presumedByteOffset) {
          var elementTraits = getElementTraits(elementType);
          var storageConstructor = getStorageConstructor(unit);
          var unitCount = elementTraits.requiredUnits * values.length;
          var storage = new storageConstructor(arrayBuffer, byteOffset, unitCount);
          for (var i = 0; i < values.length; ++i) {
            elementTraits.compress(storage, i, values[i]);
          }
          var result = new CompactValueTypeArray();
          result._unitElement = combineStorageUnitElementType(unit, elementType);
          result._byteOffset = presumedByteOffset;
          result._unitCount = unitCount;
          result._length = values.length;
          return result;
        };
        var _proto = CompactValueTypeArray.prototype;
        _proto.decompress = function decompress(arrayBuffer) {
          var _extractStorageUnitEl = extractStorageUnitElementType(this._unitElement),
            storageUnit = _extractStorageUnitEl.storageUnit,
            elementType = _extractStorageUnitEl.elementType;
          var elementTraits = getElementTraits(elementType);
          var storageConstructor = getStorageConstructor(storageUnit);
          var storage = new storageConstructor(arrayBuffer, this._byteOffset, this._unitCount);
          var result = new Array(this._length);
          for (var i = 0; i < this._length; ++i) {
            result[i] = elementTraits.decompress(storage, i);
          }
          return result;
        };
        return CompactValueTypeArray;
      }(), _class3$10.StorageUnit = StorageUnit, _class3$10.ElementType = ElementType, _class3$10), (_initializer$2$ = applyDecoratedInitializer(_class2$3i.prototype, "_byteOffset", [serializable$p], function () {
        return 0;
      }), _initializer2$2o = applyDecoratedInitializer(_class2$3i.prototype, "_unitCount", [serializable$p], function () {
        return 0;
      }), _initializer3$1N = applyDecoratedInitializer(_class2$3i.prototype, "_unitElement", [serializable$p], function () {
        return combineStorageUnitElementType(StorageUnit.Uint8, ElementType.Scalar);
      }), _initializer4$1w = applyDecoratedInitializer(_class2$3i.prototype, "_length", [serializable$p], function () {
        return 0;
      })), _class2$3i)) || _class$3F));
      function getElementTraits(elementType) {
        return BuiltinElementTypeTraits[elementType];
      }
      function getStorageConstructor(unit) {
        switch (unit) {
          case StorageUnit.Uint8:
            return Uint8Array;
          case StorageUnit.Uint16:
            return Uint16Array;
          case StorageUnit.Uint32:
            return Uint32Array;
          case StorageUnit.Int8:
            return Int8Array;
          case StorageUnit.Int16:
            return Int16Array;
          case StorageUnit.Int32:
            return Int32Array;
          case StorageUnit.Float32:
            return Float32Array;
          case StorageUnit.Float64:
            return Float64Array;
        }
      }
      var BuiltinElementTypeTraits = (_BuiltinElementTypeTr = {}, _BuiltinElementTypeTr[ElementType.Scalar] = {
        requiredUnits: 1,
        compress: function compress(storage, index, value) {
          storage[index] = value;
        },
        decompress: function decompress(storage, index) {
          return storage[index];
        }
      }, _BuiltinElementTypeTr[ElementType.Vec2] = {
        requiredUnits: 2,
        compress: function compress(storage, index, value) {
          storage[index * 2] = value.x;
          storage[index * 2 + 1] = value.y;
        },
        decompress: function decompress(storage, index) {
          return new Vec3(storage[index * 2], storage[index * 2 + 1]);
        }
      }, _BuiltinElementTypeTr[ElementType.Vec3] = {
        requiredUnits: 3,
        compress: function compress(storage, index, value) {
          storage[index * 3] = value.x;
          storage[index * 3 + 1] = value.y;
          storage[index * 3 + 2] = value.z;
        },
        decompress: function decompress(storage, index) {
          return new Vec3(storage[index * 3], storage[index * 3 + 1], storage[index * 3 + 2]);
        }
      }, _BuiltinElementTypeTr[ElementType.Vec4] = {
        requiredUnits: 4,
        compress: function compress(storage, index, value) {
          storage[index * 4] = value.x;
          storage[index * 4 + 1] = value.y;
          storage[index * 4 + 2] = value.z;
          storage[index * 4 + 3] = value.w;
        },
        decompress: function decompress(storage, index) {
          return new Vec4(storage[index * 4], storage[index * 4 + 1], storage[index * 4 + 2], storage[index * 4 + 3]);
        }
      }, _BuiltinElementTypeTr[ElementType.Quat] = {
        requiredUnits: 4,
        compress: function compress(storage, index, value) {
          storage[index * 4] = value.x;
          storage[index * 4 + 1] = value.y;
          storage[index * 4 + 2] = value.z;
          storage[index * 4 + 3] = value.w;
        },
        decompress: function decompress(storage, index) {
          return new Quat(storage[index * 4], storage[index * 4 + 1], storage[index * 4 + 2], storage[index * 4 + 3]);
        }
      }, _BuiltinElementTypeTr[ElementType.Mat4] = {
        requiredUnits: 16,
        compress: function compress(storage, index, value) {
          Mat4.toArray(storage, value, index * 16);
        },
        decompress: function decompress(storage, index) {
          return Mat4.fromArray(new Mat4(), storage, index * 16);
        }
      }, _BuiltinElementTypeTr);

      var serializeTag = exports('c0', Symbol('[[Serialize]]'));
      var deserializeTag = exports('b$', Symbol('[[Deserialize]]'));

      legacyCC._decorator = _decorator;

      function constant() {
        return 0;
      }
      function linear(k) {
        return k;
      }
      function quadIn(k) {
        return k * k;
      }
      function quadOut(k) {
        return k * (2 - k);
      }
      function quadInOut(k) {
        k *= 2;
        if (k < 1) {
          return 0.5 * k * k;
        }
        return -0.5 * (--k * (k - 2) - 1);
      }
      function cubicIn(k) {
        return k * k * k;
      }
      function cubicOut(k) {
        return --k * k * k + 1;
      }
      function cubicInOut(k) {
        k *= 2;
        if (k < 1) {
          return 0.5 * k * k * k;
        }
        return 0.5 * ((k -= 2) * k * k + 2);
      }
      function quartIn(k) {
        return k * k * k * k;
      }
      function quartOut(k) {
        return 1 - --k * k * k * k;
      }
      function quartInOut(k) {
        k *= 2;
        if (k < 1) {
          return 0.5 * k * k * k * k;
        }
        return -0.5 * ((k -= 2) * k * k * k - 2);
      }
      function quintIn(k) {
        return k * k * k * k * k;
      }
      function quintOut(k) {
        return --k * k * k * k * k + 1;
      }
      function quintInOut(k) {
        k *= 2;
        if (k < 1) {
          return 0.5 * k * k * k * k * k;
        }
        return 0.5 * ((k -= 2) * k * k * k * k + 2);
      }
      function sineIn(k) {
        if (k === 1) {
          return 1;
        }
        return 1 - Math.cos(k * Math.PI / 2);
      }
      function sineOut(k) {
        return Math.sin(k * Math.PI / 2);
      }
      function sineInOut(k) {
        return 0.5 * (1 - Math.cos(Math.PI * k));
      }
      function expoIn(k) {
        return k === 0 ? 0 : Math.pow(1024, k - 1);
      }
      function expoOut(k) {
        return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
      }
      function expoInOut(k) {
        if (k === 0) {
          return 0;
        }
        if (k === 1) {
          return 1;
        }
        k *= 2;
        if (k < 1) {
          return 0.5 * Math.pow(1024, k - 1);
        }
        return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
      }
      function circIn(k) {
        return 1 - Math.sqrt(1 - k * k);
      }
      function circOut(k) {
        return Math.sqrt(1 - --k * k);
      }
      function circInOut(k) {
        k *= 2;
        if (k < 1) {
          return -0.5 * (Math.sqrt(1 - k * k) - 1);
        }
        return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
      }
      function elasticIn(k) {
        var s;
        var a = 0.1;
        var p = 0.4;
        if (k === 0) {
          return 0;
        }
        if (k === 1) {
          return 1;
        }
        if (!a || a < 1) {
          a = 1;
          s = p / 4;
        } else {
          s = p * Math.asin(1 / a) / (2 * Math.PI);
        }
        return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
      }
      function elasticOut(k) {
        var s;
        var a = 0.1;
        var p = 0.4;
        if (k === 0) {
          return 0;
        }
        if (k === 1) {
          return 1;
        }
        if (!a || a < 1) {
          a = 1;
          s = p / 4;
        } else {
          s = p * Math.asin(1 / a) / (2 * Math.PI);
        }
        return a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1;
      }
      function elasticInOut(k) {
        var s;
        var a = 0.1;
        var p = 0.4;
        if (k === 0) {
          return 0;
        }
        if (k === 1) {
          return 1;
        }
        if (!a || a < 1) {
          a = 1;
          s = p / 4;
        } else {
          s = p * Math.asin(1 / a) / (2 * Math.PI);
        }
        k *= 2;
        if (k < 1) {
          return -0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
        }
        return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
      }
      function backIn(k) {
        if (k === 1) {
          return 1;
        }
        var s = 1.70158;
        return k * k * ((s + 1) * k - s);
      }
      function backOut(k) {
        if (k === 0) {
          return 0;
        }
        var s = 1.70158;
        return --k * k * ((s + 1) * k + s) + 1;
      }
      function backInOut(k) {
        var s = 1.70158 * 1.525;
        k *= 2;
        if (k < 1) {
          return 0.5 * (k * k * ((s + 1) * k - s));
        }
        return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
      }
      function bounceIn(k) {
        return 1 - bounceOut(1 - k);
      }
      function bounceOut(k) {
        if (k < 1 / 2.75) {
          return 7.5625 * k * k;
        } else if (k < 2 / 2.75) {
          return 7.5625 * (k -= 1.5 / 2.75) * k + 0.75;
        } else if (k < 2.5 / 2.75) {
          return 7.5625 * (k -= 2.25 / 2.75) * k + 0.9375;
        } else {
          return 7.5625 * (k -= 2.625 / 2.75) * k + 0.984375;
        }
      }
      function bounceInOut(k) {
        if (k < 0.5) {
          return bounceIn(k * 2) * 0.5;
        }
        return bounceOut(k * 2 - 1) * 0.5 + 0.5;
      }
      function smooth(k) {
        if (k <= 0) {
          return 0;
        }
        if (k >= 1) {
          return 1;
        }
        return k * k * (3 - 2 * k);
      }
      function fade(k) {
        if (k <= 0) {
          return 0;
        }
        if (k >= 1) {
          return 1;
        }
        return k * k * k * (k * (k * 6 - 15) + 10);
      }
      var quadOutIn = _makeOutIn(quadIn, quadOut);
      var cubicOutIn = _makeOutIn(cubicIn, cubicOut);
      var quartOutIn = _makeOutIn(quartIn, quartOut);
      var quintOutIn = _makeOutIn(quintIn, quintOut);
      var sineOutIn = _makeOutIn(sineIn, sineOut);
      var expoOutIn = _makeOutIn(expoIn, expoOut);
      var circOutIn = _makeOutIn(circIn, circOut);
      var elasticOutIn = _makeOutIn(elasticIn, elasticOut);
      var backOutIn = _makeOutIn(backIn, backOut);
      var bounceOutIn = _makeOutIn(bounceIn, bounceOut);
      function _makeOutIn(fnIn, fnOut) {
        return function (k) {
          if (k < 0.5) {
            return fnOut(k * 2) / 2;
          }
          return fnIn(2 * k - 1) / 2 + 0.5;
        };
      }

      var easing = /*#__PURE__*/Object.freeze({
        __proto__: null,
        constant: constant,
        linear: linear,
        quadIn: quadIn,
        quadOut: quadOut,
        quadInOut: quadInOut,
        cubicIn: cubicIn,
        cubicOut: cubicOut,
        cubicInOut: cubicInOut,
        quartIn: quartIn,
        quartOut: quartOut,
        quartInOut: quartInOut,
        quintIn: quintIn,
        quintOut: quintOut,
        quintInOut: quintInOut,
        sineIn: sineIn,
        sineOut: sineOut,
        sineInOut: sineInOut,
        expoIn: expoIn,
        expoOut: expoOut,
        expoInOut: expoInOut,
        circIn: circIn,
        circOut: circOut,
        circInOut: circInOut,
        elasticIn: elasticIn,
        elasticOut: elasticOut,
        elasticInOut: elasticInOut,
        backIn: backIn,
        backOut: backOut,
        backInOut: backInOut,
        bounceIn: bounceIn,
        bounceOut: bounceOut,
        bounceInOut: bounceInOut,
        smooth: smooth,
        fade: fade,
        quadOutIn: quadOutIn,
        cubicOutIn: cubicOutIn,
        quartOutIn: quartOutIn,
        quintOutIn: quintOutIn,
        sineOutIn: sineOutIn,
        expoOutIn: expoOutIn,
        circOutIn: circOutIn,
        elasticOutIn: elasticOutIn,
        backOutIn: backOutIn,
        bounceOutIn: bounceOutIn
      });
      exports('cB', easing);

      var _easingMethodFnMap;
      var EasingMethod; exports('c$', EasingMethod);
      (function (EasingMethod) {
        EasingMethod[EasingMethod["LINEAR"] = 0] = "LINEAR";
        EasingMethod[EasingMethod["CONSTANT"] = 1] = "CONSTANT";
        EasingMethod[EasingMethod["QUAD_IN"] = 2] = "QUAD_IN";
        EasingMethod[EasingMethod["QUAD_OUT"] = 3] = "QUAD_OUT";
        EasingMethod[EasingMethod["QUAD_IN_OUT"] = 4] = "QUAD_IN_OUT";
        EasingMethod[EasingMethod["QUAD_OUT_IN"] = 5] = "QUAD_OUT_IN";
        EasingMethod[EasingMethod["CUBIC_IN"] = 6] = "CUBIC_IN";
        EasingMethod[EasingMethod["CUBIC_OUT"] = 7] = "CUBIC_OUT";
        EasingMethod[EasingMethod["CUBIC_IN_OUT"] = 8] = "CUBIC_IN_OUT";
        EasingMethod[EasingMethod["CUBIC_OUT_IN"] = 9] = "CUBIC_OUT_IN";
        EasingMethod[EasingMethod["QUART_IN"] = 10] = "QUART_IN";
        EasingMethod[EasingMethod["QUART_OUT"] = 11] = "QUART_OUT";
        EasingMethod[EasingMethod["QUART_IN_OUT"] = 12] = "QUART_IN_OUT";
        EasingMethod[EasingMethod["QUART_OUT_IN"] = 13] = "QUART_OUT_IN";
        EasingMethod[EasingMethod["QUINT_IN"] = 14] = "QUINT_IN";
        EasingMethod[EasingMethod["QUINT_OUT"] = 15] = "QUINT_OUT";
        EasingMethod[EasingMethod["QUINT_IN_OUT"] = 16] = "QUINT_IN_OUT";
        EasingMethod[EasingMethod["QUINT_OUT_IN"] = 17] = "QUINT_OUT_IN";
        EasingMethod[EasingMethod["SINE_IN"] = 18] = "SINE_IN";
        EasingMethod[EasingMethod["SINE_OUT"] = 19] = "SINE_OUT";
        EasingMethod[EasingMethod["SINE_IN_OUT"] = 20] = "SINE_IN_OUT";
        EasingMethod[EasingMethod["SINE_OUT_IN"] = 21] = "SINE_OUT_IN";
        EasingMethod[EasingMethod["EXPO_IN"] = 22] = "EXPO_IN";
        EasingMethod[EasingMethod["EXPO_OUT"] = 23] = "EXPO_OUT";
        EasingMethod[EasingMethod["EXPO_IN_OUT"] = 24] = "EXPO_IN_OUT";
        EasingMethod[EasingMethod["EXPO_OUT_IN"] = 25] = "EXPO_OUT_IN";
        EasingMethod[EasingMethod["CIRC_IN"] = 26] = "CIRC_IN";
        EasingMethod[EasingMethod["CIRC_OUT"] = 27] = "CIRC_OUT";
        EasingMethod[EasingMethod["CIRC_IN_OUT"] = 28] = "CIRC_IN_OUT";
        EasingMethod[EasingMethod["CIRC_OUT_IN"] = 29] = "CIRC_OUT_IN";
        EasingMethod[EasingMethod["ELASTIC_IN"] = 30] = "ELASTIC_IN";
        EasingMethod[EasingMethod["ELASTIC_OUT"] = 31] = "ELASTIC_OUT";
        EasingMethod[EasingMethod["ELASTIC_IN_OUT"] = 32] = "ELASTIC_IN_OUT";
        EasingMethod[EasingMethod["ELASTIC_OUT_IN"] = 33] = "ELASTIC_OUT_IN";
        EasingMethod[EasingMethod["BACK_IN"] = 34] = "BACK_IN";
        EasingMethod[EasingMethod["BACK_OUT"] = 35] = "BACK_OUT";
        EasingMethod[EasingMethod["BACK_IN_OUT"] = 36] = "BACK_IN_OUT";
        EasingMethod[EasingMethod["BACK_OUT_IN"] = 37] = "BACK_OUT_IN";
        EasingMethod[EasingMethod["BOUNCE_IN"] = 38] = "BOUNCE_IN";
        EasingMethod[EasingMethod["BOUNCE_OUT"] = 39] = "BOUNCE_OUT";
        EasingMethod[EasingMethod["BOUNCE_IN_OUT"] = 40] = "BOUNCE_IN_OUT";
        EasingMethod[EasingMethod["BOUNCE_OUT_IN"] = 41] = "BOUNCE_OUT_IN";
        EasingMethod[EasingMethod["SMOOTH"] = 42] = "SMOOTH";
        EasingMethod[EasingMethod["FADE"] = 43] = "FADE";
      })(EasingMethod || (exports('c$', EasingMethod = {})));
      var easingMethodFnMap = (_easingMethodFnMap = {}, _easingMethodFnMap[EasingMethod.CONSTANT] = constant, _easingMethodFnMap[EasingMethod.LINEAR] = linear, _easingMethodFnMap[EasingMethod.QUAD_IN] = quadIn, _easingMethodFnMap[EasingMethod.QUAD_OUT] = quadOut, _easingMethodFnMap[EasingMethod.QUAD_IN_OUT] = quadInOut, _easingMethodFnMap[EasingMethod.QUAD_OUT_IN] = quadOutIn, _easingMethodFnMap[EasingMethod.CUBIC_IN] = cubicIn, _easingMethodFnMap[EasingMethod.CUBIC_OUT] = cubicOut, _easingMethodFnMap[EasingMethod.CUBIC_IN_OUT] = cubicInOut, _easingMethodFnMap[EasingMethod.CUBIC_OUT_IN] = cubicOutIn, _easingMethodFnMap[EasingMethod.QUART_IN] = quartIn, _easingMethodFnMap[EasingMethod.QUART_OUT] = quartOut, _easingMethodFnMap[EasingMethod.QUART_IN_OUT] = quartInOut, _easingMethodFnMap[EasingMethod.QUART_OUT_IN] = quartOutIn, _easingMethodFnMap[EasingMethod.QUINT_IN] = quintIn, _easingMethodFnMap[EasingMethod.QUINT_OUT] = quintOut, _easingMethodFnMap[EasingMethod.QUINT_IN_OUT] = quintInOut, _easingMethodFnMap[EasingMethod.QUINT_OUT_IN] = quintOutIn, _easingMethodFnMap[EasingMethod.SINE_IN] = sineIn, _easingMethodFnMap[EasingMethod.SINE_OUT] = sineOut, _easingMethodFnMap[EasingMethod.SINE_IN_OUT] = sineInOut, _easingMethodFnMap[EasingMethod.SINE_OUT_IN] = sineOutIn, _easingMethodFnMap[EasingMethod.EXPO_IN] = expoIn, _easingMethodFnMap[EasingMethod.EXPO_OUT] = expoOut, _easingMethodFnMap[EasingMethod.EXPO_IN_OUT] = expoInOut, _easingMethodFnMap[EasingMethod.EXPO_OUT_IN] = expoOutIn, _easingMethodFnMap[EasingMethod.CIRC_IN] = circIn, _easingMethodFnMap[EasingMethod.CIRC_OUT] = circOut, _easingMethodFnMap[EasingMethod.CIRC_IN_OUT] = circInOut, _easingMethodFnMap[EasingMethod.CIRC_OUT_IN] = circOutIn, _easingMethodFnMap[EasingMethod.ELASTIC_IN] = elasticIn, _easingMethodFnMap[EasingMethod.ELASTIC_OUT] = elasticOut, _easingMethodFnMap[EasingMethod.ELASTIC_IN_OUT] = elasticInOut, _easingMethodFnMap[EasingMethod.ELASTIC_OUT_IN] = elasticOutIn, _easingMethodFnMap[EasingMethod.BACK_IN] = backIn, _easingMethodFnMap[EasingMethod.BACK_OUT] = backOut, _easingMethodFnMap[EasingMethod.BACK_IN_OUT] = backInOut, _easingMethodFnMap[EasingMethod.BACK_OUT_IN] = backOutIn, _easingMethodFnMap[EasingMethod.BOUNCE_IN] = bounceIn, _easingMethodFnMap[EasingMethod.BOUNCE_OUT] = bounceOut, _easingMethodFnMap[EasingMethod.BOUNCE_IN_OUT] = bounceInOut, _easingMethodFnMap[EasingMethod.BOUNCE_OUT_IN] = bounceOutIn, _easingMethodFnMap[EasingMethod.SMOOTH] = smooth, _easingMethodFnMap[EasingMethod.FADE] = fade, _easingMethodFnMap);
      function getEasingFn(easingMethod) {
        assertIsTrue(easingMethod in easingMethodFnMap);
        return easingMethodFnMap[easingMethod];
      }

      var _CCClass$fastDefine;
      var REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START = 0;
      var REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_MASK = 0xFF << REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START;
      var REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START = 8;
      var REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_MASK = 0xFF << REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START;
      var REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START = 16;
      var REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_MASK = 0xFF << REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START;
      assertIsTrue(REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START === REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START + popCount(REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_MASK));
      assertIsTrue(REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START === REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START + popCount(REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_MASK));
      var REAL_KEYFRAME_VALUE_DEFAULT_FLAGS = RealInterpolationMode.LINEAR << REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START | TangentWeightMode.NONE << REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START | EasingMethod.LINEAR << REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START;
      var RealKeyframeValue = function (_EditorExtendable) {
        _inheritsLoose(RealKeyframeValue, _EditorExtendable);
        function RealKeyframeValue() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EditorExtendable.call.apply(_EditorExtendable, [this].concat(args)) || this;
          _this.value = 0.0;
          _this.rightTangent = 0.0;
          _this.rightTangentWeight = 0.0;
          _this.leftTangent = 0.0;
          _this.leftTangentWeight = 0.0;
          _this._flags = REAL_KEYFRAME_VALUE_DEFAULT_FLAGS;
          return _this;
        }
        _createClass(RealKeyframeValue, [{
          key: "interpolationMode",
          get: function get() {
            return (this._flags & REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_MASK) >> REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START;
          },
          set: function set(value) {
            this._flags &= ~REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_MASK;
            this._flags |= value << REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START;
          }
        }, {
          key: "tangentWeightMode",
          get: function get() {
            return (this._flags & REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_MASK) >> REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START;
          },
          set: function set(value) {
            this._flags &= ~REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_MASK;
            this._flags |= value << REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START;
          }
        }, {
          key: "easingMethod",
          get: function get() {
            return (this._flags & REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_MASK) >> REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START;
          },
          set: function set(value) {
            this._flags &= ~REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_MASK;
            this._flags |= value << REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START;
          }
        }]);
        return RealKeyframeValue;
      }(EditorExtendable);
      CCClass.fastDefine('cc.RealKeyframeValue', RealKeyframeValue, (_CCClass$fastDefine = {
        interpolationMode: RealInterpolationMode.LINEAR,
        tangentWeightMode: TangentWeightMode.NONE,
        value: 0.0,
        rightTangent: 0.0,
        rightTangentWeight: 0.0,
        leftTangent: 0.0,
        leftTangentWeight: 0.0,
        easingMethod: EasingMethod.LINEAR
      }, _CCClass$fastDefine[editorExtrasTag] = undefined, _CCClass$fastDefine));
      CCClass.Attr.setClassAttr(RealKeyframeValue, editorExtrasTag, 'editorOnly', true);
      getOrCreateSerializationMetadata(RealKeyframeValue).uniquelyReferenced = true;
      function createRealKeyframeValue(params) {
        var realKeyframeValue = new RealKeyframeValue();
        if (typeof params === 'number') {
          realKeyframeValue.value = params;
        } else {
          var interpolationMode = params.interpolationMode,
            tangentWeightMode = params.tangentWeightMode,
            value = params.value,
            rightTangent = params.rightTangent,
            rightTangentWeight = params.rightTangentWeight,
            leftTangent = params.leftTangent,
            leftTangentWeight = params.leftTangentWeight,
            easingMethod = params.easingMethod,
            editorExtras = params[editorExtrasTag];
          realKeyframeValue.value = value !== null && value !== void 0 ? value : realKeyframeValue.value;
          realKeyframeValue.rightTangent = rightTangent !== null && rightTangent !== void 0 ? rightTangent : realKeyframeValue.rightTangent;
          realKeyframeValue.rightTangentWeight = rightTangentWeight !== null && rightTangentWeight !== void 0 ? rightTangentWeight : realKeyframeValue.rightTangentWeight;
          realKeyframeValue.leftTangent = leftTangent !== null && leftTangent !== void 0 ? leftTangent : realKeyframeValue.leftTangent;
          realKeyframeValue.leftTangentWeight = leftTangentWeight !== null && leftTangentWeight !== void 0 ? leftTangentWeight : realKeyframeValue.leftTangentWeight;
          realKeyframeValue.interpolationMode = interpolationMode !== null && interpolationMode !== void 0 ? interpolationMode : realKeyframeValue.interpolationMode;
          realKeyframeValue.tangentWeightMode = tangentWeightMode !== null && tangentWeightMode !== void 0 ? tangentWeightMode : realKeyframeValue.tangentWeightMode;
          realKeyframeValue.easingMethod = easingMethod !== null && easingMethod !== void 0 ? easingMethod : realKeyframeValue.easingMethod;
          if (editorExtras) {
            realKeyframeValue[editorExtrasTag] = editorExtras;
          }
        }
        return realKeyframeValue;
      }
      var RealCurve = exports('co', function (_KeyframeCurve) {
        _inheritsLoose(RealCurve, _KeyframeCurve);
        function RealCurve() {
          var _this2;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this2 = _KeyframeCurve.call.apply(_KeyframeCurve, [this].concat(args)) || this;
          _this2.preExtrapolation = ExtrapolationMode.CLAMP;
          _this2.postExtrapolation = ExtrapolationMode.CLAMP;
          return _this2;
        }
        var _proto = RealCurve.prototype;
        _proto.evaluate = function evaluate(time) {
          var times = this._times,
            values = this._values;
          var nFrames = times.length;
          if (nFrames === 0) {
            return 0.0;
          }
          var firstTime = times[0];
          var lastTime = times[nFrames - 1];
          if (time < firstTime) {
            var preExtrapolation = this.preExtrapolation;
            var _preValue = values[0];
            if (preExtrapolation === ExtrapolationMode.CLAMP || nFrames < 2) {
              return _preValue.value;
            }
            switch (preExtrapolation) {
              case ExtrapolationMode.LINEAR:
                return linearTrend(firstTime, values[0].value, times[1], values[1].value, time);
              case ExtrapolationMode.LOOP:
                time = wrapRepeat(time, firstTime, lastTime);
                break;
              case ExtrapolationMode.PING_PONG:
                time = wrapPingPong(time, firstTime, lastTime);
                break;
              default:
                return _preValue.value;
            }
          } else if (time > lastTime) {
            var postExtrapolation = this.postExtrapolation;
            var preFrame = values[nFrames - 1];
            if (postExtrapolation === ExtrapolationMode.CLAMP || nFrames < 2) {
              return preFrame.value;
            }
            switch (postExtrapolation) {
              case ExtrapolationMode.LINEAR:
                return linearTrend(lastTime, preFrame.value, times[nFrames - 2], values[nFrames - 2].value, time);
              case ExtrapolationMode.LOOP:
                time = wrapRepeat(time, firstTime, lastTime);
                break;
              case ExtrapolationMode.PING_PONG:
                time = wrapPingPong(time, firstTime, lastTime);
                break;
              default:
                return preFrame.value;
            }
          }
          var index = binarySearchEpsilon(times, time);
          if (index >= 0) {
            return values[index].value;
          }
          var iNext = ~index;
          {
            assertIsTrue(iNext !== 0 && iNext !== nFrames && nFrames > 1);
          }
          var iPre = iNext - 1;
          var preTime = times[iPre];
          var preValue = values[iPre];
          var nextTime = times[iNext];
          var nextValue = values[iNext];
          {
            assertIsTrue(nextTime > time && time > preTime);
          }
          var dt = nextTime - preTime;
          var ratio = (time - preTime) / dt;
          return evalBetweenTwoKeyFrames(preTime, preValue, nextTime, nextValue, ratio);
        };
        _proto.addKeyFrame = function addKeyFrame(time, value) {
          return _KeyframeCurve.prototype.addKeyFrame.call(this, time, createRealKeyframeValue(value));
        };
        _proto.assignSorted = function assignSorted(times, values) {
          if (values !== undefined) {
            assertIsTrue(Array.isArray(times));
            this.setKeyframes(times.slice(), values.map(function (value) {
              return createRealKeyframeValue(value);
            }));
          } else {
            var _keyframes = Array.from(times);
            this.setKeyframes(_keyframes.map(function (_ref) {
              var time = _ref[0];
              return time;
            }), _keyframes.map(function (_ref2) {
              var value = _ref2[1];
              return createRealKeyframeValue(value);
            }));
          }
        };
        _proto.isConstant = function isConstant(tolerance) {
          if (this._values.length <= 1) {
            return true;
          }
          var firstVal = this._values[0].value;
          return this._values.every(function (frame) {
            return approx(frame.value, firstVal, tolerance);
          });
        };
        _proto[serializeTag] = function (output, context) {
          if (!context.toCCON) {
            output.writeThis();
            return;
          }
          var times = this._times,
            keyframeValues = this._values;
          var nKeyframes = times.length;
          var dataSize = 0 + OVERFLOW_BYTES + OVERFLOW_BYTES + FRAME_COUNT_BYTES$1 + TIME_BYTES$1 * nKeyframes + REAL_KEY_FRAME_VALUE_MAX_SIZE * nKeyframes;
          var dataView = new DataView(new ArrayBuffer(dataSize));
          var currentOffset = 0;
          dataView.setUint8(currentOffset, this.preExtrapolation);
          currentOffset += OVERFLOW_BYTES;
          dataView.setUint8(currentOffset, this.postExtrapolation);
          currentOffset += OVERFLOW_BYTES;
          dataView.setUint32(currentOffset, nKeyframes, true);
          currentOffset += FRAME_COUNT_BYTES$1;
          times.forEach(function (time, index) {
            return dataView.setFloat32(currentOffset + TIME_BYTES$1 * index, time, true);
          });
          currentOffset += TIME_BYTES$1 * nKeyframes;
          for (var _iterator = _createForOfIteratorHelperLoose(keyframeValues), _step; !(_step = _iterator()).done;) {
            var keyframeValue = _step.value;
            currentOffset = saveRealKeyFrameValue(dataView, keyframeValue, currentOffset);
          }
          var bytes = new Uint8Array(dataView.buffer, 0, currentOffset);
          output.writeProperty('bytes', bytes);
          var keyframeValueEditorExtras = keyframeValues.map(function (keyframeValue) {
            return keyframeValue[editorExtrasTag];
          });
          if (keyframeValueEditorExtras.some(function (extras) {
            return extras !== undefined;
          })) {
            output.writeProperty("keyframeValueEditorExtras", keyframeValueEditorExtras);
          }
        };
        _proto[deserializeTag] = function (input, context) {
          if (!context.fromCCON) {
            input.readThis();
            return;
          }
          var bytes = input.readProperty('bytes');
          var dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
          var currentOffset = 0;
          this.preExtrapolation = dataView.getUint8(currentOffset);
          currentOffset += OVERFLOW_BYTES;
          this.postExtrapolation = dataView.getUint8(currentOffset);
          currentOffset += OVERFLOW_BYTES;
          var nKeyframes = dataView.getUint32(currentOffset, true);
          currentOffset += FRAME_COUNT_BYTES$1;
          var times = Array.from({
            length: nKeyframes
          }, function (_, index) {
            return dataView.getFloat32(currentOffset + TIME_BYTES$1 * index, true);
          });
          currentOffset += TIME_BYTES$1 * nKeyframes;
          var keyframeValues = new Array(nKeyframes);
          for (var iKeyFrame = 0; iKeyFrame < nKeyframes; ++iKeyFrame) {
            var keyframeValue = createRealKeyframeValue({});
            currentOffset = loadRealKeyFrameValue(dataView, keyframeValue, currentOffset);
            keyframeValues[iKeyFrame] = keyframeValue;
          }
          assertIsTrue(currentOffset === bytes.byteLength);
          var keyframeValueEditorExtras = input.readProperty("keyframeValueEditorExtras");
          if (keyframeValueEditorExtras) {
            assertIsTrue(keyframeValueEditorExtras.length === nKeyframes);
            keyframeValueEditorExtras.forEach(function (extras, index) {
              return keyframeValues[index][editorExtrasTag] = extras;
            });
          }
          this._times = times;
          this._values = keyframeValues;
        };
        return RealCurve;
      }(KeyframeCurve));
      CCClass.fastDefine('cc.RealCurve', RealCurve, {
        _times: [],
        _values: [],
        preExtrapolation: ExtrapolationMode.CLAMP,
        postExtrapolation: ExtrapolationMode.CLAMP
      });
      var FLAGS_EASING_METHOD_BITS_START = 8;
      var FLAG_EASING_METHOD_MASK = 0xFF << FLAGS_EASING_METHOD_BITS_START;
      var KeyframeValueFlagMask$1;
      (function (KeyframeValueFlagMask) {
        KeyframeValueFlagMask[KeyframeValueFlagMask["VALUE"] = 1] = "VALUE";
        KeyframeValueFlagMask[KeyframeValueFlagMask["INTERPOLATION_MODE"] = 2] = "INTERPOLATION_MODE";
        KeyframeValueFlagMask[KeyframeValueFlagMask["TANGENT_WEIGHT_MODE"] = 4] = "TANGENT_WEIGHT_MODE";
        KeyframeValueFlagMask[KeyframeValueFlagMask["LEFT_TANGENT"] = 8] = "LEFT_TANGENT";
        KeyframeValueFlagMask[KeyframeValueFlagMask["LEFT_TANGENT_WEIGHT"] = 16] = "LEFT_TANGENT_WEIGHT";
        KeyframeValueFlagMask[KeyframeValueFlagMask["RIGHT_TANGENT"] = 32] = "RIGHT_TANGENT";
        KeyframeValueFlagMask[KeyframeValueFlagMask["RIGHT_TANGENT_WEIGHT"] = 64] = "RIGHT_TANGENT_WEIGHT";
      })(KeyframeValueFlagMask$1 || (KeyframeValueFlagMask$1 = {}));
      var OVERFLOW_BYTES = 1;
      var FRAME_COUNT_BYTES$1 = 4;
      var TIME_BYTES$1 = 4;
      var KEY_FRAME_VALUE_FLAGS_BYTES = 4;
      var VALUE_BYTES$1 = 4;
      var INTERPOLATION_MODE_BYTES$1 = 1;
      var TANGENT_WEIGHT_MODE_BYTES = 1;
      var LEFT_TANGENT_BYTES = 4;
      var LEFT_TANGENT_WEIGHT_BYTES = 4;
      var RIGHT_TANGENT_BYTES = 4;
      var RIGHT_TANGENT_WEIGHT_BYTES = 4;
      var _createRealKeyframeVa = createRealKeyframeValue({}),
        DEFAULT_INTERPOLATION_MODE = _createRealKeyframeVa.interpolationMode,
        DEFAULT_TANGENT_WEIGHT_MODE = _createRealKeyframeVa.tangentWeightMode,
        DEFAULT_LEFT_TANGENT = _createRealKeyframeVa.leftTangent,
        DEFAULT_LEFT_TANGENT_WEIGHT = _createRealKeyframeVa.leftTangentWeight,
        DEFAULT_RIGHT_TANGENT = _createRealKeyframeVa.rightTangent,
        DEFAULT_RIGHT_TANGENT_WEIGHT = _createRealKeyframeVa.rightTangentWeight;
      var REAL_KEY_FRAME_VALUE_MAX_SIZE = KEY_FRAME_VALUE_FLAGS_BYTES + VALUE_BYTES$1 + INTERPOLATION_MODE_BYTES$1 + TANGENT_WEIGHT_MODE_BYTES + LEFT_TANGENT_BYTES + LEFT_TANGENT_WEIGHT_BYTES + RIGHT_TANGENT_BYTES + RIGHT_TANGENT_WEIGHT_BYTES + 0;
      function saveRealKeyFrameValue(dataView, keyframeValue, offset) {
        var flags = 0;
        var currentOffset = offset;
        var pFlags = currentOffset;
        currentOffset += KEY_FRAME_VALUE_FLAGS_BYTES;
        var value = keyframeValue.value,
          interpolationMode = keyframeValue.interpolationMode,
          tangentWeightMode = keyframeValue.tangentWeightMode,
          rightTangent = keyframeValue.rightTangent,
          rightTangentWeight = keyframeValue.rightTangentWeight,
          leftTangent = keyframeValue.leftTangent,
          leftTangentWeight = keyframeValue.leftTangentWeight,
          easingMethod = keyframeValue.easingMethod;
        dataView.setFloat32(currentOffset, value, true);
        currentOffset += VALUE_BYTES$1;
        if (interpolationMode !== DEFAULT_INTERPOLATION_MODE) {
          flags |= KeyframeValueFlagMask$1.INTERPOLATION_MODE;
          dataView.setUint8(currentOffset, interpolationMode);
          currentOffset += INTERPOLATION_MODE_BYTES$1;
        }
        if (tangentWeightMode !== DEFAULT_TANGENT_WEIGHT_MODE) {
          flags |= KeyframeValueFlagMask$1.TANGENT_WEIGHT_MODE;
          dataView.setUint8(currentOffset, tangentWeightMode);
          currentOffset += TANGENT_WEIGHT_MODE_BYTES;
        }
        if (leftTangent !== DEFAULT_LEFT_TANGENT) {
          flags |= KeyframeValueFlagMask$1.LEFT_TANGENT;
          dataView.setFloat32(currentOffset, leftTangent, true);
          currentOffset += LEFT_TANGENT_BYTES;
        }
        if (leftTangentWeight !== DEFAULT_LEFT_TANGENT_WEIGHT) {
          flags |= KeyframeValueFlagMask$1.LEFT_TANGENT_WEIGHT;
          dataView.setFloat32(currentOffset, leftTangentWeight, true);
          currentOffset += LEFT_TANGENT_WEIGHT_BYTES;
        }
        if (rightTangent !== DEFAULT_RIGHT_TANGENT) {
          flags |= KeyframeValueFlagMask$1.RIGHT_TANGENT;
          dataView.setFloat32(currentOffset, rightTangent, true);
          currentOffset += RIGHT_TANGENT_BYTES;
        }
        if (rightTangentWeight !== DEFAULT_RIGHT_TANGENT_WEIGHT) {
          flags |= KeyframeValueFlagMask$1.RIGHT_TANGENT_WEIGHT;
          dataView.setFloat32(currentOffset, rightTangentWeight, true);
          currentOffset += RIGHT_TANGENT_WEIGHT_BYTES;
        }
        flags |= easingMethod << FLAGS_EASING_METHOD_BITS_START;
        dataView.setUint32(pFlags, flags, true);
        return currentOffset;
      }
      function loadRealKeyFrameValue(dataView, keyframeValue, offset) {
        var currentOffset = offset;
        var flags = dataView.getUint32(currentOffset, true);
        currentOffset += KEY_FRAME_VALUE_FLAGS_BYTES;
        keyframeValue.value = dataView.getFloat32(currentOffset, true);
        currentOffset += VALUE_BYTES$1;
        if (flags & KeyframeValueFlagMask$1.INTERPOLATION_MODE) {
          keyframeValue.interpolationMode = dataView.getUint8(currentOffset);
          currentOffset += INTERPOLATION_MODE_BYTES$1;
        }
        if (flags & KeyframeValueFlagMask$1.TANGENT_WEIGHT_MODE) {
          keyframeValue.tangentWeightMode = dataView.getUint8(currentOffset);
          currentOffset += TANGENT_WEIGHT_MODE_BYTES;
        }
        if (flags & KeyframeValueFlagMask$1.LEFT_TANGENT) {
          keyframeValue.leftTangent = dataView.getFloat32(currentOffset, true);
          currentOffset += LEFT_TANGENT_BYTES;
        }
        if (flags & KeyframeValueFlagMask$1.LEFT_TANGENT_WEIGHT) {
          keyframeValue.leftTangentWeight = dataView.getFloat32(currentOffset, true);
          currentOffset += LEFT_TANGENT_WEIGHT_BYTES;
        }
        if (flags & KeyframeValueFlagMask$1.RIGHT_TANGENT) {
          keyframeValue.rightTangent = dataView.getFloat32(currentOffset, true);
          currentOffset += RIGHT_TANGENT_BYTES;
        }
        if (flags & KeyframeValueFlagMask$1.RIGHT_TANGENT_WEIGHT) {
          keyframeValue.rightTangentWeight = dataView.getFloat32(currentOffset, true);
          currentOffset += RIGHT_TANGENT_WEIGHT_BYTES;
        }
        var easingMethod = (flags & FLAG_EASING_METHOD_MASK) >> FLAGS_EASING_METHOD_BITS_START;
        keyframeValue.easingMethod = easingMethod;
        return currentOffset;
      }
      function wrapRepeat(time, prevTime, nextTime) {
        return prevTime + repeat$2(time - prevTime, nextTime - prevTime);
      }
      function wrapPingPong(time, prevTime, nextTime) {
        return prevTime + pingPong(time - prevTime, nextTime - prevTime);
      }
      function linearTrend(prevTime, prevValue, nextTime, nextValue, time) {
        var slope = (nextValue - prevValue) / (nextTime - prevTime);
        return prevValue + (time - prevTime) * slope;
      }
      function evalBetweenTwoKeyFrames(prevTime, prevValue, nextTime, nextValue, ratio) {
        var dt = nextTime - prevTime;
        switch (prevValue.interpolationMode) {
          default:
          case RealInterpolationMode.CONSTANT:
            return prevValue.value;
          case RealInterpolationMode.LINEAR:
            {
              var transformedRatio = prevValue.easingMethod === EasingMethod.LINEAR ? ratio : getEasingFn(prevValue.easingMethod)(ratio);
              return lerp(prevValue.value, nextValue.value, transformedRatio);
            }
          case RealInterpolationMode.CUBIC:
            {
              var ONE_THIRD = 1.0 / 3.0;
              var prevTangent = prevValue.rightTangent,
                prevTangentWeightSpecified = prevValue.rightTangentWeight;
              var prevTangentWeightEnabled = isRightTangentWeightEnabled(prevValue.tangentWeightMode);
              var nextTangent = nextValue.leftTangent,
                nextTangentWeightSpecified = nextValue.leftTangentWeight;
              var nextTangentWeightEnabled = isLeftTangentWeightEnabled(nextValue.tangentWeightMode);
              if (!prevTangentWeightEnabled && !nextTangentWeightEnabled) {
                var p1 = prevValue.value + ONE_THIRD * prevTangent * dt;
                var p2 = nextValue.value - ONE_THIRD * nextTangent * dt;
                return bezierInterpolate(prevValue.value, p1, p2, nextValue.value, ratio);
              } else {
                var prevTangentWeight = 0.0;
                if (prevTangentWeightEnabled) {
                  prevTangentWeight = prevTangentWeightSpecified;
                } else {
                  var x = dt;
                  var _y = dt * prevTangent;
                  prevTangentWeight = Math.sqrt(x * x + _y * _y) * ONE_THIRD;
                }
                var angle0 = Math.atan(prevTangent);
                var tx0 = Math.cos(angle0) * prevTangentWeight + prevTime;
                var ty0 = Math.sin(angle0) * prevTangentWeight + prevValue.value;
                var nextTangentWeight = 0.0;
                if (nextTangentWeightEnabled) {
                  nextTangentWeight = nextTangentWeightSpecified;
                } else {
                  var _x = dt;
                  var _y2 = dt * nextTangent;
                  nextTangentWeight = Math.sqrt(_x * _x + _y2 * _y2) * ONE_THIRD;
                }
                var angle1 = Math.atan(nextTangent);
                var tx1 = -Math.cos(angle1) * nextTangentWeight + nextTime;
                var ty1 = -Math.sin(angle1) * nextTangentWeight + nextValue.value;
                var dx = dt;
                var u0x = (tx0 - prevTime) / dx;
                var u1x = (tx1 - prevTime) / dx;
                var u0y = ty0;
                var u1y = ty1;
                var coeff0 = 0.0;
                var coeff1 = 3.0 * u0x;
                var coeff2 = 3.0 * u1x - 6.0 * u0x;
                var coeff3 = 3.0 * (u0x - u1x) + 1.0;
                var solutions = [0.0, 0.0, 0.0];
                var nSolutions = solveCubic(coeff0 - ratio, coeff1, coeff2, coeff3, solutions);
                var param = getParamFromCubicSolution(solutions, nSolutions, ratio);
                var y = bezierInterpolate(prevValue.value, u0y, u1y, nextValue.value, param);
                return y;
              }
            }
        }
      }
      function isLeftTangentWeightEnabled(tangentWeightMode) {
        return (tangentWeightMode & TangentWeightMode.LEFT) !== 0;
      }
      function isRightTangentWeightEnabled(tangentWeightMode) {
        return (tangentWeightMode & TangentWeightMode.RIGHT) !== 0;
      }
      function bezierInterpolate(p0, p1, p2, p3, t) {
        var u = 1 - t;
        var coeff0 = u * u * u;
        var coeff1 = 3 * u * u * t;
        var coeff2 = 3 * u * t * t;
        var coeff3 = t * t * t;
        return coeff0 * p0 + coeff1 * p1 + coeff2 * p2 + coeff3 * p3;
      }
      function getParamFromCubicSolution(solutions, solutionsCount, x) {
        var param = x;
        if (solutionsCount === 1) {
          param = solutions[0];
        } else {
          param = -Infinity;
          for (var iSolution = 0; iSolution < solutionsCount; ++iSolution) {
            var solution = solutions[iSolution];
            if (solution >= 0.0 && solution <= 1.0) {
              if (solution > param) {
                param = solution;
              }
            }
          }
          if (param === -Infinity) {
            param = 0.0;
          }
        }
        return param;
      }

      function bezier(C1, C2, C3, C4, t) {
        var t1 = 1 - t;
        return t1 * (t1 * (C1 + (C2 * 3 - C1) * t) + C3 * 3 * t * t) + C4 * t * t * t;
      }
      legacyCC.bezier = bezier;
      var cos$2 = Math.cos;
      var acos$1 = Math.acos;
      var max$2 = Math.max;
      var pi = Math.PI;
      var tau = 2 * pi;
      var sqrt = Math.sqrt;
      function crt(v) {
        if (v < 0) {
          return -Math.pow(-v, 1 / 3);
        } else {
          return Math.pow(v, 1 / 3);
        }
      }
      function cardano(curve, x) {
        var pa = x - 0;
        var pb = x - curve[0];
        var pc = x - curve[2];
        var pd = x - 1;
        var pa3 = pa * 3;
        var pb3 = pb * 3;
        var pc3 = pc * 3;
        var d = -pa + pb3 - pc3 + pd;
        var rd = 1 / d;
        var r3 = 1 / 3;
        var a = (pa3 - 6 * pb + pc3) * rd;
        var a3 = a * r3;
        var b = (-pa3 + pb3) * rd;
        var c = pa * rd;
        var p = (3 * b - a * a) * r3;
        var p3 = p * r3;
        var q = (2 * a * a * a - 9 * a * b + 27 * c) / 27;
        var q2 = q / 2;
        var discriminant = q2 * q2 + p3 * p3 * p3;
        var u1;
        var v1;
        var x1;
        var x2;
        var x3;
        if (discriminant < 0) {
          var mp3 = -p * r3;
          var mp33 = mp3 * mp3 * mp3;
          var r = sqrt(mp33);
          var t = -q / (2 * r);
          var cosphi = t < -1 ? -1 : t > 1 ? 1 : t;
          var phi = acos$1(cosphi);
          var crtr = crt(r);
          var t1 = 2 * crtr;
          x1 = t1 * cos$2(phi * r3) - a3;
          x2 = t1 * cos$2((phi + tau) * r3) - a3;
          x3 = t1 * cos$2((phi + 2 * tau) * r3) - a3;
          if (x1 >= 0 && x1 <= 1) {
            if (x2 >= 0 && x2 <= 1) {
              if (x3 >= 0 && x3 <= 1) {
                return max$2(x1, x2, x3);
              } else {
                return max$2(x1, x2);
              }
            } else if (x3 >= 0 && x3 <= 1) {
              return max$2(x1, x3);
            } else {
              return x1;
            }
          } else if (x2 >= 0 && x2 <= 1) {
            if (x3 >= 0 && x3 <= 1) {
              return max$2(x2, x3);
            } else {
              return x2;
            }
          } else {
            return x3;
          }
        } else if (discriminant === 0) {
          u1 = q2 < 0 ? crt(-q2) : -crt(q2);
          x1 = 2 * u1 - a3;
          x2 = -u1 - a3;
          if (x1 >= 0 && x1 <= 1) {
            if (x2 >= 0 && x2 <= 1) {
              return max$2(x1, x2);
            } else {
              return x1;
            }
          } else {
            return x2;
          }
        } else {
          var sd = sqrt(discriminant);
          u1 = crt(-q2 + sd);
          v1 = crt(q2 + sd);
          x1 = u1 - v1 - a3;
          return x1;
        }
      }
      function bezierByTime(controlPoints, x) {
        var percent = cardano(controlPoints, x);
        var p1y = controlPoints[1];
        var p2y = controlPoints[3];
        return ((1 - percent) * (p1y + (p2y - p1y) * percent) * 3 + percent * percent) * percent;
      }
      legacyCC.bezierByTime = bezierByTime;

      var _dec$3I, _class$3E, _class2$3h, _initializer$2_, _initializer2$2n, _initializer3$1M, _dec2$2B, _class4$z, _class5$z, _initializer4$1v, _initializer5$1a;
      var QuatInterpolationMode; exports('ct', QuatInterpolationMode);
      (function (QuatInterpolationMode) {
        QuatInterpolationMode[QuatInterpolationMode["SLERP"] = 0] = "SLERP";
        QuatInterpolationMode[QuatInterpolationMode["CONSTANT"] = 1] = "CONSTANT";
      })(QuatInterpolationMode || (exports('ct', QuatInterpolationMode = {})));
      var QuatKeyframeValue = (_dec$3I = ccclass$M('cc.QuatKeyframeValue'), _dec$3I(_class$3E = uniquelyReferenced(_class$3E = (_class2$3h = function QuatKeyframeValue(_temp) {
        var _ref = _temp === void 0 ? {} : _temp,
          value = _ref.value,
          interpolationMode = _ref.interpolationMode,
          easingMethod = _ref.easingMethod;
        this.interpolationMode = _initializer$2_ && _initializer$2_();
        this.value = _initializer2$2n && _initializer2$2n();
        this.easingMethod = _initializer3$1M && _initializer3$1M();
        this.value = value ? Quat.clone(value) : this.value;
        this.interpolationMode = interpolationMode !== null && interpolationMode !== void 0 ? interpolationMode : this.interpolationMode;
        this.easingMethod = easingMethod !== null && easingMethod !== void 0 ? easingMethod : this.easingMethod;
      }, (_initializer$2_ = applyDecoratedInitializer(_class2$3h.prototype, "interpolationMode", [serializable$p], function () {
        return QuatInterpolationMode.SLERP;
      }), _initializer2$2n = applyDecoratedInitializer(_class2$3h.prototype, "value", [serializable$p], function () {
        return Quat.clone(Quat.IDENTITY);
      }), _initializer3$1M = applyDecoratedInitializer(_class2$3h.prototype, "easingMethod", [serializable$p], function () {
        return EasingMethod.LINEAR;
      })), _class2$3h)) || _class$3E) || _class$3E);
      function createQuatKeyframeValue(params) {
        return new QuatKeyframeValue(params);
      }
      var QuatCurve = exports('cs', (_dec2$2B = ccclass$M('cc.QuatCurve'), _dec2$2B(_class4$z = (_class5$z = function (_KeyframeCurve) {
        _inheritsLoose(QuatCurve, _KeyframeCurve);
        function QuatCurve() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _KeyframeCurve.call.apply(_KeyframeCurve, [this].concat(args)) || this;
          _this.preExtrapolation = _initializer4$1v && _initializer4$1v();
          _this.postExtrapolation = _initializer5$1a && _initializer5$1a();
          return _this;
        }
        var _proto = QuatCurve.prototype;
        _proto.evaluate = function evaluate(time, quat) {
          var _quat;
          (_quat = quat) !== null && _quat !== void 0 ? _quat : quat = new Quat();
          var times = this._times,
            values = this._values,
            postExtrapolation = this.postExtrapolation,
            preExtrapolation = this.preExtrapolation;
          var nFrames = times.length;
          if (nFrames === 0) {
            return quat;
          }
          var firstTime = times[0];
          var lastTime = times[nFrames - 1];
          if (time < firstTime) {
            var _preValue = values[0];
            switch (preExtrapolation) {
              case ExtrapolationMode.LOOP:
                time = firstTime + repeat$2(time - firstTime, lastTime - firstTime);
                break;
              case ExtrapolationMode.PING_PONG:
                time = firstTime + pingPong(time - firstTime, lastTime - firstTime);
                break;
              case ExtrapolationMode.CLAMP:
              default:
                return Quat.copy(quat, _preValue.value);
            }
          } else if (time > lastTime) {
            var _preValue2 = values[nFrames - 1];
            switch (postExtrapolation) {
              case ExtrapolationMode.LOOP:
                time = firstTime + repeat$2(time - firstTime, lastTime - firstTime);
                break;
              case ExtrapolationMode.PING_PONG:
                time = firstTime + pingPong(time - firstTime, lastTime - firstTime);
                break;
              case ExtrapolationMode.CLAMP:
              default:
                return Quat.copy(quat, _preValue2.value);
            }
          }
          var index = binarySearchEpsilon(times, time);
          if (index >= 0) {
            return Quat.copy(quat, values[index].value);
          }
          var iNext = ~index;
          assertIsTrue(iNext !== 0 && iNext !== nFrames && nFrames > 1);
          var iPre = iNext - 1;
          var preTime = times[iPre];
          var preValue = values[iPre];
          var nextTime = times[iNext];
          var nextValue = values[iNext];
          assertIsTrue(nextTime > time && time > preTime);
          var dt = nextTime - preTime;
          var ratio = (time - preTime) / dt;
          switch (preValue.interpolationMode) {
            default:
            case QuatInterpolationMode.CONSTANT:
              return Quat.copy(quat, preValue.value);
            case QuatInterpolationMode.SLERP:
              {
                var easingMethod = preValue.easingMethod;
                var transformedRatio = easingMethod === EasingMethod.LINEAR ? ratio : Array.isArray(easingMethod) ? bezierByTime(easingMethod, ratio) : getEasingFn(easingMethod)(ratio);
                return Quat.slerp(quat, preValue.value, nextValue.value, transformedRatio);
              }
          }
        };
        _proto.addKeyFrame = function addKeyFrame(time, value) {
          var keyframeValue = new QuatKeyframeValue(value);
          return _KeyframeCurve.prototype.addKeyFrame.call(this, time, keyframeValue);
        };
        _proto.assignSorted = function assignSorted(times, values) {
          if (values !== undefined) {
            assertIsTrue(Array.isArray(times));
            this.setKeyframes(times.slice(), values.map(function (value) {
              return createQuatKeyframeValue(value);
            }));
          } else {
            var _keyframes = Array.from(times);
            this.setKeyframes(_keyframes.map(function (_ref2) {
              var time = _ref2[0];
              return time;
            }), _keyframes.map(function (_ref3) {
              var value = _ref3[1];
              return createQuatKeyframeValue(value);
            }));
          }
        };
        _proto[serializeTag] = function (output, context) {
          if (!context.toCCON) {
            output.writeThis();
            return;
          }
          var times = this._times,
            keyframeValues = this._values;
          var interpolationModeRepeated = true;
          keyframeValues.forEach(function (keyframeValue, _index, _ref4) {
            var firstKeyframeValue = _ref4[0];
            if (interpolationModeRepeated && keyframeValue.interpolationMode !== firstKeyframeValue.interpolationMode) {
              interpolationModeRepeated = false;
            }
          });
          var nKeyframes = times.length;
          var nFrames = nKeyframes;
          var interpolationModesSize = INTERPOLATION_MODE_BYTES * (interpolationModeRepeated ? 1 : nFrames);
          var easingMethodsSize = keyframeValues.reduce(function (result, _ref5) {
            var easingMethod = _ref5.easingMethod;
            return result += Array.isArray(easingMethod) ? EASING_METHOD_BYTES + EASING_METHOD_BEZIER_COMPONENT_BYTES * 4 : EASING_METHOD_BYTES;
          }, 0);
          var dataSize = 0;
          dataSize += FLAGS_BYTES + FRAME_COUNT_BYTES + TIME_BYTES * nFrames + VALUE_BYTES * 4 * nFrames + easingMethodsSize + interpolationModesSize + 0;
          var dataView = new DataView(new ArrayBuffer(dataSize));
          var P = 0;
          var flags = 0;
          if (interpolationModeRepeated) {
            flags |= KeyframeValueFlagMask.INTERPOLATION_MODE;
          }
          dataView.setUint32(P, flags, true);
          P += FLAGS_BYTES;
          dataView.setUint32(P, nFrames, true);
          P += FRAME_COUNT_BYTES;
          times.forEach(function (time, index) {
            return dataView.setFloat32(P + TIME_BYTES * index, time, true);
          });
          P += TIME_BYTES * nFrames;
          keyframeValues.forEach(function (_ref6, index) {
            var _ref6$value = _ref6.value,
              x = _ref6$value.x,
              y = _ref6$value.y,
              z = _ref6$value.z,
              w = _ref6$value.w;
            var pQuat = P + VALUE_BYTES * 4 * index;
            dataView.setFloat32(pQuat + VALUE_BYTES * 0, x, true);
            dataView.setFloat32(pQuat + VALUE_BYTES * 1, y, true);
            dataView.setFloat32(pQuat + VALUE_BYTES * 2, z, true);
            dataView.setFloat32(pQuat + VALUE_BYTES * 3, w, true);
          });
          P += VALUE_BYTES * 4 * nFrames;
          keyframeValues.forEach(function (_ref7, index) {
            var easingMethod = _ref7.easingMethod;
            if (!Array.isArray(easingMethod)) {
              dataView.setUint8(P, easingMethod);
              ++P;
            } else {
              dataView.setUint8(P, EASING_METHOD_BEZIER_TAG);
              ++P;
              dataView.setFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 0, easingMethod[0], true);
              dataView.setFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 1, easingMethod[1], true);
              dataView.setFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 2, easingMethod[2], true);
              dataView.setFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 3, easingMethod[3], true);
              P += EASING_METHOD_BEZIER_COMPONENT_BYTES * 4;
            }
          });
          var INTERPOLATION_MODES_START = P;
          P += interpolationModesSize;
          var pInterpolationMode = INTERPOLATION_MODES_START;
          keyframeValues.forEach(function (_ref8) {
            var interpolationMode = _ref8.interpolationMode;
            dataView.setUint8(pInterpolationMode, interpolationMode);
            if (!interpolationModeRepeated) {
              pInterpolationMode += INTERPOLATION_MODE_BYTES;
            }
          });
          var bytes = new Uint8Array(dataView.buffer);
          output.writeProperty('bytes', bytes);
        };
        _proto[deserializeTag] = function (input, context) {
          if (!context.fromCCON) {
            input.readThis();
            return;
          }
          var bytes = input.readProperty('bytes');
          var dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
          var P = 0;
          var flags = dataView.getUint32(P, true);
          P += FLAGS_BYTES;
          var interpolationModeRepeated = flags & KeyframeValueFlagMask.INTERPOLATION_MODE;
          var nFrames = dataView.getUint32(P, true);
          P += FRAME_COUNT_BYTES;
          var times = Array.from({
            length: nFrames
          }, function (_, index) {
            return dataView.getFloat32(P + TIME_BYTES * index, true);
          });
          P += TIME_BYTES * nFrames;
          var P_VALUES = P;
          P += VALUE_BYTES * 4 * nFrames;
          var keyframeValues = Array.from({
            length: nFrames
          }, function (_, index) {
            var pQuat = P_VALUES + VALUE_BYTES * 4 * index;
            var x = dataView.getFloat32(pQuat + VALUE_BYTES * 0, true);
            var y = dataView.getFloat32(pQuat + VALUE_BYTES * 1, true);
            var z = dataView.getFloat32(pQuat + VALUE_BYTES * 2, true);
            var w = dataView.getFloat32(pQuat + VALUE_BYTES * 3, true);
            var easingMethod = dataView.getUint8(P);
            ++P;
            var keyframeValue = createQuatKeyframeValue({
              value: {
                x: x,
                y: y,
                z: z,
                w: w
              }
            });
            if (easingMethod !== EASING_METHOD_BEZIER_TAG) {
              keyframeValue.easingMethod = easingMethod;
            } else {
              keyframeValue.easingMethod = [dataView.getFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 0, true), dataView.getFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 1, true), dataView.getFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 2, true), dataView.getFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 3, true)];
              P += EASING_METHOD_BEZIER_COMPONENT_BYTES * 4;
            }
            return keyframeValue;
          });
          if (interpolationModeRepeated) {
            var interpolationMode = dataView.getUint8(P);
            ++P;
            for (var iKeyframe = 0; iKeyframe < nFrames; ++iKeyframe) {
              keyframeValues[iKeyframe].interpolationMode = interpolationMode;
            }
          } else {
            for (var _iKeyframe = 0; _iKeyframe < nFrames; ++_iKeyframe) {
              var _interpolationMode = dataView.getUint8(P + _iKeyframe);
              keyframeValues[_iKeyframe].interpolationMode = _interpolationMode;
            }
            P += nFrames;
          }
          this._times = times;
          this._values = keyframeValues;
        };
        return QuatCurve;
      }(KeyframeCurve), (_initializer4$1v = applyDecoratedInitializer(_class5$z.prototype, "preExtrapolation", [serializable$p], function () {
        return ExtrapolationMode.CLAMP;
      }), _initializer5$1a = applyDecoratedInitializer(_class5$z.prototype, "postExtrapolation", [serializable$p], function () {
        return ExtrapolationMode.CLAMP;
      })), _class5$z)) || _class4$z));
      var KeyframeValueFlagMask;
      (function (KeyframeValueFlagMask) {
        KeyframeValueFlagMask[KeyframeValueFlagMask["INTERPOLATION_MODE"] = 1] = "INTERPOLATION_MODE";
      })(KeyframeValueFlagMask || (KeyframeValueFlagMask = {}));
      var FLAGS_BYTES = 1;
      var FRAME_COUNT_BYTES = 4;
      var TIME_BYTES = 4;
      var VALUE_BYTES = 4;
      var INTERPOLATION_MODE_BYTES = 1;
      var EASING_METHOD_BYTES = 1;
      var EASING_METHOD_BEZIER_TAG = 255;
      var EASING_METHOD_BEZIER_COMPONENT_BYTES = 4;

      var _dec$3H, _class$3D;
      var ObjectCurve = exports('cu', (_dec$3H = ccclass$M('cc.ObjectCurve'), _dec$3H(_class$3D = function (_KeyframeCurve) {
        _inheritsLoose(ObjectCurve, _KeyframeCurve);
        function ObjectCurve() {
          return _KeyframeCurve.apply(this, arguments) || this;
        }
        var _proto = ObjectCurve.prototype;
        _proto.evaluate = function evaluate(time) {
          var iSearch = this.searchKeyframe(time);
          if (iSearch >= 0) {
            return this._values[iSearch];
          }
          var iPrev = clamp$1(~iSearch - 1, 0, this._values.length - 1);
          return this._values[iPrev];
        };
        return ObjectCurve;
      }(KeyframeCurve)) || _class$3D));

      var Mode$4 = Enum({
        Blend: 0,
        Fixed: 1
      });
      var ColorKey = exports('cv', function ColorKey() {
        this.color = Color$1.WHITE.clone();
        this.time = 0;
      });
      CCClass.fastDefine('cc.ColorKey', ColorKey, {
        color: Color$1.WHITE.clone(),
        time: 0
      });
      CCClass.Attr.setClassAttr(ColorKey, 'color', 'visible', true);
      CCClass.Attr.setClassAttr(ColorKey, 'time', 'visible', true);
      var AlphaKey = exports('cw', function AlphaKey() {
        this.alpha = 1;
        this.time = 0;
      });
      CCClass.fastDefine('cc.AlphaKey', AlphaKey, {
        alpha: 1,
        time: 0
      });
      CCClass.Attr.setClassAttr(AlphaKey, 'alpha', 'visible', true);
      CCClass.Attr.setClassAttr(AlphaKey, 'time', 'visible', true);
      var Gradient = exports('cx', function () {
        function Gradient() {
          this.colorKeys = [];
          this.alphaKeys = [];
          this.mode = Mode$4.Blend;
        }
        var _proto = Gradient.prototype;
        _proto.setKeys = function setKeys(colorKeys, alphaKeys) {
          this.colorKeys = colorKeys;
          this.alphaKeys = alphaKeys;
        };
        _proto.sortKeys = function sortKeys() {
          if (this.colorKeys.length > 1) {
            this.colorKeys.sort(function (a, b) {
              return a.time - b.time;
            });
          }
          if (this.alphaKeys.length > 1) {
            this.alphaKeys.sort(function (a, b) {
              return a.time - b.time;
            });
          }
        };
        _proto.evaluate = function evaluate(time) {
          return this.evaluateFast(new Color$1(), time);
        };
        _proto.evaluateFast = function evaluateFast(out, time) {
          this.getRGB(out, time);
          out._set_a_unsafe(this.getAlpha(time));
          return out;
        };
        _proto.randomColor = function randomColor() {
          return this.getRandomColor(new Color$1());
        };
        _proto.getRandomColor = function getRandomColor(out) {
          var c = this.colorKeys[Math.trunc(random() * this.colorKeys.length)];
          var a = this.alphaKeys[Math.trunc(random() * this.alphaKeys.length)];
          out.set(c.color);
          out._set_a_unsafe(a.alpha);
          return out;
        };
        _proto.getRGB = function getRGB(out, time) {
          var colorKeys = this.colorKeys;
          var length = colorKeys.length;
          if (length > 1) {
            time = repeat$2(time, 1.0 + EPSILON$3);
            for (var i = 1; i < length; ++i) {
              var preTime = colorKeys[i - 1].time;
              var curTime = colorKeys[i].time;
              if (time >= preTime && time < curTime) {
                if (this.mode === Mode$4.Fixed) {
                  Color$1.copy(out, colorKeys[i].color);
                  return out;
                }
                var factor = (time - preTime) / (curTime - preTime);
                Color$1.lerp(out, colorKeys[i - 1].color, colorKeys[i].color, factor);
                return out;
              }
            }
            var lastIndex = length - 1;
            if (approx(time, colorKeys[lastIndex].time, EPSILON$3)) {
              Color$1.copy(out, colorKeys[lastIndex].color);
            } else if (time < colorKeys[0].time) {
              Color$1.lerp(out, Color$1.BLACK, colorKeys[0].color, time / colorKeys[0].time);
            } else if (time > colorKeys[lastIndex].time) {
              Color$1.lerp(out, colorKeys[lastIndex].color, Color$1.BLACK, (time - colorKeys[lastIndex].time) / (1 - colorKeys[lastIndex].time));
            }
          } else if (length === 1) {
            Color$1.copy(out, colorKeys[0].color);
          } else {
            Color$1.copy(out, Color$1.WHITE);
          }
          return out;
        };
        _proto.getAlpha = function getAlpha(time) {
          var basicAlpha = 0;
          var alphaKeys = this.alphaKeys;
          var length = alphaKeys.length;
          if (length > 1) {
            time = repeat$2(time, 1.0 + EPSILON$3);
            for (var i = 1; i < length; ++i) {
              var preTime = alphaKeys[i - 1].time;
              var curTime = alphaKeys[i].time;
              if (time >= preTime && time < curTime) {
                if (this.mode === Mode$4.Fixed) {
                  return alphaKeys[i].alpha;
                }
                var factor = (time - preTime) / (curTime - preTime);
                return lerp(alphaKeys[i - 1].alpha, alphaKeys[i].alpha, factor);
              }
            }
            var lastIndex = length - 1;
            if (approx(time, alphaKeys[lastIndex].time, EPSILON$3)) {
              return alphaKeys[lastIndex].alpha;
            } else if (time < alphaKeys[0].time) {
              return lerp(basicAlpha, alphaKeys[0].alpha, time / alphaKeys[0].time);
            } else if (time > alphaKeys[lastIndex].time) {
              return lerp(alphaKeys[lastIndex].alpha, basicAlpha, (time - alphaKeys[lastIndex].time) / (1 - alphaKeys[lastIndex].time));
            }
            return 255;
          } else if (length === 1) {
            return alphaKeys[0].alpha;
          } else {
            return 255;
          }
        };
        return Gradient;
      }());
      Gradient.Mode = Mode$4;
      CCClass.fastDefine('cc.Gradient', Gradient, {
        colorKeys: [],
        alphaKeys: [],
        mode: Mode$4.Blend
      });
      CCClass.Attr.setClassAttr(Gradient, 'colorKeys', 'visible', true);
      CCClass.Attr.setClassAttr(Gradient, 'alphaKeys', 'visible', true);
      CCClass.Attr.setClassAttr(Gradient, 'mode', 'visible', true);

      var LOOK_FORWARD = 3;
      var Keyframe = function Keyframe() {
        this.time = 0;
        this.value = 0;
        this.inTangent = 0;
        this.outTangent = 0;
      };
      CCClass.fastDefine('cc.Keyframe', Keyframe, {
        time: 0,
        value: 0,
        inTangent: 0,
        outTangent: 0
      });
      var OptimizedKey = function () {
        function OptimizedKey() {
          this.index = void 0;
          this.time = void 0;
          this.endTime = void 0;
          this.coefficient = void 0;
          this.index = -1;
          this.time = 0;
          this.endTime = 0;
          this.coefficient = new Float32Array(4);
        }
        var _proto = OptimizedKey.prototype;
        _proto.evaluate = function evaluate(T) {
          var t = T - this.time;
          return evalOptCurve(t, this.coefficient);
        };
        return OptimizedKey;
      }();
      function evalOptCurve(t, coefs) {
        return t * (t * (t * coefs[0] + coefs[1]) + coefs[2]) + coefs[3];
      }
      var AnimationCurve = function () {
        function AnimationCurve(keyFrames) {
          if (keyFrames === void 0) {
            keyFrames = null;
          }
          this._curve = void 0;
          this.cachedKey = void 0;
          if (keyFrames instanceof RealCurve) {
            this._curve = keyFrames;
          } else {
            var curve = new RealCurve();
            this._curve = curve;
            curve.preExtrapolation = ExtrapolationMode.LOOP;
            curve.postExtrapolation = ExtrapolationMode.CLAMP;
            if (!keyFrames) {
              curve.assignSorted([[0.0, {
                interpolationMode: RealInterpolationMode.CUBIC,
                value: 1.0
              }], [1.0, {
                interpolationMode: RealInterpolationMode.CUBIC,
                value: 1.0
              }]]);
            } else {
              curve.assignSorted(keyFrames.map(function (legacyKeyframe) {
                return [legacyKeyframe.time, {
                  interpolationMode: RealInterpolationMode.CUBIC,
                  value: legacyKeyframe.value,
                  leftTangent: legacyKeyframe.inTangent,
                  rightTangent: legacyKeyframe.outTangent
                }];
              }));
            }
          }
          this.cachedKey = new OptimizedKey();
        }
        var _proto2 = AnimationCurve.prototype;
        _proto2.addKey = function addKey(keyFrame) {
          if (!keyFrame) {
            this._curve.clear();
          } else {
            this._curve.addKeyFrame(keyFrame.time, {
              interpolationMode: RealInterpolationMode.CUBIC,
              value: keyFrame.value,
              leftTangent: keyFrame.inTangent,
              rightTangent: keyFrame.outTangent
            });
          }
        };
        _proto2.evaluate_slow = function evaluate_slow(time) {
          return this._curve.evaluate(time);
        };
        _proto2.evaluate = function evaluate(time) {
          var cachedKey = this.cachedKey,
            curve = this._curve;
          var nKeyframes = curve.keyFramesCount;
          var lastKeyframeIndex = nKeyframes - 1;
          var wrappedTime = time;
          var extrapolationMode = time < 0 ? curve.preExtrapolation : curve.postExtrapolation;
          var startTime = curve.getKeyframeTime(0);
          var endTime = curve.getKeyframeTime(lastKeyframeIndex);
          switch (extrapolationMode) {
            case ExtrapolationMode.LOOP:
              wrappedTime = repeat$2(time - startTime, endTime - startTime) + startTime;
              break;
            case ExtrapolationMode.PING_PONG:
              wrappedTime = pingPong(time - startTime, endTime - startTime) + startTime;
              break;
            case ExtrapolationMode.CLAMP:
            default:
              wrappedTime = clamp$1(time, startTime, endTime);
              break;
          }
          if (wrappedTime >= cachedKey.time && wrappedTime < cachedKey.endTime) {
            return cachedKey.evaluate(wrappedTime);
          }
          var leftIndex = this.findIndex(cachedKey, wrappedTime);
          var rightIndex = Math.min(leftIndex + 1, lastKeyframeIndex);
          this.calcOptimizedKey(cachedKey, leftIndex, rightIndex);
          return cachedKey.evaluate(wrappedTime);
        };
        _proto2.calcOptimizedKey = function calcOptimizedKey(optKey, leftIndex, rightIndex) {
          var lhsTime = this._curve.getKeyframeTime(leftIndex);
          var rhsTime = this._curve.getKeyframeTime(rightIndex);
          var _this$_curve$getKeyfr = this._curve.getKeyframeValue(leftIndex),
            lhsValue = _this$_curve$getKeyfr.value,
            lhsOutTangent = _this$_curve$getKeyfr.leftTangent;
          var _this$_curve$getKeyfr2 = this._curve.getKeyframeValue(rightIndex),
            rhsValue = _this$_curve$getKeyfr2.value,
            rhsInTangent = _this$_curve$getKeyfr2.rightTangent;
          optKey.index = leftIndex;
          optKey.time = lhsTime;
          optKey.endTime = rhsTime;
          var dx = rhsTime - lhsTime;
          var dy = rhsValue - lhsValue;
          var length = 1 / (dx * dx);
          var d1 = lhsOutTangent * dx;
          var d2 = rhsInTangent * dx;
          optKey.coefficient[0] = (d1 + d2 - dy - dy) * length / dx;
          optKey.coefficient[1] = (dy + dy + dy - d1 - d1 - d2) * length;
          optKey.coefficient[2] = lhsOutTangent;
          optKey.coefficient[3] = lhsValue;
        };
        _proto2.findIndex = function findIndex(optKey, t) {
          var curve = this._curve;
          var nKeyframes = curve.keyFramesCount;
          var cachedIndex = optKey.index;
          if (cachedIndex !== -1) {
            var cachedTime = curve.getKeyframeTime(cachedIndex);
            if (t > cachedTime) {
              for (var i = 0; i < LOOK_FORWARD; i++) {
                var currIndex = cachedIndex + i;
                if (currIndex + 1 < nKeyframes && curve.getKeyframeTime(currIndex + 1) > t) {
                  return currIndex;
                }
              }
            } else {
              for (var _i = 0; _i < LOOK_FORWARD; _i++) {
                var _currIndex = cachedIndex - _i;
                if (_currIndex >= 0 && curve.getKeyframeTime(_currIndex - 1) <= t) {
                  return _currIndex - 1;
                }
              }
            }
          }
          var left = 0;
          var right = nKeyframes;
          var mid;
          while (right - left > 1) {
            mid = Math.floor((left + right) / 2);
            if (curve.getKeyframeTime(mid) >= t) {
              right = mid;
            } else {
              left = mid;
            }
          }
          return left;
        };
        _createClass(AnimationCurve, [{
          key: "_internalCurve",
          get: function get() {
            return this._curve;
          }
        }, {
          key: "keyFrames",
          get: function get() {
            return Array.from(this._curve.keyframes()).map(function (_ref) {
              var time = _ref[0],
                value = _ref[1];
              var legacyKeyframe = new Keyframe();
              legacyKeyframe.time = time;
              legacyKeyframe.value = value.value;
              legacyKeyframe.inTangent = value.leftTangent;
              legacyKeyframe.outTangent = value.rightTangent;
              return legacyKeyframe;
            });
          },
          set: function set(value) {
            this._curve.assignSorted(value.map(function (legacyCurve) {
              return [legacyCurve.time, {
                interpolationMode: RealInterpolationMode.CUBIC,
                value: legacyCurve.value,
                leftTangent: legacyCurve.inTangent,
                rightTangent: legacyCurve.outTangent
              }];
            }));
          }
        }, {
          key: "preWrapMode",
          get: function get() {
            return toLegacyWrapMode(this._curve.preExtrapolation);
          },
          set: function set(value) {
            this._curve.preExtrapolation = fromLegacyWrapMode(value);
          }
        }, {
          key: "postWrapMode",
          get: function get() {
            return toLegacyWrapMode(this._curve.postExtrapolation);
          },
          set: function set(value) {
            this._curve.postExtrapolation = fromLegacyWrapMode(value);
          }
        }]);
        return AnimationCurve;
      }();
      AnimationCurve.defaultKF = [{
        time: 0,
        value: 1,
        inTangent: 0,
        outTangent: 0
      }, {
        time: 1,
        value: 1,
        inTangent: 0,
        outTangent: 0
      }];
      CCClass.fastDefine('cc.AnimationCurve', AnimationCurve, {
        _curve: null
      });
      var WrapModeMask;
      (function (WrapModeMask) {
        WrapModeMask[WrapModeMask["Default"] = 0] = "Default";
        WrapModeMask[WrapModeMask["Normal"] = 1] = "Normal";
        WrapModeMask[WrapModeMask["Loop"] = 2] = "Loop";
        WrapModeMask[WrapModeMask["ShouldWrap"] = 4] = "ShouldWrap";
        WrapModeMask[WrapModeMask["Clamp"] = 8] = "Clamp";
        WrapModeMask[WrapModeMask["PingPong"] = 22] = "PingPong";
        WrapModeMask[WrapModeMask["Reverse"] = 36] = "Reverse";
      })(WrapModeMask || (WrapModeMask = {}));
      function fromLegacyWrapMode(legacyWrapMode) {
        switch (legacyWrapMode) {
          default:
          case WrapModeMask.Default:
          case WrapModeMask.Normal:
          case WrapModeMask.Clamp:
            return ExtrapolationMode.CLAMP;
          case WrapModeMask.PingPong:
            return ExtrapolationMode.PING_PONG;
          case WrapModeMask.Loop:
            return ExtrapolationMode.LOOP;
        }
      }
      function toLegacyWrapMode(extrapolationMode) {
        switch (extrapolationMode) {
          default:
          case ExtrapolationMode.LINEAR:
          case ExtrapolationMode.CLAMP:
            return WrapModeMask.Clamp;
          case ExtrapolationMode.PING_PONG:
            return WrapModeMask.PingPong;
          case ExtrapolationMode.LOOP:
            return WrapModeMask.Loop;
        }
      }
      function constructLegacyCurveAndConvert() {
        var curve = new RealCurve();
        curve.assignSorted([[0.0, {
          interpolationMode: RealInterpolationMode.CUBIC,
          value: 1.0
        }], [1.0, {
          interpolationMode: RealInterpolationMode.CUBIC,
          value: 1.0
        }]]);
        return curve;
      }

      var SplineMode;
      (function (SplineMode) {
        SplineMode[SplineMode["LINEAR"] = 0] = "LINEAR";
        SplineMode[SplineMode["BEZIER"] = 1] = "BEZIER";
        SplineMode[SplineMode["CATMULL_ROM"] = 2] = "CATMULL_ROM";
      })(SplineMode || (SplineMode = {}));
      var SPLINE_WHOLE_INDEX = 0xffffffff;
      var _v0 = new Vec3();
      var _v1$1 = new Vec3();
      var _v2$1 = new Vec3();
      var _v3$4 = new Vec3();
      var Spline = function () {
        function Spline(mode, knots) {
          if (mode === void 0) {
            mode = SplineMode.CATMULL_ROM;
          }
          if (knots === void 0) {
            knots = [];
          }
          this._type = void 0;
          this._mode = SplineMode.CATMULL_ROM;
          this._knots = [];
          this._type = enums.SHAPE_SPLINE;
          this._mode = mode;
          for (var i = 0; i < knots.length; i++) {
            this._knots[i] = new Vec3(knots[i]);
          }
        }
        Spline.create = function create(mode, knots) {
          if (knots === void 0) {
            knots = [];
          }
          return new Spline(mode, knots);
        };
        Spline.clone = function clone(s) {
          return new Spline(s.mode, s.knots);
        };
        Spline.copy = function copy(out, s) {
          out._mode = s.mode;
          out._knots.length = 0;
          var knots = s.knots;
          var length = knots.length;
          for (var i = 0; i < length; i++) {
            out._knots[i] = new Vec3(knots[i]);
          }
          return out;
        };
        var _proto = Spline.prototype;
        _proto.setModeAndKnots = function setModeAndKnots(mode, knots) {
          this._mode = mode;
          this._knots.length = 0;
          for (var i = 0; i < knots.length; i++) {
            this._knots[i] = new Vec3(knots[i]);
          }
        };
        _proto.clearKnots = function clearKnots() {
          this._knots.length = 0;
        };
        _proto.getKnotCount = function getKnotCount() {
          return this._knots.length;
        };
        _proto.addKnot = function addKnot(knot) {
          this._knots.push(new Vec3(knot));
        };
        _proto.insertKnot = function insertKnot(index, knot) {
          var item = new Vec3(knot);
          if (index >= this._knots.length) {
            this._knots.push(item);
            return;
          }
          this._knots.splice(index, 0, item);
        };
        _proto.removeKnot = function removeKnot(index) {
          assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index');
          this._knots.splice(index, 1);
        };
        _proto.setKnot = function setKnot(index, knot) {
          assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index');
          this._knots[index].set(knot);
        };
        _proto.getKnot = function getKnot(index) {
          assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index');
          return this._knots[index];
        };
        _proto.getPoint = function getPoint(t, index) {
          if (index === void 0) {
            index = SPLINE_WHOLE_INDEX;
          }
          t = clamp$1(t, 0.0, 1.0);
          var segments = this.getSegments();
          if (segments === 0) {
            return new Vec3(0.0, 0.0, 0.0);
          }
          if (index === SPLINE_WHOLE_INDEX) {
            var deltaT = 1.0 / segments;
            index = Math.floor(t / deltaT);
            t = t % deltaT / deltaT;
          }
          if (index >= segments) {
            return new Vec3(this._knots[this._knots.length - 1]);
          }
          switch (this._mode) {
            case SplineMode.LINEAR:
              return Spline.calcLinear(this._knots[index], this._knots[index + 1], t);
            case SplineMode.BEZIER:
              return Spline.calcBezier(this._knots[index * 4], this._knots[index * 4 + 1], this._knots[index * 4 + 2], this._knots[index * 4 + 3], t);
            case SplineMode.CATMULL_ROM:
              {
                var v0 = index > 0 ? this._knots[index - 1] : this._knots[index];
                var v3 = index + 2 < this._knots.length ? this._knots[index + 2] : this._knots[index + 1];
                return Spline.calcCatmullRom(v0, this._knots[index], this._knots[index + 1], v3, t);
              }
            default:
              return new Vec3(0.0, 0.0, 0.0);
          }
        };
        _proto.getPoints = function getPoints(num, index) {
          if (index === void 0) {
            index = SPLINE_WHOLE_INDEX;
          }
          if (num === 0) {
            return [];
          }
          if (num === 1) {
            var point = this.getPoint(0.0, index);
            return [point];
          }
          var points = [];
          var deltaT = 1.0 / (num - 1.0);
          for (var i = 0; i < num; i++) {
            var t = i * deltaT;
            var _point = this.getPoint(t, index);
            points.push(_point);
          }
          return points;
        };
        _proto.getSegments = function getSegments() {
          var count = this._knots.length;
          switch (this._mode) {
            case SplineMode.LINEAR:
            case SplineMode.CATMULL_ROM:
              if (count < 2) {
                warnID(14300);
                return 0;
              }
              return count - 1;
            case SplineMode.BEZIER:
              if (count < 4 || count % 4 != 0) {
                warnID(14301);
                return 0;
              }
              return count / 4;
            default:
              assertIsTrue(false, 'Spline error: invalid mode');
          }
        };
        Spline.calcLinear = function calcLinear(v0, v1, t) {
          var result = new Vec3();
          Vec3.multiplyScalar(_v0, v0, 1.0 - t);
          Vec3.multiplyScalar(_v1$1, v1, t);
          Vec3.add(result, _v0, _v1$1);
          return result;
        };
        Spline.calcBezier = function calcBezier(v0, v1, v2, v3, t) {
          var result = new Vec3();
          var s = 1.0 - t;
          Vec3.multiplyScalar(_v0, v0, s * s * s);
          Vec3.multiplyScalar(_v1$1, v1, 3.0 * t * s * s);
          Vec3.multiplyScalar(_v2$1, v2, 3.0 * t * t * s);
          Vec3.multiplyScalar(_v3$4, v3, t * t * t);
          Vec3.add(_v0, _v0, _v1$1);
          Vec3.add(_v2$1, _v2$1, _v3$4);
          Vec3.add(result, _v0, _v2$1);
          return result;
        };
        Spline.calcCatmullRom = function calcCatmullRom(v0, v1, v2, v3, t) {
          var result = new Vec3();
          var t2 = t * t;
          var t3 = t2 * t;
          Vec3.multiplyScalar(_v0, v0, -0.5 * t3 + t2 - 0.5 * t);
          Vec3.multiplyScalar(_v1$1, v1, 1.5 * t3 - 2.5 * t2 + 1.0);
          Vec3.multiplyScalar(_v2$1, v2, -1.5 * t3 + 2.0 * t2 + 0.5 * t);
          Vec3.multiplyScalar(_v3$4, v3, 0.5 * t3 - 0.5 * t2);
          Vec3.add(_v0, _v0, _v1$1);
          Vec3.add(_v2$1, _v2$1, _v3$4);
          Vec3.add(result, _v0, _v2$1);
          return result;
        };
        _createClass(Spline, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "mode",
          get: function get() {
            return this._mode;
          }
        }, {
          key: "knots",
          get: function get() {
            return this._knots;
          }
        }]);
        return Spline;
      }();

      var ERaycastMode;
      (function (ERaycastMode) {
        ERaycastMode[ERaycastMode["ALL"] = 0] = "ALL";
        ERaycastMode[ERaycastMode["CLOSEST"] = 1] = "CLOSEST";
        ERaycastMode[ERaycastMode["ANY"] = 2] = "ANY";
      })(ERaycastMode || (ERaycastMode = {}));

      replaceProperty(intersect, 'intersect', [{
        name: 'ray_aabb',
        newName: 'rayAABB'
      }, {
        name: 'ray_plane',
        newName: 'rayPlane'
      }, {
        name: 'ray_triangle',
        newName: 'rayTriangle'
      }, {
        name: 'ray_sphere',
        newName: 'raySphere'
      }, {
        name: 'ray_obb',
        newName: 'rayOBB'
      }, {
        name: 'ray_capsule',
        newName: 'rayCapsule'
      }, {
        name: 'ray_subMesh',
        newName: 'raySubMesh'
      }, {
        name: 'ray_mesh',
        newName: 'rayMesh'
      }, {
        name: 'ray_model',
        newName: 'rayModel'
      }, {
        name: 'line_plane',
        newName: 'linePlane'
      }, {
        name: 'line_triangle',
        newName: 'lineTriangle'
      }, {
        name: 'line_aabb',
        newName: 'lineAABB'
      }, {
        name: 'line_obb',
        newName: 'lineOBB'
      }, {
        name: 'line_sphere',
        newName: 'lineSphere'
      }, {
        name: 'aabb_aabb',
        newName: 'aabbWithAABB'
      }, {
        name: 'aabb_obb',
        newName: 'aabbWithOBB'
      }, {
        name: 'aabb_plane',
        newName: 'aabbPlane'
      }, {
        name: 'aabb_frustum',
        newName: 'aabbFrustum'
      }, {
        name: 'aabbFrustum_accurate',
        newName: 'aabbFrustumAccurate'
      }, {
        name: 'obb_point',
        newName: 'obbPoint'
      }, {
        name: 'obb_plane',
        newName: 'obbPlane'
      }, {
        name: 'obb_frustum',
        newName: 'obbFrustum'
      }, {
        name: 'obbFrustum_accurate',
        newName: 'obbFrustumAccurate'
      }, {
        name: 'obb_obb',
        newName: 'obbWithOBB'
      }, {
        name: 'obb_capsule',
        newName: 'obbCapsule'
      }, {
        name: 'sphere_plane',
        newName: 'spherePlane'
      }, {
        name: 'sphere_frustum',
        newName: 'sphereFrustum'
      }, {
        name: 'sphereFrustum_accurate',
        newName: 'sphereFrustumAccurate'
      }, {
        name: 'sphere_sphere',
        newName: 'sphereWithSphere'
      }, {
        name: 'sphere_aabb',
        newName: 'sphereAABB'
      }, {
        name: 'sphere_obb',
        newName: 'sphereOBB'
      }, {
        name: 'sphere_capsule',
        newName: 'sphereCapsule'
      }, {
        name: 'capsule_capsule',
        newName: 'capsuleWithCapsule'
      }]);
      function deprecatedClassMessage(oldClassName, newClassName) {
        console.warn(oldClassName + " is deprecated, please use " + newClassName + " instead.");
      }
      var line = function (_Line) {
        _inheritsLoose(line, _Line);
        function line() {
          var _this;
          _this = _Line.call(this) || this;
          deprecatedClassMessage('line', 'Line');
          return _this;
        }
        return line;
      }(Line$1);
      var plane$1 = function (_Plane) {
        _inheritsLoose(plane, _Plane);
        function plane() {
          var _this2;
          _this2 = _Plane.call(this) || this;
          deprecatedClassMessage('plane', 'Plane');
          return _this2;
        }
        return plane;
      }(Plane);
      var ray = function (_Ray) {
        _inheritsLoose(ray, _Ray);
        function ray() {
          var _this3;
          _this3 = _Ray.call(this) || this;
          deprecatedClassMessage('ray', 'Ray');
          return _this3;
        }
        return ray;
      }(Ray);
      var triangle = function (_Triangle) {
        _inheritsLoose(triangle, _Triangle);
        function triangle() {
          var _this4;
          _this4 = _Triangle.call(this) || this;
          deprecatedClassMessage('triangle', 'Triangle');
          return _this4;
        }
        return triangle;
      }(Triangle$1);
      var sphere$1 = function (_Sphere) {
        _inheritsLoose(sphere, _Sphere);
        function sphere() {
          var _this5;
          _this5 = _Sphere.call(this) || this;
          deprecatedClassMessage('sphere', 'Sphere');
          return _this5;
        }
        return sphere;
      }(Sphere);
      var aabb = function (_AABB) {
        _inheritsLoose(aabb, _AABB);
        function aabb() {
          var _this6;
          _this6 = _AABB.call(this) || this;
          deprecatedClassMessage('aabb', 'AABB');
          return _this6;
        }
        return aabb;
      }(AABB);
      var obb = function (_OBB) {
        _inheritsLoose(obb, _OBB);
        function obb() {
          var _this7;
          _this7 = _OBB.call(this) || this;
          deprecatedClassMessage('obb', 'OBB');
          return _this7;
        }
        return obb;
      }(OBB);
      var capsule$1 = function (_Capsule) {
        _inheritsLoose(capsule, _Capsule);
        function capsule() {
          var _this8;
          _this8 = _Capsule.call(this) || this;
          deprecatedClassMessage('capsule', 'Capsule');
          return _this8;
        }
        return capsule;
      }(Capsule);
      var frustum = function (_Frustum) {
        _inheritsLoose(frustum, _Frustum);
        function frustum() {
          var _this9;
          _this9 = _Frustum.call(this) || this;
          deprecatedClassMessage('frustum', 'Frustum');
          return _this9;
        }
        return frustum;
      }(Frustum);

      var geometry = /*#__PURE__*/Object.freeze({
        __proto__: null,
        distance: distance,
        enums: enums,
        intersect: intersect,
        Line: Line$1,
        Plane: Plane,
        Ray: Ray,
        Triangle: Triangle$1,
        Sphere: Sphere,
        AABB: AABB,
        OBB: OBB,
        Capsule: Capsule,
        Frustum: Frustum,
        Keyframe: Keyframe,
        AnimationCurve: AnimationCurve,
        get WrapModeMask () { return WrapModeMask; },
        get SplineMode () { return SplineMode; },
        Spline: Spline,
        constructLegacyCurveAndConvert: constructLegacyCurveAndConvert,
        OptimizedKey: OptimizedKey,
        evalOptCurve: evalOptCurve,
        get ERaycastMode () { return ERaycastMode; },
        line: line,
        plane: plane$1,
        ray: ray,
        triangle: triangle,
        sphere: sphere$1,
        aabb: aabb,
        obb: obb,
        capsule: capsule$1,
        frustum: frustum
      });
      exports('aK', geometry);

      var ScalableContainer = function () {
        function ScalableContainer() {
          this._poolHandle = -1;
          scalableContainerManager.addContainer(this);
        }
        var _proto = ScalableContainer.prototype;
        _proto.destroy = function destroy() {
          scalableContainerManager.removeContainer(this);
        };
        return ScalableContainer;
      }();
      var ScalableContainerManager = function () {
        function ScalableContainerManager() {
          this._pools = [];
          this._lastShrinkPassed = 0;
          this.shrinkTimeSpan = 5;
        }
        var _proto2 = ScalableContainerManager.prototype;
        _proto2.addContainer = function addContainer(pool) {
          if (pool._poolHandle !== -1) return;
          pool._poolHandle = this._pools.length;
          this._pools.push(pool);
        };
        _proto2.removeContainer = function removeContainer(pool) {
          if (pool._poolHandle === -1) return;
          this._pools[this._pools.length - 1]._poolHandle = pool._poolHandle;
          fastRemoveAt$2(this._pools, pool._poolHandle);
          pool._poolHandle = -1;
        };
        _proto2.tryShrink = function tryShrink() {
          for (var i = 0; i < this._pools.length; i++) {
            this._pools[i].tryShrink();
          }
        };
        _proto2.update = function update(dt) {
          this._lastShrinkPassed += dt;
          if (this._lastShrinkPassed > this.shrinkTimeSpan) {
            this.tryShrink();
            this._lastShrinkPassed -= this.shrinkTimeSpan;
          }
        };
        return ScalableContainerManager;
      }();
      var scalableContainerManager = new ScalableContainerManager();

      var Pool = exports('bx', function (_ScalableContainer) {
        _inheritsLoose(Pool, _ScalableContainer);
        function Pool(ctor, elementsPerBatch, dtor) {
          var _this;
          _this = _ScalableContainer.call(this) || this;
          _this._ctor = void 0;
          _this._elementsPerBatch = void 0;
          _this._nextAvail = void 0;
          _this._freePool = [];
          _this._dtor = void 0;
          _this._ctor = ctor;
          _this._dtor = dtor || null;
          _this._elementsPerBatch = Math.max(elementsPerBatch, 1);
          _this._nextAvail = _this._elementsPerBatch - 1;
          for (var i = 0; i < _this._elementsPerBatch; ++i) {
            _this._freePool.push(ctor());
          }
          return _this;
        }
        var _proto = Pool.prototype;
        _proto.alloc = function alloc() {
          if (this._nextAvail < 0) {
            this._freePool.length = this._elementsPerBatch;
            for (var i = 0; i < this._elementsPerBatch; i++) {
              this._freePool[i] = this._ctor();
            }
            this._nextAvail = this._elementsPerBatch - 1;
          }
          return this._freePool[this._nextAvail--];
        };
        _proto.free = function free(obj) {
          this._freePool[++this._nextAvail] = obj;
        };
        _proto.freeArray = function freeArray(objs) {
          this._freePool.length = this._nextAvail + 1;
          Array.prototype.push.apply(this._freePool, objs);
          this._nextAvail += objs.length;
        };
        _proto.tryShrink = function tryShrink() {
          if (this._nextAvail >> 1 > this._elementsPerBatch) {
            if (this._dtor) {
              for (var i = this._nextAvail >> 1; i <= this._nextAvail; i++) {
                this._dtor(this._freePool[i]);
              }
            }
            this._freePool.length = this._nextAvail >> 1;
            this._nextAvail = this._freePool.length - 1;
          }
        };
        _proto.destroy = function destroy() {
          var dtor = arguments.length > 0 ? arguments[0] : null;
          if (dtor) {
            warnID(14100);
          }
          var readDtor = dtor || this._dtor;
          if (readDtor) {
            for (var i = 0; i <= this._nextAvail; i++) {
              readDtor(this._freePool[i]);
            }
          }
          this._freePool.length = 0;
          this._nextAvail = -1;
          _ScalableContainer.prototype.destroy.call(this);
        };
        return Pool;
      }(ScalableContainer));

      var RecyclePool = exports('by', function (_ScalableContainer) {
        _inheritsLoose(RecyclePool, _ScalableContainer);
        function RecyclePool(fn, size, dtor) {
          var _this;
          _this = _ScalableContainer.call(this) || this;
          _this._fn = void 0;
          _this._dtor = null;
          _this._count = 0;
          _this._data = void 0;
          _this._initSize = 0;
          _this._fn = fn;
          _this._dtor = dtor || null;
          _this._data = new Array(size);
          _this._initSize = size;
          for (var i = 0; i < size; ++i) {
            _this._data[i] = fn();
          }
          return _this;
        }
        var _proto = RecyclePool.prototype;
        _proto.reset = function reset() {
          this._count = 0;
        };
        _proto.resize = function resize(size) {
          if (size > this._data.length) {
            for (var i = this._data.length; i < size; ++i) {
              this._data[i] = this._fn();
            }
          }
        };
        _proto.add = function add() {
          if (this._count >= this._data.length) {
            this.resize(this._data.length << 1);
          }
          return this._data[this._count++];
        };
        _proto.destroy = function destroy() {
          if (this._dtor) {
            for (var i = 0; i < this._data.length; i++) {
              this._dtor(this._data[i]);
            }
          }
          this._data.length = 0;
          this._count = 0;
          _ScalableContainer.prototype.destroy.call(this);
        };
        _proto.tryShrink = function tryShrink() {
          if (this._data.length >> 2 > this._count) {
            var length = Math.max(this._initSize, this._data.length >> 1);
            if (this._dtor) {
              for (var i = length; i < this._data.length; i++) {
                this._dtor(this._data[i]);
              }
            }
            this._data.length = length;
          }
        };
        _proto.removeAt = function removeAt(idx) {
          if (idx >= this._count) {
            return;
          }
          var last = this._count - 1;
          var tmp = this._data[idx];
          this._data[idx] = this._data[last];
          this._data[last] = tmp;
          this._count -= 1;
        };
        _createClass(RecyclePool, [{
          key: "length",
          get: function get() {
            return this._count;
          }
        }, {
          key: "data",
          get: function get() {
            return this._data;
          }
        }]);
        return RecyclePool;
      }(ScalableContainer));

      var CachedArray = exports('bz', function (_ScalableContainer) {
        _inheritsLoose(CachedArray, _ScalableContainer);
        function CachedArray(length, compareFn) {
          var _this;
          _this = _ScalableContainer.call(this) || this;
          _this.array = void 0;
          _this.length = 0;
          _this._compareFn = void 0;
          _this._initSize = 0;
          _this.array = new Array(length);
          _this._initSize = length;
          _this.length = 0;
          _this._compareFn = compareFn;
          return _this;
        }
        var _proto = CachedArray.prototype;
        _proto.push = function push(item) {
          this.array[this.length++] = item;
        };
        _proto.pop = function pop() {
          return this.array[--this.length];
        };
        _proto.get = function get(idx) {
          return this.array[idx];
        };
        _proto.clear = function clear() {
          this.length = 0;
        };
        _proto.destroy = function destroy() {
          this.length = 0;
          this.array.length = 0;
          _ScalableContainer.prototype.destroy.call(this);
        };
        _proto.tryShrink = function tryShrink() {
          if (this.array.length >> 2 > this.length) {
            this.array.length = Math.max(this._initSize, this.array.length >> 1);
          }
        };
        _proto.sort = function sort() {
          this.array.length = this.length;
          this.array.sort(this._compareFn);
        };
        _proto.concat = function concat(array) {
          for (var i = 0; i < array.length; ++i) {
            this.array[this.length++] = array[i];
          }
        };
        _proto.fastRemove = function fastRemove(idx) {
          if (idx >= this.length || idx < 0) {
            return;
          }
          var last = --this.length;
          this.array[idx] = this.array[last];
        };
        _proto.indexOf = function indexOf(val) {
          for (var i = 0, len = this.length; i < len; ++i) {
            if (this.array[i] === val) {
              return i;
            }
          }
          return -1;
        };
        return CachedArray;
      }(ScalableContainer));

      var index$4 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        Pool: Pool,
        RecyclePool: RecyclePool,
        CachedArray: CachedArray
      });
      exports('aJ', index$4);

      var System = exports('cA', function () {
        function System() {
          this._id = '';
          this._priority = 0;
          this._executeInEditMode = false;
        }
        System.sortByPriority = function sortByPriority(a, b) {
          if (a._priority < b._priority) {
            return 1;
          } else if (a._priority > b.priority) {
            return -1;
          } else {
            return 0;
          }
        };
        var _proto = System.prototype;
        _proto.init = function init() {};
        _proto.update = function update(dt) {};
        _proto.postUpdate = function postUpdate(dt) {};
        _proto.destroy = function destroy() {};
        _createClass(System, [{
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(value) {
            this._priority = value;
          }
        }, {
          key: "id",
          get: function get() {
            return this._id;
          },
          set: function set(id) {
            this._id = id;
          }
        }]);
        return System;
      }());
      System.Priority = Enum({
        LOW: 0,
        MEDIUM: 100,
        HIGH: 200,
        SCHEDULER: 1 << 31 >>> 0
      });

      var MAX_POOL_SIZE$1 = 20;
      var idGenerator$3 = new IDGenerator('Scheduler');
      var ListEntry = function () {
        ListEntry.get = function get(target, priority, paused, markedForDeletion) {
          var result = ListEntry._listEntries.pop();
          if (result) {
            result.target = target;
            result.priority = priority;
            result.paused = paused;
            result.markedForDeletion = markedForDeletion;
          } else {
            result = new ListEntry(target, priority, paused, markedForDeletion);
          }
          return result;
        };
        ListEntry.put = function put(entry) {
          if (ListEntry._listEntries.length < MAX_POOL_SIZE$1) {
            entry.target = null;
            ListEntry._listEntries.push(entry);
          }
        };
        function ListEntry(target, priority, paused, markedForDeletion) {
          this.target = void 0;
          this.priority = void 0;
          this.paused = void 0;
          this.markedForDeletion = void 0;
          this.target = target;
          this.priority = priority;
          this.paused = paused;
          this.markedForDeletion = markedForDeletion;
        }
        return ListEntry;
      }();
      ListEntry._listEntries = [];
      var HashUpdateEntry = function () {
        HashUpdateEntry.get = function get(list, entry, target, callback) {
          var result = HashUpdateEntry._hashUpdateEntries.pop();
          if (result) {
            result.list = list;
            result.entry = entry;
            result.target = target;
            result.callback = callback;
          } else {
            result = new HashUpdateEntry(list, entry, target, callback);
          }
          return result;
        };
        HashUpdateEntry.put = function put(entry) {
          if (HashUpdateEntry._hashUpdateEntries.length < MAX_POOL_SIZE$1) {
            entry.list = entry.entry = entry.target = entry.callback = null;
            HashUpdateEntry._hashUpdateEntries.push(entry);
          }
        };
        function HashUpdateEntry(list, entry, target, callback) {
          this.list = void 0;
          this.entry = void 0;
          this.target = void 0;
          this.callback = void 0;
          this.list = list;
          this.entry = entry;
          this.target = target;
          this.callback = callback;
        }
        return HashUpdateEntry;
      }();
      HashUpdateEntry._hashUpdateEntries = [];
      var HashTimerEntry = function () {
        HashTimerEntry.get = function get(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) {
          var result = HashTimerEntry._hashTimerEntries.pop();
          if (result) {
            result.timers = timers;
            result.target = target;
            result.timerIndex = timerIndex;
            result.currentTimer = currentTimer;
            result.currentTimerSalvaged = currentTimerSalvaged;
            result.paused = paused;
          } else {
            result = new HashTimerEntry(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused);
          }
          return result;
        };
        HashTimerEntry.put = function put(entry) {
          if (HashTimerEntry._hashTimerEntries.length < MAX_POOL_SIZE$1) {
            entry.timers = entry.target = entry.currentTimer = null;
            HashTimerEntry._hashTimerEntries.push(entry);
          }
        };
        function HashTimerEntry(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) {
          this.timers = void 0;
          this.target = void 0;
          this.timerIndex = void 0;
          this.currentTimer = void 0;
          this.currentTimerSalvaged = void 0;
          this.paused = void 0;
          this.timers = timers;
          this.target = target;
          this.timerIndex = timerIndex;
          this.currentTimer = currentTimer;
          this.currentTimerSalvaged = currentTimerSalvaged;
          this.paused = paused;
        }
        return HashTimerEntry;
      }();
      HashTimerEntry._hashTimerEntries = [];
      var CallbackTimer = function () {
        CallbackTimer.get = function get() {
          return CallbackTimer._timers.pop() || new CallbackTimer();
        };
        CallbackTimer.put = function put(timer) {
          if (CallbackTimer._timers.length < MAX_POOL_SIZE$1 && !timer._lock) {
            timer._scheduler = timer._target = timer._callback = null;
            CallbackTimer._timers.push(timer);
          }
        };
        function CallbackTimer() {
          this._lock = void 0;
          this._scheduler = void 0;
          this._elapsed = void 0;
          this._runForever = void 0;
          this._useDelay = void 0;
          this._timesExecuted = void 0;
          this._repeat = void 0;
          this._delay = void 0;
          this._interval = void 0;
          this._target = void 0;
          this._callback = void 0;
          this._lock = false;
          this._scheduler = null;
          this._elapsed = -1;
          this._runForever = false;
          this._useDelay = false;
          this._timesExecuted = 0;
          this._repeat = 0;
          this._delay = 0;
          this._interval = 0;
          this._target = null;
        }
        var _proto = CallbackTimer.prototype;
        _proto.initWithCallback = function initWithCallback(scheduler, callback, target, seconds, repeat, delay) {
          this._lock = false;
          this._scheduler = scheduler;
          this._target = target;
          this._callback = callback;
          this._timesExecuted = 0;
          this._elapsed = -1;
          this._interval = seconds;
          this._delay = delay;
          this._useDelay = this._delay > 0;
          this._repeat = repeat;
          this._runForever = this._repeat === legacyCC.macro.REPEAT_FOREVER;
          return true;
        };
        _proto.getInterval = function getInterval() {
          return this._interval;
        };
        _proto.setInterval = function setInterval(interval) {
          this._interval = interval;
        };
        _proto.update = function update(dt) {
          if (this._elapsed === -1) {
            this._elapsed = 0;
            this._timesExecuted = 0;
          } else {
            this._elapsed += dt;
            if (this._runForever && !this._useDelay) {
              if (this._elapsed >= this._interval) {
                this.trigger();
                this._elapsed = 0;
              }
            } else {
              if (this._useDelay) {
                if (this._elapsed >= this._delay) {
                  this.trigger();
                  this._elapsed -= this._delay;
                  this._timesExecuted += 1;
                  this._useDelay = false;
                }
              } else if (this._elapsed >= this._interval) {
                this.trigger();
                this._elapsed = 0;
                this._timesExecuted += 1;
              }
              if (this._callback && !this._runForever && this._timesExecuted > this._repeat) {
                this.cancel();
              }
            }
          }
        };
        _proto.getCallback = function getCallback() {
          return this._callback;
        };
        _proto.trigger = function trigger() {
          if (this._target && this._callback) {
            this._lock = true;
            this._callback.call(this._target, this._elapsed);
            this._lock = false;
          }
        };
        _proto.cancel = function cancel() {
          if (this._scheduler && this._callback && this._target) {
            this._scheduler.unscheduleForTimer(this, this._target);
          }
        };
        return CallbackTimer;
      }();
      CallbackTimer._timers = [];
      var Scheduler = exports('cn', function (_System) {
        _inheritsLoose(Scheduler, _System);
        Scheduler.enableForTarget = function enableForTarget(target) {
          var found = false;
          if (target.uuid) {
            found = true;
          } else if (target.id) {
            found = true;
          }
          if (!found) {
            target.id = idGenerator$3.getNewId();
          }
        };
        function Scheduler() {
          var _this;
          _this = _System.call(this) || this;
          _this._timeScale = void 0;
          _this._updatesNegList = void 0;
          _this._updates0List = void 0;
          _this._updatesPosList = void 0;
          _this._hashForUpdates = void 0;
          _this._hashForTimers = void 0;
          _this._currentTarget = void 0;
          _this._currentTargetSalvaged = void 0;
          _this._updateHashLocked = void 0;
          _this._arrayForTimers = void 0;
          _this._timeScale = 1.0;
          _this._updatesNegList = [];
          _this._updates0List = [];
          _this._updatesPosList = [];
          _this._hashForUpdates = createMap(true);
          _this._hashForTimers = createMap(true);
          _this._currentTarget = null;
          _this._currentTargetSalvaged = false;
          _this._updateHashLocked = false;
          _this._arrayForTimers = [];
          return _this;
        }
        var _proto2 = Scheduler.prototype;
        _proto2.setTimeScale = function setTimeScale(timeScale) {
          this._timeScale = timeScale;
        };
        _proto2.getTimeScale = function getTimeScale() {
          return this._timeScale;
        };
        _proto2.update = function update(dt) {
          this._updateHashLocked = true;
          if (this._timeScale !== 1) {
            dt *= this._timeScale;
          }
          var i;
          var list;
          var len;
          var entry;
          for (i = 0, list = this._updatesNegList, len = list.length; i < len; i++) {
            entry = list[i];
            if (!entry.paused && !entry.markedForDeletion && entry.target) {
              var _entry$target$update, _entry$target;
              (_entry$target$update = (_entry$target = entry.target).update) === null || _entry$target$update === void 0 ? void 0 : _entry$target$update.call(_entry$target, dt);
            }
          }
          for (i = 0, list = this._updates0List, len = list.length; i < len; i++) {
            entry = list[i];
            if (!entry.paused && !entry.markedForDeletion && entry.target) {
              var _entry$target$update2, _entry$target2;
              (_entry$target$update2 = (_entry$target2 = entry.target).update) === null || _entry$target$update2 === void 0 ? void 0 : _entry$target$update2.call(_entry$target2, dt);
            }
          }
          for (i = 0, list = this._updatesPosList, len = list.length; i < len; i++) {
            entry = list[i];
            if (!entry.paused && !entry.markedForDeletion && entry.target) {
              var _entry$target$update3, _entry$target3;
              (_entry$target$update3 = (_entry$target3 = entry.target).update) === null || _entry$target$update3 === void 0 ? void 0 : _entry$target$update3.call(_entry$target3, dt);
            }
          }
          var elt;
          var arr = this._arrayForTimers;
          for (i = 0; i < arr.length; i++) {
            var _this$_currentTarget$;
            elt = arr[i];
            this._currentTarget = elt;
            this._currentTargetSalvaged = false;
            if (!elt.paused && elt.timers) {
              for (elt.timerIndex = 0; elt.timerIndex < elt.timers.length; ++elt.timerIndex) {
                elt.currentTimer = elt.timers[elt.timerIndex];
                elt.currentTimerSalvaged = false;
                elt.currentTimer.update(dt);
                elt.currentTimer = null;
              }
            }
            if (this._currentTargetSalvaged && ((_this$_currentTarget$ = this._currentTarget.timers) === null || _this$_currentTarget$ === void 0 ? void 0 : _this$_currentTarget$.length) === 0) {
              this._removeHashElement(this._currentTarget);
              --i;
            }
          }
          for (i = 0, list = this._updatesNegList; i < list.length;) {
            entry = list[i];
            if (entry.markedForDeletion) {
              this._removeUpdateFromHash(entry);
            } else {
              i++;
            }
          }
          for (i = 0, list = this._updates0List; i < list.length;) {
            entry = list[i];
            if (entry.markedForDeletion) {
              this._removeUpdateFromHash(entry);
            } else {
              i++;
            }
          }
          for (i = 0, list = this._updatesPosList; i < list.length;) {
            entry = list[i];
            if (entry.markedForDeletion) {
              this._removeUpdateFromHash(entry);
            } else {
              i++;
            }
          }
          this._updateHashLocked = false;
          this._currentTarget = null;
        };
        _proto2.schedule = function schedule(callbackTmp, targetTmp, interval, repeat, delay, paused) {
          var _repeat, _delay;
          var callback;
          var target;
          if (typeof callbackTmp !== 'function') {
            warnID(1514);
            callback = targetTmp;
            target = callbackTmp;
          } else {
            callback = callbackTmp;
            target = targetTmp;
          }
          if (arguments.length === 3 || arguments.length === 4 || arguments.length === 5) {
            paused = !!repeat;
            repeat = legacyCC.macro.REPEAT_FOREVER;
            delay = 0;
          }
          assertID(Boolean(target), 1502);
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForTimers[targetId];
          if (!element) {
            element = HashTimerEntry.get(null, target, 0, null, false, Boolean(paused));
            this._arrayForTimers.push(element);
            this._hashForTimers[targetId] = element;
          } else if (element.paused !== paused) {
            warnID(1511);
          }
          var timer;
          var i;
          if (element.timers == null) {
            element.timers = [];
          } else {
            for (i = 0; i < element.timers.length; ++i) {
              timer = element.timers[i];
              if (timer && callback === timer.getCallback()) {
                logID(1507, timer.getInterval(), interval);
                timer.setInterval(interval);
                return;
              }
            }
          }
          timer = CallbackTimer.get();
          timer.initWithCallback(this, callback, target, interval, (_repeat = repeat) !== null && _repeat !== void 0 ? _repeat : 0, (_delay = delay) !== null && _delay !== void 0 ? _delay : 0);
          element.timers.push(timer);
          if (this._currentTarget === element && this._currentTargetSalvaged) {
            this._currentTargetSalvaged = false;
          }
        };
        _proto2.scheduleUpdate = function scheduleUpdate(target, priority, paused) {
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var hashElement = this._hashForUpdates[targetId];
          if (hashElement && hashElement.entry) {
            if (hashElement.entry.priority !== priority) {
              if (this._updateHashLocked) {
                logID(1506);
                hashElement.entry.markedForDeletion = false;
                hashElement.entry.paused = paused;
                return;
              } else {
                this.unscheduleUpdate(target);
              }
            } else {
              hashElement.entry.markedForDeletion = false;
              hashElement.entry.paused = paused;
              return;
            }
          }
          var listElement = ListEntry.get(target, priority, paused, false);
          var ppList;
          if (priority === 0) {
            ppList = this._updates0List;
            this._appendIn(ppList, listElement);
          } else {
            ppList = priority < 0 ? this._updatesNegList : this._updatesPosList;
            this._priorityIn(ppList, listElement, priority);
          }
          this._hashForUpdates[targetId] = HashUpdateEntry.get(ppList, listElement, target, null);
        };
        _proto2.unschedule = function unschedule(callback, target) {
          if (!target || !callback) {
            return;
          }
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForTimers[targetId];
          if (element) {
            var timers = element.timers;
            if (!timers) {
              return;
            }
            for (var i = 0, li = timers.length; i < li; i++) {
              var timer = timers[i];
              if (callback === timer.getCallback()) {
                if (timer === element.currentTimer && !element.currentTimerSalvaged) {
                  element.currentTimerSalvaged = true;
                }
                timers.splice(i, 1);
                CallbackTimer.put(timer);
                if (element.timerIndex >= i) {
                  element.timerIndex--;
                }
                if (timers.length === 0) {
                  if (this._currentTarget === element) {
                    this._currentTargetSalvaged = true;
                  } else {
                    this._removeHashElement(element);
                  }
                }
                return;
              }
            }
          }
        };
        _proto2.unscheduleForTimer = function unscheduleForTimer(timerToUnschedule, target) {
          var targetId = target.uuid || target.id;
          var element = this._hashForTimers[targetId];
          var timers = element.timers;
          if (!timers) {
            return;
          }
          for (var i = 0, li = timers.length; i < li; i++) {
            var timer = timers[i];
            if (timer === timerToUnschedule) {
              timers.splice(i, 1);
              if (timers.length === 0) {
                this._currentTargetSalvaged = true;
              }
              return;
            }
          }
        };
        _proto2.unscheduleUpdate = function unscheduleUpdate(target) {
          if (!target) {
            return;
          }
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForUpdates[targetId];
          if (element !== null && element !== void 0 && element.entry) {
            if (this._updateHashLocked) {
              element.entry.markedForDeletion = true;
            } else {
              this._removeUpdateFromHash(element.entry);
            }
          }
        };
        _proto2.unscheduleAllForTarget = function unscheduleAllForTarget(target) {
          if (!target) {
            return;
          }
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForTimers[targetId];
          if (element !== null && element !== void 0 && element.timers) {
            var timers = element.timers;
            if (element.currentTimer && timers.indexOf(element.currentTimer) > -1 && !element.currentTimerSalvaged) {
              element.currentTimerSalvaged = true;
            }
            for (var i = 0, l = timers.length; i < l; i++) {
              CallbackTimer.put(timers[i]);
            }
            timers.length = 0;
            if (this._currentTarget === element) {
              this._currentTargetSalvaged = true;
            } else {
              this._removeHashElement(element);
            }
          }
          this.unscheduleUpdate(target);
        };
        _proto2.unscheduleAll = function unscheduleAll() {
          this.unscheduleAllWithMinPriority(System.Priority.SCHEDULER);
        };
        _proto2.unscheduleAllWithMinPriority = function unscheduleAllWithMinPriority(minPriority) {
          var i;
          var element;
          var arr = this._arrayForTimers;
          for (i = arr.length - 1; i >= 0; i--) {
            element = arr[i];
            if (element.target) {
              this.unscheduleAllForTarget(element.target);
            }
          }
          var entry;
          var temp_length = 0;
          if (minPriority < 0) {
            for (i = 0; i < this._updatesNegList.length;) {
              var _entry;
              temp_length = this._updatesNegList.length;
              entry = this._updatesNegList[i];
              if ((_entry = entry) !== null && _entry !== void 0 && _entry.target && entry.priority >= minPriority) {
                this.unscheduleUpdate(entry.target);
              }
              if (temp_length === this._updatesNegList.length) {
                i++;
              }
            }
          }
          if (minPriority <= 0) {
            for (i = 0; i < this._updates0List.length;) {
              var _entry2;
              temp_length = this._updates0List.length;
              entry = this._updates0List[i];
              if ((_entry2 = entry) !== null && _entry2 !== void 0 && _entry2.target) {
                this.unscheduleUpdate(entry.target);
              }
              if (temp_length === this._updates0List.length) {
                i++;
              }
            }
          }
          for (i = 0; i < this._updatesPosList.length;) {
            var _entry3;
            temp_length = this._updatesPosList.length;
            entry = this._updatesPosList[i];
            if ((_entry3 = entry) !== null && _entry3 !== void 0 && _entry3.target && entry.priority >= minPriority) {
              this.unscheduleUpdate(entry.target);
            }
            if (temp_length === this._updatesPosList.length) {
              i++;
            }
          }
        };
        _proto2.isScheduled = function isScheduled(callback, target) {
          assertID(Boolean(callback), 1508);
          assertID(Boolean(target), 1509);
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return false;
          }
          var element = this._hashForTimers[targetId];
          if (!element) {
            return false;
          }
          if (element.timers == null) {
            return false;
          } else {
            var timers = element.timers;
            for (var i = 0; i < timers.length; ++i) {
              var timer = timers[i];
              if (callback === timer.getCallback()) {
                return true;
              }
            }
            return false;
          }
        };
        _proto2.pauseAllTargets = function pauseAllTargets() {
          return this.pauseAllTargetsWithMinPriority(System.Priority.SCHEDULER);
        };
        _proto2.pauseAllTargetsWithMinPriority = function pauseAllTargetsWithMinPriority(minPriority) {
          var idsWithSelectors = [];
          var element;
          var locArrayForTimers = this._arrayForTimers;
          var i;
          var li;
          for (i = 0, li = locArrayForTimers.length; i < li; i++) {
            var _element;
            element = locArrayForTimers[i];
            if ((_element = element) !== null && _element !== void 0 && _element.target) {
              element.paused = true;
              idsWithSelectors.push(element.target);
            }
          }
          var entry;
          if (minPriority < 0) {
            for (i = 0; i < this._updatesNegList.length; i++) {
              var _entry4;
              entry = this._updatesNegList[i];
              if ((_entry4 = entry) !== null && _entry4 !== void 0 && _entry4.target) {
                if (entry.priority >= minPriority) {
                  entry.paused = true;
                  idsWithSelectors.push(entry.target);
                }
              }
            }
          }
          if (minPriority <= 0) {
            for (i = 0; i < this._updates0List.length; i++) {
              var _entry5;
              entry = this._updates0List[i];
              if ((_entry5 = entry) !== null && _entry5 !== void 0 && _entry5.target) {
                entry.paused = true;
                idsWithSelectors.push(entry.target);
              }
            }
          }
          for (i = 0; i < this._updatesPosList.length; i++) {
            var _entry6;
            entry = this._updatesPosList[i];
            if ((_entry6 = entry) !== null && _entry6 !== void 0 && _entry6.target) {
              if (entry.priority >= minPriority) {
                entry.paused = true;
                idsWithSelectors.push(entry.target);
              }
            }
          }
          return idsWithSelectors;
        };
        _proto2.resumeTargets = function resumeTargets(targetsToResume) {
          if (!targetsToResume) {
            return;
          }
          for (var i = 0; i < targetsToResume.length; i++) {
            this.resumeTarget(targetsToResume[i]);
          }
        };
        _proto2.pauseTarget = function pauseTarget(target) {
          assertID(Boolean(target), 1503);
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForTimers[targetId];
          if (element) {
            element.paused = true;
          }
          var elementUpdate = this._hashForUpdates[targetId];
          if (elementUpdate !== null && elementUpdate !== void 0 && elementUpdate.entry) {
            elementUpdate.entry.paused = true;
          }
        };
        _proto2.resumeTarget = function resumeTarget(target) {
          assertID(Boolean(target), 1504);
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForTimers[targetId];
          if (element) {
            element.paused = false;
          }
          var elementUpdate = this._hashForUpdates[targetId];
          if (elementUpdate !== null && elementUpdate !== void 0 && elementUpdate.entry) {
            elementUpdate.entry.paused = false;
          }
        };
        _proto2.isTargetPaused = function isTargetPaused(target) {
          assertID(Boolean(target), 1505);
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return false;
          }
          var element = this._hashForTimers[targetId];
          if (element) {
            return element.paused;
          }
          var elementUpdate = this._hashForUpdates[targetId];
          if (elementUpdate !== null && elementUpdate !== void 0 && elementUpdate.entry) {
            return elementUpdate.entry.paused;
          }
          return false;
        };
        _proto2._removeHashElement = function _removeHashElement(element) {
          if (!element.target) {
            return;
          }
          var targetId = element.target.uuid || element.target.id;
          if (typeof targetId === 'undefined') {
            return;
          }
          delete this._hashForTimers[targetId];
          var arr = this._arrayForTimers;
          for (var i = 0, l = arr.length; i < l; i++) {
            if (arr[i] === element) {
              arr.splice(i, 1);
              break;
            }
          }
          HashTimerEntry.put(element);
        };
        _proto2._removeUpdateFromHash = function _removeUpdateFromHash(entry) {
          if (!entry.target) {
            return;
          }
          var targetId = entry.target.uuid || entry.target.id;
          if (typeof targetId === 'undefined') {
            return;
          }
          var element = this._hashForUpdates[targetId];
          if (element) {
            var list = element.list;
            var listEntry = element.entry;
            if (list) {
              for (var i = 0, l = list.length; i < l; i++) {
                if (list[i] === listEntry) {
                  list.splice(i, 1);
                  break;
                }
              }
            }
            delete this._hashForUpdates[targetId];
            if (listEntry) {
              ListEntry.put(listEntry);
            }
            HashUpdateEntry.put(element);
          }
        };
        _proto2._priorityIn = function _priorityIn(ppList, listElement, priority) {
          for (var i = 0; i < ppList.length; i++) {
            if (priority < ppList[i].priority) {
              ppList.splice(i, 0, listElement);
              return;
            }
          }
          ppList.push(listElement);
        };
        _proto2._appendIn = function _appendIn(ppList, listElement) {
          ppList.push(listElement);
        };
        return Scheduler;
      }(System));
      Scheduler.ID = 'scheduler';
      legacyCC.Scheduler = Scheduler;

      var vmath = {};
      replaceProperty(vmath, 'vmath', [{
        name: 'vec2',
        newName: 'Vec2',
        target: math,
        targetName: 'math'
      }, {
        name: 'vec3',
        newName: 'Vec3',
        target: math,
        targetName: 'math'
      }, {
        name: 'vec4',
        newName: 'Vec4',
        target: math,
        targetName: 'math'
      }, {
        name: 'quat',
        newName: 'Quat',
        target: math,
        targetName: 'math'
      }, {
        name: 'mat3',
        newName: 'Mat3',
        target: math,
        targetName: 'math'
      }, {
        name: 'mat4',
        newName: 'Mat4',
        target: math,
        targetName: 'math'
      }, {
        name: 'color4',
        newName: 'Color',
        target: math,
        targetName: 'math'
      }, {
        name: 'rect',
        newName: 'Rect',
        target: math,
        targetName: 'math'
      }, {
        name: 'approx',
        newName: 'approx',
        target: math,
        targetName: 'math'
      }, {
        name: 'EPSILON',
        newName: 'EPSILON',
        target: math,
        targetName: 'math'
      }, {
        name: 'equals',
        newName: 'equals',
        target: math,
        targetName: 'math'
      }, {
        name: 'clamp',
        newName: 'clamp',
        target: math,
        targetName: 'math'
      }, {
        name: 'clamp01',
        newName: 'clamp01',
        target: math,
        targetName: 'math'
      }, {
        name: 'lerp',
        newName: 'lerp',
        target: math,
        targetName: 'math'
      }, {
        name: 'toRadian',
        newName: 'toRadian',
        target: math,
        targetName: 'math'
      }, {
        name: 'toDegree',
        newName: 'toDegree',
        target: math,
        targetName: 'math'
      }, {
        name: 'random',
        newName: 'random',
        target: math,
        targetName: 'math'
      }, {
        name: 'randomRange',
        newName: 'randomRange',
        target: math,
        targetName: 'math'
      }, {
        name: 'randomRangeInt',
        newName: 'randomRangeInt',
        target: math,
        targetName: 'math'
      }, {
        name: 'pseudoRandom',
        newName: 'pseudoRandom',
        target: math,
        targetName: 'math'
      }, {
        name: 'pseudoRandomRangeInt',
        newName: 'pseudoRandomRangeInt',
        target: math,
        targetName: 'math'
      }, {
        name: 'nextPow2',
        newName: 'nextPow2',
        target: math,
        targetName: 'math'
      }, {
        name: 'repeat',
        newName: 'repeat',
        target: math,
        targetName: 'math'
      }, {
        name: 'pingPong',
        newName: 'pingPong',
        target: math,
        targetName: 'math'
      }, {
        name: 'inverseLerp',
        newName: 'inverseLerp',
        target: math,
        targetName: 'math'
      }]);
      legacyCC.vmath = vmath;
      replaceProperty(Scheduler.prototype, 'Scheduler.prototype', [{
        name: 'enableForTarget',
        newName: 'enableForTarget',
        target: Scheduler,
        targetName: 'Scheduler'
      }]);
      replaceProperty(Scheduler, 'Scheduler', [{
        name: 'PRIORITY_SYSTEM',
        newName: 'System.Priority.SCHEDULER',
        customGetter: function customGetter() {
          return System.Priority.SCHEDULER;
        }
      }]);
      removeProperty(Scheduler, 'Scheduler', [{
        name: 'PRIORITY_NON_SYSTEM',
        suggest: 'Use enum` System.Priority` instead'
      }]);

      deprecateModuleExportedName({
        replaceProperty: {
          since: '3.6.0',
          removed: false
        },
        removeProperty: {
          since: '3.6.0',
          removed: false
        },
        markAsWarning: {
          since: '3.6.0',
          removed: false
        },
        setDefaultLogTimes: {
          since: '3.6.0',
          removed: false
        }
      });

      var fastRemoveAt$1 = fastRemoveAt$2;
      function empty() {}
      var CallbackInfo = function () {
        function CallbackInfo() {
          this.callback = empty;
          this.target = undefined;
          this.once = false;
        }
        var _proto = CallbackInfo.prototype;
        _proto.set = function set(callback, target, once) {
          this.callback = callback || empty;
          this.target = target;
          this.once = !!once;
        };
        _proto.reset = function reset() {
          this.target = undefined;
          this.callback = empty;
          this.once = false;
        };
        _proto.check = function check() {
          if (isCCObject(this.target) && !isValid(this.target, true)) {
            return false;
          } else {
            return true;
          }
        };
        return CallbackInfo;
      }();
      var callbackInfoPool = new Pool(function () {
        return new CallbackInfo();
      }, 32);
      var CallbackList = function () {
        function CallbackList() {
          this.callbackInfos = [];
          this.isInvoking = false;
          this.containCanceled = false;
        }
        var _proto2 = CallbackList.prototype;
        _proto2.removeByCallback = function removeByCallback(cb) {
          for (var i = 0; i < this.callbackInfos.length; ++i) {
            var info = this.callbackInfos[i];
            if (info && info.callback === cb) {
              info.reset();
              callbackInfoPool.free(info);
              fastRemoveAt$1(this.callbackInfos, i);
              --i;
            }
          }
        };
        _proto2.removeByTarget = function removeByTarget(target) {
          for (var i = 0; i < this.callbackInfos.length; ++i) {
            var info = this.callbackInfos[i];
            if (info && info.target === target) {
              info.reset();
              callbackInfoPool.free(info);
              fastRemoveAt$1(this.callbackInfos, i);
              --i;
            }
          }
        };
        _proto2.cancel = function cancel(index) {
          var info = this.callbackInfos[index];
          if (info) {
            info.reset();
            if (this.isInvoking) {
              this.callbackInfos[index] = null;
            } else {
              fastRemoveAt$1(this.callbackInfos, index);
            }
            callbackInfoPool.free(info);
          }
          this.containCanceled = true;
        };
        _proto2.cancelAll = function cancelAll() {
          for (var i = 0; i < this.callbackInfos.length; i++) {
            var info = this.callbackInfos[i];
            if (info) {
              info.reset();
              callbackInfoPool.free(info);
              this.callbackInfos[i] = null;
            }
          }
          this.containCanceled = true;
        };
        _proto2.purgeCanceled = function purgeCanceled() {
          for (var i = this.callbackInfos.length - 1; i >= 0; --i) {
            var info = this.callbackInfos[i];
            if (!info) {
              fastRemoveAt$1(this.callbackInfos, i);
            }
          }
          this.containCanceled = false;
        };
        _proto2.clear = function clear() {
          this.cancelAll();
          this.callbackInfos.length = 0;
          this.isInvoking = false;
          this.containCanceled = false;
        };
        return CallbackList;
      }();
      var MAX_SIZE$1 = 16;
      var callbackListPool = new Pool(function () {
        return new CallbackList();
      }, MAX_SIZE$1);
      var CallbacksInvoker = exports('d0', function () {
        function CallbacksInvoker() {
          this._callbackTable = createMap(true);
          this._offCallback = void 0;
        }
        var _proto3 = CallbacksInvoker.prototype;
        _proto3.on = function on(key, callback, target, once) {
          if (!this.hasEventListener(key, callback, target)) {
            var list = this._callbackTable[key];
            if (!list) {
              list = this._callbackTable[key] = callbackListPool.alloc();
            }
            var info = callbackInfoPool.alloc();
            info.set(callback, target, once);
            list.callbackInfos.push(info);
          }
          return callback;
        };
        _proto3.hasEventListener = function hasEventListener(key, callback, target) {
          var list = this._callbackTable && this._callbackTable[key];
          if (!list) {
            return false;
          }
          var infos = list.callbackInfos;
          if (!callback) {
            if (list.isInvoking) {
              for (var i = 0; i < infos.length; ++i) {
                if (infos[i]) {
                  return true;
                }
              }
              return false;
            } else {
              return infos.length > 0;
            }
          }
          for (var _i = 0; _i < infos.length; ++_i) {
            var info = infos[_i];
            if (info && info.check() && info.callback === callback && info.target === target) {
              return true;
            }
          }
          return false;
        };
        _proto3.removeAll = function removeAll(keyOrTarget) {
          var type = typeof keyOrTarget;
          if (type === 'string' || type === 'number') {
            var list = this._callbackTable && this._callbackTable[keyOrTarget];
            if (list) {
              if (list.isInvoking) {
                list.cancelAll();
              } else {
                list.clear();
                callbackListPool.free(list);
                delete this._callbackTable[keyOrTarget];
              }
            }
          } else if (keyOrTarget) {
            for (var key in this._callbackTable) {
              var _list = this._callbackTable[key];
              if (_list.isInvoking) {
                var infos = _list.callbackInfos;
                for (var i = 0; i < infos.length; ++i) {
                  var info = infos[i];
                  if (info && info.target === keyOrTarget) {
                    _list.cancel(i);
                  }
                }
              } else {
                _list.removeByTarget(keyOrTarget);
              }
            }
          }
        };
        _proto3.off = function off(key, callback, target) {
          var _this$_offCallback;
          var list = this._callbackTable && this._callbackTable[key];
          if (list) {
            var infos = list.callbackInfos;
            if (callback) {
              for (var i = 0; i < infos.length; ++i) {
                var info = infos[i];
                if (info && info.callback === callback && info.target === target) {
                  list.cancel(i);
                  break;
                }
              }
            } else {
              this.removeAll(key);
            }
          }
          (_this$_offCallback = this._offCallback) === null || _this$_offCallback === void 0 ? void 0 : _this$_offCallback.call(this);
        };
        _proto3.emit = function emit(key, arg0, arg1, arg2, arg3, arg4) {
          var list = this._callbackTable && this._callbackTable[key];
          if (list) {
            var rootInvoker = !list.isInvoking;
            list.isInvoking = true;
            var infos = list.callbackInfos;
            for (var i = 0, len = infos.length; i < len; ++i) {
              var info = infos[i];
              if (info) {
                var callback = info.callback;
                var target = info.target;
                if (info.once) {
                  this.off(key, callback, target);
                }
                if (!info.check()) {
                  this.off(key, callback, target);
                } else if (target) {
                  callback.call(target, arg0, arg1, arg2, arg3, arg4);
                } else {
                  callback(arg0, arg1, arg2, arg3, arg4);
                }
              }
            }
            if (rootInvoker) {
              list.isInvoking = false;
              if (list.containCanceled) {
                list.purgeCanceled();
              }
            }
          }
        };
        _proto3.clear = function clear() {
          for (var key in this._callbackTable) {
            var list = this._callbackTable[key];
            if (list) {
              list.clear();
              callbackListPool.free(list);
              delete this._callbackTable[key];
            }
          }
        };
        _proto3._registerOffCallback = function _registerOffCallback(cb) {
          this._offCallback = cb;
        };
        return CallbacksInvoker;
      }());

      function Eventify(base) {
        var Eventified = function (_ref) {
          _inheritsLoose(Eventified, _ref);
          function Eventified() {
            var _this;
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = arguments[_key];
            }
            _this = _ref.call.apply(_ref, [this].concat(args)) || this;
            _this._callbackTable = createMap(true);
            return _this;
          }
          var _proto = Eventified.prototype;
          _proto.once = function once(type, callback, target) {
            return this.on(type, callback, target, true);
          };
          _proto.targetOff = function targetOff(typeOrTarget) {
            this.removeAll(typeOrTarget);
          };
          return Eventified;
        }(base);
        var callbacksInvokerPrototype = CallbacksInvoker.prototype;
        var propertyKeys = Object.getOwnPropertyNames(callbacksInvokerPrototype).concat(Object.getOwnPropertySymbols(callbacksInvokerPrototype));
        for (var iPropertyKey = 0; iPropertyKey < propertyKeys.length; ++iPropertyKey) {
          var propertyKey = propertyKeys[iPropertyKey];
          if (!(propertyKey in Eventified.prototype)) {
            var propertyDescriptor = Object.getOwnPropertyDescriptor(callbacksInvokerPrototype, propertyKey);
            if (propertyDescriptor) {
              Object.defineProperty(Eventified.prototype, propertyKey, propertyDescriptor);
            }
          }
        }
        return Eventified;
      }

      var Empty = function Empty() {};
      var EventTarget = exports('c3', Eventify(Empty));
      legacyCC.EventTarget = EventTarget;

      var AsyncDelegate = exports('c5', function () {
        function AsyncDelegate() {
          this._delegates = [];
        }
        var _proto = AsyncDelegate.prototype;
        _proto.add = function add(callback) {
          if (!this._delegates.includes(callback)) {
            this._delegates.push(callback);
          }
        };
        _proto.hasListener = function hasListener(callback) {
          return this._delegates.includes(callback);
        };
        _proto.remove = function remove(callback) {
          fastRemove(this._delegates, callback);
        };
        _proto.dispatch = function dispatch() {
          var _arguments = arguments;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          return Promise.all(this._delegates.map(function (func) {
            return func.apply(void 0, _arguments);
          }).filter(Boolean));
        };
        return AsyncDelegate;
      }());

      var BrowserType;
      (function (BrowserType) {
        BrowserType["UNKNOWN"] = "unknown";
        BrowserType["WECHAT"] = "wechat";
        BrowserType["ANDROID"] = "androidbrowser";
        BrowserType["IE"] = "ie";
        BrowserType["EDGE"] = "edge";
        BrowserType["QQ"] = "qqbrowser";
        BrowserType["MOBILE_QQ"] = "mqqbrowser";
        BrowserType["UC"] = "ucbrowser";
        BrowserType["UCBS"] = "ucbs";
        BrowserType["BROWSER_360"] = "360browser";
        BrowserType["BAIDU_APP"] = "baiduboxapp";
        BrowserType["BAIDU"] = "baidubrowser";
        BrowserType["MAXTHON"] = "maxthon";
        BrowserType["OPERA"] = "opera";
        BrowserType["OUPENG"] = "oupeng";
        BrowserType["MIUI"] = "miuibrowser";
        BrowserType["FIREFOX"] = "firefox";
        BrowserType["SAFARI"] = "safari";
        BrowserType["CHROME"] = "chrome";
        BrowserType["LIEBAO"] = "liebao";
        BrowserType["QZONE"] = "qzone";
        BrowserType["SOUGOU"] = "sogou";
        BrowserType["HUAWEI"] = "huawei";
      })(BrowserType || (BrowserType = {}));

      var Language;
      (function (Language) {
        Language["UNKNOWN"] = "unknown";
        Language["ENGLISH"] = "en";
        Language["CHINESE"] = "zh";
        Language["FRENCH"] = "fr";
        Language["ITALIAN"] = "it";
        Language["GERMAN"] = "de";
        Language["SPANISH"] = "es";
        Language["DUTCH"] = "du";
        Language["RUSSIAN"] = "ru";
        Language["KOREAN"] = "ko";
        Language["JAPANESE"] = "ja";
        Language["HUNGARIAN"] = "hu";
        Language["PORTUGUESE"] = "pt";
        Language["ARABIC"] = "ar";
        Language["NORWEGIAN"] = "no";
        Language["POLISH"] = "pl";
        Language["TURKISH"] = "tr";
        Language["UKRAINIAN"] = "uk";
        Language["ROMANIAN"] = "ro";
        Language["BULGARIAN"] = "bg";
        Language["HINDI"] = "hi";
      })(Language || (Language = {}));

      var NetworkType;
      (function (NetworkType) {
        NetworkType[NetworkType["NONE"] = 0] = "NONE";
        NetworkType[NetworkType["LAN"] = 1] = "LAN";
        NetworkType[NetworkType["WWAN"] = 2] = "WWAN";
      })(NetworkType || (NetworkType = {}));

      var OS;
      (function (OS) {
        OS["UNKNOWN"] = "Unknown";
        OS["IOS"] = "iOS";
        OS["ANDROID"] = "Android";
        OS["WINDOWS"] = "Windows";
        OS["LINUX"] = "Linux";
        OS["OSX"] = "OS X";
        OS["OHOS"] = "OHOS";
        OS["OPENHARMONY"] = "OpenHarmony";
      })(OS || (OS = {}));

      var Platform;
      (function (Platform) {
        Platform["UNKNOWN"] = "UNKNOWN";
        Platform["EDITOR_PAGE"] = "EDITOR_PAGE";
        Platform["EDITOR_CORE"] = "EDITOR_CORE";
        Platform["MOBILE_BROWSER"] = "MOBILE_BROWSER";
        Platform["DESKTOP_BROWSER"] = "DESKTOP_BROWSER";
        Platform["WIN32"] = "WIN32";
        Platform["ANDROID"] = "ANDROID";
        Platform["IOS"] = "IOS";
        Platform["MACOS"] = "MACOS";
        Platform["OHOS"] = "OHOS";
        Platform["OPENHARMONY"] = "OPENHARMONY";
        Platform["WECHAT_GAME"] = "WECHAT_GAME";
        Platform["WECHAT_MINI_PROGRAM"] = "WECHAT_MINI_PROGRAM";
        Platform["BAIDU_MINI_GAME"] = "BAIDU_MINI_GAME";
        Platform["XIAOMI_QUICK_GAME"] = "XIAOMI_QUICK_GAME";
        Platform["ALIPAY_MINI_GAME"] = "ALIPAY_MINI_GAME";
        Platform["TAOBAO_CREATIVE_APP"] = "TAOBAO_CREATIVE_APP";
        Platform["TAOBAO_MINI_GAME"] = "TAOBAO_MINI_GAME";
        Platform["BYTEDANCE_MINI_GAME"] = "BYTEDANCE_MINI_GAME";
        Platform["OPPO_MINI_GAME"] = "OPPO_MINI_GAME";
        Platform["VIVO_MINI_GAME"] = "VIVO_MINI_GAME";
        Platform["HUAWEI_QUICK_GAME"] = "HUAWEI_QUICK_GAME";
        Platform["COCOSPLAY"] = "COCOSPLAY";
        Platform["LINKSURE_MINI_GAME"] = "LINKSURE_MINI_GAME";
        Platform["QTT_MINI_GAME"] = "QTT_MINI_GAME";
      })(Platform || (Platform = {}));

      var Feature$1;
      (function (Feature) {
        Feature["WEBP"] = "WEBP";
        Feature["IMAGE_BITMAP"] = "IMAGE_BITMAP";
        Feature["WEB_VIEW"] = "WEB_VIEW";
        Feature["VIDEO_PLAYER"] = "VIDEO_PLAYER";
        Feature["SAFE_AREA"] = "SAFE_AREA";
        Feature["HPE"] = "HPE";
        Feature["INPUT_TOUCH"] = "INPUT_TOUCH";
        Feature["EVENT_KEYBOARD"] = "EVENT_KEYBOARD";
        Feature["EVENT_MOUSE"] = "EVENT_MOUSE";
        Feature["EVENT_TOUCH"] = "EVENT_TOUCH";
        Feature["EVENT_ACCELEROMETER"] = "EVENT_ACCELEROMETER";
        Feature["EVENT_GAMEPAD"] = "EVENT_GAMEPAD";
        Feature["EVENT_HANDLE"] = "EVENT_HANDLE";
        Feature["EVENT_HMD"] = "EVENT_HMD";
        Feature["EVENT_HANDHELD"] = "EVENT_HANDHELD";
        Feature["WASM"] = "WASM";
      })(Feature$1 || (Feature$1 = {}));

      var SystemInfo = function (_EventTarget) {
        _inheritsLoose(SystemInfo, _EventTarget);
        function SystemInfo() {
          var _getBattery, _ref, _this$_featureMap;
          var _this;
          _this = _EventTarget.call(this) || this;
          _this.networkType = void 0;
          _this.isNative = void 0;
          _this.isBrowser = void 0;
          _this.isMobile = void 0;
          _this.isLittleEndian = void 0;
          _this.platform = void 0;
          _this.language = void 0;
          _this.nativeLanguage = void 0;
          _this.os = void 0;
          _this.osVersion = void 0;
          _this.osMainVersion = void 0;
          _this.browserType = void 0;
          _this.browserVersion = void 0;
          _this.isXR = void 0;
          _this._battery = void 0;
          _this._featureMap = void 0;
          _this._initPromise = void 0;
          var nav = window.navigator;
          var ua = nav.userAgent.toLowerCase();
          (_getBattery = (_ref = nav).getBattery) === null || _getBattery === void 0 ? void 0 : _getBattery.call(_ref).then(function (battery) {
            _this._battery = battery;
          });
          _this.networkType = NetworkType.LAN;
          _this.isNative = false;
          _this.isBrowser = true;
          {
            _this.isMobile = /mobile|android|iphone|ipad/.test(ua);
            _this.platform = _this.isMobile ? Platform.MOBILE_BROWSER : Platform.DESKTOP_BROWSER;
          }
          _this.isLittleEndian = function () {
            var buffer = new ArrayBuffer(2);
            new DataView(buffer).setInt16(0, 256, true);
            return new Int16Array(buffer)[0] === 256;
          }();
          var currLanguage = nav.language;
          _this.nativeLanguage = currLanguage.toLowerCase();
          currLanguage = currLanguage || nav.browserLanguage;
          currLanguage = currLanguage ? currLanguage.split('-')[0] : Language.ENGLISH;
          _this.language = currLanguage;
          var isAndroid = false;
          var iOS = false;
          var osVersion = '';
          var osMajorVersion = 0;
          var uaResult = /android\s*(\d+(?:\.\d+)*)/i.exec(ua) || /android\s*(\d+(?:\.\d+)*)/i.exec(nav.platform);
          if (uaResult) {
            isAndroid = true;
            osVersion = uaResult[1] || '';
            osMajorVersion = parseInt(osVersion) || 0;
          }
          uaResult = /(iPad|iPhone|iPod).*OS ((\d+_?){2,3})/i.exec(ua);
          if (uaResult) {
            iOS = true;
            osVersion = uaResult[2] || '';
            osMajorVersion = parseInt(osVersion) || 0;
          } else if (/(iPhone|iPad|iPod)/.exec(nav.platform) || nav.platform === 'MacIntel' && nav.maxTouchPoints && nav.maxTouchPoints > 1) {
            iOS = true;
            osVersion = '';
            osMajorVersion = 0;
          }
          var osName = OS.UNKNOWN;
          if (nav.appVersion.indexOf('Win') !== -1) {
            osName = OS.WINDOWS;
          } else if (iOS) {
            osName = OS.IOS;
          } else if (nav.appVersion.indexOf('Mac') !== -1) {
            osName = OS.OSX;
          } else if (nav.appVersion.indexOf('X11') !== -1 && nav.appVersion.indexOf('Linux') === -1) {
            osName = OS.LINUX;
          } else if (isAndroid) {
            osName = OS.ANDROID;
          } else if (nav.appVersion.indexOf('Linux') !== -1 || ua.indexOf('ubuntu') !== -1) {
            osName = OS.LINUX;
          }
          _this.os = osName;
          _this.osVersion = osVersion;
          _this.osMainVersion = osMajorVersion;
          _this.browserType = BrowserType.UNKNOWN;
          var typeReg0 = /wechat|weixin|micromessenger/i;
          var typeReg1 = /mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|ucbs|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|miuibrowser/i;
          var typeReg2 = /qq|qqbrowser|ucbrowser|ubrowser|edge|HuaweiBrowser/i;
          var typeReg3 = /chrome|safari|firefox|trident|opera|opr\/|oupeng/i;
          var browserTypes = typeReg0.exec(ua) || typeReg1.exec(ua) || typeReg2.exec(ua) || typeReg3.exec(ua);
          var browserType = browserTypes ? browserTypes[0].toLowerCase() : OS.UNKNOWN;
          if (browserType === 'safari' && isAndroid) {
            browserType = BrowserType.ANDROID;
          } else if (browserType === 'qq' && /android.*applewebkit/i.test(ua)) {
            browserType = BrowserType.ANDROID;
          }
          var typeMap = {
            micromessenger: BrowserType.WECHAT,
            wechat: BrowserType.WECHAT,
            weixin: BrowserType.WECHAT,
            trident: BrowserType.IE,
            edge: BrowserType.EDGE,
            '360 aphone': BrowserType.BROWSER_360,
            mxbrowser: BrowserType.MAXTHON,
            'opr/': BrowserType.OPERA,
            ubrowser: BrowserType.UC,
            huaweibrowser: BrowserType.HUAWEI
          };
          _this.browserType = typeMap[browserType] || browserType;
          _this.browserVersion = '';
          var versionReg1 = /(mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|uc|ucbs|360 aphone|360|baiduboxapp|baidu|maxthon|mxbrowser|miui(?:.hybrid)?)(mobile)?(browser)?\/?([\d.]+)/i;
          var versionReg2 = /(qq|chrome|safari|firefox|trident|opera|opr\/|oupeng)(mobile)?(browser)?\/?([\d.]+)/i;
          var tmp = versionReg1.exec(ua);
          if (!tmp) {
            tmp = versionReg2.exec(ua);
          }
          _this.browserVersion = tmp ? tmp[4] : '';
          _this.isXR = false;
          var _tmpCanvas1 = document.createElement('canvas');
          !!_tmpCanvas1.getContext('2d');
          var supportWebp;
          try {
            supportWebp = TEST ? false : _tmpCanvas1.toDataURL('image/webp').startsWith('data:image/webp');
          } catch (e) {
            supportWebp = false;
          }
          if (_this.os === OS.IOS) {
            var _exec;
            var result = (_exec = / applewebkit\/(\d+)/.exec(ua)) === null || _exec === void 0 ? void 0 : _exec[1];
            if (typeof result === 'string') {
              if (Number.parseInt(result) >= 604) {
                supportWebp = true;
              }
            }
          } else if (_this.browserType === BrowserType.SAFARI) {
            var _exec2;
            var _result = (_exec2 = / version\/(\d+)/.exec(ua)) === null || _exec2 === void 0 ? void 0 : _exec2[1];
            if (typeof _result === 'string') {
              if (Number.parseInt(_result) >= 14) {
                supportWebp = true;
              }
            }
          }
          var supportTouch = document.documentElement.ontouchstart !== undefined || document.ontouchstart !== undefined || EDITOR;
          var supportMouse = document.documentElement.onmouseup !== undefined || EDITOR;
          var supportXR = typeof navigator.xr !== 'undefined';
          var supportWasm = function () {
            var isSafari_15_4 = (_this.os === OS.IOS || _this.os === OS.OSX) && /(OS 15_4)|(Version\/15.4)/.test(window.navigator.userAgent);
            if (isSafari_15_4) {
              return false;
            }
            try {
              if (typeof WebAssembly === 'object' && typeof WebAssembly.instantiate === 'function') {
                var module = new WebAssembly.Module(new Uint8Array([0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]));
                if (module instanceof WebAssembly.Module) {
                  return new WebAssembly.Instance(module) instanceof WebAssembly.Instance;
                }
              }
            } catch (e) {
              return false;
            }
            return false;
          }();
          _this._featureMap = (_this$_featureMap = {}, _this$_featureMap[Feature$1.WEBP] = supportWebp, _this$_featureMap[Feature$1.IMAGE_BITMAP] = false, _this$_featureMap[Feature$1.WEB_VIEW] = true, _this$_featureMap[Feature$1.VIDEO_PLAYER] = true, _this$_featureMap[Feature$1.SAFE_AREA] = false, _this$_featureMap[Feature$1.HPE] = false, _this$_featureMap[Feature$1.INPUT_TOUCH] = supportTouch, _this$_featureMap[Feature$1.EVENT_KEYBOARD] = document.documentElement.onkeyup !== undefined || EDITOR, _this$_featureMap[Feature$1.EVENT_MOUSE] = supportMouse, _this$_featureMap[Feature$1.EVENT_TOUCH] = supportTouch || supportMouse, _this$_featureMap[Feature$1.EVENT_ACCELEROMETER] = window.DeviceMotionEvent !== undefined || window.DeviceOrientationEvent !== undefined, _this$_featureMap[Feature$1.EVENT_GAMEPAD] = navigator.getGamepads !== undefined || navigator.webkitGetGamepads !== undefined || supportXR, _this$_featureMap[Feature$1.EVENT_HANDLE] = PREVIEW, _this$_featureMap[Feature$1.EVENT_HMD] = supportXR, _this$_featureMap[Feature$1.EVENT_HANDHELD] = supportXR, _this$_featureMap[Feature$1.WASM] = supportWasm, _this$_featureMap);
          _this._initPromise = [];
          _this._initPromise.push(_this._supportsImageBitmapPromise());
          _this._registerEvent();
          return _this;
        }
        var _proto = SystemInfo.prototype;
        _proto._supportsImageBitmapPromise = function _supportsImageBitmapPromise() {
          var _this2 = this;
          if (typeof createImageBitmap !== 'undefined' && typeof Blob !== 'undefined') {
            var canvas = document.createElement('canvas');
            canvas.width = canvas.height = 2;
            var promise = createImageBitmap(canvas, {});
            if (promise instanceof Promise) {
              return promise.then(function (imageBitmap) {
                _this2._setFeature(Feature$1.IMAGE_BITMAP, true);
                imageBitmap === null || imageBitmap === void 0 ? void 0 : imageBitmap.close();
              });
            } else {
              console.warn('The return value of createImageBitmap is not Promise.');
            }
          }
          return Promise.resolve();
        };
        _proto._registerEvent = function _registerEvent() {
          var _this3 = this;
          var hiddenPropName;
          if (typeof document.hidden !== 'undefined') {
            hiddenPropName = 'hidden';
          } else if (typeof document.mozHidden !== 'undefined') {
            hiddenPropName = 'mozHidden';
          } else if (typeof document.msHidden !== 'undefined') {
            hiddenPropName = 'msHidden';
          } else if (typeof document.webkitHidden !== 'undefined') {
            hiddenPropName = 'webkitHidden';
          } else {
            hiddenPropName = 'hidden';
          }
          var hidden = false;
          var onHidden = function onHidden() {
            if (!hidden) {
              hidden = true;
              _this3.emit('hide');
            }
          };
          var onShown = function onShown(arg0, arg1, arg2, arg3, arg4) {
            if (hidden) {
              hidden = false;
              _this3.emit('show', arg0, arg1, arg2, arg3, arg4);
            }
          };
          if (hiddenPropName) {
            var changeList = ['visibilitychange', 'mozvisibilitychange', 'msvisibilitychange', 'webkitvisibilitychange', 'qbrowserVisibilityChange'];
            for (var i = 0; i < changeList.length; i++) {
              document.addEventListener(changeList[i], function (event) {
                var visible = document[hiddenPropName];
                visible = visible || event.hidden;
                if (visible) {
                  onHidden();
                } else {
                  onShown();
                }
              });
            }
          } else {
            window.addEventListener('blur', onHidden);
            window.addEventListener('focus', onShown);
          }
          if (window.navigator.userAgent.indexOf('MicroMessenger') > -1) {
            window.onfocus = onShown;
          }
          if ('onpageshow' in window && 'onpagehide' in window) {
            window.addEventListener('pagehide', onHidden);
            window.addEventListener('pageshow', onShown);
            document.addEventListener('pagehide', onHidden);
            document.addEventListener('pageshow', onShown);
          }
        };
        _proto._setFeature = function _setFeature(feature, value) {
          return this._featureMap[feature] = value;
        };
        _proto.init = function init() {
          return Promise.all(this._initPromise);
        };
        _proto.hasFeature = function hasFeature(feature) {
          return this._featureMap[feature];
        };
        _proto.getBatteryLevel = function getBatteryLevel() {
          if (this._battery) {
            return this._battery.level;
          } else {
            {
              console.warn('getBatteryLevel is not supported');
            }
            return 1;
          }
        };
        _proto.triggerGC = function triggerGC() {
          {
            console.warn('triggerGC is not supported.');
          }
        };
        _proto.openURL = function openURL(url) {
          window.open(url);
        };
        _proto.now = function now() {
          if (Date.now) {
            return Date.now();
          }
          return +new Date();
        };
        _proto.restartJSVM = function restartJSVM() {
          {
            console.warn('restartJSVM is not supported.');
          }
        };
        _proto.exit = function exit() {
          window.close();
        };
        _proto.close = function close() {
          this.emit('close');
        };
        return SystemInfo;
      }(EventTarget);
      var systemInfo = new SystemInfo();

      var EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/;
      var DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/;
      var NORMALIZE_RE = /[^\.\/]+\/\.\.\//;
      function join() {
        var result = '';
        for (var _len = arguments.length, segments = new Array(_len), _key = 0; _key < _len; _key++) {
          segments[_key] = arguments[_key];
        }
        for (var _i = 0, _segments = segments; _i < _segments.length; _i++) {
          var segment = _segments[_i];
          result = (result + (result === '' ? '' : '/') + segment).replace(/(\/|\\\\)$/, '');
        }
        return result;
      }
      function extname(path) {
        var temp = EXTNAME_RE.exec(path);
        return temp ? temp[1] : '';
      }
      function mainFileName(fileName) {
        if (fileName) {
          var idx = fileName.lastIndexOf('.');
          if (idx !== -1) {
            return fileName.substring(0, idx);
          }
        }
        return fileName;
      }
      function basename(path, extName) {
        var index = path.indexOf('?');
        if (index > 0) {
          path = path.substring(0, index);
        }
        var reg = /(\/|\\)([^\/\\]+)$/g;
        var result = reg.exec(path.replace(/(\/|\\)$/, ''));
        if (!result) {
          return path;
        }
        var baseName = result[2];
        if (extName && path.substring(path.length - extName.length).toLowerCase() === extName.toLowerCase()) {
          return baseName.substring(0, baseName.length - extName.length);
        }
        return baseName;
      }
      function dirname(path) {
        var temp = DIRNAME_RE.exec(path);
        return temp ? temp[2] : '';
      }
      function changeExtname(path, extName) {
        extName = extName || '';
        var index = path.indexOf('?');
        var tempStr = '';
        if (index > 0) {
          tempStr = path.substring(index);
          path = path.substring(0, index);
        }
        index = path.lastIndexOf('.');
        if (index < 0) {
          return path + extName + tempStr;
        }
        return path.substring(0, index) + extName + tempStr;
      }
      function changeBasename(path, newBaseName, keepExt) {
        if (newBaseName.indexOf('.') === 0) {
          return changeExtname(path, newBaseName);
        }
        var index = path.indexOf('?');
        var tempStr = '';
        var ext = keepExt ? extname(path) : '';
        if (index > 0) {
          tempStr = path.substring(index);
          path = path.substring(0, index);
        }
        index = path.lastIndexOf('/');
        index = index <= 0 ? 0 : index + 1;
        return path.substring(0, index) + newBaseName + ext + tempStr;
      }
      function _normalize(url) {
        var oldUrl = url = String(url);
        do {
          oldUrl = url;
          url = url.replace(NORMALIZE_RE, '');
        } while (oldUrl.length !== url.length);
        return url;
      }
      function stripSep(path) {
        return path.replace(/[\/\\]$/, '');
      }
      function getSeperator() {
        return systemInfo.os === OS.WINDOWS ? '\\' : '/';
      }

      var path = /*#__PURE__*/Object.freeze({
        __proto__: null,
        join: join,
        extname: extname,
        mainFileName: mainFileName,
        basename: basename,
        dirname: dirname,
        changeExtname: changeExtname,
        changeBasename: changeBasename,
        _normalize: _normalize,
        stripSep: stripSep,
        getSeperator: getSeperator
      });
      exports('bG', path);

      var _vec3$1 = new Vec3();
      function WorldNode3DToLocalNodeUI(mainCamera, wpos, uiNode, out) {
        if (!out) {
          out = new Vec3();
        }
        mainCamera.convertToUINode(wpos, uiNode, out);
        var pos = uiNode.position;
        out.add(pos);
        return out;
      }
      function WorldNode3DToWorldNodeUI(mainCamera, wpos, out) {
        if (!out) {
          out = new Vec3();
        }
        mainCamera.worldToScreen(wpos, out);
        out.x /= legacyCC.view.getScaleX();
        out.y /= legacyCC.view.getScaleY();
        return out;
      }
      var convertUtils = exports('bQ', {
        WorldNode3DToLocalNodeUI: WorldNode3DToLocalNodeUI,
        WorldNode3DToWorldNodeUI: WorldNode3DToWorldNodeUI
      });
      legacyCC.pipelineUtils = convertUtils;
      replaceProperty(legacyCC.pipelineUtils, 'cc.pipelineUtils', [{
        name: 'WorldNode3DToLocalNodeUI',
        newName: 'convertToUINode',
        targetName: 'cc.Camera.prototype',
        customFunction: function customFunction() {
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          var camera = args[0];
          var out = args[3] || _vec3$1;
          camera.convertToUINode(args[1], args[2], out);
          out.add(args[2].position);
          return args[3] || out.clone();
        }
      }]);

      markAsWarning(js$1, 'js', [{
        name: 'js',
        suggest: "'js.js' is deprecated since v3.7.0, please access 'js' directly instead."
      }]);

      var EVENT_TIMEOUT = 200;
      var orientationMap$2 = {
        auto: Orientation$1.AUTO,
        landscape: Orientation$1.LANDSCAPE,
        portrait: Orientation$1.PORTRAIT
      };
      var WindowType;
      (function (WindowType) {
        WindowType[WindowType["Unknown"] = 0] = "Unknown";
        WindowType[WindowType["SubFrame"] = 1] = "SubFrame";
        WindowType[WindowType["BrowserWindow"] = 2] = "BrowserWindow";
        WindowType[WindowType["Fullscreen"] = 3] = "Fullscreen";
      })(WindowType || (WindowType = {}));
      var ScreenAdapter = function (_EventTarget) {
        _inheritsLoose(ScreenAdapter, _EventTarget);
        var _proto = ScreenAdapter.prototype;
        _proto._updateFrame = function _updateFrame() {
          this._updateFrameState();
          this._resizeFrame();
        };
        function ScreenAdapter() {
          var _this;
          _this = _EventTarget.call(this) || this;
          _this.isFrameRotated = false;
          _this.handleResizeEvent = true;
          _this._gameFrame = void 0;
          _this._gameContainer = void 0;
          _this._gameCanvas = void 0;
          _this._isProportionalToFrame = false;
          _this._cachedFrameStyle = {
            width: '0px',
            height: '0px'
          };
          _this._cachedContainerStyle = {
            width: '0px',
            height: '0px'
          };
          _this._cbToUpdateFrameBuffer = void 0;
          _this._supportFullScreen = false;
          _this._touchEventName = void 0;
          _this._onFullscreenChange = void 0;
          _this._onFullscreenError = void 0;
          _this._orientationChangeTimeoutId = -1;
          _this._cachedFrameSize = new Size$1(0, 0);
          _this._exactFitScreen = false;
          _this._isHeadlessMode = false;
          _this._fn = {};
          _this._fnGroup = [['requestFullscreen', 'exitFullscreen', 'fullscreenchange', 'fullscreenEnabled', 'fullscreenElement', 'fullscreenerror'], ['requestFullScreen', 'exitFullScreen', 'fullScreenchange', 'fullScreenEnabled', 'fullScreenElement', 'fullscreenerror'], ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitIsFullScreen', 'webkitCurrentFullScreenElement', 'webkitfullscreenerror'], ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozfullscreenchange', 'mozFullScreen', 'mozFullScreenElement', 'mozfullscreenerror'], ['msRequestFullscreen', 'msExitFullscreen', 'MSFullscreenChange', 'msFullscreenEnabled', 'msFullscreenElement', 'msfullscreenerror']];
          _this._resolutionScale = 1;
          _this._orientation = Orientation$1.AUTO;
          _this._orientationDevice = Orientation$1.AUTO;
          _this._gameFrame = document.getElementById('GameDiv');
          _this._gameContainer = document.getElementById('Cocos3dGameContainer');
          _this._gameCanvas = document.getElementById('GameCanvas');
          {
            if (!_this._gameFrame) {
              var _this$_gameCanvas, _this$_gameCanvas$par;
              _this._gameFrame = document.createElement('div');
              _this._gameFrame.setAttribute('id', 'GameDiv');
              (_this$_gameCanvas = _this._gameCanvas) === null || _this$_gameCanvas === void 0 ? void 0 : (_this$_gameCanvas$par = _this$_gameCanvas.parentNode) === null || _this$_gameCanvas$par === void 0 ? void 0 : _this$_gameCanvas$par.insertBefore(_this._gameFrame, _this._gameCanvas);
              _this._gameFrame.appendChild(_this._gameCanvas);
            }
            if (!_this._gameContainer) {
              var _this$_gameCanvas2, _this$_gameCanvas2$pa;
              _this._gameContainer = document.createElement('div');
              _this._gameContainer.setAttribute('id', 'Cocos3dGameContainer');
              (_this$_gameCanvas2 = _this._gameCanvas) === null || _this$_gameCanvas2 === void 0 ? void 0 : (_this$_gameCanvas2$pa = _this$_gameCanvas2.parentNode) === null || _this$_gameCanvas2$pa === void 0 ? void 0 : _this$_gameCanvas2$pa.insertBefore(_this._gameContainer, _this._gameCanvas);
              _this._gameContainer.appendChild(_this._gameCanvas);
            }
          }
          var fnList;
          var fnGroup = _this._fnGroup;
          for (var i = 0; i < fnGroup.length; i++) {
            fnList = fnGroup[i];
            if (typeof document[fnList[1]] !== 'undefined') {
              for (var _i = 0; _i < fnList.length; _i++) {
                _this._fn[fnGroup[0][_i]] = fnList[_i];
              }
              break;
            }
          }
          _this._supportFullScreen = _this._fn.requestFullscreen !== undefined;
          _this._touchEventName = 'ontouchstart' in window ? 'touchend' : 'mousedown';
          _this._registerEvent();
          return _this;
        }
        _proto.init = function init(options, cbToRebuildFrameBuffer) {
          this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer;
          this.orientation = orientationMap$2[options.configOrientation];
          this._exactFitScreen = options.exactFitScreen;
          this._isHeadlessMode = options.isHeadlessMode;
          this._resizeFrame();
        };
        _proto.requestFullScreen = function requestFullScreen() {
          var _this2 = this;
          return new Promise(function (resolve, reject) {
            if (_this2.isFullScreen) {
              resolve();
              return;
            }
            _this2._cachedFrameSize = _this2.windowSize;
            _this2._doRequestFullScreen().then(function () {
              resolve();
            })["catch"](function () {
              var fullscreenTarget = _this2._getFullscreenTarget();
              if (!fullscreenTarget) {
                reject(new Error('Cannot access fullscreen target'));
                return;
              }
              fullscreenTarget.addEventListener(_this2._touchEventName, function () {
                _this2._doRequestFullScreen().then(function () {
                  resolve();
                })["catch"](reject);
              }, {
                once: true,
                capture: true
              });
            });
          });
        };
        _proto.exitFullScreen = function exitFullScreen() {
          var _this3 = this;
          return new Promise(function (resolve, reject) {
            var requestPromise = document[_this3._fn.exitFullscreen]();
            if (window.Promise && requestPromise instanceof Promise) {
              requestPromise.then(function () {
                _this3.windowSize = _this3._cachedFrameSize;
                resolve();
              })["catch"](reject);
              return;
            }
            _this3.windowSize = _this3._cachedFrameSize;
            resolve();
          });
        };
        _proto._registerEvent = function _registerEvent() {
          var _this4 = this;
          document.addEventListener(this._fn.fullscreenerror, function () {
            var _this4$_onFullscreenE;
            (_this4$_onFullscreenE = _this4._onFullscreenError) === null || _this4$_onFullscreenE === void 0 ? void 0 : _this4$_onFullscreenE.call(_this4);
          });
          window.addEventListener('resize', function () {
            _this4._resizeFrame();
          });
          var notifyOrientationChange = function notifyOrientationChange(orientation) {
            if (orientation === _this4._orientationDevice) {
              return;
            }
            _this4._orientationDevice = orientation;
            _this4._updateFrame();
            _this4.emit('orientation-change', orientation);
          };
          var getOrientation = function getOrientation() {
            var tmpOrientation = Orientation$1.PORTRAIT;
            switch (window.orientation) {
              case 0:
                tmpOrientation = Orientation$1.PORTRAIT;
                break;
              case 90:
                tmpOrientation = Orientation$1.LANDSCAPE_RIGHT;
                break;
              case -90:
                tmpOrientation = Orientation$1.LANDSCAPE_LEFT;
                break;
              case 180:
                tmpOrientation = Orientation$1.PORTRAIT_UPSIDE_DOWN;
                break;
              default:
                tmpOrientation = _this4._orientationDevice;
                break;
            }
            return tmpOrientation;
          };
          var handleOrientationChange;
          var orientationChangeCallback = function orientationChangeCallback() {
            if (_this4._orientationChangeTimeoutId !== -1) {
              clearTimeout(_this4._orientationChangeTimeoutId);
            }
            _this4._orientationChangeTimeoutId = setTimeout(function () {
              handleOrientationChange();
            }, EVENT_TIMEOUT);
          };
          if (typeof window.matchMedia === 'function') {
            var updateDPRChangeListener = function updateDPRChangeListener() {
              var _window$matchMedia, _window$matchMedia$ad;
              var dpr = window.devicePixelRatio;
              (_window$matchMedia = window.matchMedia("(resolution: " + dpr + "dppx)")) === null || _window$matchMedia === void 0 ? void 0 : (_window$matchMedia$ad = _window$matchMedia.addEventListener) === null || _window$matchMedia$ad === void 0 ? void 0 : _window$matchMedia$ad.call(_window$matchMedia, 'change', function () {
                _this4.emit('window-resize', _this4.windowSize.width, _this4.windowSize.height);
                updateDPRChangeListener();
              }, {
                once: true
              });
            };
            updateDPRChangeListener();
            var mediaQueryPortrait = window.matchMedia('(orientation: portrait)');
            var mediaQueryLandscape = window.matchMedia('(orientation: landscape)');
            var hasScreeOrientation = screen.orientation;
            handleOrientationChange = function handleOrientationChange() {
              var tmpOrientation = _this4._orientationDevice;
              if (mediaQueryPortrait.matches) {
                tmpOrientation = Orientation$1.PORTRAIT;
                if (hasScreeOrientation) {
                  var orientationType = screen.orientation.type;
                  if (orientationType === 'portrait-primary') {
                    tmpOrientation = Orientation$1.PORTRAIT;
                  } else {
                    tmpOrientation = Orientation$1.PORTRAIT_UPSIDE_DOWN;
                  }
                }
              } else if (mediaQueryLandscape.matches) {
                tmpOrientation = Orientation$1.LANDSCAPE;
                if (hasScreeOrientation) {
                  var _orientationType = screen.orientation.type;
                  if (_orientationType === 'landscape-primary') {
                    tmpOrientation = Orientation$1.LANDSCAPE_LEFT;
                  } else {
                    tmpOrientation = Orientation$1.LANDSCAPE_RIGHT;
                  }
                }
              }
              notifyOrientationChange(tmpOrientation);
            };
            mediaQueryPortrait.addEventListener('change', orientationChangeCallback);
            mediaQueryLandscape.addEventListener('change', orientationChangeCallback);
          } else {
            handleOrientationChange = function handleOrientationChange() {
              var tmpOrientation = getOrientation();
              notifyOrientationChange(tmpOrientation);
            };
            window.addEventListener('orientationchange', orientationChangeCallback);
          }
          document.addEventListener(this._fn.fullscreenchange, function () {
            var _this4$_onFullscreenC;
            (_this4$_onFullscreenC = _this4._onFullscreenChange) === null || _this4$_onFullscreenC === void 0 ? void 0 : _this4$_onFullscreenC.call(_this4);
            _this4.emit('fullscreen-change', _this4.windowSize.width, _this4.windowSize.height);
          });
        };
        _proto._convertToSizeInCssPixels = function _convertToSizeInCssPixels(size) {
          var clonedSize = size.clone();
          var dpr = this.devicePixelRatio;
          clonedSize.width /= dpr;
          clonedSize.height /= dpr;
          return clonedSize;
        };
        _proto._resizeFrame = function _resizeFrame(sizeInCssPixels) {
          if (!this._gameFrame) {
            return;
          }
          this._gameFrame.style.display = 'flex';
          this._gameFrame.style['justify-content'] = 'center';
          this._gameFrame.style['align-items'] = 'center';
          if (this._windowType === WindowType.SubFrame) {
            if (!sizeInCssPixels) {
              this._updateContainer();
              return;
            }
            this._gameFrame.style.width = sizeInCssPixels.width + "px";
            this._gameFrame.style.height = sizeInCssPixels.height + "px";
          } else {
            var winWidth = window.innerWidth;
            var winHeight = window.innerHeight;
            var inputHeight = document.body.scrollHeight - winHeight;
            if (systemInfo.os === OS.ANDROID && winHeight < inputHeight) {
              winHeight += inputHeight;
            }
            if (this.isFrameRotated) {
              this._gameFrame.style['-webkit-transform'] = 'rotate(90deg)';
              this._gameFrame.style.transform = 'rotate(90deg)';
              this._gameFrame.style['-webkit-transform-origin'] = '0px 0px 0px';
              this._gameFrame.style.transformOrigin = '0px 0px 0px';
              this._gameFrame.style.margin = "0 0 0 " + winWidth + "px";
              this._gameFrame.style.width = winHeight + "px";
              this._gameFrame.style.height = winWidth + "px";
            } else {
              this._gameFrame.style['-webkit-transform'] = 'rotate(0deg)';
              this._gameFrame.style.transform = 'rotate(0deg)';
              this._gameFrame.style.margin = '0px auto';
              this._gameFrame.style.width = winWidth + "px";
              this._gameFrame.style.height = winHeight + "px";
            }
          }
          this._updateContainer();
        };
        _proto._getFullscreenTarget = function _getFullscreenTarget() {
          var windowType = this._windowType;
          if (windowType === WindowType.Fullscreen) {
            return document[this._fn.fullscreenElement];
          }
          if (windowType === WindowType.SubFrame) {
            return this._gameFrame;
          }
          return document.body;
        };
        _proto._doRequestFullScreen = function _doRequestFullScreen() {
          var _this5 = this;
          return new Promise(function (resolve, reject) {
            if (!_this5._supportFullScreen) {
              reject(new Error('fullscreen is not supported'));
              return;
            }
            var fullscreenTarget = _this5._getFullscreenTarget();
            if (!fullscreenTarget) {
              reject(new Error('Cannot access fullscreen target'));
              return;
            }
            _this5._onFullscreenChange = undefined;
            _this5._onFullscreenError = undefined;
            var requestPromise = fullscreenTarget[_this5._fn.requestFullscreen]();
            if (window.Promise && requestPromise instanceof Promise) {
              requestPromise.then(resolve)["catch"](reject);
            } else {
              _this5._onFullscreenChange = resolve;
              _this5._onFullscreenError = reject;
            }
          });
        };
        _proto._updateFrameState = function _updateFrameState() {
          var orientation = this.orientation;
          var width = window.innerWidth;
          var height = window.innerHeight;
          var isBrowserLandscape = width > height;
          this.isFrameRotated = systemInfo.isMobile && (isBrowserLandscape && orientation === Orientation$1.PORTRAIT || !isBrowserLandscape && orientation === Orientation$1.LANDSCAPE);
        };
        _proto._updateContainer = function _updateContainer() {
          if (!this._gameContainer) {
            warnID(9201);
            return;
          }
          if (this.isProportionalToFrame) {
            if (!this._gameFrame) {
              warnID(9201);
              return;
            }
            var designedResolution = legacyCC.view.getDesignResolutionSize();
            var frame = this._gameFrame;
            var frameW = frame.clientWidth;
            var frameH = frame.clientHeight;
            var designW = designedResolution.width;
            var designH = designedResolution.height;
            var scaleX = frameW / designW;
            var scaleY = frameH / designH;
            var containerStyle = this._gameContainer.style;
            var containerW;
            var containerH;
            if (scaleX < scaleY) {
              containerW = frameW;
              containerH = designH * scaleX;
            } else {
              containerW = designW * scaleY;
              containerH = frameH;
            }
            containerStyle.width = containerW + "px";
            containerStyle.height = containerH + "px";
          } else {
            var _containerStyle = this._gameContainer.style;
            _containerStyle.width = '100%';
            _containerStyle.height = '100%';
          }
          if (this._gameFrame && (this._cachedFrameStyle.width !== this._gameFrame.style.width || this._cachedFrameStyle.height !== this._gameFrame.style.height || this._cachedContainerStyle.width !== this._gameContainer.style.width || this._cachedContainerStyle.height !== this._gameContainer.style.height)) {
            this.emit('window-resize', this.windowSize.width, this.windowSize.height);
            this._cachedFrameStyle.width = this._gameFrame.style.width;
            this._cachedFrameStyle.height = this._gameFrame.style.height;
            this._cachedContainerStyle.width = this._gameContainer.style.width;
            this._cachedContainerStyle.height = this._gameContainer.style.height;
          }
        };
        _createClass(ScreenAdapter, [{
          key: "supportFullScreen",
          get: function get() {
            return this._supportFullScreen;
          }
        }, {
          key: "isFullScreen",
          get: function get() {
            if (!this._supportFullScreen) {
              return false;
            }
            return !!document[this._fn.fullscreenElement];
          }
        }, {
          key: "devicePixelRatio",
          get: function get() {
            var _window$devicePixelRa;
            return Math.min((_window$devicePixelRa = window.devicePixelRatio) !== null && _window$devicePixelRa !== void 0 ? _window$devicePixelRa : 1, 2);
          }
        }, {
          key: "windowSize",
          get: function get() {
            var result = this._windowSizeInCssPixels;
            var dpr = this.devicePixelRatio;
            result.width *= dpr;
            result.height *= dpr;
            return result;
          },
          set: function set(size) {
            if (this._windowType !== WindowType.SubFrame) {
              warnID(9202);
              return;
            }
            this._resizeFrame(this._convertToSizeInCssPixels(size));
          }
        }, {
          key: "resolution",
          get: function get() {
            var windowSize = this.windowSize;
            var resolutionScale = this.resolutionScale;
            return new Size$1(windowSize.width * resolutionScale, windowSize.height * resolutionScale);
          }
        }, {
          key: "resolutionScale",
          get: function get() {
            return this._resolutionScale;
          },
          set: function set(v) {
            var _this$_cbToUpdateFram;
            if (v === this._resolutionScale) {
              return;
            }
            this._resolutionScale = v;
            (_this$_cbToUpdateFram = this._cbToUpdateFrameBuffer) === null || _this$_cbToUpdateFram === void 0 ? void 0 : _this$_cbToUpdateFram.call(this);
          }
        }, {
          key: "orientation",
          get: function get() {
            return this._orientation;
          },
          set: function set(value) {
            if (this._orientation === value) {
              return;
            }
            this._orientation = value;
            this._updateFrame();
          }
        }, {
          key: "safeAreaEdge",
          get: function get() {
            var dpr = this.devicePixelRatio;
            var _top = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-top') || '0') * dpr;
            var _bottom = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-bottom') || '0') * dpr;
            var _left = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-left') || '0') * dpr;
            var _right = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-right') || '0') * dpr;
            return {
              top: _top,
              bottom: _bottom,
              left: _left,
              right: _right
            };
          }
        }, {
          key: "isProportionalToFrame",
          get: function get() {
            return this._isProportionalToFrame;
          },
          set: function set(v) {
            if (this._isProportionalToFrame === v) {
              return;
            }
            this._isProportionalToFrame = v;
            this._updateContainer();
          }
        }, {
          key: "_windowSizeInCssPixels",
          get: function get() {
            if (this.isProportionalToFrame) {
              if (!this._gameContainer) {
                warnID(9201);
                return new Size$1(0, 0);
              }
              return new Size$1(this._gameContainer.clientWidth, this._gameContainer.clientHeight);
            }
            var fullscreenTarget;
            var width;
            var height;
            switch (this._windowType) {
              case WindowType.SubFrame:
                if (!this._gameFrame) {
                  warnID(9201);
                  return new Size$1(0, 0);
                }
                return new Size$1(this._gameFrame.clientWidth, this._gameFrame.clientHeight);
              case WindowType.Fullscreen:
                fullscreenTarget = this._getFullscreenTarget();
                width = this.isFrameRotated ? fullscreenTarget.clientHeight : fullscreenTarget.clientWidth;
                height = this.isFrameRotated ? fullscreenTarget.clientWidth : fullscreenTarget.clientHeight;
                return new Size$1(width, height);
              case WindowType.BrowserWindow:
                width = this.isFrameRotated ? window.innerHeight : window.innerWidth;
                height = this.isFrameRotated ? window.innerWidth : window.innerHeight;
                return new Size$1(width, height);
              case WindowType.Unknown:
              default:
                return new Size$1(0, 0);
            }
          }
        }, {
          key: "_windowType",
          get: function get() {
            if (this._isHeadlessMode) {
              return WindowType.Unknown;
            }
            if (this.isFullScreen) {
              return WindowType.Fullscreen;
            }
            if (!this._gameFrame) {
              warnID(9201);
              return WindowType.Unknown;
            }
            if (this._exactFitScreen) {
              return WindowType.BrowserWindow;
            }
            return WindowType.SubFrame;
          }
        }]);
        return ScreenAdapter;
      }(EventTarget);
      var screenAdapter = new ScreenAdapter();

      var Screen = function () {
        function Screen() {}
        var _proto = Screen.prototype;
        _proto.init = function init() {
          var _settings$querySettin, _settings$querySettin2;
          var exactFitScreen = (_settings$querySettin = settings.querySettings(Settings.Category.SCREEN, 'exactFitScreen')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : true;
          var orientation = (_settings$querySettin2 = settings.querySettings(Settings.Category.SCREEN, 'orientation')) !== null && _settings$querySettin2 !== void 0 ? _settings$querySettin2 : 'auto';
          var isHeadlessMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode') === 3;
          screenAdapter.init({
            exactFitScreen: exactFitScreen,
            configOrientation: orientation,
            isHeadlessMode: isHeadlessMode
          }, function () {
            var _director$root;
            var director = legacyCC.director;
            if (!((_director$root = director.root) !== null && _director$root !== void 0 && _director$root.pipeline)) {
              warnID(1220);
              return;
            }
            director.root.pipeline.shadingScale = screenAdapter.resolutionScale;
          });
        };
        _proto.fullScreen = function fullScreen() {
          return screenAdapter.isFullScreen;
        };
        _proto.requestFullScreen = function requestFullScreen(element, onFullScreenChange, onFullScreenError) {
          if (arguments.length > 0) {
            warnID(1400, 'screen.requestFullScreen(element, onFullScreenChange?, onFullScreenError?)', 'screen.requestFullScreen(): Promise');
          }
          return screenAdapter.requestFullScreen().then(function () {
            onFullScreenChange === null || onFullScreenChange === void 0 ? void 0 : onFullScreenChange.call(document);
          })["catch"](function (err) {
            error(err);
            onFullScreenError === null || onFullScreenError === void 0 ? void 0 : onFullScreenError.call(document);
          });
        };
        _proto.exitFullScreen = function exitFullScreen() {
          return screenAdapter.exitFullScreen();
        };
        _proto.autoFullScreen = function autoFullScreen(element, onFullScreenChange) {
          var _this$requestFullScre;
          (_this$requestFullScre = this.requestFullScreen(element, onFullScreenChange)) === null || _this$requestFullScre === void 0 ? void 0 : _this$requestFullScre["catch"](function (e) {
            warn(e);
          });
        };
        _proto.disableAutoFullScreen = function disableAutoFullScreen(element) {};
        _proto.on = function on(type, callback, target) {
          screenAdapter.on(type, callback, target);
        };
        _proto.once = function once(type, callback, target) {
          screenAdapter.once(type, callback, target);
        };
        _proto.off = function off(type, callback, target) {
          screenAdapter.off(type, callback, target);
        };
        _createClass(Screen, [{
          key: "devicePixelRatio",
          get: function get() {
            return screenAdapter.devicePixelRatio;
          }
        }, {
          key: "windowSize",
          get: function get() {
            return screenAdapter.windowSize;
          },
          set: function set(size) {
            screenAdapter.windowSize = size;
          }
        }, {
          key: "resolution",
          get: function get() {
            return screenAdapter.resolution;
          }
        }, {
          key: "supportsFullScreen",
          get: function get() {
            return screenAdapter.supportFullScreen;
          }
        }]);
        return Screen;
      }();
      var screen$1 = exports('cj', new Screen());
      legacyCC.screen = screen$1;

      var sys = exports('ck', {
        Feature: Feature$1,
        hasFeature: function hasFeature(feature) {
          return systemInfo.hasFeature(feature);
        },
        NetworkType: NetworkType,
        Language: Language,
        OS: OS,
        Platform: Platform,
        BrowserType: BrowserType,
        isNative: systemInfo.isNative,
        isBrowser: systemInfo.isBrowser,
        isMobile: systemInfo.isMobile,
        isLittleEndian: systemInfo.isLittleEndian,
        platform: systemInfo.platform,
        language: systemInfo.language,
        languageCode: systemInfo.nativeLanguage,
        os: systemInfo.os,
        osVersion: systemInfo.osVersion,
        osMainVersion: systemInfo.osMainVersion,
        browserType: systemInfo.browserType,
        browserVersion: systemInfo.browserVersion,
        isXR: systemInfo.isXR,
        windowPixelResolution: screen$1.windowSize,
        capabilities: {
          canvas: true,
          opengl: true,
          webp: systemInfo.hasFeature(Feature$1.WEBP),
          imageBitmap: systemInfo.hasFeature(Feature$1.IMAGE_BITMAP),
          touches: systemInfo.hasFeature(Feature$1.INPUT_TOUCH),
          mouse: systemInfo.hasFeature(Feature$1.EVENT_MOUSE),
          keyboard: systemInfo.hasFeature(Feature$1.EVENT_KEYBOARD),
          accelerometer: systemInfo.hasFeature(Feature$1.EVENT_ACCELEROMETER)
        },
        localStorage: {},
        getNetworkType: function getNetworkType() {
          return systemInfo.networkType;
        },
        getBatteryLevel: function getBatteryLevel() {
          return systemInfo.getBatteryLevel();
        },
        garbageCollect: function garbageCollect() {
          systemInfo.triggerGC();
        },
        isObjectValid: function isObjectValid(obj) {
          if (obj === null || obj === undefined) {
            return false;
          }
          return true;
        },
        __isWebIOS14OrIPadOS14Env: false,
        dump: function dump() {
          var str = '';
          str += "isMobile : " + this.isMobile + "\r\n";
          str += "language : " + this.language + "\r\n";
          str += "browserType : " + this.browserType + "\r\n";
          str += "browserVersion : " + this.browserVersion + "\r\n";
          str += "supports webp: " + sys.hasFeature(Feature$1.WEBP) + "\r\n";
          str += "supports bitmap: " + sys.hasFeature(Feature$1.IMAGE_BITMAP) + "\r\n";
          str += "supports touches: " + sys.hasFeature(Feature$1.INPUT_TOUCH) + "\r\n";
          str += "supports mouse: " + sys.hasFeature(Feature$1.EVENT_MOUSE) + "\r\n";
          str += "supports keyboard: " + sys.hasFeature(Feature$1.EVENT_KEYBOARD) + "\r\n";
          str += "supports accelerometer: " + sys.hasFeature(Feature$1.EVENT_ACCELEROMETER) + "\r\n";
          str += "os : " + this.os + "\r\n";
          str += "osVersion : " + this.osVersion + "\r\n";
          str += "platform : " + this.platform + "\r\n";
          str += "Using " + (legacyCC.game.renderType === legacyCC.game.RENDER_TYPE_WEBGL ? 'WEBGL' : 'CANVAS') + " renderer.\r\n";
          log(str);
        },
        openURL: function openURL(url) {
          systemInfo.openURL(url);
        },
        init: function init() {
          var _this = this;
          return Promise.resolve().then(function () {
            return systemInfo.init();
          }).then(function () {
            try {
              var localStorage = sys.localStorage = window.localStorage;
              localStorage.setItem('storage', '');
              localStorage.removeItem('storage');
              localStorage = null;
            } catch (e) {
              var warn = function warn() {
                warnID(5200);
              };
              _this.localStorage = {
                getItem: warn,
                setItem: warn,
                clear: warn,
                removeItem: warn,
                key: warn,
                length: 0
              };
            }
            {
              _this.__isWebIOS14OrIPadOS14Env = (sys.os === OS.IOS || sys.os === OS.OSX) && systemInfo.isBrowser && /(OS 14)|(Version\/14)/.test(window.navigator.userAgent);
            }
          });
        },
        now: function now() {
          return systemInfo.now();
        },
        restartVM: function restartVM() {
          systemInfo.restartJSVM();
        },
        getSafeAreaRect: function getSafeAreaRect() {
          var locView = legacyCC.view;
          var edge = screenAdapter.safeAreaEdge;
          var windowSize = screenAdapter.windowSize;
          var leftBottom = new Vec2(edge.left, edge.bottom);
          var rightTop = new Vec2(windowSize.width - edge.right, windowSize.height - edge.top);
          locView._convertToUISpace(leftBottom);
          locView._convertToUISpace(rightTop);
          var x = leftBottom.x;
          var y = leftBottom.y;
          var width = rightTop.x - leftBottom.x;
          var height = rightTop.y - leftBottom.y;
          return new Rect$1(x, y, width, height);
        }
      });
      legacyCC.sys = sys;

      markAsWarning(legacyCC, 'cc', [{
        name: 'winSize',
        suggest: 'please use view.getVisibleSize() instead.'
      }]);
      markAsWarning(sys, 'sys', [{
        name: 'capabilities',
        suggest: 'please use sys.hasFeature() method instead.'
      }]);
      replaceProperty(sys, 'sys', ['UNKNOWN', 'ENGLISH', 'CHINESE', 'FRENCH', 'ITALIAN', 'GERMAN', 'SPANISH', 'DUTCH', 'RUSSIAN', 'KOREAN', 'JAPANESE', 'HUNGARIAN', 'PORTUGUESE', 'ARABIC', 'NORWEGIAN', 'POLISH', 'TURKISH', 'UKRAINIAN', 'ROMANIAN', 'BULGARIAN'].map(function (item) {
        return {
          name: "LANGUAGE_" + item,
          newName: item,
          target: sys.Language,
          targetName: 'sys.Language'
        };
      }));
      replaceProperty(sys, 'sys', ['UNKNOWN', 'IOS', 'ANDROID', 'WINDOWS', 'LINUX', 'OSX'].map(function (item) {
        return {
          name: "OS_" + item,
          newName: item,
          target: sys.OS,
          targetName: 'sys.OS'
        };
      }));
      replaceProperty(sys, 'sys', ['UNKNOWN', 'WECHAT', 'ANDROID', 'IE', 'EDGE', 'QQ', 'MOBILE_QQ', 'UC', 'UCBS', 'BAIDU_APP', 'BAIDU', 'MAXTHON', 'OPERA', 'OUPENG', 'MIUI', 'FIREFOX', 'SAFARI', 'CHROME', 'LIEBAO', 'QZONE', 'SOUGOU', 'HUAWEI'].map(function (item) {
        return {
          name: "BROWSER_TYPE_" + item,
          newName: item,
          target: sys.BrowserType,
          targetName: 'sys.BrowserType'
        };
      }));
      replaceProperty(sys, 'sys', [{
        name: 'BROWSER_TYPE_360',
        newName: 'BROWSER_360',
        target: sys.BrowserType,
        targetName: 'sys.BrowserType'
      }]);
      replaceProperty(sys, 'sys', ['UNKNOWN', 'EDITOR_PAGE', 'EDITOR_CORE', 'MOBILE_BROWSER', 'DESKTOP_BROWSER', 'WIN32', 'MACOS', 'IOS', 'ANDROID', 'OHOS', 'WECHAT_GAME', 'BAIDU_MINI_GAME', 'XIAOMI_QUICK_GAME', 'ALIPAY_MINI_GAME', 'BYTEDANCE_MINI_GAME', 'OPPO_MINI_GAME', 'VIVO_MINI_GAME', 'HUAWEI_QUICK_GAME', 'COCOSPLAY', 'LINKSURE_MINI_GAME', 'QTT_MINI_GAME'].map(function (item) {
        return {
          name: item,
          target: sys.Platform,
          targetName: 'sys.Platform'
        };
      }));
      replaceProperty(sys, 'sys', [{
        name: 'IPHONE',
        newName: 'IOS',
        target: sys.Platform,
        targetName: 'sys.Platform'
      }, {
        name: 'IPAD',
        newName: 'IOS',
        target: sys.Platform,
        targetName: 'sys.Platform'
      }]);
      removeProperty(sys, 'sys', ['LINUX', 'BLACKBERRY', 'NACL', 'EMSCRIPTEN', 'TIZEN', 'WINRT', 'WP8', 'QQ_PLAY', 'FB_PLAYABLE_ADS'].map(function (item) {
        return {
          name: item
        };
      }));
      replaceProperty(sys, 'sys', [{
        name: 'windowPixelResolution',
        target: screen$1,
        targetName: 'screen',
        newName: 'windowSize'
      }]);
      markAsWarning(screen$1, 'screen', [{
        name: 'autoFullScreen',
        suggest: 'please use screen.requestFullScreen() instead.'
      }, {
        name: 'disableAutoFullScreen'
      }]);

      var visibleRect = exports('cm', {
        topLeft: legacyCC.v2(0, 0),
        topRight: legacyCC.v2(0, 0),
        top: legacyCC.v2(0, 0),
        bottomLeft: legacyCC.v2(0, 0),
        bottomRight: legacyCC.v2(0, 0),
        bottom: legacyCC.v2(0, 0),
        center: legacyCC.v2(0, 0),
        left: legacyCC.v2(0, 0),
        right: legacyCC.v2(0, 0),
        width: 0,
        height: 0,
        init: function init(visibleRect_) {
          var w = this.width = visibleRect_.width;
          var h = this.height = visibleRect_.height;
          var l = visibleRect_.x;
          var b = visibleRect_.y;
          var t = b + h;
          var r = l + w;
          this.topLeft.x = l;
          this.topLeft.y = t;
          this.topRight.x = r;
          this.topRight.y = t;
          this.top.x = l + w / 2;
          this.top.y = t;
          this.bottomLeft.x = l;
          this.bottomLeft.y = b;
          this.bottomRight.x = r;
          this.bottomRight.y = b;
          this.bottom.x = l + w / 2;
          this.bottom.y = b;
          this.center.x = l + w / 2;
          this.center.y = b + h / 2;
          this.left.x = l;
          this.left.y = b + h / 2;
          this.right.x = r;
          this.right.y = b + h / 2;
        }
      });
      legacyCC.visibleRect = visibleRect;

      var getUint8ForString = String.prototype.charCodeAt;
      function getUint8ForArray(idx) {
        return this[idx];
      }
      function murmurhash2_32_gc(input, seed) {
        var l = input.length;
        var h = seed ^ l;
        var i = 0;
        var getUint8 = typeof input === 'string' ? getUint8ForString : getUint8ForArray;
        while (l >= 4) {
          var k = getUint8.call(input, i) & 0xff | (getUint8.call(input, ++i) & 0xff) << 8 | (getUint8.call(input, ++i) & 0xff) << 16 | (getUint8.call(input, ++i) & 0xff) << 24;
          k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
          k ^= k >>> 24;
          k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
          h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k;
          l -= 4;
          ++i;
        }
        switch (l) {
          case 3:
            h ^= (getUint8.call(input, i + 2) & 0xff) << 16;
          case 2:
            h ^= (getUint8.call(input, i + 1) & 0xff) << 8;
          case 1:
            h ^= getUint8.call(input, i) & 0xff;
            h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
            break;
        }
        h ^= h >>> 13;
        h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
        h ^= h >>> 15;
        return h >>> 0;
      }

      legacyCC.easing = easing;

      function syncNodeValues(node) {
        var lpos = node._lpos;
        node.setPositionForJS(lpos.x, lpos.y, lpos.z);
        var lscale = node._lscale;
        node.setScaleForJS(lscale.x, lscale.y, lscale.z);
        var lrot = node._lrot;
        node.setRotationForJS(lrot.x, lrot.y, lrot.z, lrot.w);
        var euler = node._euler;
        node.setRotationFromEulerForJS(euler.x, euler.y, euler.z);
      }
      function updateChildrenForDeserialize(node) {
        if (!node) {
          return;
        }
        var children = node.children;
        if (!children) {
          return;
        }
        var len = children.length;
        if (!len) {
          return;
        }
        node._setChildren(children);
        for (var i = 0; i < len; ++i) {
          var child = children[i];
          updateChildrenForDeserialize(child);
        }
      }
      function ExtraEventMethods() {}
      ExtraEventMethods.prototype.once = function once(type, callback, target) {
        return this.on(type, callback, target, true);
      };
      ExtraEventMethods.prototype.targetOff = function targetOff(typeOrTarget) {
        this.removeAll(typeOrTarget);
      };

      var jsbUtils = /*#__PURE__*/Object.freeze({
        __proto__: null,
        syncNodeValues: syncNodeValues,
        updateChildrenForDeserialize: updateChildrenForDeserialize,
        ExtraEventMethods: ExtraEventMethods
      });
      exports('cF', jsbUtils);

      function shift(array, first, last) {
        assertsArrayIndex(array, first);
        assertsArrayIndex(array, last);
        if (first === last) {
          return array;
        }
        var element = array[first];
        if (first < last) {
          for (var iElement = first + 1; iElement <= last; ++iElement) {
            array[iElement - 1] = array[iElement];
          }
        } else {
          for (var _iElement = first; _iElement !== last; --_iElement) {
            array[_iElement] = array[_iElement - 1];
          }
        }
        array[last] = element;
        return array;
      }

      var GarbageCollectionManager = function () {
        function GarbageCollectionManager() {
          this._finalizationRegistry = null;
          this._gcObjects = new WeakMap();
        }
        var _proto = GarbageCollectionManager.prototype;
        _proto.registerGCObject = function registerGCObject(gcObject) {
          {
            return gcObject;
          }
        };
        _proto.init = function init() {};
        _proto.finalizationRegistryCallback = function finalizationRegistryCallback(token) {
          var gcObject = this._gcObjects.get(token);
          if (gcObject) {
            this._gcObjects["delete"](token);
            gcObject.destroy();
          }
          this._finalizationRegistry.unregister(token);
        };
        _proto.destroy = function destroy() {};
        return GarbageCollectionManager;
      }();
      var garbageCollectionManager = exports('cT', new GarbageCollectionManager());

      var GCObject = exports('cU', function () {
        function GCObject() {
          return garbageCollectionManager.registerGCObject(this);
        }
        var _proto = GCObject.prototype;
        _proto.destroy = function destroy() {};
        return GCObject;
      }());

      function deepFlatten(strList, array) {
        for (var _iterator = _createForOfIteratorHelperLoose(array), _step; !(_step = _iterator()).done;) {
          var item = _step.value;
          if (Array.isArray(item)) {
            deepFlatten(strList, item);
          } else {
            strList.push(item);
          }
        }
      }
      function flattenCodeArray(array) {
        var separator = '';
        var strList = [];
        deepFlatten(strList, array);
        return strList.join(separator);
      }

      function applyMixins(derivedCtor, baseCtors) {
        baseCtors.forEach(function (baseCtor) {
          Object.getOwnPropertyNames(baseCtor.prototype).forEach(function (name) {
            if (name !== 'constructor') {
              Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
            }
          });
        });
      }

      legacyCC.math = math;
      legacyCC.geometry = geometry;

      var deepCopy = function deepCopy(target, source, Ctor) {
        for (var i = 0; i < source.length; ++i) {
          if (target.length <= i) target.push(new Ctor());
          target[i].copy(source[i]);
        }
        target.length = source.length;
      };
      var ObjectType;
      (function (ObjectType) {
        ObjectType[ObjectType["UNKNOWN"] = 0] = "UNKNOWN";
        ObjectType[ObjectType["SWAPCHAIN"] = 1] = "SWAPCHAIN";
        ObjectType[ObjectType["BUFFER"] = 2] = "BUFFER";
        ObjectType[ObjectType["TEXTURE"] = 3] = "TEXTURE";
        ObjectType[ObjectType["RENDER_PASS"] = 4] = "RENDER_PASS";
        ObjectType[ObjectType["FRAMEBUFFER"] = 5] = "FRAMEBUFFER";
        ObjectType[ObjectType["SAMPLER"] = 6] = "SAMPLER";
        ObjectType[ObjectType["SHADER"] = 7] = "SHADER";
        ObjectType[ObjectType["DESCRIPTOR_SET_LAYOUT"] = 8] = "DESCRIPTOR_SET_LAYOUT";
        ObjectType[ObjectType["PIPELINE_LAYOUT"] = 9] = "PIPELINE_LAYOUT";
        ObjectType[ObjectType["PIPELINE_STATE"] = 10] = "PIPELINE_STATE";
        ObjectType[ObjectType["DESCRIPTOR_SET"] = 11] = "DESCRIPTOR_SET";
        ObjectType[ObjectType["INPUT_ASSEMBLER"] = 12] = "INPUT_ASSEMBLER";
        ObjectType[ObjectType["COMMAND_BUFFER"] = 13] = "COMMAND_BUFFER";
        ObjectType[ObjectType["QUEUE"] = 14] = "QUEUE";
        ObjectType[ObjectType["QUERY_POOL"] = 15] = "QUERY_POOL";
        ObjectType[ObjectType["GLOBAL_BARRIER"] = 16] = "GLOBAL_BARRIER";
        ObjectType[ObjectType["TEXTURE_BARRIER"] = 17] = "TEXTURE_BARRIER";
        ObjectType[ObjectType["BUFFER_BARRIER"] = 18] = "BUFFER_BARRIER";
        ObjectType[ObjectType["COUNT"] = 19] = "COUNT";
      })(ObjectType || (ObjectType = {}));
      var Status;
      (function (Status) {
        Status[Status["UNREADY"] = 0] = "UNREADY";
        Status[Status["FAILED"] = 1] = "FAILED";
        Status[Status["SUCCESS"] = 2] = "SUCCESS";
      })(Status || (Status = {}));
      var API;
      (function (API) {
        API[API["UNKNOWN"] = 0] = "UNKNOWN";
        API[API["GLES2"] = 1] = "GLES2";
        API[API["GLES3"] = 2] = "GLES3";
        API[API["METAL"] = 3] = "METAL";
        API[API["VULKAN"] = 4] = "VULKAN";
        API[API["NVN"] = 5] = "NVN";
        API[API["WEBGL"] = 6] = "WEBGL";
        API[API["WEBGL2"] = 7] = "WEBGL2";
        API[API["WEBGPU"] = 8] = "WEBGPU";
      })(API || (API = {}));
      var SurfaceTransform;
      (function (SurfaceTransform) {
        SurfaceTransform[SurfaceTransform["IDENTITY"] = 0] = "IDENTITY";
        SurfaceTransform[SurfaceTransform["ROTATE_90"] = 1] = "ROTATE_90";
        SurfaceTransform[SurfaceTransform["ROTATE_180"] = 2] = "ROTATE_180";
        SurfaceTransform[SurfaceTransform["ROTATE_270"] = 3] = "ROTATE_270";
      })(SurfaceTransform || (SurfaceTransform = {}));
      var Feature;
      (function (Feature) {
        Feature[Feature["ELEMENT_INDEX_UINT"] = 0] = "ELEMENT_INDEX_UINT";
        Feature[Feature["INSTANCED_ARRAYS"] = 1] = "INSTANCED_ARRAYS";
        Feature[Feature["MULTIPLE_RENDER_TARGETS"] = 2] = "MULTIPLE_RENDER_TARGETS";
        Feature[Feature["BLEND_MINMAX"] = 3] = "BLEND_MINMAX";
        Feature[Feature["COMPUTE_SHADER"] = 4] = "COMPUTE_SHADER";
        Feature[Feature["INPUT_ATTACHMENT_BENEFIT"] = 5] = "INPUT_ATTACHMENT_BENEFIT";
        Feature[Feature["SUBPASS_COLOR_INPUT"] = 6] = "SUBPASS_COLOR_INPUT";
        Feature[Feature["SUBPASS_DEPTH_STENCIL_INPUT"] = 7] = "SUBPASS_DEPTH_STENCIL_INPUT";
        Feature[Feature["RASTERIZATION_ORDER_COHERENT"] = 8] = "RASTERIZATION_ORDER_COHERENT";
        Feature[Feature["MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL"] = 9] = "MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL";
        Feature[Feature["COUNT"] = 10] = "COUNT";
      })(Feature || (Feature = {}));
      var Format;
      (function (Format) {
        Format[Format["UNKNOWN"] = 0] = "UNKNOWN";
        Format[Format["A8"] = 1] = "A8";
        Format[Format["L8"] = 2] = "L8";
        Format[Format["LA8"] = 3] = "LA8";
        Format[Format["R8"] = 4] = "R8";
        Format[Format["R8SN"] = 5] = "R8SN";
        Format[Format["R8UI"] = 6] = "R8UI";
        Format[Format["R8I"] = 7] = "R8I";
        Format[Format["R16F"] = 8] = "R16F";
        Format[Format["R16UI"] = 9] = "R16UI";
        Format[Format["R16I"] = 10] = "R16I";
        Format[Format["R32F"] = 11] = "R32F";
        Format[Format["R32UI"] = 12] = "R32UI";
        Format[Format["R32I"] = 13] = "R32I";
        Format[Format["RG8"] = 14] = "RG8";
        Format[Format["RG8SN"] = 15] = "RG8SN";
        Format[Format["RG8UI"] = 16] = "RG8UI";
        Format[Format["RG8I"] = 17] = "RG8I";
        Format[Format["RG16F"] = 18] = "RG16F";
        Format[Format["RG16UI"] = 19] = "RG16UI";
        Format[Format["RG16I"] = 20] = "RG16I";
        Format[Format["RG32F"] = 21] = "RG32F";
        Format[Format["RG32UI"] = 22] = "RG32UI";
        Format[Format["RG32I"] = 23] = "RG32I";
        Format[Format["RGB8"] = 24] = "RGB8";
        Format[Format["SRGB8"] = 25] = "SRGB8";
        Format[Format["RGB8SN"] = 26] = "RGB8SN";
        Format[Format["RGB8UI"] = 27] = "RGB8UI";
        Format[Format["RGB8I"] = 28] = "RGB8I";
        Format[Format["RGB16F"] = 29] = "RGB16F";
        Format[Format["RGB16UI"] = 30] = "RGB16UI";
        Format[Format["RGB16I"] = 31] = "RGB16I";
        Format[Format["RGB32F"] = 32] = "RGB32F";
        Format[Format["RGB32UI"] = 33] = "RGB32UI";
        Format[Format["RGB32I"] = 34] = "RGB32I";
        Format[Format["RGBA8"] = 35] = "RGBA8";
        Format[Format["BGRA8"] = 36] = "BGRA8";
        Format[Format["SRGB8_A8"] = 37] = "SRGB8_A8";
        Format[Format["RGBA8SN"] = 38] = "RGBA8SN";
        Format[Format["RGBA8UI"] = 39] = "RGBA8UI";
        Format[Format["RGBA8I"] = 40] = "RGBA8I";
        Format[Format["RGBA16F"] = 41] = "RGBA16F";
        Format[Format["RGBA16UI"] = 42] = "RGBA16UI";
        Format[Format["RGBA16I"] = 43] = "RGBA16I";
        Format[Format["RGBA32F"] = 44] = "RGBA32F";
        Format[Format["RGBA32UI"] = 45] = "RGBA32UI";
        Format[Format["RGBA32I"] = 46] = "RGBA32I";
        Format[Format["R5G6B5"] = 47] = "R5G6B5";
        Format[Format["R11G11B10F"] = 48] = "R11G11B10F";
        Format[Format["RGB5A1"] = 49] = "RGB5A1";
        Format[Format["RGBA4"] = 50] = "RGBA4";
        Format[Format["RGB10A2"] = 51] = "RGB10A2";
        Format[Format["RGB10A2UI"] = 52] = "RGB10A2UI";
        Format[Format["RGB9E5"] = 53] = "RGB9E5";
        Format[Format["DEPTH"] = 54] = "DEPTH";
        Format[Format["DEPTH_STENCIL"] = 55] = "DEPTH_STENCIL";
        Format[Format["BC1"] = 56] = "BC1";
        Format[Format["BC1_ALPHA"] = 57] = "BC1_ALPHA";
        Format[Format["BC1_SRGB"] = 58] = "BC1_SRGB";
        Format[Format["BC1_SRGB_ALPHA"] = 59] = "BC1_SRGB_ALPHA";
        Format[Format["BC2"] = 60] = "BC2";
        Format[Format["BC2_SRGB"] = 61] = "BC2_SRGB";
        Format[Format["BC3"] = 62] = "BC3";
        Format[Format["BC3_SRGB"] = 63] = "BC3_SRGB";
        Format[Format["BC4"] = 64] = "BC4";
        Format[Format["BC4_SNORM"] = 65] = "BC4_SNORM";
        Format[Format["BC5"] = 66] = "BC5";
        Format[Format["BC5_SNORM"] = 67] = "BC5_SNORM";
        Format[Format["BC6H_UF16"] = 68] = "BC6H_UF16";
        Format[Format["BC6H_SF16"] = 69] = "BC6H_SF16";
        Format[Format["BC7"] = 70] = "BC7";
        Format[Format["BC7_SRGB"] = 71] = "BC7_SRGB";
        Format[Format["ETC_RGB8"] = 72] = "ETC_RGB8";
        Format[Format["ETC2_RGB8"] = 73] = "ETC2_RGB8";
        Format[Format["ETC2_SRGB8"] = 74] = "ETC2_SRGB8";
        Format[Format["ETC2_RGB8_A1"] = 75] = "ETC2_RGB8_A1";
        Format[Format["ETC2_SRGB8_A1"] = 76] = "ETC2_SRGB8_A1";
        Format[Format["ETC2_RGBA8"] = 77] = "ETC2_RGBA8";
        Format[Format["ETC2_SRGB8_A8"] = 78] = "ETC2_SRGB8_A8";
        Format[Format["EAC_R11"] = 79] = "EAC_R11";
        Format[Format["EAC_R11SN"] = 80] = "EAC_R11SN";
        Format[Format["EAC_RG11"] = 81] = "EAC_RG11";
        Format[Format["EAC_RG11SN"] = 82] = "EAC_RG11SN";
        Format[Format["PVRTC_RGB2"] = 83] = "PVRTC_RGB2";
        Format[Format["PVRTC_RGBA2"] = 84] = "PVRTC_RGBA2";
        Format[Format["PVRTC_RGB4"] = 85] = "PVRTC_RGB4";
        Format[Format["PVRTC_RGBA4"] = 86] = "PVRTC_RGBA4";
        Format[Format["PVRTC2_2BPP"] = 87] = "PVRTC2_2BPP";
        Format[Format["PVRTC2_4BPP"] = 88] = "PVRTC2_4BPP";
        Format[Format["ASTC_RGBA_4X4"] = 89] = "ASTC_RGBA_4X4";
        Format[Format["ASTC_RGBA_5X4"] = 90] = "ASTC_RGBA_5X4";
        Format[Format["ASTC_RGBA_5X5"] = 91] = "ASTC_RGBA_5X5";
        Format[Format["ASTC_RGBA_6X5"] = 92] = "ASTC_RGBA_6X5";
        Format[Format["ASTC_RGBA_6X6"] = 93] = "ASTC_RGBA_6X6";
        Format[Format["ASTC_RGBA_8X5"] = 94] = "ASTC_RGBA_8X5";
        Format[Format["ASTC_RGBA_8X6"] = 95] = "ASTC_RGBA_8X6";
        Format[Format["ASTC_RGBA_8X8"] = 96] = "ASTC_RGBA_8X8";
        Format[Format["ASTC_RGBA_10X5"] = 97] = "ASTC_RGBA_10X5";
        Format[Format["ASTC_RGBA_10X6"] = 98] = "ASTC_RGBA_10X6";
        Format[Format["ASTC_RGBA_10X8"] = 99] = "ASTC_RGBA_10X8";
        Format[Format["ASTC_RGBA_10X10"] = 100] = "ASTC_RGBA_10X10";
        Format[Format["ASTC_RGBA_12X10"] = 101] = "ASTC_RGBA_12X10";
        Format[Format["ASTC_RGBA_12X12"] = 102] = "ASTC_RGBA_12X12";
        Format[Format["ASTC_SRGBA_4X4"] = 103] = "ASTC_SRGBA_4X4";
        Format[Format["ASTC_SRGBA_5X4"] = 104] = "ASTC_SRGBA_5X4";
        Format[Format["ASTC_SRGBA_5X5"] = 105] = "ASTC_SRGBA_5X5";
        Format[Format["ASTC_SRGBA_6X5"] = 106] = "ASTC_SRGBA_6X5";
        Format[Format["ASTC_SRGBA_6X6"] = 107] = "ASTC_SRGBA_6X6";
        Format[Format["ASTC_SRGBA_8X5"] = 108] = "ASTC_SRGBA_8X5";
        Format[Format["ASTC_SRGBA_8X6"] = 109] = "ASTC_SRGBA_8X6";
        Format[Format["ASTC_SRGBA_8X8"] = 110] = "ASTC_SRGBA_8X8";
        Format[Format["ASTC_SRGBA_10X5"] = 111] = "ASTC_SRGBA_10X5";
        Format[Format["ASTC_SRGBA_10X6"] = 112] = "ASTC_SRGBA_10X6";
        Format[Format["ASTC_SRGBA_10X8"] = 113] = "ASTC_SRGBA_10X8";
        Format[Format["ASTC_SRGBA_10X10"] = 114] = "ASTC_SRGBA_10X10";
        Format[Format["ASTC_SRGBA_12X10"] = 115] = "ASTC_SRGBA_12X10";
        Format[Format["ASTC_SRGBA_12X12"] = 116] = "ASTC_SRGBA_12X12";
        Format[Format["COUNT"] = 117] = "COUNT";
      })(Format || (Format = {}));
      var FormatType;
      (function (FormatType) {
        FormatType[FormatType["NONE"] = 0] = "NONE";
        FormatType[FormatType["UNORM"] = 1] = "UNORM";
        FormatType[FormatType["SNORM"] = 2] = "SNORM";
        FormatType[FormatType["UINT"] = 3] = "UINT";
        FormatType[FormatType["INT"] = 4] = "INT";
        FormatType[FormatType["UFLOAT"] = 5] = "UFLOAT";
        FormatType[FormatType["FLOAT"] = 6] = "FLOAT";
      })(FormatType || (FormatType = {}));
      var Type$1;
      (function (Type) {
        Type[Type["UNKNOWN"] = 0] = "UNKNOWN";
        Type[Type["BOOL"] = 1] = "BOOL";
        Type[Type["BOOL2"] = 2] = "BOOL2";
        Type[Type["BOOL3"] = 3] = "BOOL3";
        Type[Type["BOOL4"] = 4] = "BOOL4";
        Type[Type["INT"] = 5] = "INT";
        Type[Type["INT2"] = 6] = "INT2";
        Type[Type["INT3"] = 7] = "INT3";
        Type[Type["INT4"] = 8] = "INT4";
        Type[Type["UINT"] = 9] = "UINT";
        Type[Type["UINT2"] = 10] = "UINT2";
        Type[Type["UINT3"] = 11] = "UINT3";
        Type[Type["UINT4"] = 12] = "UINT4";
        Type[Type["FLOAT"] = 13] = "FLOAT";
        Type[Type["FLOAT2"] = 14] = "FLOAT2";
        Type[Type["FLOAT3"] = 15] = "FLOAT3";
        Type[Type["FLOAT4"] = 16] = "FLOAT4";
        Type[Type["MAT2"] = 17] = "MAT2";
        Type[Type["MAT2X3"] = 18] = "MAT2X3";
        Type[Type["MAT2X4"] = 19] = "MAT2X4";
        Type[Type["MAT3X2"] = 20] = "MAT3X2";
        Type[Type["MAT3"] = 21] = "MAT3";
        Type[Type["MAT3X4"] = 22] = "MAT3X4";
        Type[Type["MAT4X2"] = 23] = "MAT4X2";
        Type[Type["MAT4X3"] = 24] = "MAT4X3";
        Type[Type["MAT4"] = 25] = "MAT4";
        Type[Type["SAMPLER1D"] = 26] = "SAMPLER1D";
        Type[Type["SAMPLER1D_ARRAY"] = 27] = "SAMPLER1D_ARRAY";
        Type[Type["SAMPLER2D"] = 28] = "SAMPLER2D";
        Type[Type["SAMPLER2D_ARRAY"] = 29] = "SAMPLER2D_ARRAY";
        Type[Type["SAMPLER3D"] = 30] = "SAMPLER3D";
        Type[Type["SAMPLER_CUBE"] = 31] = "SAMPLER_CUBE";
        Type[Type["SAMPLER"] = 32] = "SAMPLER";
        Type[Type["TEXTURE1D"] = 33] = "TEXTURE1D";
        Type[Type["TEXTURE1D_ARRAY"] = 34] = "TEXTURE1D_ARRAY";
        Type[Type["TEXTURE2D"] = 35] = "TEXTURE2D";
        Type[Type["TEXTURE2D_ARRAY"] = 36] = "TEXTURE2D_ARRAY";
        Type[Type["TEXTURE3D"] = 37] = "TEXTURE3D";
        Type[Type["TEXTURE_CUBE"] = 38] = "TEXTURE_CUBE";
        Type[Type["IMAGE1D"] = 39] = "IMAGE1D";
        Type[Type["IMAGE1D_ARRAY"] = 40] = "IMAGE1D_ARRAY";
        Type[Type["IMAGE2D"] = 41] = "IMAGE2D";
        Type[Type["IMAGE2D_ARRAY"] = 42] = "IMAGE2D_ARRAY";
        Type[Type["IMAGE3D"] = 43] = "IMAGE3D";
        Type[Type["IMAGE_CUBE"] = 44] = "IMAGE_CUBE";
        Type[Type["SUBPASS_INPUT"] = 45] = "SUBPASS_INPUT";
        Type[Type["COUNT"] = 46] = "COUNT";
      })(Type$1 || (Type$1 = {}));
      var BufferUsageBit;
      (function (BufferUsageBit) {
        BufferUsageBit[BufferUsageBit["NONE"] = 0] = "NONE";
        BufferUsageBit[BufferUsageBit["TRANSFER_SRC"] = 1] = "TRANSFER_SRC";
        BufferUsageBit[BufferUsageBit["TRANSFER_DST"] = 2] = "TRANSFER_DST";
        BufferUsageBit[BufferUsageBit["INDEX"] = 4] = "INDEX";
        BufferUsageBit[BufferUsageBit["VERTEX"] = 8] = "VERTEX";
        BufferUsageBit[BufferUsageBit["UNIFORM"] = 16] = "UNIFORM";
        BufferUsageBit[BufferUsageBit["STORAGE"] = 32] = "STORAGE";
        BufferUsageBit[BufferUsageBit["INDIRECT"] = 64] = "INDIRECT";
      })(BufferUsageBit || (BufferUsageBit = {}));
      var BufferFlagBit;
      (function (BufferFlagBit) {
        BufferFlagBit[BufferFlagBit["NONE"] = 0] = "NONE";
      })(BufferFlagBit || (BufferFlagBit = {}));
      var MemoryAccessBit;
      (function (MemoryAccessBit) {
        MemoryAccessBit[MemoryAccessBit["NONE"] = 0] = "NONE";
        MemoryAccessBit[MemoryAccessBit["READ_ONLY"] = 1] = "READ_ONLY";
        MemoryAccessBit[MemoryAccessBit["WRITE_ONLY"] = 2] = "WRITE_ONLY";
        MemoryAccessBit[MemoryAccessBit["READ_WRITE"] = 3] = "READ_WRITE";
      })(MemoryAccessBit || (MemoryAccessBit = {}));
      var MemoryUsageBit;
      (function (MemoryUsageBit) {
        MemoryUsageBit[MemoryUsageBit["NONE"] = 0] = "NONE";
        MemoryUsageBit[MemoryUsageBit["DEVICE"] = 1] = "DEVICE";
        MemoryUsageBit[MemoryUsageBit["HOST"] = 2] = "HOST";
      })(MemoryUsageBit || (MemoryUsageBit = {}));
      var TextureType;
      (function (TextureType) {
        TextureType[TextureType["TEX1D"] = 0] = "TEX1D";
        TextureType[TextureType["TEX2D"] = 1] = "TEX2D";
        TextureType[TextureType["TEX3D"] = 2] = "TEX3D";
        TextureType[TextureType["CUBE"] = 3] = "CUBE";
        TextureType[TextureType["TEX1D_ARRAY"] = 4] = "TEX1D_ARRAY";
        TextureType[TextureType["TEX2D_ARRAY"] = 5] = "TEX2D_ARRAY";
      })(TextureType || (TextureType = {}));
      var TextureUsageBit;
      (function (TextureUsageBit) {
        TextureUsageBit[TextureUsageBit["NONE"] = 0] = "NONE";
        TextureUsageBit[TextureUsageBit["TRANSFER_SRC"] = 1] = "TRANSFER_SRC";
        TextureUsageBit[TextureUsageBit["TRANSFER_DST"] = 2] = "TRANSFER_DST";
        TextureUsageBit[TextureUsageBit["SAMPLED"] = 4] = "SAMPLED";
        TextureUsageBit[TextureUsageBit["STORAGE"] = 8] = "STORAGE";
        TextureUsageBit[TextureUsageBit["COLOR_ATTACHMENT"] = 16] = "COLOR_ATTACHMENT";
        TextureUsageBit[TextureUsageBit["DEPTH_STENCIL_ATTACHMENT"] = 32] = "DEPTH_STENCIL_ATTACHMENT";
        TextureUsageBit[TextureUsageBit["INPUT_ATTACHMENT"] = 64] = "INPUT_ATTACHMENT";
      })(TextureUsageBit || (TextureUsageBit = {}));
      var TextureFlagBit;
      (function (TextureFlagBit) {
        TextureFlagBit[TextureFlagBit["NONE"] = 0] = "NONE";
        TextureFlagBit[TextureFlagBit["GEN_MIPMAP"] = 1] = "GEN_MIPMAP";
        TextureFlagBit[TextureFlagBit["GENERAL_LAYOUT"] = 2] = "GENERAL_LAYOUT";
        TextureFlagBit[TextureFlagBit["EXTERNAL_OES"] = 4] = "EXTERNAL_OES";
        TextureFlagBit[TextureFlagBit["EXTERNAL_NORMAL"] = 8] = "EXTERNAL_NORMAL";
        TextureFlagBit[TextureFlagBit["LAZILY_ALLOCATED"] = 16] = "LAZILY_ALLOCATED";
        TextureFlagBit[TextureFlagBit["MUTABLE_VIEW_FORMAT"] = 64] = "MUTABLE_VIEW_FORMAT";
        TextureFlagBit[TextureFlagBit["MUTABLE_STORAGE"] = 128] = "MUTABLE_STORAGE";
      })(TextureFlagBit || (TextureFlagBit = {}));
      var FormatFeatureBit;
      (function (FormatFeatureBit) {
        FormatFeatureBit[FormatFeatureBit["NONE"] = 0] = "NONE";
        FormatFeatureBit[FormatFeatureBit["RENDER_TARGET"] = 1] = "RENDER_TARGET";
        FormatFeatureBit[FormatFeatureBit["SAMPLED_TEXTURE"] = 2] = "SAMPLED_TEXTURE";
        FormatFeatureBit[FormatFeatureBit["LINEAR_FILTER"] = 4] = "LINEAR_FILTER";
        FormatFeatureBit[FormatFeatureBit["STORAGE_TEXTURE"] = 8] = "STORAGE_TEXTURE";
        FormatFeatureBit[FormatFeatureBit["VERTEX_ATTRIBUTE"] = 16] = "VERTEX_ATTRIBUTE";
      })(FormatFeatureBit || (FormatFeatureBit = {}));
      var SampleCount;
      (function (SampleCount) {
        SampleCount[SampleCount["X1"] = 1] = "X1";
        SampleCount[SampleCount["X2"] = 2] = "X2";
        SampleCount[SampleCount["X4"] = 4] = "X4";
        SampleCount[SampleCount["X8"] = 8] = "X8";
        SampleCount[SampleCount["X16"] = 16] = "X16";
        SampleCount[SampleCount["X32"] = 32] = "X32";
        SampleCount[SampleCount["X64"] = 64] = "X64";
      })(SampleCount || (SampleCount = {}));
      var VsyncMode;
      (function (VsyncMode) {
        VsyncMode[VsyncMode["OFF"] = 0] = "OFF";
        VsyncMode[VsyncMode["ON"] = 1] = "ON";
        VsyncMode[VsyncMode["RELAXED"] = 2] = "RELAXED";
        VsyncMode[VsyncMode["MAILBOX"] = 3] = "MAILBOX";
        VsyncMode[VsyncMode["HALF"] = 4] = "HALF";
      })(VsyncMode || (VsyncMode = {}));
      var Filter$1;
      (function (Filter) {
        Filter[Filter["NONE"] = 0] = "NONE";
        Filter[Filter["POINT"] = 1] = "POINT";
        Filter[Filter["LINEAR"] = 2] = "LINEAR";
        Filter[Filter["ANISOTROPIC"] = 3] = "ANISOTROPIC";
      })(Filter$1 || (Filter$1 = {}));
      var Address;
      (function (Address) {
        Address[Address["WRAP"] = 0] = "WRAP";
        Address[Address["MIRROR"] = 1] = "MIRROR";
        Address[Address["CLAMP"] = 2] = "CLAMP";
        Address[Address["BORDER"] = 3] = "BORDER";
      })(Address || (Address = {}));
      var ComparisonFunc;
      (function (ComparisonFunc) {
        ComparisonFunc[ComparisonFunc["NEVER"] = 0] = "NEVER";
        ComparisonFunc[ComparisonFunc["LESS"] = 1] = "LESS";
        ComparisonFunc[ComparisonFunc["EQUAL"] = 2] = "EQUAL";
        ComparisonFunc[ComparisonFunc["LESS_EQUAL"] = 3] = "LESS_EQUAL";
        ComparisonFunc[ComparisonFunc["GREATER"] = 4] = "GREATER";
        ComparisonFunc[ComparisonFunc["NOT_EQUAL"] = 5] = "NOT_EQUAL";
        ComparisonFunc[ComparisonFunc["GREATER_EQUAL"] = 6] = "GREATER_EQUAL";
        ComparisonFunc[ComparisonFunc["ALWAYS"] = 7] = "ALWAYS";
      })(ComparisonFunc || (ComparisonFunc = {}));
      var StencilOp;
      (function (StencilOp) {
        StencilOp[StencilOp["ZERO"] = 0] = "ZERO";
        StencilOp[StencilOp["KEEP"] = 1] = "KEEP";
        StencilOp[StencilOp["REPLACE"] = 2] = "REPLACE";
        StencilOp[StencilOp["INCR"] = 3] = "INCR";
        StencilOp[StencilOp["DECR"] = 4] = "DECR";
        StencilOp[StencilOp["INVERT"] = 5] = "INVERT";
        StencilOp[StencilOp["INCR_WRAP"] = 6] = "INCR_WRAP";
        StencilOp[StencilOp["DECR_WRAP"] = 7] = "DECR_WRAP";
      })(StencilOp || (StencilOp = {}));
      var BlendFactor;
      (function (BlendFactor) {
        BlendFactor[BlendFactor["ZERO"] = 0] = "ZERO";
        BlendFactor[BlendFactor["ONE"] = 1] = "ONE";
        BlendFactor[BlendFactor["SRC_ALPHA"] = 2] = "SRC_ALPHA";
        BlendFactor[BlendFactor["DST_ALPHA"] = 3] = "DST_ALPHA";
        BlendFactor[BlendFactor["ONE_MINUS_SRC_ALPHA"] = 4] = "ONE_MINUS_SRC_ALPHA";
        BlendFactor[BlendFactor["ONE_MINUS_DST_ALPHA"] = 5] = "ONE_MINUS_DST_ALPHA";
        BlendFactor[BlendFactor["SRC_COLOR"] = 6] = "SRC_COLOR";
        BlendFactor[BlendFactor["DST_COLOR"] = 7] = "DST_COLOR";
        BlendFactor[BlendFactor["ONE_MINUS_SRC_COLOR"] = 8] = "ONE_MINUS_SRC_COLOR";
        BlendFactor[BlendFactor["ONE_MINUS_DST_COLOR"] = 9] = "ONE_MINUS_DST_COLOR";
        BlendFactor[BlendFactor["SRC_ALPHA_SATURATE"] = 10] = "SRC_ALPHA_SATURATE";
        BlendFactor[BlendFactor["CONSTANT_COLOR"] = 11] = "CONSTANT_COLOR";
        BlendFactor[BlendFactor["ONE_MINUS_CONSTANT_COLOR"] = 12] = "ONE_MINUS_CONSTANT_COLOR";
        BlendFactor[BlendFactor["CONSTANT_ALPHA"] = 13] = "CONSTANT_ALPHA";
        BlendFactor[BlendFactor["ONE_MINUS_CONSTANT_ALPHA"] = 14] = "ONE_MINUS_CONSTANT_ALPHA";
      })(BlendFactor || (BlendFactor = {}));
      var BlendOp;
      (function (BlendOp) {
        BlendOp[BlendOp["ADD"] = 0] = "ADD";
        BlendOp[BlendOp["SUB"] = 1] = "SUB";
        BlendOp[BlendOp["REV_SUB"] = 2] = "REV_SUB";
        BlendOp[BlendOp["MIN"] = 3] = "MIN";
        BlendOp[BlendOp["MAX"] = 4] = "MAX";
      })(BlendOp || (BlendOp = {}));
      var ColorMask;
      (function (ColorMask) {
        ColorMask[ColorMask["NONE"] = 0] = "NONE";
        ColorMask[ColorMask["R"] = 1] = "R";
        ColorMask[ColorMask["G"] = 2] = "G";
        ColorMask[ColorMask["B"] = 4] = "B";
        ColorMask[ColorMask["A"] = 8] = "A";
        ColorMask[ColorMask["ALL"] = 15] = "ALL";
      })(ColorMask || (ColorMask = {}));
      var ShaderStageFlagBit;
      (function (ShaderStageFlagBit) {
        ShaderStageFlagBit[ShaderStageFlagBit["NONE"] = 0] = "NONE";
        ShaderStageFlagBit[ShaderStageFlagBit["VERTEX"] = 1] = "VERTEX";
        ShaderStageFlagBit[ShaderStageFlagBit["CONTROL"] = 2] = "CONTROL";
        ShaderStageFlagBit[ShaderStageFlagBit["EVALUATION"] = 4] = "EVALUATION";
        ShaderStageFlagBit[ShaderStageFlagBit["GEOMETRY"] = 8] = "GEOMETRY";
        ShaderStageFlagBit[ShaderStageFlagBit["FRAGMENT"] = 16] = "FRAGMENT";
        ShaderStageFlagBit[ShaderStageFlagBit["COMPUTE"] = 32] = "COMPUTE";
        ShaderStageFlagBit[ShaderStageFlagBit["ALL"] = 63] = "ALL";
      })(ShaderStageFlagBit || (ShaderStageFlagBit = {}));
      var LoadOp;
      (function (LoadOp) {
        LoadOp[LoadOp["LOAD"] = 0] = "LOAD";
        LoadOp[LoadOp["CLEAR"] = 1] = "CLEAR";
        LoadOp[LoadOp["DISCARD"] = 2] = "DISCARD";
      })(LoadOp || (LoadOp = {}));
      var StoreOp;
      (function (StoreOp) {
        StoreOp[StoreOp["STORE"] = 0] = "STORE";
        StoreOp[StoreOp["DISCARD"] = 1] = "DISCARD";
      })(StoreOp || (StoreOp = {}));
      var AccessFlagBit;
      (function (AccessFlagBit) {
        AccessFlagBit[AccessFlagBit["NONE"] = 0] = "NONE";
        AccessFlagBit[AccessFlagBit["INDIRECT_BUFFER"] = 1] = "INDIRECT_BUFFER";
        AccessFlagBit[AccessFlagBit["INDEX_BUFFER"] = 2] = "INDEX_BUFFER";
        AccessFlagBit[AccessFlagBit["VERTEX_BUFFER"] = 4] = "VERTEX_BUFFER";
        AccessFlagBit[AccessFlagBit["VERTEX_SHADER_READ_UNIFORM_BUFFER"] = 8] = "VERTEX_SHADER_READ_UNIFORM_BUFFER";
        AccessFlagBit[AccessFlagBit["VERTEX_SHADER_READ_TEXTURE"] = 16] = "VERTEX_SHADER_READ_TEXTURE";
        AccessFlagBit[AccessFlagBit["VERTEX_SHADER_READ_OTHER"] = 32] = "VERTEX_SHADER_READ_OTHER";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_READ_UNIFORM_BUFFER"] = 64] = "FRAGMENT_SHADER_READ_UNIFORM_BUFFER";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_READ_TEXTURE"] = 128] = "FRAGMENT_SHADER_READ_TEXTURE";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT"] = 256] = "FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT"] = 512] = "FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_READ_OTHER"] = 1024] = "FRAGMENT_SHADER_READ_OTHER";
        AccessFlagBit[AccessFlagBit["COLOR_ATTACHMENT_READ"] = 2048] = "COLOR_ATTACHMENT_READ";
        AccessFlagBit[AccessFlagBit["DEPTH_STENCIL_ATTACHMENT_READ"] = 4096] = "DEPTH_STENCIL_ATTACHMENT_READ";
        AccessFlagBit[AccessFlagBit["COMPUTE_SHADER_READ_UNIFORM_BUFFER"] = 8192] = "COMPUTE_SHADER_READ_UNIFORM_BUFFER";
        AccessFlagBit[AccessFlagBit["COMPUTE_SHADER_READ_TEXTURE"] = 16384] = "COMPUTE_SHADER_READ_TEXTURE";
        AccessFlagBit[AccessFlagBit["COMPUTE_SHADER_READ_OTHER"] = 32768] = "COMPUTE_SHADER_READ_OTHER";
        AccessFlagBit[AccessFlagBit["TRANSFER_READ"] = 65536] = "TRANSFER_READ";
        AccessFlagBit[AccessFlagBit["HOST_READ"] = 131072] = "HOST_READ";
        AccessFlagBit[AccessFlagBit["PRESENT"] = 262144] = "PRESENT";
        AccessFlagBit[AccessFlagBit["VERTEX_SHADER_WRITE"] = 524288] = "VERTEX_SHADER_WRITE";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_WRITE"] = 1048576] = "FRAGMENT_SHADER_WRITE";
        AccessFlagBit[AccessFlagBit["COLOR_ATTACHMENT_WRITE"] = 2097152] = "COLOR_ATTACHMENT_WRITE";
        AccessFlagBit[AccessFlagBit["DEPTH_STENCIL_ATTACHMENT_WRITE"] = 4194304] = "DEPTH_STENCIL_ATTACHMENT_WRITE";
        AccessFlagBit[AccessFlagBit["COMPUTE_SHADER_WRITE"] = 8388608] = "COMPUTE_SHADER_WRITE";
        AccessFlagBit[AccessFlagBit["TRANSFER_WRITE"] = 16777216] = "TRANSFER_WRITE";
        AccessFlagBit[AccessFlagBit["HOST_PREINITIALIZED"] = 33554432] = "HOST_PREINITIALIZED";
        AccessFlagBit[AccessFlagBit["HOST_WRITE"] = 67108864] = "HOST_WRITE";
      })(AccessFlagBit || (AccessFlagBit = {}));
      var ResolveMode;
      (function (ResolveMode) {
        ResolveMode[ResolveMode["NONE"] = 0] = "NONE";
        ResolveMode[ResolveMode["SAMPLE_ZERO"] = 1] = "SAMPLE_ZERO";
        ResolveMode[ResolveMode["AVERAGE"] = 2] = "AVERAGE";
        ResolveMode[ResolveMode["MIN"] = 3] = "MIN";
        ResolveMode[ResolveMode["MAX"] = 4] = "MAX";
      })(ResolveMode || (ResolveMode = {}));
      var PipelineBindPoint;
      (function (PipelineBindPoint) {
        PipelineBindPoint[PipelineBindPoint["GRAPHICS"] = 0] = "GRAPHICS";
        PipelineBindPoint[PipelineBindPoint["COMPUTE"] = 1] = "COMPUTE";
        PipelineBindPoint[PipelineBindPoint["RAY_TRACING"] = 2] = "RAY_TRACING";
      })(PipelineBindPoint || (PipelineBindPoint = {}));
      var PrimitiveMode;
      (function (PrimitiveMode) {
        PrimitiveMode[PrimitiveMode["POINT_LIST"] = 0] = "POINT_LIST";
        PrimitiveMode[PrimitiveMode["LINE_LIST"] = 1] = "LINE_LIST";
        PrimitiveMode[PrimitiveMode["LINE_STRIP"] = 2] = "LINE_STRIP";
        PrimitiveMode[PrimitiveMode["LINE_LOOP"] = 3] = "LINE_LOOP";
        PrimitiveMode[PrimitiveMode["LINE_LIST_ADJACENCY"] = 4] = "LINE_LIST_ADJACENCY";
        PrimitiveMode[PrimitiveMode["LINE_STRIP_ADJACENCY"] = 5] = "LINE_STRIP_ADJACENCY";
        PrimitiveMode[PrimitiveMode["ISO_LINE_LIST"] = 6] = "ISO_LINE_LIST";
        PrimitiveMode[PrimitiveMode["TRIANGLE_LIST"] = 7] = "TRIANGLE_LIST";
        PrimitiveMode[PrimitiveMode["TRIANGLE_STRIP"] = 8] = "TRIANGLE_STRIP";
        PrimitiveMode[PrimitiveMode["TRIANGLE_FAN"] = 9] = "TRIANGLE_FAN";
        PrimitiveMode[PrimitiveMode["TRIANGLE_LIST_ADJACENCY"] = 10] = "TRIANGLE_LIST_ADJACENCY";
        PrimitiveMode[PrimitiveMode["TRIANGLE_STRIP_ADJACENCY"] = 11] = "TRIANGLE_STRIP_ADJACENCY";
        PrimitiveMode[PrimitiveMode["TRIANGLE_PATCH_ADJACENCY"] = 12] = "TRIANGLE_PATCH_ADJACENCY";
        PrimitiveMode[PrimitiveMode["QUAD_PATCH_LIST"] = 13] = "QUAD_PATCH_LIST";
      })(PrimitiveMode || (PrimitiveMode = {}));
      var PolygonMode;
      (function (PolygonMode) {
        PolygonMode[PolygonMode["FILL"] = 0] = "FILL";
        PolygonMode[PolygonMode["POINT"] = 1] = "POINT";
        PolygonMode[PolygonMode["LINE"] = 2] = "LINE";
      })(PolygonMode || (PolygonMode = {}));
      var ShadeModel;
      (function (ShadeModel) {
        ShadeModel[ShadeModel["GOURAND"] = 0] = "GOURAND";
        ShadeModel[ShadeModel["FLAT"] = 1] = "FLAT";
      })(ShadeModel || (ShadeModel = {}));
      var CullMode;
      (function (CullMode) {
        CullMode[CullMode["NONE"] = 0] = "NONE";
        CullMode[CullMode["FRONT"] = 1] = "FRONT";
        CullMode[CullMode["BACK"] = 2] = "BACK";
      })(CullMode || (CullMode = {}));
      var DynamicStateFlagBit;
      (function (DynamicStateFlagBit) {
        DynamicStateFlagBit[DynamicStateFlagBit["NONE"] = 0] = "NONE";
        DynamicStateFlagBit[DynamicStateFlagBit["LINE_WIDTH"] = 1] = "LINE_WIDTH";
        DynamicStateFlagBit[DynamicStateFlagBit["DEPTH_BIAS"] = 2] = "DEPTH_BIAS";
        DynamicStateFlagBit[DynamicStateFlagBit["BLEND_CONSTANTS"] = 4] = "BLEND_CONSTANTS";
        DynamicStateFlagBit[DynamicStateFlagBit["DEPTH_BOUNDS"] = 8] = "DEPTH_BOUNDS";
        DynamicStateFlagBit[DynamicStateFlagBit["STENCIL_WRITE_MASK"] = 16] = "STENCIL_WRITE_MASK";
        DynamicStateFlagBit[DynamicStateFlagBit["STENCIL_COMPARE_MASK"] = 32] = "STENCIL_COMPARE_MASK";
      })(DynamicStateFlagBit || (DynamicStateFlagBit = {}));
      var StencilFace;
      (function (StencilFace) {
        StencilFace[StencilFace["FRONT"] = 1] = "FRONT";
        StencilFace[StencilFace["BACK"] = 2] = "BACK";
        StencilFace[StencilFace["ALL"] = 3] = "ALL";
      })(StencilFace || (StencilFace = {}));
      var DescriptorType;
      (function (DescriptorType) {
        DescriptorType[DescriptorType["UNKNOWN"] = 0] = "UNKNOWN";
        DescriptorType[DescriptorType["UNIFORM_BUFFER"] = 1] = "UNIFORM_BUFFER";
        DescriptorType[DescriptorType["DYNAMIC_UNIFORM_BUFFER"] = 2] = "DYNAMIC_UNIFORM_BUFFER";
        DescriptorType[DescriptorType["STORAGE_BUFFER"] = 4] = "STORAGE_BUFFER";
        DescriptorType[DescriptorType["DYNAMIC_STORAGE_BUFFER"] = 8] = "DYNAMIC_STORAGE_BUFFER";
        DescriptorType[DescriptorType["SAMPLER_TEXTURE"] = 16] = "SAMPLER_TEXTURE";
        DescriptorType[DescriptorType["SAMPLER"] = 32] = "SAMPLER";
        DescriptorType[DescriptorType["TEXTURE"] = 64] = "TEXTURE";
        DescriptorType[DescriptorType["STORAGE_IMAGE"] = 128] = "STORAGE_IMAGE";
        DescriptorType[DescriptorType["INPUT_ATTACHMENT"] = 256] = "INPUT_ATTACHMENT";
      })(DescriptorType || (DescriptorType = {}));
      var QueueType;
      (function (QueueType) {
        QueueType[QueueType["GRAPHICS"] = 0] = "GRAPHICS";
        QueueType[QueueType["COMPUTE"] = 1] = "COMPUTE";
        QueueType[QueueType["TRANSFER"] = 2] = "TRANSFER";
      })(QueueType || (QueueType = {}));
      var QueryType;
      (function (QueryType) {
        QueryType[QueryType["OCCLUSION"] = 0] = "OCCLUSION";
        QueryType[QueryType["PIPELINE_STATISTICS"] = 1] = "PIPELINE_STATISTICS";
        QueryType[QueryType["TIMESTAMP"] = 2] = "TIMESTAMP";
      })(QueryType || (QueryType = {}));
      var CommandBufferType;
      (function (CommandBufferType) {
        CommandBufferType[CommandBufferType["PRIMARY"] = 0] = "PRIMARY";
        CommandBufferType[CommandBufferType["SECONDARY"] = 1] = "SECONDARY";
      })(CommandBufferType || (CommandBufferType = {}));
      var ClearFlagBit;
      (function (ClearFlagBit) {
        ClearFlagBit[ClearFlagBit["NONE"] = 0] = "NONE";
        ClearFlagBit[ClearFlagBit["COLOR"] = 1] = "COLOR";
        ClearFlagBit[ClearFlagBit["DEPTH"] = 2] = "DEPTH";
        ClearFlagBit[ClearFlagBit["STENCIL"] = 4] = "STENCIL";
        ClearFlagBit[ClearFlagBit["DEPTH_STENCIL"] = 6] = "DEPTH_STENCIL";
        ClearFlagBit[ClearFlagBit["ALL"] = 7] = "ALL";
      })(ClearFlagBit || (ClearFlagBit = {}));
      var BarrierType;
      (function (BarrierType) {
        BarrierType[BarrierType["FULL"] = 0] = "FULL";
        BarrierType[BarrierType["SPLIT_BEGIN"] = 1] = "SPLIT_BEGIN";
        BarrierType[BarrierType["SPLIT_END"] = 2] = "SPLIT_END";
      })(BarrierType || (BarrierType = {}));
      var PassType;
      (function (PassType) {
        PassType[PassType["RASTER"] = 0] = "RASTER";
        PassType[PassType["COMPUTE"] = 1] = "COMPUTE";
        PassType[PassType["COPY"] = 2] = "COPY";
        PassType[PassType["MOVE"] = 3] = "MOVE";
        PassType[PassType["RAYTRACE"] = 4] = "RAYTRACE";
        PassType[PassType["PRESENT"] = 5] = "PRESENT";
      })(PassType || (PassType = {}));
      var Size = function () {
        function Size(x, y, z) {
          if (x === void 0) {
            x = 0;
          }
          if (y === void 0) {
            y = 0;
          }
          if (z === void 0) {
            z = 0;
          }
          this.x = x;
          this.y = y;
          this.z = z;
        }
        var _proto = Size.prototype;
        _proto.copy = function copy(info) {
          this.x = info.x;
          this.y = info.y;
          this.z = info.z;
          return this;
        };
        return Size;
      }();
      var DeviceCaps = function () {
        function DeviceCaps(maxVertexAttributes, maxVertexUniformVectors, maxFragmentUniformVectors, maxTextureUnits, maxImageUnits, maxVertexTextureUnits, maxColorRenderTargets, maxShaderStorageBufferBindings, maxShaderStorageBlockSize, maxUniformBufferBindings, maxUniformBlockSize, maxTextureSize, maxCubeMapTextureSize, maxArrayTextureLayers, max3DTextureSize, uboOffsetAlignment, maxComputeSharedMemorySize, maxComputeWorkGroupInvocations, maxComputeWorkGroupSize, maxComputeWorkGroupCount, supportQuery, clipSpaceMinZ, screenSpaceSignY, clipSpaceSignY) {
          if (maxVertexAttributes === void 0) {
            maxVertexAttributes = 0;
          }
          if (maxVertexUniformVectors === void 0) {
            maxVertexUniformVectors = 0;
          }
          if (maxFragmentUniformVectors === void 0) {
            maxFragmentUniformVectors = 0;
          }
          if (maxTextureUnits === void 0) {
            maxTextureUnits = 0;
          }
          if (maxImageUnits === void 0) {
            maxImageUnits = 0;
          }
          if (maxVertexTextureUnits === void 0) {
            maxVertexTextureUnits = 0;
          }
          if (maxColorRenderTargets === void 0) {
            maxColorRenderTargets = 0;
          }
          if (maxShaderStorageBufferBindings === void 0) {
            maxShaderStorageBufferBindings = 0;
          }
          if (maxShaderStorageBlockSize === void 0) {
            maxShaderStorageBlockSize = 0;
          }
          if (maxUniformBufferBindings === void 0) {
            maxUniformBufferBindings = 0;
          }
          if (maxUniformBlockSize === void 0) {
            maxUniformBlockSize = 0;
          }
          if (maxTextureSize === void 0) {
            maxTextureSize = 0;
          }
          if (maxCubeMapTextureSize === void 0) {
            maxCubeMapTextureSize = 0;
          }
          if (maxArrayTextureLayers === void 0) {
            maxArrayTextureLayers = 0;
          }
          if (max3DTextureSize === void 0) {
            max3DTextureSize = 0;
          }
          if (uboOffsetAlignment === void 0) {
            uboOffsetAlignment = 1;
          }
          if (maxComputeSharedMemorySize === void 0) {
            maxComputeSharedMemorySize = 0;
          }
          if (maxComputeWorkGroupInvocations === void 0) {
            maxComputeWorkGroupInvocations = 0;
          }
          if (maxComputeWorkGroupSize === void 0) {
            maxComputeWorkGroupSize = new Size();
          }
          if (maxComputeWorkGroupCount === void 0) {
            maxComputeWorkGroupCount = new Size();
          }
          if (supportQuery === void 0) {
            supportQuery = false;
          }
          if (clipSpaceMinZ === void 0) {
            clipSpaceMinZ = -1;
          }
          if (screenSpaceSignY === void 0) {
            screenSpaceSignY = 1;
          }
          if (clipSpaceSignY === void 0) {
            clipSpaceSignY = 1;
          }
          this.maxVertexAttributes = maxVertexAttributes;
          this.maxVertexUniformVectors = maxVertexUniformVectors;
          this.maxFragmentUniformVectors = maxFragmentUniformVectors;
          this.maxTextureUnits = maxTextureUnits;
          this.maxImageUnits = maxImageUnits;
          this.maxVertexTextureUnits = maxVertexTextureUnits;
          this.maxColorRenderTargets = maxColorRenderTargets;
          this.maxShaderStorageBufferBindings = maxShaderStorageBufferBindings;
          this.maxShaderStorageBlockSize = maxShaderStorageBlockSize;
          this.maxUniformBufferBindings = maxUniformBufferBindings;
          this.maxUniformBlockSize = maxUniformBlockSize;
          this.maxTextureSize = maxTextureSize;
          this.maxCubeMapTextureSize = maxCubeMapTextureSize;
          this.maxArrayTextureLayers = maxArrayTextureLayers;
          this.max3DTextureSize = max3DTextureSize;
          this.uboOffsetAlignment = uboOffsetAlignment;
          this.maxComputeSharedMemorySize = maxComputeSharedMemorySize;
          this.maxComputeWorkGroupInvocations = maxComputeWorkGroupInvocations;
          this.maxComputeWorkGroupSize = maxComputeWorkGroupSize;
          this.maxComputeWorkGroupCount = maxComputeWorkGroupCount;
          this.supportQuery = supportQuery;
          this.clipSpaceMinZ = clipSpaceMinZ;
          this.screenSpaceSignY = screenSpaceSignY;
          this.clipSpaceSignY = clipSpaceSignY;
        }
        var _proto2 = DeviceCaps.prototype;
        _proto2.copy = function copy(info) {
          this.maxVertexAttributes = info.maxVertexAttributes;
          this.maxVertexUniformVectors = info.maxVertexUniformVectors;
          this.maxFragmentUniformVectors = info.maxFragmentUniformVectors;
          this.maxTextureUnits = info.maxTextureUnits;
          this.maxImageUnits = info.maxImageUnits;
          this.maxVertexTextureUnits = info.maxVertexTextureUnits;
          this.maxColorRenderTargets = info.maxColorRenderTargets;
          this.maxShaderStorageBufferBindings = info.maxShaderStorageBufferBindings;
          this.maxShaderStorageBlockSize = info.maxShaderStorageBlockSize;
          this.maxUniformBufferBindings = info.maxUniformBufferBindings;
          this.maxUniformBlockSize = info.maxUniformBlockSize;
          this.maxTextureSize = info.maxTextureSize;
          this.maxCubeMapTextureSize = info.maxCubeMapTextureSize;
          this.maxArrayTextureLayers = info.maxArrayTextureLayers;
          this.max3DTextureSize = info.max3DTextureSize;
          this.uboOffsetAlignment = info.uboOffsetAlignment;
          this.maxComputeSharedMemorySize = info.maxComputeSharedMemorySize;
          this.maxComputeWorkGroupInvocations = info.maxComputeWorkGroupInvocations;
          this.maxComputeWorkGroupSize.copy(info.maxComputeWorkGroupSize);
          this.maxComputeWorkGroupCount.copy(info.maxComputeWorkGroupCount);
          this.supportQuery = info.supportQuery;
          this.clipSpaceMinZ = info.clipSpaceMinZ;
          this.screenSpaceSignY = info.screenSpaceSignY;
          this.clipSpaceSignY = info.clipSpaceSignY;
          return this;
        };
        return DeviceCaps;
      }();
      var DeviceOptions = function () {
        function DeviceOptions(enableBarrierDeduce) {
          if (enableBarrierDeduce === void 0) {
            enableBarrierDeduce = true;
          }
          this.enableBarrierDeduce = enableBarrierDeduce;
        }
        var _proto3 = DeviceOptions.prototype;
        _proto3.copy = function copy(info) {
          this.enableBarrierDeduce = info.enableBarrierDeduce;
          return this;
        };
        return DeviceOptions;
      }();
      var Offset = function () {
        function Offset(x, y, z) {
          if (x === void 0) {
            x = 0;
          }
          if (y === void 0) {
            y = 0;
          }
          if (z === void 0) {
            z = 0;
          }
          this.x = x;
          this.y = y;
          this.z = z;
        }
        var _proto4 = Offset.prototype;
        _proto4.copy = function copy(info) {
          this.x = info.x;
          this.y = info.y;
          this.z = info.z;
          return this;
        };
        return Offset;
      }();
      var Rect = function () {
        function Rect(x, y, width, height) {
          if (x === void 0) {
            x = 0;
          }
          if (y === void 0) {
            y = 0;
          }
          if (width === void 0) {
            width = 0;
          }
          if (height === void 0) {
            height = 0;
          }
          this.x = x;
          this.y = y;
          this.width = width;
          this.height = height;
        }
        var _proto5 = Rect.prototype;
        _proto5.copy = function copy(info) {
          this.x = info.x;
          this.y = info.y;
          this.width = info.width;
          this.height = info.height;
          return this;
        };
        return Rect;
      }();
      var Extent = function () {
        function Extent(width, height, depth) {
          if (width === void 0) {
            width = 0;
          }
          if (height === void 0) {
            height = 0;
          }
          if (depth === void 0) {
            depth = 1;
          }
          this.width = width;
          this.height = height;
          this.depth = depth;
        }
        var _proto6 = Extent.prototype;
        _proto6.copy = function copy(info) {
          this.width = info.width;
          this.height = info.height;
          this.depth = info.depth;
          return this;
        };
        return Extent;
      }();
      var TextureSubresLayers = function () {
        function TextureSubresLayers(mipLevel, baseArrayLayer, layerCount) {
          if (mipLevel === void 0) {
            mipLevel = 0;
          }
          if (baseArrayLayer === void 0) {
            baseArrayLayer = 0;
          }
          if (layerCount === void 0) {
            layerCount = 1;
          }
          this.mipLevel = mipLevel;
          this.baseArrayLayer = baseArrayLayer;
          this.layerCount = layerCount;
        }
        var _proto7 = TextureSubresLayers.prototype;
        _proto7.copy = function copy(info) {
          this.mipLevel = info.mipLevel;
          this.baseArrayLayer = info.baseArrayLayer;
          this.layerCount = info.layerCount;
          return this;
        };
        return TextureSubresLayers;
      }();
      var TextureSubresRange = function () {
        function TextureSubresRange(baseMipLevel, levelCount, baseArrayLayer, layerCount) {
          if (baseMipLevel === void 0) {
            baseMipLevel = 0;
          }
          if (levelCount === void 0) {
            levelCount = 1;
          }
          if (baseArrayLayer === void 0) {
            baseArrayLayer = 0;
          }
          if (layerCount === void 0) {
            layerCount = 1;
          }
          this.baseMipLevel = baseMipLevel;
          this.levelCount = levelCount;
          this.baseArrayLayer = baseArrayLayer;
          this.layerCount = layerCount;
        }
        var _proto8 = TextureSubresRange.prototype;
        _proto8.copy = function copy(info) {
          this.baseMipLevel = info.baseMipLevel;
          this.levelCount = info.levelCount;
          this.baseArrayLayer = info.baseArrayLayer;
          this.layerCount = info.layerCount;
          return this;
        };
        return TextureSubresRange;
      }();
      var TextureCopy = function () {
        function TextureCopy(srcSubres, srcOffset, dstSubres, dstOffset, extent) {
          if (srcSubres === void 0) {
            srcSubres = new TextureSubresLayers();
          }
          if (srcOffset === void 0) {
            srcOffset = new Offset();
          }
          if (dstSubres === void 0) {
            dstSubres = new TextureSubresLayers();
          }
          if (dstOffset === void 0) {
            dstOffset = new Offset();
          }
          if (extent === void 0) {
            extent = new Extent();
          }
          this.srcSubres = srcSubres;
          this.srcOffset = srcOffset;
          this.dstSubres = dstSubres;
          this.dstOffset = dstOffset;
          this.extent = extent;
        }
        var _proto9 = TextureCopy.prototype;
        _proto9.copy = function copy(info) {
          this.srcSubres.copy(info.srcSubres);
          this.srcOffset.copy(info.srcOffset);
          this.dstSubres.copy(info.dstSubres);
          this.dstOffset.copy(info.dstOffset);
          this.extent.copy(info.extent);
          return this;
        };
        return TextureCopy;
      }();
      var TextureBlit = function () {
        function TextureBlit(srcSubres, srcOffset, srcExtent, dstSubres, dstOffset, dstExtent) {
          if (srcSubres === void 0) {
            srcSubres = new TextureSubresLayers();
          }
          if (srcOffset === void 0) {
            srcOffset = new Offset();
          }
          if (srcExtent === void 0) {
            srcExtent = new Extent();
          }
          if (dstSubres === void 0) {
            dstSubres = new TextureSubresLayers();
          }
          if (dstOffset === void 0) {
            dstOffset = new Offset();
          }
          if (dstExtent === void 0) {
            dstExtent = new Extent();
          }
          this.srcSubres = srcSubres;
          this.srcOffset = srcOffset;
          this.srcExtent = srcExtent;
          this.dstSubres = dstSubres;
          this.dstOffset = dstOffset;
          this.dstExtent = dstExtent;
        }
        var _proto10 = TextureBlit.prototype;
        _proto10.copy = function copy(info) {
          this.srcSubres.copy(info.srcSubres);
          this.srcOffset.copy(info.srcOffset);
          this.srcExtent.copy(info.srcExtent);
          this.dstSubres.copy(info.dstSubres);
          this.dstOffset.copy(info.dstOffset);
          this.dstExtent.copy(info.dstExtent);
          return this;
        };
        return TextureBlit;
      }();
      var BufferTextureCopy = function () {
        function BufferTextureCopy(buffOffset, buffStride, buffTexHeight, texOffset, texExtent, texSubres) {
          if (buffOffset === void 0) {
            buffOffset = 0;
          }
          if (buffStride === void 0) {
            buffStride = 0;
          }
          if (buffTexHeight === void 0) {
            buffTexHeight = 0;
          }
          if (texOffset === void 0) {
            texOffset = new Offset();
          }
          if (texExtent === void 0) {
            texExtent = new Extent();
          }
          if (texSubres === void 0) {
            texSubres = new TextureSubresLayers();
          }
          this.buffOffset = buffOffset;
          this.buffStride = buffStride;
          this.buffTexHeight = buffTexHeight;
          this.texOffset = texOffset;
          this.texExtent = texExtent;
          this.texSubres = texSubres;
        }
        var _proto11 = BufferTextureCopy.prototype;
        _proto11.copy = function copy(info) {
          this.buffOffset = info.buffOffset;
          this.buffStride = info.buffStride;
          this.buffTexHeight = info.buffTexHeight;
          this.texOffset.copy(info.texOffset);
          this.texExtent.copy(info.texExtent);
          this.texSubres.copy(info.texSubres);
          return this;
        };
        return BufferTextureCopy;
      }();
      var Viewport = function () {
        function Viewport(left, top, width, height, minDepth, maxDepth) {
          if (left === void 0) {
            left = 0;
          }
          if (top === void 0) {
            top = 0;
          }
          if (width === void 0) {
            width = 0;
          }
          if (height === void 0) {
            height = 0;
          }
          if (minDepth === void 0) {
            minDepth = 0;
          }
          if (maxDepth === void 0) {
            maxDepth = 1;
          }
          this.left = left;
          this.top = top;
          this.width = width;
          this.height = height;
          this.minDepth = minDepth;
          this.maxDepth = maxDepth;
        }
        var _proto12 = Viewport.prototype;
        _proto12.copy = function copy(info) {
          this.left = info.left;
          this.top = info.top;
          this.width = info.width;
          this.height = info.height;
          this.minDepth = info.minDepth;
          this.maxDepth = info.maxDepth;
          return this;
        };
        _proto12.reset = function reset() {
          this.left = 0;
          this.top = 0;
          this.width = 0;
          this.height = 0;
          this.minDepth = 0;
          this.maxDepth = 1;
        };
        return Viewport;
      }();
      var Color = function () {
        function Color(x, y, z, w) {
          if (x === void 0) {
            x = 0;
          }
          if (y === void 0) {
            y = 0;
          }
          if (z === void 0) {
            z = 0;
          }
          if (w === void 0) {
            w = 0;
          }
          this.x = x;
          this.y = y;
          this.z = z;
          this.w = w;
        }
        var _proto13 = Color.prototype;
        _proto13.copy = function copy(info) {
          this.x = info.x;
          this.y = info.y;
          this.z = info.z;
          this.w = info.w;
          return this;
        };
        _proto13.set = function set(x, y, z, w) {
          this.x = x;
          this.y = y;
          this.z = z;
          this.w = w;
          return this;
        };
        _proto13.reset = function reset() {
          this.x = 0;
          this.y = 0;
          this.z = 0;
          this.w = 0;
        };
        return Color;
      }();
      var BindingMappingInfo = function () {
        function BindingMappingInfo(maxBlockCounts, maxSamplerTextureCounts, maxSamplerCounts, maxTextureCounts, maxBufferCounts, maxImageCounts, maxSubpassInputCounts, setIndices) {
          if (maxBlockCounts === void 0) {
            maxBlockCounts = [0];
          }
          if (maxSamplerTextureCounts === void 0) {
            maxSamplerTextureCounts = [0];
          }
          if (maxSamplerCounts === void 0) {
            maxSamplerCounts = [0];
          }
          if (maxTextureCounts === void 0) {
            maxTextureCounts = [0];
          }
          if (maxBufferCounts === void 0) {
            maxBufferCounts = [0];
          }
          if (maxImageCounts === void 0) {
            maxImageCounts = [0];
          }
          if (maxSubpassInputCounts === void 0) {
            maxSubpassInputCounts = [0];
          }
          if (setIndices === void 0) {
            setIndices = [0];
          }
          this.maxBlockCounts = maxBlockCounts;
          this.maxSamplerTextureCounts = maxSamplerTextureCounts;
          this.maxSamplerCounts = maxSamplerCounts;
          this.maxTextureCounts = maxTextureCounts;
          this.maxBufferCounts = maxBufferCounts;
          this.maxImageCounts = maxImageCounts;
          this.maxSubpassInputCounts = maxSubpassInputCounts;
          this.setIndices = setIndices;
        }
        var _proto14 = BindingMappingInfo.prototype;
        _proto14.copy = function copy(info) {
          this.maxBlockCounts = info.maxBlockCounts.slice();
          this.maxSamplerTextureCounts = info.maxSamplerTextureCounts.slice();
          this.maxSamplerCounts = info.maxSamplerCounts.slice();
          this.maxTextureCounts = info.maxTextureCounts.slice();
          this.maxBufferCounts = info.maxBufferCounts.slice();
          this.maxImageCounts = info.maxImageCounts.slice();
          this.maxSubpassInputCounts = info.maxSubpassInputCounts.slice();
          this.setIndices = info.setIndices.slice();
          return this;
        };
        return BindingMappingInfo;
      }();
      var SwapchainInfo = function () {
        function SwapchainInfo(windowId, windowHandle, vsyncMode, width, height) {
          if (windowId === void 0) {
            windowId = 0;
          }
          if (windowHandle === void 0) {
            windowHandle = null;
          }
          if (vsyncMode === void 0) {
            vsyncMode = VsyncMode.ON;
          }
          if (width === void 0) {
            width = 0;
          }
          if (height === void 0) {
            height = 0;
          }
          this.windowId = windowId;
          this.windowHandle = windowHandle;
          this.vsyncMode = vsyncMode;
          this.width = width;
          this.height = height;
        }
        var _proto15 = SwapchainInfo.prototype;
        _proto15.copy = function copy(info) {
          this.windowId = info.windowId;
          this.windowHandle = info.windowHandle;
          this.vsyncMode = info.vsyncMode;
          this.width = info.width;
          this.height = info.height;
          return this;
        };
        return SwapchainInfo;
      }();
      var DeviceInfo = function () {
        function DeviceInfo(bindingMappingInfo) {
          if (bindingMappingInfo === void 0) {
            bindingMappingInfo = new BindingMappingInfo();
          }
          this.bindingMappingInfo = bindingMappingInfo;
        }
        var _proto16 = DeviceInfo.prototype;
        _proto16.copy = function copy(info) {
          this.bindingMappingInfo.copy(info.bindingMappingInfo);
          return this;
        };
        return DeviceInfo;
      }();
      var BufferInfo = function () {
        function BufferInfo(usage, memUsage, size, stride, flags) {
          if (usage === void 0) {
            usage = BufferUsageBit.NONE;
          }
          if (memUsage === void 0) {
            memUsage = MemoryUsageBit.NONE;
          }
          if (size === void 0) {
            size = 0;
          }
          if (stride === void 0) {
            stride = 1;
          }
          if (flags === void 0) {
            flags = BufferFlagBit.NONE;
          }
          this.usage = usage;
          this.memUsage = memUsage;
          this.size = size;
          this.stride = stride;
          this.flags = flags;
        }
        var _proto17 = BufferInfo.prototype;
        _proto17.copy = function copy(info) {
          this.usage = info.usage;
          this.memUsage = info.memUsage;
          this.size = info.size;
          this.stride = info.stride;
          this.flags = info.flags;
          return this;
        };
        return BufferInfo;
      }();
      var BufferViewInfo = function () {
        function BufferViewInfo(buffer, offset, range) {
          if (buffer === void 0) {
            buffer = null;
          }
          if (offset === void 0) {
            offset = 0;
          }
          if (range === void 0) {
            range = 0;
          }
          this.buffer = buffer;
          this.offset = offset;
          this.range = range;
        }
        var _proto18 = BufferViewInfo.prototype;
        _proto18.copy = function copy(info) {
          this.buffer = info.buffer;
          this.offset = info.offset;
          this.range = info.range;
          return this;
        };
        return BufferViewInfo;
      }();
      var DrawInfo = function () {
        function DrawInfo(vertexCount, firstVertex, indexCount, firstIndex, vertexOffset, instanceCount, firstInstance) {
          if (vertexCount === void 0) {
            vertexCount = 0;
          }
          if (firstVertex === void 0) {
            firstVertex = 0;
          }
          if (indexCount === void 0) {
            indexCount = 0;
          }
          if (firstIndex === void 0) {
            firstIndex = 0;
          }
          if (vertexOffset === void 0) {
            vertexOffset = 0;
          }
          if (instanceCount === void 0) {
            instanceCount = 0;
          }
          if (firstInstance === void 0) {
            firstInstance = 0;
          }
          this.vertexCount = vertexCount;
          this.firstVertex = firstVertex;
          this.indexCount = indexCount;
          this.firstIndex = firstIndex;
          this.vertexOffset = vertexOffset;
          this.instanceCount = instanceCount;
          this.firstInstance = firstInstance;
        }
        var _proto19 = DrawInfo.prototype;
        _proto19.copy = function copy(info) {
          this.vertexCount = info.vertexCount;
          this.firstVertex = info.firstVertex;
          this.indexCount = info.indexCount;
          this.firstIndex = info.firstIndex;
          this.vertexOffset = info.vertexOffset;
          this.instanceCount = info.instanceCount;
          this.firstInstance = info.firstInstance;
          return this;
        };
        return DrawInfo;
      }();
      var DispatchInfo = function () {
        function DispatchInfo(groupCountX, groupCountY, groupCountZ, indirectBuffer, indirectOffset) {
          if (groupCountX === void 0) {
            groupCountX = 0;
          }
          if (groupCountY === void 0) {
            groupCountY = 0;
          }
          if (groupCountZ === void 0) {
            groupCountZ = 0;
          }
          if (indirectBuffer === void 0) {
            indirectBuffer = null;
          }
          if (indirectOffset === void 0) {
            indirectOffset = 0;
          }
          this.groupCountX = groupCountX;
          this.groupCountY = groupCountY;
          this.groupCountZ = groupCountZ;
          this.indirectBuffer = indirectBuffer;
          this.indirectOffset = indirectOffset;
        }
        var _proto20 = DispatchInfo.prototype;
        _proto20.copy = function copy(info) {
          this.groupCountX = info.groupCountX;
          this.groupCountY = info.groupCountY;
          this.groupCountZ = info.groupCountZ;
          this.indirectBuffer = info.indirectBuffer;
          this.indirectOffset = info.indirectOffset;
          return this;
        };
        return DispatchInfo;
      }();
      var IndirectBuffer = function () {
        function IndirectBuffer(drawInfos) {
          if (drawInfos === void 0) {
            drawInfos = [];
          }
          this.drawInfos = drawInfos;
        }
        var _proto21 = IndirectBuffer.prototype;
        _proto21.copy = function copy(info) {
          deepCopy(this.drawInfos, info.drawInfos, DrawInfo);
          return this;
        };
        return IndirectBuffer;
      }();
      var TextureInfo = function () {
        function TextureInfo(type, usage, format, width, height, flags, layerCount, levelCount, samples, depth, externalRes) {
          if (type === void 0) {
            type = TextureType.TEX2D;
          }
          if (usage === void 0) {
            usage = TextureUsageBit.NONE;
          }
          if (format === void 0) {
            format = Format.UNKNOWN;
          }
          if (width === void 0) {
            width = 0;
          }
          if (height === void 0) {
            height = 0;
          }
          if (flags === void 0) {
            flags = TextureFlagBit.NONE;
          }
          if (layerCount === void 0) {
            layerCount = 1;
          }
          if (levelCount === void 0) {
            levelCount = 1;
          }
          if (samples === void 0) {
            samples = SampleCount.X1;
          }
          if (depth === void 0) {
            depth = 1;
          }
          if (externalRes === void 0) {
            externalRes = 0;
          }
          this.type = type;
          this.usage = usage;
          this.format = format;
          this.width = width;
          this.height = height;
          this.flags = flags;
          this.layerCount = layerCount;
          this.levelCount = levelCount;
          this.samples = samples;
          this.depth = depth;
          this.externalRes = externalRes;
        }
        var _proto22 = TextureInfo.prototype;
        _proto22.copy = function copy(info) {
          this.type = info.type;
          this.usage = info.usage;
          this.format = info.format;
          this.width = info.width;
          this.height = info.height;
          this.flags = info.flags;
          this.layerCount = info.layerCount;
          this.levelCount = info.levelCount;
          this.samples = info.samples;
          this.depth = info.depth;
          this.externalRes = info.externalRes;
          return this;
        };
        return TextureInfo;
      }();
      var TextureViewInfo = function () {
        function TextureViewInfo(texture, type, format, baseLevel, levelCount, baseLayer, layerCount) {
          if (texture === void 0) {
            texture = null;
          }
          if (type === void 0) {
            type = TextureType.TEX2D;
          }
          if (format === void 0) {
            format = Format.UNKNOWN;
          }
          if (baseLevel === void 0) {
            baseLevel = 0;
          }
          if (levelCount === void 0) {
            levelCount = 1;
          }
          if (baseLayer === void 0) {
            baseLayer = 0;
          }
          if (layerCount === void 0) {
            layerCount = 1;
          }
          this.texture = texture;
          this.type = type;
          this.format = format;
          this.baseLevel = baseLevel;
          this.levelCount = levelCount;
          this.baseLayer = baseLayer;
          this.layerCount = layerCount;
        }
        var _proto23 = TextureViewInfo.prototype;
        _proto23.copy = function copy(info) {
          this.texture = info.texture;
          this.type = info.type;
          this.format = info.format;
          this.baseLevel = info.baseLevel;
          this.levelCount = info.levelCount;
          this.baseLayer = info.baseLayer;
          this.layerCount = info.layerCount;
          return this;
        };
        return TextureViewInfo;
      }();
      var SamplerInfo = function () {
        function SamplerInfo(minFilter, magFilter, mipFilter, addressU, addressV, addressW, maxAnisotropy, cmpFunc) {
          if (minFilter === void 0) {
            minFilter = Filter$1.LINEAR;
          }
          if (magFilter === void 0) {
            magFilter = Filter$1.LINEAR;
          }
          if (mipFilter === void 0) {
            mipFilter = Filter$1.NONE;
          }
          if (addressU === void 0) {
            addressU = Address.WRAP;
          }
          if (addressV === void 0) {
            addressV = Address.WRAP;
          }
          if (addressW === void 0) {
            addressW = Address.WRAP;
          }
          if (maxAnisotropy === void 0) {
            maxAnisotropy = 0;
          }
          if (cmpFunc === void 0) {
            cmpFunc = ComparisonFunc.ALWAYS;
          }
          this.minFilter = minFilter;
          this.magFilter = magFilter;
          this.mipFilter = mipFilter;
          this.addressU = addressU;
          this.addressV = addressV;
          this.addressW = addressW;
          this.maxAnisotropy = maxAnisotropy;
          this.cmpFunc = cmpFunc;
        }
        var _proto24 = SamplerInfo.prototype;
        _proto24.copy = function copy(info) {
          this.minFilter = info.minFilter;
          this.magFilter = info.magFilter;
          this.mipFilter = info.mipFilter;
          this.addressU = info.addressU;
          this.addressV = info.addressV;
          this.addressW = info.addressW;
          this.maxAnisotropy = info.maxAnisotropy;
          this.cmpFunc = info.cmpFunc;
          return this;
        };
        return SamplerInfo;
      }();
      var Uniform = function () {
        function Uniform(name, type, count) {
          if (name === void 0) {
            name = '';
          }
          if (type === void 0) {
            type = Type$1.UNKNOWN;
          }
          if (count === void 0) {
            count = 0;
          }
          this.name = name;
          this.type = type;
          this.count = count;
        }
        var _proto25 = Uniform.prototype;
        _proto25.copy = function copy(info) {
          this.name = info.name;
          this.type = info.type;
          this.count = info.count;
          return this;
        };
        return Uniform;
      }();
      var UniformBlock = function () {
        function UniformBlock(set, binding, name, members, count, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (members === void 0) {
            members = [];
          }
          if (count === void 0) {
            count = 0;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.members = members;
          this.count = count;
          this.flattened = flattened;
        }
        var _proto26 = UniformBlock.prototype;
        _proto26.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          deepCopy(this.members, info.members, Uniform);
          this.count = info.count;
          this.flattened = info.flattened;
          return this;
        };
        return UniformBlock;
      }();
      var UniformSamplerTexture = function () {
        function UniformSamplerTexture(set, binding, name, type, count, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (type === void 0) {
            type = Type$1.UNKNOWN;
          }
          if (count === void 0) {
            count = 0;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.type = type;
          this.count = count;
          this.flattened = flattened;
        }
        var _proto27 = UniformSamplerTexture.prototype;
        _proto27.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.type = info.type;
          this.count = info.count;
          this.flattened = info.flattened;
          return this;
        };
        return UniformSamplerTexture;
      }();
      var UniformSampler = function () {
        function UniformSampler(set, binding, name, count, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (count === void 0) {
            count = 0;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.count = count;
          this.flattened = flattened;
        }
        var _proto28 = UniformSampler.prototype;
        _proto28.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.count = info.count;
          this.flattened = info.flattened;
          return this;
        };
        return UniformSampler;
      }();
      var UniformTexture = function () {
        function UniformTexture(set, binding, name, type, count, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (type === void 0) {
            type = Type$1.UNKNOWN;
          }
          if (count === void 0) {
            count = 0;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.type = type;
          this.count = count;
          this.flattened = flattened;
        }
        var _proto29 = UniformTexture.prototype;
        _proto29.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.type = info.type;
          this.count = info.count;
          this.flattened = info.flattened;
          return this;
        };
        return UniformTexture;
      }();
      var UniformStorageImage = function () {
        function UniformStorageImage(set, binding, name, type, count, memoryAccess, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (type === void 0) {
            type = Type$1.UNKNOWN;
          }
          if (count === void 0) {
            count = 0;
          }
          if (memoryAccess === void 0) {
            memoryAccess = MemoryAccessBit.READ_WRITE;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.type = type;
          this.count = count;
          this.memoryAccess = memoryAccess;
          this.flattened = flattened;
        }
        var _proto30 = UniformStorageImage.prototype;
        _proto30.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.type = info.type;
          this.count = info.count;
          this.memoryAccess = info.memoryAccess;
          this.flattened = info.flattened;
          return this;
        };
        return UniformStorageImage;
      }();
      var UniformStorageBuffer = function () {
        function UniformStorageBuffer(set, binding, name, count, memoryAccess, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (count === void 0) {
            count = 0;
          }
          if (memoryAccess === void 0) {
            memoryAccess = MemoryAccessBit.READ_WRITE;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.count = count;
          this.memoryAccess = memoryAccess;
          this.flattened = flattened;
        }
        var _proto31 = UniformStorageBuffer.prototype;
        _proto31.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.count = info.count;
          this.memoryAccess = info.memoryAccess;
          this.flattened = info.flattened;
          return this;
        };
        return UniformStorageBuffer;
      }();
      var UniformInputAttachment = function () {
        function UniformInputAttachment(set, binding, name, count, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (count === void 0) {
            count = 0;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.count = count;
          this.flattened = flattened;
        }
        var _proto32 = UniformInputAttachment.prototype;
        _proto32.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.count = info.count;
          this.flattened = info.flattened;
          return this;
        };
        return UniformInputAttachment;
      }();
      var ShaderStage = function () {
        function ShaderStage(stage, source) {
          if (stage === void 0) {
            stage = ShaderStageFlagBit.NONE;
          }
          if (source === void 0) {
            source = '';
          }
          this.stage = stage;
          this.source = source;
        }
        var _proto33 = ShaderStage.prototype;
        _proto33.copy = function copy(info) {
          this.stage = info.stage;
          this.source = info.source;
          return this;
        };
        return ShaderStage;
      }();
      var Attribute = function () {
        function Attribute(name, format, isNormalized, stream, isInstanced, location) {
          if (name === void 0) {
            name = '';
          }
          if (format === void 0) {
            format = Format.UNKNOWN;
          }
          if (isNormalized === void 0) {
            isNormalized = false;
          }
          if (stream === void 0) {
            stream = 0;
          }
          if (isInstanced === void 0) {
            isInstanced = false;
          }
          if (location === void 0) {
            location = 0;
          }
          this.name = name;
          this.format = format;
          this.isNormalized = isNormalized;
          this.stream = stream;
          this.isInstanced = isInstanced;
          this.location = location;
        }
        var _proto34 = Attribute.prototype;
        _proto34.copy = function copy(info) {
          this.name = info.name;
          this.format = info.format;
          this.isNormalized = info.isNormalized;
          this.stream = info.stream;
          this.isInstanced = info.isInstanced;
          this.location = info.location;
          return this;
        };
        return Attribute;
      }();
      var ShaderInfo = function () {
        function ShaderInfo(name, stages, attributes, blocks, buffers, samplerTextures, samplers, textures, images, subpassInputs) {
          if (name === void 0) {
            name = '';
          }
          if (stages === void 0) {
            stages = [];
          }
          if (attributes === void 0) {
            attributes = [];
          }
          if (blocks === void 0) {
            blocks = [];
          }
          if (buffers === void 0) {
            buffers = [];
          }
          if (samplerTextures === void 0) {
            samplerTextures = [];
          }
          if (samplers === void 0) {
            samplers = [];
          }
          if (textures === void 0) {
            textures = [];
          }
          if (images === void 0) {
            images = [];
          }
          if (subpassInputs === void 0) {
            subpassInputs = [];
          }
          this.name = name;
          this.stages = stages;
          this.attributes = attributes;
          this.blocks = blocks;
          this.buffers = buffers;
          this.samplerTextures = samplerTextures;
          this.samplers = samplers;
          this.textures = textures;
          this.images = images;
          this.subpassInputs = subpassInputs;
        }
        var _proto35 = ShaderInfo.prototype;
        _proto35.copy = function copy(info) {
          this.name = info.name;
          deepCopy(this.stages, info.stages, ShaderStage);
          deepCopy(this.attributes, info.attributes, Attribute);
          deepCopy(this.blocks, info.blocks, UniformBlock);
          deepCopy(this.buffers, info.buffers, UniformStorageBuffer);
          deepCopy(this.samplerTextures, info.samplerTextures, UniformSamplerTexture);
          deepCopy(this.samplers, info.samplers, UniformSampler);
          deepCopy(this.textures, info.textures, UniformTexture);
          deepCopy(this.images, info.images, UniformStorageImage);
          deepCopy(this.subpassInputs, info.subpassInputs, UniformInputAttachment);
          return this;
        };
        return ShaderInfo;
      }();
      var InputAssemblerInfo = function () {
        function InputAssemblerInfo(attributes, vertexBuffers, indexBuffer, indirectBuffer) {
          if (attributes === void 0) {
            attributes = [];
          }
          if (vertexBuffers === void 0) {
            vertexBuffers = [];
          }
          if (indexBuffer === void 0) {
            indexBuffer = null;
          }
          if (indirectBuffer === void 0) {
            indirectBuffer = null;
          }
          this.attributes = attributes;
          this.vertexBuffers = vertexBuffers;
          this.indexBuffer = indexBuffer;
          this.indirectBuffer = indirectBuffer;
        }
        var _proto36 = InputAssemblerInfo.prototype;
        _proto36.copy = function copy(info) {
          deepCopy(this.attributes, info.attributes, Attribute);
          this.vertexBuffers = info.vertexBuffers.slice();
          this.indexBuffer = info.indexBuffer;
          this.indirectBuffer = info.indirectBuffer;
          return this;
        };
        return InputAssemblerInfo;
      }();
      var ColorAttachment = function () {
        function ColorAttachment(format, sampleCount, loadOp, storeOp, barrier) {
          if (format === void 0) {
            format = Format.UNKNOWN;
          }
          if (sampleCount === void 0) {
            sampleCount = SampleCount.X1;
          }
          if (loadOp === void 0) {
            loadOp = LoadOp.CLEAR;
          }
          if (storeOp === void 0) {
            storeOp = StoreOp.STORE;
          }
          if (barrier === void 0) {
            barrier = null;
          }
          this.format = format;
          this.sampleCount = sampleCount;
          this.loadOp = loadOp;
          this.storeOp = storeOp;
          this.barrier = barrier;
        }
        var _proto37 = ColorAttachment.prototype;
        _proto37.copy = function copy(info) {
          this.format = info.format;
          this.sampleCount = info.sampleCount;
          this.loadOp = info.loadOp;
          this.storeOp = info.storeOp;
          this.barrier = info.barrier;
          return this;
        };
        return ColorAttachment;
      }();
      var DepthStencilAttachment = function () {
        function DepthStencilAttachment(format, sampleCount, depthLoadOp, depthStoreOp, stencilLoadOp, stencilStoreOp, barrier) {
          if (format === void 0) {
            format = Format.UNKNOWN;
          }
          if (sampleCount === void 0) {
            sampleCount = SampleCount.X1;
          }
          if (depthLoadOp === void 0) {
            depthLoadOp = LoadOp.CLEAR;
          }
          if (depthStoreOp === void 0) {
            depthStoreOp = StoreOp.STORE;
          }
          if (stencilLoadOp === void 0) {
            stencilLoadOp = LoadOp.CLEAR;
          }
          if (stencilStoreOp === void 0) {
            stencilStoreOp = StoreOp.STORE;
          }
          if (barrier === void 0) {
            barrier = null;
          }
          this.format = format;
          this.sampleCount = sampleCount;
          this.depthLoadOp = depthLoadOp;
          this.depthStoreOp = depthStoreOp;
          this.stencilLoadOp = stencilLoadOp;
          this.stencilStoreOp = stencilStoreOp;
          this.barrier = barrier;
        }
        var _proto38 = DepthStencilAttachment.prototype;
        _proto38.copy = function copy(info) {
          this.format = info.format;
          this.sampleCount = info.sampleCount;
          this.depthLoadOp = info.depthLoadOp;
          this.depthStoreOp = info.depthStoreOp;
          this.stencilLoadOp = info.stencilLoadOp;
          this.stencilStoreOp = info.stencilStoreOp;
          this.barrier = info.barrier;
          return this;
        };
        return DepthStencilAttachment;
      }();
      var SubpassInfo = function () {
        function SubpassInfo(inputs, colors, resolves, preserves, depthStencil, depthStencilResolve, depthResolveMode, stencilResolveMode) {
          if (inputs === void 0) {
            inputs = [];
          }
          if (colors === void 0) {
            colors = [];
          }
          if (resolves === void 0) {
            resolves = [];
          }
          if (preserves === void 0) {
            preserves = [];
          }
          if (depthStencil === void 0) {
            depthStencil = -1;
          }
          if (depthStencilResolve === void 0) {
            depthStencilResolve = -1;
          }
          if (depthResolveMode === void 0) {
            depthResolveMode = ResolveMode.NONE;
          }
          if (stencilResolveMode === void 0) {
            stencilResolveMode = ResolveMode.NONE;
          }
          this.inputs = inputs;
          this.colors = colors;
          this.resolves = resolves;
          this.preserves = preserves;
          this.depthStencil = depthStencil;
          this.depthStencilResolve = depthStencilResolve;
          this.depthResolveMode = depthResolveMode;
          this.stencilResolveMode = stencilResolveMode;
        }
        var _proto39 = SubpassInfo.prototype;
        _proto39.copy = function copy(info) {
          this.inputs = info.inputs.slice();
          this.colors = info.colors.slice();
          this.resolves = info.resolves.slice();
          this.preserves = info.preserves.slice();
          this.depthStencil = info.depthStencil;
          this.depthStencilResolve = info.depthStencilResolve;
          this.depthResolveMode = info.depthResolveMode;
          this.stencilResolveMode = info.stencilResolveMode;
          return this;
        };
        return SubpassInfo;
      }();
      var SubpassDependency = function () {
        function SubpassDependency(srcSubpass, dstSubpass, generalBarrier, prevAccesses, nextAccesses) {
          if (srcSubpass === void 0) {
            srcSubpass = 0;
          }
          if (dstSubpass === void 0) {
            dstSubpass = 0;
          }
          if (generalBarrier === void 0) {
            generalBarrier = null;
          }
          if (prevAccesses === void 0) {
            prevAccesses = [AccessFlagBit.NONE];
          }
          if (nextAccesses === void 0) {
            nextAccesses = [AccessFlagBit.NONE];
          }
          this.srcSubpass = srcSubpass;
          this.dstSubpass = dstSubpass;
          this.generalBarrier = generalBarrier;
          this.prevAccesses = prevAccesses;
          this.nextAccesses = nextAccesses;
        }
        var _proto40 = SubpassDependency.prototype;
        _proto40.copy = function copy(info) {
          this.srcSubpass = info.srcSubpass;
          this.dstSubpass = info.dstSubpass;
          this.generalBarrier = info.generalBarrier;
          this.prevAccesses = info.prevAccesses.slice();
          this.nextAccesses = info.nextAccesses.slice();
          return this;
        };
        return SubpassDependency;
      }();
      var RenderPassInfo = function () {
        function RenderPassInfo(colorAttachments, depthStencilAttachment, depthStencilResolveAttachment, subpasses, dependencies) {
          if (colorAttachments === void 0) {
            colorAttachments = [];
          }
          if (depthStencilAttachment === void 0) {
            depthStencilAttachment = new DepthStencilAttachment();
          }
          if (depthStencilResolveAttachment === void 0) {
            depthStencilResolveAttachment = new DepthStencilAttachment();
          }
          if (subpasses === void 0) {
            subpasses = [];
          }
          if (dependencies === void 0) {
            dependencies = [];
          }
          this.colorAttachments = colorAttachments;
          this.depthStencilAttachment = depthStencilAttachment;
          this.depthStencilResolveAttachment = depthStencilResolveAttachment;
          this.subpasses = subpasses;
          this.dependencies = dependencies;
        }
        var _proto41 = RenderPassInfo.prototype;
        _proto41.copy = function copy(info) {
          deepCopy(this.colorAttachments, info.colorAttachments, ColorAttachment);
          this.depthStencilAttachment.copy(info.depthStencilAttachment);
          this.depthStencilResolveAttachment.copy(info.depthStencilResolveAttachment);
          deepCopy(this.subpasses, info.subpasses, SubpassInfo);
          deepCopy(this.dependencies, info.dependencies, SubpassDependency);
          return this;
        };
        return RenderPassInfo;
      }();
      var GeneralBarrierInfo = function () {
        function GeneralBarrierInfo(prevAccesses, nextAccesses, type) {
          if (prevAccesses === void 0) {
            prevAccesses = AccessFlagBit.NONE;
          }
          if (nextAccesses === void 0) {
            nextAccesses = AccessFlagBit.NONE;
          }
          if (type === void 0) {
            type = BarrierType.FULL;
          }
          this.prevAccesses = prevAccesses;
          this.nextAccesses = nextAccesses;
          this.type = type;
        }
        var _proto42 = GeneralBarrierInfo.prototype;
        _proto42.copy = function copy(info) {
          this.prevAccesses = info.prevAccesses;
          this.nextAccesses = info.nextAccesses;
          this.type = info.type;
          return this;
        };
        return GeneralBarrierInfo;
      }();
      var TextureBarrierInfo = function () {
        function TextureBarrierInfo(prevAccesses, nextAccesses, type, baseMipLevel, levelCount, baseSlice, sliceCount, discardContents, srcQueue, dstQueue) {
          if (prevAccesses === void 0) {
            prevAccesses = AccessFlagBit.NONE;
          }
          if (nextAccesses === void 0) {
            nextAccesses = AccessFlagBit.NONE;
          }
          if (type === void 0) {
            type = BarrierType.FULL;
          }
          if (baseMipLevel === void 0) {
            baseMipLevel = 0;
          }
          if (levelCount === void 0) {
            levelCount = 1;
          }
          if (baseSlice === void 0) {
            baseSlice = 0;
          }
          if (sliceCount === void 0) {
            sliceCount = 1;
          }
          if (discardContents === void 0) {
            discardContents = false;
          }
          if (srcQueue === void 0) {
            srcQueue = null;
          }
          if (dstQueue === void 0) {
            dstQueue = null;
          }
          this.prevAccesses = prevAccesses;
          this.nextAccesses = nextAccesses;
          this.type = type;
          this.baseMipLevel = baseMipLevel;
          this.levelCount = levelCount;
          this.baseSlice = baseSlice;
          this.sliceCount = sliceCount;
          this.discardContents = discardContents;
          this.srcQueue = srcQueue;
          this.dstQueue = dstQueue;
        }
        var _proto43 = TextureBarrierInfo.prototype;
        _proto43.copy = function copy(info) {
          this.prevAccesses = info.prevAccesses;
          this.nextAccesses = info.nextAccesses;
          this.type = info.type;
          this.baseMipLevel = info.baseMipLevel;
          this.levelCount = info.levelCount;
          this.baseSlice = info.baseSlice;
          this.sliceCount = info.sliceCount;
          this.discardContents = info.discardContents;
          this.srcQueue = info.srcQueue;
          this.dstQueue = info.dstQueue;
          return this;
        };
        return TextureBarrierInfo;
      }();
      var BufferBarrierInfo = function () {
        function BufferBarrierInfo(prevAccesses, nextAccesses, type, offset, size, discardContents, srcQueue, dstQueue) {
          if (prevAccesses === void 0) {
            prevAccesses = AccessFlagBit.NONE;
          }
          if (nextAccesses === void 0) {
            nextAccesses = AccessFlagBit.NONE;
          }
          if (type === void 0) {
            type = BarrierType.FULL;
          }
          if (offset === void 0) {
            offset = 0;
          }
          if (size === void 0) {
            size = 0;
          }
          if (discardContents === void 0) {
            discardContents = false;
          }
          if (srcQueue === void 0) {
            srcQueue = null;
          }
          if (dstQueue === void 0) {
            dstQueue = null;
          }
          this.prevAccesses = prevAccesses;
          this.nextAccesses = nextAccesses;
          this.type = type;
          this.offset = offset;
          this.size = size;
          this.discardContents = discardContents;
          this.srcQueue = srcQueue;
          this.dstQueue = dstQueue;
        }
        var _proto44 = BufferBarrierInfo.prototype;
        _proto44.copy = function copy(info) {
          this.prevAccesses = info.prevAccesses;
          this.nextAccesses = info.nextAccesses;
          this.type = info.type;
          this.offset = info.offset;
          this.size = info.size;
          this.discardContents = info.discardContents;
          this.srcQueue = info.srcQueue;
          this.dstQueue = info.dstQueue;
          return this;
        };
        return BufferBarrierInfo;
      }();
      var FramebufferInfo = function () {
        function FramebufferInfo(renderPass, colorTextures, depthStencilTexture, depthStencilResolveTexture) {
          if (renderPass === void 0) {
            renderPass = null;
          }
          if (colorTextures === void 0) {
            colorTextures = [];
          }
          if (depthStencilTexture === void 0) {
            depthStencilTexture = null;
          }
          if (depthStencilResolveTexture === void 0) {
            depthStencilResolveTexture = null;
          }
          this.renderPass = renderPass;
          this.colorTextures = colorTextures;
          this.depthStencilTexture = depthStencilTexture;
          this.depthStencilResolveTexture = depthStencilResolveTexture;
        }
        var _proto45 = FramebufferInfo.prototype;
        _proto45.copy = function copy(info) {
          this.renderPass = info.renderPass;
          this.colorTextures = info.colorTextures.slice();
          this.depthStencilTexture = info.depthStencilTexture;
          this.depthStencilResolveTexture = info.depthStencilResolveTexture;
          return this;
        };
        return FramebufferInfo;
      }();
      var DescriptorSetLayoutBinding = function () {
        function DescriptorSetLayoutBinding(binding, descriptorType, count, stageFlags, immutableSamplers) {
          if (binding === void 0) {
            binding = -1;
          }
          if (descriptorType === void 0) {
            descriptorType = DescriptorType.UNKNOWN;
          }
          if (count === void 0) {
            count = 0;
          }
          if (stageFlags === void 0) {
            stageFlags = ShaderStageFlagBit.NONE;
          }
          if (immutableSamplers === void 0) {
            immutableSamplers = [];
          }
          this.binding = binding;
          this.descriptorType = descriptorType;
          this.count = count;
          this.stageFlags = stageFlags;
          this.immutableSamplers = immutableSamplers;
        }
        var _proto46 = DescriptorSetLayoutBinding.prototype;
        _proto46.copy = function copy(info) {
          this.binding = info.binding;
          this.descriptorType = info.descriptorType;
          this.count = info.count;
          this.stageFlags = info.stageFlags;
          this.immutableSamplers = info.immutableSamplers.slice();
          return this;
        };
        return DescriptorSetLayoutBinding;
      }();
      var DescriptorSetLayoutInfo = function () {
        function DescriptorSetLayoutInfo(bindings) {
          if (bindings === void 0) {
            bindings = [];
          }
          this.bindings = bindings;
        }
        var _proto47 = DescriptorSetLayoutInfo.prototype;
        _proto47.copy = function copy(info) {
          deepCopy(this.bindings, info.bindings, DescriptorSetLayoutBinding);
          return this;
        };
        _proto47.reset = function reset() {
          this.bindings.length = 0;
        };
        return DescriptorSetLayoutInfo;
      }();
      var DescriptorSetInfo = function () {
        function DescriptorSetInfo(layout) {
          if (layout === void 0) {
            layout = null;
          }
          this.layout = layout;
        }
        var _proto48 = DescriptorSetInfo.prototype;
        _proto48.copy = function copy(info) {
          this.layout = info.layout;
          return this;
        };
        return DescriptorSetInfo;
      }();
      var PipelineLayoutInfo = function () {
        function PipelineLayoutInfo(setLayouts) {
          if (setLayouts === void 0) {
            setLayouts = [];
          }
          this.setLayouts = setLayouts;
        }
        var _proto49 = PipelineLayoutInfo.prototype;
        _proto49.copy = function copy(info) {
          this.setLayouts = info.setLayouts.slice();
          return this;
        };
        return PipelineLayoutInfo;
      }();
      var InputState = function () {
        function InputState(attributes) {
          if (attributes === void 0) {
            attributes = [];
          }
          this.attributes = attributes;
        }
        var _proto50 = InputState.prototype;
        _proto50.copy = function copy(info) {
          deepCopy(this.attributes, info.attributes, Attribute);
          return this;
        };
        return InputState;
      }();
      var CommandBufferInfo = function () {
        function CommandBufferInfo(queue, type) {
          if (queue === void 0) {
            queue = null;
          }
          if (type === void 0) {
            type = CommandBufferType.PRIMARY;
          }
          this.queue = queue;
          this.type = type;
        }
        var _proto51 = CommandBufferInfo.prototype;
        _proto51.copy = function copy(info) {
          this.queue = info.queue;
          this.type = info.type;
          return this;
        };
        return CommandBufferInfo;
      }();
      var QueueInfo = function () {
        function QueueInfo(type) {
          if (type === void 0) {
            type = QueueType.GRAPHICS;
          }
          this.type = type;
        }
        var _proto52 = QueueInfo.prototype;
        _proto52.copy = function copy(info) {
          this.type = info.type;
          return this;
        };
        return QueueInfo;
      }();
      var QueryPoolInfo = function () {
        function QueryPoolInfo(type, maxQueryObjects, forceWait) {
          if (type === void 0) {
            type = QueryType.OCCLUSION;
          }
          if (maxQueryObjects === void 0) {
            maxQueryObjects = 32767;
          }
          if (forceWait === void 0) {
            forceWait = true;
          }
          this.type = type;
          this.maxQueryObjects = maxQueryObjects;
          this.forceWait = forceWait;
        }
        var _proto53 = QueryPoolInfo.prototype;
        _proto53.copy = function copy(info) {
          this.type = info.type;
          this.maxQueryObjects = info.maxQueryObjects;
          this.forceWait = info.forceWait;
          return this;
        };
        return QueryPoolInfo;
      }();
      var FormatInfo = function FormatInfo(name, size, count, type, hasAlpha, hasDepth, hasStencil, isCompressed) {
        if (name === void 0) {
          name = '';
        }
        if (size === void 0) {
          size = 0;
        }
        if (count === void 0) {
          count = 0;
        }
        if (type === void 0) {
          type = FormatType.NONE;
        }
        if (hasAlpha === void 0) {
          hasAlpha = false;
        }
        if (hasDepth === void 0) {
          hasDepth = false;
        }
        if (hasStencil === void 0) {
          hasStencil = false;
        }
        if (isCompressed === void 0) {
          isCompressed = false;
        }
        this.name = name;
        this.size = size;
        this.count = count;
        this.type = type;
        this.hasAlpha = hasAlpha;
        this.hasDepth = hasDepth;
        this.hasStencil = hasStencil;
        this.isCompressed = isCompressed;
      };
      var MemoryStatus = function () {
        function MemoryStatus(bufferSize, textureSize) {
          if (bufferSize === void 0) {
            bufferSize = 0;
          }
          if (textureSize === void 0) {
            textureSize = 0;
          }
          this.bufferSize = bufferSize;
          this.textureSize = textureSize;
        }
        var _proto54 = MemoryStatus.prototype;
        _proto54.copy = function copy(info) {
          this.bufferSize = info.bufferSize;
          this.textureSize = info.textureSize;
          return this;
        };
        return MemoryStatus;
      }();
      var DynamicStencilStates = function () {
        function DynamicStencilStates(writeMask, compareMask, reference) {
          if (writeMask === void 0) {
            writeMask = 0;
          }
          if (compareMask === void 0) {
            compareMask = 0;
          }
          if (reference === void 0) {
            reference = 0;
          }
          this.writeMask = writeMask;
          this.compareMask = compareMask;
          this.reference = reference;
        }
        var _proto55 = DynamicStencilStates.prototype;
        _proto55.copy = function copy(info) {
          this.writeMask = info.writeMask;
          this.compareMask = info.compareMask;
          this.reference = info.reference;
          return this;
        };
        return DynamicStencilStates;
      }();
      var DynamicStates = function () {
        function DynamicStates(viewport, scissor, blendConstant, lineWidth, depthBiasConstant, depthBiasClamp, depthBiasSlope, depthMinBounds, depthMaxBounds, stencilStatesFront, stencilStatesBack) {
          if (viewport === void 0) {
            viewport = new Viewport();
          }
          if (scissor === void 0) {
            scissor = new Rect();
          }
          if (blendConstant === void 0) {
            blendConstant = new Color();
          }
          if (lineWidth === void 0) {
            lineWidth = 1;
          }
          if (depthBiasConstant === void 0) {
            depthBiasConstant = 0;
          }
          if (depthBiasClamp === void 0) {
            depthBiasClamp = 0;
          }
          if (depthBiasSlope === void 0) {
            depthBiasSlope = 0;
          }
          if (depthMinBounds === void 0) {
            depthMinBounds = 0;
          }
          if (depthMaxBounds === void 0) {
            depthMaxBounds = 0;
          }
          if (stencilStatesFront === void 0) {
            stencilStatesFront = new DynamicStencilStates();
          }
          if (stencilStatesBack === void 0) {
            stencilStatesBack = new DynamicStencilStates();
          }
          this.viewport = viewport;
          this.scissor = scissor;
          this.blendConstant = blendConstant;
          this.lineWidth = lineWidth;
          this.depthBiasConstant = depthBiasConstant;
          this.depthBiasClamp = depthBiasClamp;
          this.depthBiasSlope = depthBiasSlope;
          this.depthMinBounds = depthMinBounds;
          this.depthMaxBounds = depthMaxBounds;
          this.stencilStatesFront = stencilStatesFront;
          this.stencilStatesBack = stencilStatesBack;
        }
        var _proto56 = DynamicStates.prototype;
        _proto56.copy = function copy(info) {
          this.viewport.copy(info.viewport);
          this.scissor.copy(info.scissor);
          this.blendConstant.copy(info.blendConstant);
          this.lineWidth = info.lineWidth;
          this.depthBiasConstant = info.depthBiasConstant;
          this.depthBiasClamp = info.depthBiasClamp;
          this.depthBiasSlope = info.depthBiasSlope;
          this.depthMinBounds = info.depthMinBounds;
          this.depthMaxBounds = info.depthMaxBounds;
          this.stencilStatesFront.copy(info.stencilStatesFront);
          this.stencilStatesBack.copy(info.stencilStatesBack);
          return this;
        };
        return DynamicStates;
      }();
      var GFXObject = function (_GCObject) {
        _inheritsLoose(GFXObject, _GCObject);
        function GFXObject(objectType) {
          var _this;
          _this = _GCObject.call(this) || this;
          _this._objectType = ObjectType.UNKNOWN;
          _this._objectID = 0;
          _this._typedID = 0;
          _this._objectType = objectType;
          _this._objectID = GFXObject._idTable[ObjectType.UNKNOWN]++;
          _this._typedID = GFXObject._idTable[objectType]++;
          return _this;
        }
        _createClass(GFXObject, [{
          key: "objectType",
          get: function get() {
            return this._objectType;
          }
        }, {
          key: "objectID",
          get: function get() {
            return this._objectID;
          }
        }, {
          key: "typedID",
          get: function get() {
            return this._typedID;
          }
        }]);
        return GFXObject;
      }(GCObject);
      GFXObject._idTable = Array(ObjectType.COUNT).fill(1 << 16);
      var AttributeName;
      (function (AttributeName) {
        AttributeName["ATTR_POSITION"] = "a_position";
        AttributeName["ATTR_NORMAL"] = "a_normal";
        AttributeName["ATTR_TANGENT"] = "a_tangent";
        AttributeName["ATTR_BITANGENT"] = "a_bitangent";
        AttributeName["ATTR_WEIGHTS"] = "a_weights";
        AttributeName["ATTR_JOINTS"] = "a_joints";
        AttributeName["ATTR_COLOR"] = "a_color";
        AttributeName["ATTR_COLOR1"] = "a_color1";
        AttributeName["ATTR_COLOR2"] = "a_color2";
        AttributeName["ATTR_TEX_COORD"] = "a_texCoord";
        AttributeName["ATTR_TEX_COORD1"] = "a_texCoord1";
        AttributeName["ATTR_TEX_COORD2"] = "a_texCoord2";
        AttributeName["ATTR_TEX_COORD3"] = "a_texCoord3";
        AttributeName["ATTR_TEX_COORD4"] = "a_texCoord4";
        AttributeName["ATTR_TEX_COORD5"] = "a_texCoord5";
        AttributeName["ATTR_TEX_COORD6"] = "a_texCoord6";
        AttributeName["ATTR_TEX_COORD7"] = "a_texCoord7";
        AttributeName["ATTR_TEX_COORD8"] = "a_texCoord8";
        AttributeName["ATTR_BATCH_ID"] = "a_batch_id";
        AttributeName["ATTR_BATCH_UV"] = "a_batch_uv";
      })(AttributeName || (AttributeName = {}));
      var FormatInfos = Object.freeze([new FormatInfo('UNKNOWN', 0, 0, FormatType.NONE, false, false, false, false), new FormatInfo('A8', 1, 1, FormatType.UNORM, true, false, false, false), new FormatInfo('L8', 1, 1, FormatType.UNORM, false, false, false, false), new FormatInfo('LA8', 1, 2, FormatType.UNORM, true, false, false, false), new FormatInfo('R8', 1, 1, FormatType.UNORM, false, false, false, false), new FormatInfo('R8SN', 1, 1, FormatType.SNORM, false, false, false, false), new FormatInfo('R8UI', 1, 1, FormatType.UINT, false, false, false, false), new FormatInfo('R8I', 1, 1, FormatType.INT, false, false, false, false), new FormatInfo('R16F', 2, 1, FormatType.FLOAT, false, false, false, false), new FormatInfo('R16UI', 2, 1, FormatType.UINT, false, false, false, false), new FormatInfo('R16I', 2, 1, FormatType.INT, false, false, false, false), new FormatInfo('R32F', 4, 1, FormatType.FLOAT, false, false, false, false), new FormatInfo('R32UI', 4, 1, FormatType.UINT, false, false, false, false), new FormatInfo('R32I', 4, 1, FormatType.INT, false, false, false, false), new FormatInfo('RG8', 2, 2, FormatType.UNORM, false, false, false, false), new FormatInfo('RG8SN', 2, 2, FormatType.SNORM, false, false, false, false), new FormatInfo('RG8UI', 2, 2, FormatType.UINT, false, false, false, false), new FormatInfo('RG8I', 2, 2, FormatType.INT, false, false, false, false), new FormatInfo('RG16F', 4, 2, FormatType.FLOAT, false, false, false, false), new FormatInfo('RG16UI', 4, 2, FormatType.UINT, false, false, false, false), new FormatInfo('RG16I', 4, 2, FormatType.INT, false, false, false, false), new FormatInfo('RG32F', 8, 2, FormatType.FLOAT, false, false, false, false), new FormatInfo('RG32UI', 8, 2, FormatType.UINT, false, false, false, false), new FormatInfo('RG32I', 8, 2, FormatType.INT, false, false, false, false), new FormatInfo('RGB8', 3, 3, FormatType.UNORM, false, false, false, false), new FormatInfo('SRGB8', 3, 3, FormatType.UNORM, false, false, false, false), new FormatInfo('RGB8SN', 3, 3, FormatType.SNORM, false, false, false, false), new FormatInfo('RGB8UI', 3, 3, FormatType.UINT, false, false, false, false), new FormatInfo('RGB8I', 3, 3, FormatType.INT, false, false, false, false), new FormatInfo('RGB16F', 6, 3, FormatType.FLOAT, false, false, false, false), new FormatInfo('RGB16UI', 6, 3, FormatType.UINT, false, false, false, false), new FormatInfo('RGB16I', 6, 3, FormatType.INT, false, false, false, false), new FormatInfo('RGB32F', 12, 3, FormatType.FLOAT, false, false, false, false), new FormatInfo('RGB32UI', 12, 3, FormatType.UINT, false, false, false, false), new FormatInfo('RGB32I', 12, 3, FormatType.INT, false, false, false, false), new FormatInfo('RGBA8', 4, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('BGRA8', 4, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('SRGB8_A8', 4, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGBA8SN', 4, 4, FormatType.SNORM, true, false, false, false), new FormatInfo('RGBA8UI', 4, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGBA8I', 4, 4, FormatType.INT, true, false, false, false), new FormatInfo('RGBA16F', 8, 4, FormatType.FLOAT, true, false, false, false), new FormatInfo('RGBA16UI', 8, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGBA16I', 8, 4, FormatType.INT, true, false, false, false), new FormatInfo('RGBA32F', 16, 4, FormatType.FLOAT, true, false, false, false), new FormatInfo('RGBA32UI', 16, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGBA32I', 16, 4, FormatType.INT, true, false, false, false), new FormatInfo('R5G6B5', 2, 3, FormatType.UNORM, false, false, false, false), new FormatInfo('R11G11B10F', 4, 3, FormatType.FLOAT, false, false, false, false), new FormatInfo('RGB5A1', 2, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGBA4', 2, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGB10A2', 2, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGB10A2UI', 2, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGB9E5', 2, 4, FormatType.FLOAT, true, false, false, false), new FormatInfo('DEPTH', 4, 1, FormatType.FLOAT, false, true, false, false), new FormatInfo('DEPTH_STENCIL', 5, 2, FormatType.FLOAT, false, true, true, false), new FormatInfo('BC1', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('BC1_ALPHA', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC1_SRGB', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('BC1_SRGB_ALPHA', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC2', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC2_SRGB', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC3', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC3_SRGB', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC4', 1, 1, FormatType.UNORM, false, false, false, true), new FormatInfo('BC4_SNORM', 1, 1, FormatType.SNORM, false, false, false, true), new FormatInfo('BC5', 1, 2, FormatType.UNORM, false, false, false, true), new FormatInfo('BC5_SNORM', 1, 2, FormatType.SNORM, false, false, false, true), new FormatInfo('BC6H_UF16', 1, 3, FormatType.UFLOAT, false, false, false, true), new FormatInfo('BC6H_SF16', 1, 3, FormatType.FLOAT, false, false, false, true), new FormatInfo('BC7', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC7_SRGB', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC_RGB8', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('ETC2_RGB8', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('ETC2_SRGB8', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('ETC2_RGB8_A1', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC2_SRGB8_A1', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC2_RGBA8', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC2_SRGB8_A8', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('EAC_R11', 1, 1, FormatType.UNORM, false, false, false, true), new FormatInfo('EAC_R11SN', 1, 1, FormatType.SNORM, false, false, false, true), new FormatInfo('EAC_RG11', 2, 2, FormatType.UNORM, false, false, false, true), new FormatInfo('EAC_RG11SN', 2, 2, FormatType.SNORM, false, false, false, true), new FormatInfo('PVRTC_RGB2', 2, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('PVRTC_RGBA2', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('PVRTC_RGB4', 2, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('PVRTC_RGBA4', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('PVRTC2_2BPP', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('PVRTC2_4BPP', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_4x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_5x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_5x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_6x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_6x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_8x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_8x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_8x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_12x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_12x12', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_4x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_5x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_5x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_6x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_6x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_8x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_8x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_8x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_12x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_12x12', 1, 4, FormatType.UNORM, true, false, false, true)]);
      var DESCRIPTOR_BUFFER_TYPE = DescriptorType.UNIFORM_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER | DescriptorType.STORAGE_BUFFER | DescriptorType.DYNAMIC_STORAGE_BUFFER;
      var DESCRIPTOR_SAMPLER_TYPE = DescriptorType.SAMPLER_TEXTURE | DescriptorType.SAMPLER | DescriptorType.TEXTURE | DescriptorType.STORAGE_IMAGE | DescriptorType.INPUT_ATTACHMENT;
      var DESCRIPTOR_DYNAMIC_TYPE = DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER;
      var DRAW_INFO_SIZE = 28;
      function IsPowerOf2(x) {
        return x > 0 && (x & x - 1) === 0;
      }
      function FormatSize(format, width, height, depth) {
        if (!FormatInfos[format].isCompressed) {
          return width * height * depth * FormatInfos[format].size;
        } else {
          switch (format) {
            case Format.BC1:
            case Format.BC1_ALPHA:
            case Format.BC1_SRGB:
            case Format.BC1_SRGB_ALPHA:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth;
            case Format.BC2:
            case Format.BC2_SRGB:
            case Format.BC3:
            case Format.BC3_SRGB:
            case Format.BC4:
            case Format.BC4_SNORM:
            case Format.BC6H_SF16:
            case Format.BC6H_UF16:
            case Format.BC7:
            case Format.BC7_SRGB:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth;
            case Format.BC5:
            case Format.BC5_SNORM:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 32 * depth;
            case Format.ETC_RGB8:
            case Format.ETC2_RGB8:
            case Format.ETC2_SRGB8:
            case Format.ETC2_RGB8_A1:
            case Format.EAC_R11:
            case Format.EAC_R11SN:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth;
            case Format.ETC2_RGBA8:
            case Format.ETC2_SRGB8_A1:
            case Format.EAC_RG11:
            case Format.EAC_RG11SN:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth;
            case Format.PVRTC_RGB2:
            case Format.PVRTC_RGBA2:
            case Format.PVRTC2_2BPP:
              return Math.ceil(width / 8) * Math.ceil(height / 4) * 8 * depth;
            case Format.PVRTC_RGB4:
            case Format.PVRTC_RGBA4:
            case Format.PVRTC2_4BPP:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth;
            case Format.ASTC_RGBA_4X4:
            case Format.ASTC_SRGBA_4X4:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth;
            case Format.ASTC_RGBA_5X4:
            case Format.ASTC_SRGBA_5X4:
              return Math.ceil(width / 5) * Math.ceil(height / 4) * 16 * depth;
            case Format.ASTC_RGBA_5X5:
            case Format.ASTC_SRGBA_5X5:
              return Math.ceil(width / 5) * Math.ceil(height / 5) * 16 * depth;
            case Format.ASTC_RGBA_6X5:
            case Format.ASTC_SRGBA_6X5:
              return Math.ceil(width / 6) * Math.ceil(height / 5) * 16 * depth;
            case Format.ASTC_RGBA_6X6:
            case Format.ASTC_SRGBA_6X6:
              return Math.ceil(width / 6) * Math.ceil(height / 6) * 16 * depth;
            case Format.ASTC_RGBA_8X5:
            case Format.ASTC_SRGBA_8X5:
              return Math.ceil(width / 8) * Math.ceil(height / 5) * 16 * depth;
            case Format.ASTC_RGBA_8X6:
            case Format.ASTC_SRGBA_8X6:
              return Math.ceil(width / 8) * Math.ceil(height / 6) * 16 * depth;
            case Format.ASTC_RGBA_8X8:
            case Format.ASTC_SRGBA_8X8:
              return Math.ceil(width / 8) * Math.ceil(height / 8) * 16 * depth;
            case Format.ASTC_RGBA_10X5:
            case Format.ASTC_SRGBA_10X5:
              return Math.ceil(width / 10) * Math.ceil(height / 5) * 16 * depth;
            case Format.ASTC_RGBA_10X6:
            case Format.ASTC_SRGBA_10X6:
              return Math.ceil(width / 10) * Math.ceil(height / 6) * 16 * depth;
            case Format.ASTC_RGBA_10X8:
            case Format.ASTC_SRGBA_10X8:
              return Math.ceil(width / 10) * Math.ceil(height / 8) * 16 * depth;
            case Format.ASTC_RGBA_10X10:
            case Format.ASTC_SRGBA_10X10:
              return Math.ceil(width / 10) * Math.ceil(height / 10) * 16 * depth;
            case Format.ASTC_RGBA_12X10:
            case Format.ASTC_SRGBA_12X10:
              return Math.ceil(width / 12) * Math.ceil(height / 10) * 16 * depth;
            case Format.ASTC_RGBA_12X12:
            case Format.ASTC_SRGBA_12X12:
              return Math.ceil(width / 12) * Math.ceil(height / 12) * 16 * depth;
            default:
              {
                return 0;
              }
          }
        }
      }
      function FormatSurfaceSize(format, width, height, depth, mips) {
        var size = 0;
        for (var i = 0; i < mips; ++i) {
          size += FormatSize(format, width, height, depth);
          width = Math.max(width >> 1, 1);
          height = Math.max(height >> 1, 1);
        }
        return size;
      }
      var _type2size = [0, 4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16, 16, 24, 32, 24, 36, 48, 32, 48, 64, 4, 4, 4, 4, 4, 4];
      function GetTypeSize(type) {
        return _type2size[type] || 0;
      }
      function getTypedArrayConstructor(info) {
        if (info.isCompressed) {
          return Uint8Array;
        }
        var stride = info.size / info.count;
        switch (info.type) {
          case FormatType.UNORM:
          case FormatType.UINT:
            {
              switch (stride) {
                case 1:
                  return Uint8Array;
                case 2:
                  return Uint16Array;
                case 4:
                  return Uint32Array;
                default:
                  return Uint8Array;
              }
            }
          case FormatType.SNORM:
          case FormatType.INT:
            {
              switch (stride) {
                case 1:
                  return Int8Array;
                case 2:
                  return Int16Array;
                case 4:
                  return Int32Array;
                default:
                  return Int8Array;
              }
            }
          case FormatType.FLOAT:
            {
              switch (stride) {
                case 2:
                  return Uint16Array;
                case 4:
                  return Float32Array;
                default:
                  return Float32Array;
              }
            }
        }
        return Float32Array;
      }
      function formatAlignment(format) {
        switch (format) {
          case Format.BC1:
          case Format.BC1_ALPHA:
          case Format.BC1_SRGB:
          case Format.BC1_SRGB_ALPHA:
          case Format.BC2:
          case Format.BC2_SRGB:
          case Format.BC3:
          case Format.BC3_SRGB:
          case Format.BC4:
          case Format.BC4_SNORM:
          case Format.BC6H_SF16:
          case Format.BC6H_UF16:
          case Format.BC7:
          case Format.BC7_SRGB:
          case Format.BC5:
          case Format.BC5_SNORM:
          case Format.ETC_RGB8:
          case Format.ETC2_RGB8:
          case Format.ETC2_SRGB8:
          case Format.ETC2_RGB8_A1:
          case Format.EAC_R11:
          case Format.EAC_R11SN:
          case Format.ETC2_RGBA8:
          case Format.ETC2_SRGB8_A1:
          case Format.EAC_RG11:
          case Format.EAC_RG11SN:
            return {
              width: 4,
              height: 4
            };
          case Format.PVRTC_RGB2:
          case Format.PVRTC_RGBA2:
          case Format.PVRTC2_2BPP:
            return {
              width: 8,
              height: 4
            };
          case Format.PVRTC_RGB4:
          case Format.PVRTC_RGBA4:
          case Format.PVRTC2_4BPP:
            return {
              width: 4,
              height: 4
            };
          case Format.ASTC_RGBA_4X4:
          case Format.ASTC_SRGBA_4X4:
            return {
              width: 4,
              height: 4
            };
          case Format.ASTC_RGBA_5X4:
          case Format.ASTC_SRGBA_5X4:
            return {
              width: 5,
              height: 4
            };
          case Format.ASTC_RGBA_5X5:
          case Format.ASTC_SRGBA_5X5:
            return {
              width: 5,
              height: 5
            };
          case Format.ASTC_RGBA_6X5:
          case Format.ASTC_SRGBA_6X5:
            return {
              width: 6,
              height: 5
            };
          case Format.ASTC_RGBA_6X6:
          case Format.ASTC_SRGBA_6X6:
            return {
              width: 6,
              height: 6
            };
          case Format.ASTC_RGBA_8X5:
          case Format.ASTC_SRGBA_8X5:
            return {
              width: 8,
              height: 5
            };
          case Format.ASTC_RGBA_8X6:
          case Format.ASTC_SRGBA_8X6:
            return {
              width: 8,
              height: 6
            };
          case Format.ASTC_RGBA_8X8:
          case Format.ASTC_SRGBA_8X8:
            return {
              width: 8,
              height: 8
            };
          case Format.ASTC_RGBA_10X5:
          case Format.ASTC_SRGBA_10X5:
            return {
              width: 10,
              height: 5
            };
          case Format.ASTC_RGBA_10X6:
          case Format.ASTC_SRGBA_10X6:
            return {
              width: 10,
              height: 6
            };
          case Format.ASTC_RGBA_10X8:
          case Format.ASTC_SRGBA_10X8:
            return {
              width: 10,
              height: 8
            };
          case Format.ASTC_RGBA_10X10:
          case Format.ASTC_SRGBA_10X10:
            return {
              width: 10,
              height: 10
            };
          case Format.ASTC_RGBA_12X10:
          case Format.ASTC_SRGBA_12X10:
            return {
              width: 12,
              height: 10
            };
          case Format.ASTC_RGBA_12X12:
          case Format.ASTC_SRGBA_12X12:
            return {
              width: 12,
              height: 12
            };
          default:
            return {
              width: 1,
              height: 1
            };
        }
      }
      function alignTo(size, alignment) {
        return Math.ceil(size / alignment) * alignment;
      }

      var defines = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get ObjectType () { return ObjectType; },
        get Status () { return Status; },
        get API () { return API; },
        get SurfaceTransform () { return SurfaceTransform; },
        get Feature () { return Feature; },
        get Format () { return Format; },
        get FormatType () { return FormatType; },
        get Type () { return Type$1; },
        get BufferUsageBit () { return BufferUsageBit; },
        get BufferFlagBit () { return BufferFlagBit; },
        get MemoryAccessBit () { return MemoryAccessBit; },
        get MemoryUsageBit () { return MemoryUsageBit; },
        get TextureType () { return TextureType; },
        get TextureUsageBit () { return TextureUsageBit; },
        get TextureFlagBit () { return TextureFlagBit; },
        get FormatFeatureBit () { return FormatFeatureBit; },
        get SampleCount () { return SampleCount; },
        get VsyncMode () { return VsyncMode; },
        get Filter () { return Filter$1; },
        get Address () { return Address; },
        get ComparisonFunc () { return ComparisonFunc; },
        get StencilOp () { return StencilOp; },
        get BlendFactor () { return BlendFactor; },
        get BlendOp () { return BlendOp; },
        get ColorMask () { return ColorMask; },
        get ShaderStageFlagBit () { return ShaderStageFlagBit; },
        get LoadOp () { return LoadOp; },
        get StoreOp () { return StoreOp; },
        get AccessFlagBit () { return AccessFlagBit; },
        get ResolveMode () { return ResolveMode; },
        get PipelineBindPoint () { return PipelineBindPoint; },
        get PrimitiveMode () { return PrimitiveMode; },
        get PolygonMode () { return PolygonMode; },
        get ShadeModel () { return ShadeModel; },
        get CullMode () { return CullMode; },
        get DynamicStateFlagBit () { return DynamicStateFlagBit; },
        get StencilFace () { return StencilFace; },
        get DescriptorType () { return DescriptorType; },
        get QueueType () { return QueueType; },
        get QueryType () { return QueryType; },
        get CommandBufferType () { return CommandBufferType; },
        get ClearFlagBit () { return ClearFlagBit; },
        get BarrierType () { return BarrierType; },
        get PassType () { return PassType; },
        Size: Size,
        DeviceCaps: DeviceCaps,
        DeviceOptions: DeviceOptions,
        Offset: Offset,
        Rect: Rect,
        Extent: Extent,
        TextureSubresLayers: TextureSubresLayers,
        TextureSubresRange: TextureSubresRange,
        TextureCopy: TextureCopy,
        TextureBlit: TextureBlit,
        BufferTextureCopy: BufferTextureCopy,
        Viewport: Viewport,
        Color: Color,
        BindingMappingInfo: BindingMappingInfo,
        SwapchainInfo: SwapchainInfo,
        DeviceInfo: DeviceInfo,
        BufferInfo: BufferInfo,
        BufferViewInfo: BufferViewInfo,
        DrawInfo: DrawInfo,
        DispatchInfo: DispatchInfo,
        IndirectBuffer: IndirectBuffer,
        TextureInfo: TextureInfo,
        TextureViewInfo: TextureViewInfo,
        SamplerInfo: SamplerInfo,
        Uniform: Uniform,
        UniformBlock: UniformBlock,
        UniformSamplerTexture: UniformSamplerTexture,
        UniformSampler: UniformSampler,
        UniformTexture: UniformTexture,
        UniformStorageImage: UniformStorageImage,
        UniformStorageBuffer: UniformStorageBuffer,
        UniformInputAttachment: UniformInputAttachment,
        ShaderStage: ShaderStage,
        Attribute: Attribute,
        ShaderInfo: ShaderInfo,
        InputAssemblerInfo: InputAssemblerInfo,
        ColorAttachment: ColorAttachment,
        DepthStencilAttachment: DepthStencilAttachment,
        SubpassInfo: SubpassInfo,
        SubpassDependency: SubpassDependency,
        RenderPassInfo: RenderPassInfo,
        GeneralBarrierInfo: GeneralBarrierInfo,
        TextureBarrierInfo: TextureBarrierInfo,
        BufferBarrierInfo: BufferBarrierInfo,
        FramebufferInfo: FramebufferInfo,
        DescriptorSetLayoutBinding: DescriptorSetLayoutBinding,
        DescriptorSetLayoutInfo: DescriptorSetLayoutInfo,
        DescriptorSetInfo: DescriptorSetInfo,
        PipelineLayoutInfo: PipelineLayoutInfo,
        InputState: InputState,
        CommandBufferInfo: CommandBufferInfo,
        QueueInfo: QueueInfo,
        QueryPoolInfo: QueryPoolInfo,
        FormatInfo: FormatInfo,
        MemoryStatus: MemoryStatus,
        DynamicStencilStates: DynamicStencilStates,
        DynamicStates: DynamicStates,
        GFXObject: GFXObject,
        get AttributeName () { return AttributeName; },
        FormatInfos: FormatInfos,
        DESCRIPTOR_BUFFER_TYPE: DESCRIPTOR_BUFFER_TYPE,
        DESCRIPTOR_SAMPLER_TYPE: DESCRIPTOR_SAMPLER_TYPE,
        DESCRIPTOR_DYNAMIC_TYPE: DESCRIPTOR_DYNAMIC_TYPE,
        DRAW_INFO_SIZE: DRAW_INFO_SIZE,
        IsPowerOf2: IsPowerOf2,
        FormatSize: FormatSize,
        FormatSurfaceSize: FormatSurfaceSize,
        GetTypeSize: GetTypeSize,
        getTypedArrayConstructor: getTypedArrayConstructor,
        formatAlignment: formatAlignment,
        alignTo: alignTo
      });

      var Buffer = function (_GFXObject) {
        _inheritsLoose(Buffer, _GFXObject);
        function Buffer() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.BUFFER) || this;
          _this._usage = BufferUsageBit.NONE;
          _this._memUsage = MemoryUsageBit.NONE;
          _this._size = 0;
          _this._stride = 1;
          _this._count = 0;
          _this._flags = BufferFlagBit.NONE;
          _this._isBufferView = false;
          return _this;
        }
        _createClass(Buffer, [{
          key: "usage",
          get: function get() {
            return this._usage;
          }
        }, {
          key: "memUsage",
          get: function get() {
            return this._memUsage;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          }
        }, {
          key: "stride",
          get: function get() {
            return this._stride;
          }
        }, {
          key: "count",
          get: function get() {
            return this._count;
          }
        }, {
          key: "flags",
          get: function get() {
            return this._flags;
          }
        }]);
        return Buffer;
      }(GFXObject);

      var CommandBuffer = function (_GFXObject) {
        _inheritsLoose(CommandBuffer, _GFXObject);
        function CommandBuffer() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.COMMAND_BUFFER) || this;
          _this._queue = null;
          _this._type = CommandBufferType.PRIMARY;
          _this._numDrawCalls = 0;
          _this._numInstances = 0;
          _this._numTris = 0;
          return _this;
        }
        _createClass(CommandBuffer, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "queue",
          get: function get() {
            return this._queue;
          }
        }, {
          key: "numDrawCalls",
          get: function get() {
            return this._numDrawCalls;
          }
        }, {
          key: "numInstances",
          get: function get() {
            return this._numInstances;
          }
        }, {
          key: "numTris",
          get: function get() {
            return this._numTris;
          }
        }]);
        return CommandBuffer;
      }(GFXObject);

      var Device = function () {
        function Device() {
          this._gfxAPI = API.UNKNOWN;
          this._renderer = '';
          this._vendor = '';
          this._features = new Array(Feature.COUNT);
          this._formatFeatures = new Array(Format.COUNT);
          this._queue = null;
          this._cmdBuff = null;
          this._numDrawCalls = 0;
          this._numInstances = 0;
          this._numTris = 0;
          this._memoryStatus = new MemoryStatus();
          this._caps = new DeviceCaps();
          this._bindingMappingInfo = new BindingMappingInfo();
          this._samplers = new Map();
          this._generalBarrierss = new Map();
          this._textureBarriers = new Map();
          this._bufferBarriers = new Map();
        }
        var _proto = Device.prototype;
        _proto.hasFeature = function hasFeature(feature) {
          return this._features[feature];
        };
        _proto.getFormatFeatures = function getFormatFeatures(format) {
          return this._formatFeatures[format];
        };
        _proto.enableAutoBarrier = function enableAutoBarrier(en) {};
        _proto.getMaxSampleCount = function getMaxSampleCount(format, usage, flags) {
          return SampleCount.X1;
        };
        _createClass(Device, [{
          key: "gfxAPI",
          get: function get() {
            return this._gfxAPI;
          }
        }, {
          key: "queue",
          get: function get() {
            return this._queue;
          }
        }, {
          key: "commandBuffer",
          get: function get() {
            return this._cmdBuff;
          }
        }, {
          key: "renderer",
          get: function get() {
            return this._renderer;
          }
        }, {
          key: "vendor",
          get: function get() {
            return this._vendor;
          }
        }, {
          key: "numDrawCalls",
          get: function get() {
            return this._numDrawCalls;
          }
        }, {
          key: "numInstances",
          get: function get() {
            return this._numInstances;
          }
        }, {
          key: "numTris",
          get: function get() {
            return this._numTris;
          }
        }, {
          key: "memoryStatus",
          get: function get() {
            return this._memoryStatus;
          }
        }, {
          key: "capabilities",
          get: function get() {
            return this._caps;
          }
        }, {
          key: "bindingMappingInfo",
          get: function get() {
            return this._bindingMappingInfo;
          }
        }]);
        return Device;
      }();
      Device.canvas = void 0;
      var DefaultResource = function () {
        function DefaultResource(device) {
          this._texture2D = null;
          this._texture3D = null;
          this._textureCube = null;
          this._texture2DArray = null;
          var bufferSize = 64;
          var buffer = new Uint8Array(bufferSize);
          buffer.fill(255);
          if (device.capabilities.maxTextureSize >= 2) {
            this._texture2D = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE));
            var copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 1));
            device.copyBuffersToTexture([buffer], this._texture2D, [copyRegion]);
          }
          if (device.capabilities.maxTextureSize >= 2) {
            this._textureCube = device.createTexture(new TextureInfo(TextureType.CUBE, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE, 6));
            var _copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 1));
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
            _copyRegion.texSubres.baseArrayLayer = 1;
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
            _copyRegion.texSubres.baseArrayLayer = 2;
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
            _copyRegion.texSubres.baseArrayLayer = 3;
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
            _copyRegion.texSubres.baseArrayLayer = 4;
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
            _copyRegion.texSubres.baseArrayLayer = 5;
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
          }
          if (device.capabilities.max3DTextureSize >= 2) {
            this._texture3D = device.createTexture(new TextureInfo(TextureType.TEX3D, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE, 1, 1, SampleCount.X1, 2));
            var _copyRegion2 = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 2), new TextureSubresLayers(0, 0, 1));
            device.copyBuffersToTexture([buffer], this._texture3D, [_copyRegion2]);
          }
          if (device.capabilities.maxArrayTextureLayers >= 2) {
            this._texture2DArray = device.createTexture(new TextureInfo(TextureType.TEX2D_ARRAY, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE, 2));
            var _copyRegion3 = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 1), new TextureSubresLayers(0, 0, 1));
            device.copyBuffersToTexture([buffer], this._texture2DArray, [_copyRegion3]);
            _copyRegion3.texSubres.baseArrayLayer = 1;
            device.copyBuffersToTexture([buffer], this._texture2DArray, [_copyRegion3]);
          }
        }
        var _proto2 = DefaultResource.prototype;
        _proto2.getTexture = function getTexture(type) {
          switch (type) {
            case TextureType.TEX2D:
              return this._texture2D;
            case TextureType.TEX3D:
              return this._texture3D;
            case TextureType.CUBE:
              return this._textureCube;
            case TextureType.TEX2D_ARRAY:
              return this._texture2DArray;
            default:
              return null;
          }
        };
        return DefaultResource;
      }();

      var Swapchain = function (_GFXObject) {
        _inheritsLoose(Swapchain, _GFXObject);
        function Swapchain() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.SWAPCHAIN) || this;
          _this._transform = SurfaceTransform.IDENTITY;
          _this._colorTexture = null;
          _this._depthStencilTexture = null;
          return _this;
        }
        _createClass(Swapchain, [{
          key: "colorTexture",
          get: function get() {
            return this._colorTexture;
          }
        }, {
          key: "depthStencilTexture",
          get: function get() {
            return this._depthStencilTexture;
          }
        }, {
          key: "surfaceTransform",
          get: function get() {
            return this._transform;
          }
        }, {
          key: "width",
          get: function get() {
            return this._colorTexture.width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._colorTexture.height;
          }
        }]);
        return Swapchain;
      }(GFXObject);

      var Framebuffer = function (_GFXObject) {
        _inheritsLoose(Framebuffer, _GFXObject);
        function Framebuffer() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.FRAMEBUFFER) || this;
          _this._renderPass = null;
          _this._colorTextures = [];
          _this._depthStencilTexture = null;
          _this._width = 0;
          _this._height = 0;
          return _this;
        }
        _createClass(Framebuffer, [{
          key: "renderPass",
          get: function get() {
            return this._renderPass;
          }
        }, {
          key: "colorTextures",
          get: function get() {
            return this._colorTextures;
          }
        }, {
          key: "depthStencilTexture",
          get: function get() {
            return this._depthStencilTexture;
          }
        }, {
          key: "width",
          get: function get() {
            if (this.colorTextures.length > 0) {
              return this.colorTextures[0].width;
            } else if (this.depthStencilTexture) {
              return this.depthStencilTexture.width;
            }
            return this._width;
          }
        }, {
          key: "height",
          get: function get() {
            if (this.colorTextures.length > 0) {
              return this.colorTextures[0].height;
            } else if (this.depthStencilTexture) {
              return this.depthStencilTexture.height;
            }
            return this._height;
          }
        }]);
        return Framebuffer;
      }(GFXObject);

      var InputAssembler = function (_GFXObject) {
        _inheritsLoose(InputAssembler, _GFXObject);
        function InputAssembler() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.INPUT_ASSEMBLER) || this;
          _this._attributes = [];
          _this._attributesHash = 0;
          _this._vertexBuffers = [];
          _this._indexBuffer = null;
          _this._indirectBuffer = null;
          _this._drawInfo = new DrawInfo();
          return _this;
        }
        var _proto = InputAssembler.prototype;
        _proto.getVertexBuffer = function getVertexBuffer(stream) {
          if (stream === void 0) {
            stream = 0;
          }
          if (stream < this._vertexBuffers.length) {
            return this._vertexBuffers[stream];
          } else {
            return null;
          }
        };
        _proto.computeAttributesHash = function computeAttributesHash() {
          var res = 'attrs';
          for (var i = 0; i < this.attributes.length; ++i) {
            var at = this.attributes[i];
            res += "," + at.name + "," + at.format + "," + at.isNormalized + "," + at.stream + "," + at.isInstanced + "," + at.location;
          }
          return murmurhash2_32_gc(res, 666);
        };
        _createClass(InputAssembler, [{
          key: "attributes",
          get: function get() {
            return this._attributes;
          }
        }, {
          key: "vertexBuffers",
          get: function get() {
            return this._vertexBuffers;
          }
        }, {
          key: "indexBuffer",
          get: function get() {
            return this._indexBuffer;
          }
        }, {
          key: "indirectBuffer",
          get: function get() {
            return this._indirectBuffer;
          }
        }, {
          key: "attributesHash",
          get: function get() {
            return this._attributesHash;
          }
        }, {
          key: "vertexCount",
          get: function get() {
            return this._drawInfo.vertexCount;
          },
          set: function set(count) {
            this._drawInfo.vertexCount = count;
          }
        }, {
          key: "firstVertex",
          get: function get() {
            return this._drawInfo.firstVertex;
          },
          set: function set(first) {
            this._drawInfo.firstVertex = first;
          }
        }, {
          key: "indexCount",
          get: function get() {
            return this._drawInfo.indexCount;
          },
          set: function set(count) {
            this._drawInfo.indexCount = count;
          }
        }, {
          key: "firstIndex",
          get: function get() {
            return this._drawInfo.firstIndex;
          },
          set: function set(first) {
            this._drawInfo.firstIndex = first;
          }
        }, {
          key: "vertexOffset",
          get: function get() {
            return this._drawInfo.vertexOffset;
          },
          set: function set(offset) {
            this._drawInfo.vertexOffset = offset;
          }
        }, {
          key: "instanceCount",
          get: function get() {
            return this._drawInfo.instanceCount;
          },
          set: function set(count) {
            this._drawInfo.instanceCount = count;
          }
        }, {
          key: "firstInstance",
          get: function get() {
            return this._drawInfo.firstInstance;
          },
          set: function set(first) {
            this._drawInfo.firstInstance = first;
          }
        }, {
          key: "drawInfo",
          get: function get() {
            return this._drawInfo;
          },
          set: function set(info) {
            this._drawInfo = info;
          }
        }]);
        return InputAssembler;
      }(GFXObject);

      var DescriptorSet = function (_GFXObject) {
        _inheritsLoose(DescriptorSet, _GFXObject);
        function DescriptorSet() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.DESCRIPTOR_SET) || this;
          _this._layout = null;
          _this._buffers = [];
          _this._textures = [];
          _this._samplers = [];
          _this._isDirty = false;
          return _this;
        }
        var _proto = DescriptorSet.prototype;
        _proto.bindBuffer = function bindBuffer(binding, buffer, index) {
          if (index === void 0) {
            index = 0;
          }
          var bindingIndex = this._layout.bindingIndices[binding];
          var info = this._layout.bindings[bindingIndex];
          if (!info) {
            return;
          }
          if (info.descriptorType & DESCRIPTOR_BUFFER_TYPE) {
            var descriptorIndex = this._layout.descriptorIndices[binding];
            if (this._buffers[descriptorIndex + index] !== buffer) {
              this._buffers[descriptorIndex + index] = buffer;
              this._isDirty = true;
            }
          }
        };
        _proto.bindSampler = function bindSampler(binding, sampler, index) {
          if (index === void 0) {
            index = 0;
          }
          var bindingIndex = this._layout.bindingIndices[binding];
          var info = this._layout.bindings[bindingIndex];
          if (!info) {
            return;
          }
          if (info.descriptorType & DESCRIPTOR_SAMPLER_TYPE) {
            var descriptorIndex = this._layout.descriptorIndices[binding];
            if (this._samplers[descriptorIndex + index] !== sampler) {
              this._samplers[descriptorIndex + index] = sampler;
              this._isDirty = true;
            }
          }
        };
        _proto.bindTexture = function bindTexture(binding, texture, index, flags) {
          if (index === void 0) {
            index = 0;
          }
          var bindingIndex = this._layout.bindingIndices[binding];
          var info = this._layout.bindings[bindingIndex];
          if (!info) {
            return;
          }
          if (info.descriptorType & DESCRIPTOR_SAMPLER_TYPE) {
            var descriptorIndex = this._layout.descriptorIndices[binding];
            if (this._textures[descriptorIndex + index] !== texture) {
              this._textures[descriptorIndex + index] = texture;
              this._isDirty = true;
            }
          }
        };
        _proto.getBuffer = function getBuffer(binding, index) {
          if (index === void 0) {
            index = 0;
          }
          var descriptorIndex = this._layout.descriptorIndices[binding];
          return this._buffers[descriptorIndex + index];
        };
        _proto.getSampler = function getSampler(binding, index) {
          if (index === void 0) {
            index = 0;
          }
          var descriptorIndex = this._layout.descriptorIndices[binding];
          return this._samplers[descriptorIndex + index];
        };
        _proto.getTexture = function getTexture(binding, index) {
          if (index === void 0) {
            index = 0;
          }
          var descriptorIndex = this._layout.descriptorIndices[binding];
          return this._textures[descriptorIndex + index];
        };
        _createClass(DescriptorSet, [{
          key: "layout",
          get: function get() {
            return this._layout;
          }
        }]);
        return DescriptorSet;
      }(GFXObject);

      var DescriptorSetLayout = function (_GFXObject) {
        _inheritsLoose(DescriptorSetLayout, _GFXObject);
        function DescriptorSetLayout() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.DESCRIPTOR_SET_LAYOUT) || this;
          _this._bindings = [];
          _this._bindingIndices = [];
          _this._descriptorIndices = [];
          return _this;
        }
        _createClass(DescriptorSetLayout, [{
          key: "bindings",
          get: function get() {
            return this._bindings;
          }
        }, {
          key: "bindingIndices",
          get: function get() {
            return this._bindingIndices;
          }
        }, {
          key: "descriptorIndices",
          get: function get() {
            return this._descriptorIndices;
          }
        }]);
        return DescriptorSetLayout;
      }(GFXObject);

      var PipelineLayout = function (_GFXObject) {
        _inheritsLoose(PipelineLayout, _GFXObject);
        function PipelineLayout() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.PIPELINE_LAYOUT) || this;
          _this._setLayouts = [];
          return _this;
        }
        _createClass(PipelineLayout, [{
          key: "setLayouts",
          get: function get() {
            return this._setLayouts;
          }
        }]);
        return PipelineLayout;
      }(GFXObject);

      var RasterizerState = function () {
        function RasterizerState(isDiscard, polygonMode, shadeModel, cullMode, isFrontFaceCCW, depthBiasEnabled, depthBias, depthBiasClamp, depthBiasSlop, isDepthClip, isMultisample, lineWidth) {
          if (isDiscard === void 0) {
            isDiscard = false;
          }
          if (polygonMode === void 0) {
            polygonMode = PolygonMode.FILL;
          }
          if (shadeModel === void 0) {
            shadeModel = ShadeModel.GOURAND;
          }
          if (cullMode === void 0) {
            cullMode = CullMode.BACK;
          }
          if (isFrontFaceCCW === void 0) {
            isFrontFaceCCW = true;
          }
          if (depthBiasEnabled === void 0) {
            depthBiasEnabled = false;
          }
          if (depthBias === void 0) {
            depthBias = 0;
          }
          if (depthBiasClamp === void 0) {
            depthBiasClamp = 0.0;
          }
          if (depthBiasSlop === void 0) {
            depthBiasSlop = 0.0;
          }
          if (isDepthClip === void 0) {
            isDepthClip = true;
          }
          if (isMultisample === void 0) {
            isMultisample = false;
          }
          if (lineWidth === void 0) {
            lineWidth = 1.0;
          }
          this.isDiscard = isDiscard;
          this.polygonMode = polygonMode;
          this.shadeModel = shadeModel;
          this.cullMode = cullMode;
          this.isFrontFaceCCW = isFrontFaceCCW;
          this.depthBiasEnabled = depthBiasEnabled;
          this.depthBias = depthBias;
          this.depthBiasClamp = depthBiasClamp;
          this.depthBiasSlop = depthBiasSlop;
          this.isDepthClip = isDepthClip;
          this.isMultisample = isMultisample;
          this.lineWidth = lineWidth;
        }
        var _proto = RasterizerState.prototype;
        _proto.reset = function reset() {
          this.isDiscard = false;
          this.polygonMode = PolygonMode.FILL;
          this.shadeModel = ShadeModel.GOURAND;
          this.cullMode = CullMode.BACK;
          this.isFrontFaceCCW = true;
          this.depthBiasEnabled = false;
          this.depthBias = 0;
          this.depthBiasClamp = 0.0;
          this.depthBiasSlop = 0.0;
          this.isDepthClip = true;
          this.isMultisample = false;
          this.lineWidth = 1.0;
        };
        _proto.assign = function assign(rs) {
          Object.assign(this, rs);
        };
        _proto.destroy = function destroy() {};
        _createClass(RasterizerState, [{
          key: "native",
          get: function get() {
            return this;
          }
        }]);
        return RasterizerState;
      }();
      var DepthStencilState = function () {
        function DepthStencilState(depthTest, depthWrite, depthFunc, stencilTestFront, stencilFuncFront, stencilReadMaskFront, stencilWriteMaskFront, stencilFailOpFront, stencilZFailOpFront, stencilPassOpFront, stencilRefFront, stencilTestBack, stencilFuncBack, stencilReadMaskBack, stencilWriteMaskBack, stencilFailOpBack, stencilZFailOpBack, stencilPassOpBack, stencilRefBack) {
          if (depthTest === void 0) {
            depthTest = true;
          }
          if (depthWrite === void 0) {
            depthWrite = true;
          }
          if (depthFunc === void 0) {
            depthFunc = ComparisonFunc.LESS;
          }
          if (stencilTestFront === void 0) {
            stencilTestFront = false;
          }
          if (stencilFuncFront === void 0) {
            stencilFuncFront = ComparisonFunc.ALWAYS;
          }
          if (stencilReadMaskFront === void 0) {
            stencilReadMaskFront = 0xffff;
          }
          if (stencilWriteMaskFront === void 0) {
            stencilWriteMaskFront = 0xffff;
          }
          if (stencilFailOpFront === void 0) {
            stencilFailOpFront = StencilOp.KEEP;
          }
          if (stencilZFailOpFront === void 0) {
            stencilZFailOpFront = StencilOp.KEEP;
          }
          if (stencilPassOpFront === void 0) {
            stencilPassOpFront = StencilOp.KEEP;
          }
          if (stencilRefFront === void 0) {
            stencilRefFront = 1;
          }
          if (stencilTestBack === void 0) {
            stencilTestBack = false;
          }
          if (stencilFuncBack === void 0) {
            stencilFuncBack = ComparisonFunc.ALWAYS;
          }
          if (stencilReadMaskBack === void 0) {
            stencilReadMaskBack = 0xffff;
          }
          if (stencilWriteMaskBack === void 0) {
            stencilWriteMaskBack = 0xffff;
          }
          if (stencilFailOpBack === void 0) {
            stencilFailOpBack = StencilOp.KEEP;
          }
          if (stencilZFailOpBack === void 0) {
            stencilZFailOpBack = StencilOp.KEEP;
          }
          if (stencilPassOpBack === void 0) {
            stencilPassOpBack = StencilOp.KEEP;
          }
          if (stencilRefBack === void 0) {
            stencilRefBack = 1;
          }
          this.depthTest = depthTest;
          this.depthWrite = depthWrite;
          this.depthFunc = depthFunc;
          this.stencilTestFront = stencilTestFront;
          this.stencilFuncFront = stencilFuncFront;
          this.stencilReadMaskFront = stencilReadMaskFront;
          this.stencilWriteMaskFront = stencilWriteMaskFront;
          this.stencilFailOpFront = stencilFailOpFront;
          this.stencilZFailOpFront = stencilZFailOpFront;
          this.stencilPassOpFront = stencilPassOpFront;
          this.stencilRefFront = stencilRefFront;
          this.stencilTestBack = stencilTestBack;
          this.stencilFuncBack = stencilFuncBack;
          this.stencilReadMaskBack = stencilReadMaskBack;
          this.stencilWriteMaskBack = stencilWriteMaskBack;
          this.stencilFailOpBack = stencilFailOpBack;
          this.stencilZFailOpBack = stencilZFailOpBack;
          this.stencilPassOpBack = stencilPassOpBack;
          this.stencilRefBack = stencilRefBack;
        }
        var _proto2 = DepthStencilState.prototype;
        _proto2.reset = function reset() {
          this.depthTest = true;
          this.depthWrite = true;
          this.depthFunc = ComparisonFunc.LESS;
          this.stencilTestFront = false;
          this.stencilFuncFront = ComparisonFunc.ALWAYS;
          this.stencilReadMaskFront = 0xffff;
          this.stencilWriteMaskFront = 0xffff;
          this.stencilFailOpFront = StencilOp.KEEP;
          this.stencilZFailOpFront = StencilOp.KEEP;
          this.stencilPassOpFront = StencilOp.KEEP;
          this.stencilRefFront = 1;
          this.stencilTestBack = false;
          this.stencilFuncBack = ComparisonFunc.ALWAYS;
          this.stencilReadMaskBack = 0xffff;
          this.stencilWriteMaskBack = 0xffff;
          this.stencilFailOpBack = StencilOp.KEEP;
          this.stencilZFailOpBack = StencilOp.KEEP;
          this.stencilPassOpBack = StencilOp.KEEP;
          this.stencilRefBack = 1;
        };
        _proto2.assign = function assign(dss) {
          Object.assign(this, dss);
        };
        _proto2.destroy = function destroy() {};
        _createClass(DepthStencilState, [{
          key: "native",
          get: function get() {
            return this;
          }
        }]);
        return DepthStencilState;
      }();
      var BlendTarget = function () {
        function BlendTarget(blend, blendSrc, blendDst, blendEq, blendSrcAlpha, blendDstAlpha, blendAlphaEq, blendColorMask) {
          if (blend === void 0) {
            blend = false;
          }
          if (blendSrc === void 0) {
            blendSrc = BlendFactor.ONE;
          }
          if (blendDst === void 0) {
            blendDst = BlendFactor.ZERO;
          }
          if (blendEq === void 0) {
            blendEq = BlendOp.ADD;
          }
          if (blendSrcAlpha === void 0) {
            blendSrcAlpha = BlendFactor.ONE;
          }
          if (blendDstAlpha === void 0) {
            blendDstAlpha = BlendFactor.ZERO;
          }
          if (blendAlphaEq === void 0) {
            blendAlphaEq = BlendOp.ADD;
          }
          if (blendColorMask === void 0) {
            blendColorMask = ColorMask.ALL;
          }
          this.blend = blend;
          this.blendSrc = blendSrc;
          this.blendDst = blendDst;
          this.blendEq = blendEq;
          this.blendSrcAlpha = blendSrcAlpha;
          this.blendDstAlpha = blendDstAlpha;
          this.blendAlphaEq = blendAlphaEq;
          this.blendColorMask = blendColorMask;
        }
        var _proto3 = BlendTarget.prototype;
        _proto3.reset = function reset() {
          this.blend = false;
          this.blendSrc = BlendFactor.ONE;
          this.blendDst = BlendFactor.ZERO;
          this.blendEq = BlendOp.ADD;
          this.blendSrcAlpha = BlendFactor.ONE;
          this.blendDstAlpha = BlendFactor.ZERO;
          this.blendAlphaEq = BlendOp.ADD;
          this.blendColorMask = ColorMask.ALL;
        };
        _proto3.assign = function assign(target) {
          Object.assign(this, target);
        };
        _proto3.destroy = function destroy() {};
        return BlendTarget;
      }();
      var BlendState$1 = function () {
        function BlendState(isA2C, isIndepend, blendColor, targets) {
          if (isA2C === void 0) {
            isA2C = false;
          }
          if (isIndepend === void 0) {
            isIndepend = false;
          }
          if (blendColor === void 0) {
            blendColor = new Color();
          }
          if (targets === void 0) {
            targets = [new BlendTarget()];
          }
          this.isA2C = isA2C;
          this.isIndepend = isIndepend;
          this.blendColor = blendColor;
          this.targets = targets;
        }
        var _proto4 = BlendState.prototype;
        _proto4.setTarget = function setTarget(index, target) {
          var tg = this.targets[index];
          if (!tg) {
            tg = this.targets[index] = new BlendTarget();
          }
          Object.assign(tg, target);
        };
        _proto4.reset = function reset() {
          this.isA2C = false;
          this.isIndepend = false;
          this.blendColor.x = 0;
          this.blendColor.y = 0;
          this.blendColor.z = 0;
          this.blendColor.w = 0;
          this.targets.length = 1;
          this.targets[0].reset();
        };
        _proto4.destroy = function destroy() {};
        _createClass(BlendState, [{
          key: "native",
          get: function get() {
            return this;
          }
        }]);
        return BlendState;
      }();

      var PipelineStateInfo = function PipelineStateInfo(shader, pipelineLayout, renderPass, inputState, rasterizerState, depthStencilState, blendState, primitive, dynamicStates, bindPoint) {
        if (shader === void 0) {
          shader = null;
        }
        if (pipelineLayout === void 0) {
          pipelineLayout = null;
        }
        if (renderPass === void 0) {
          renderPass = null;
        }
        if (inputState === void 0) {
          inputState = new InputState();
        }
        if (rasterizerState === void 0) {
          rasterizerState = new RasterizerState();
        }
        if (depthStencilState === void 0) {
          depthStencilState = new DepthStencilState();
        }
        if (blendState === void 0) {
          blendState = new BlendState$1();
        }
        if (primitive === void 0) {
          primitive = PrimitiveMode.TRIANGLE_LIST;
        }
        if (dynamicStates === void 0) {
          dynamicStates = DynamicStateFlagBit.NONE;
        }
        if (bindPoint === void 0) {
          bindPoint = PipelineBindPoint.GRAPHICS;
        }
        this.shader = shader;
        this.pipelineLayout = pipelineLayout;
        this.renderPass = renderPass;
        this.inputState = inputState;
        this.rasterizerState = rasterizerState;
        this.depthStencilState = depthStencilState;
        this.blendState = blendState;
        this.primitive = primitive;
        this.dynamicStates = dynamicStates;
        this.bindPoint = bindPoint;
      };
      var PipelineState = function (_GFXObject) {
        _inheritsLoose(PipelineState, _GFXObject);
        function PipelineState() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.PIPELINE_STATE) || this;
          _this._shader = null;
          _this._pipelineLayout = null;
          _this._primitive = PrimitiveMode.TRIANGLE_LIST;
          _this._is = null;
          _this._rs = new RasterizerState();
          _this._dss = new DepthStencilState();
          _this._bs = new BlendState$1();
          _this._dynamicStates = DynamicStateFlagBit.NONE;
          _this._renderPass = null;
          return _this;
        }
        _createClass(PipelineState, [{
          key: "shader",
          get: function get() {
            return this._shader;
          }
        }, {
          key: "pipelineLayout",
          get: function get() {
            return this._pipelineLayout;
          }
        }, {
          key: "primitive",
          get: function get() {
            return this._primitive;
          }
        }, {
          key: "rasterizerState",
          get: function get() {
            return this._rs;
          }
        }, {
          key: "depthStencilState",
          get: function get() {
            return this._dss;
          }
        }, {
          key: "blendState",
          get: function get() {
            return this._bs;
          }
        }, {
          key: "inputState",
          get: function get() {
            return this._is;
          }
        }, {
          key: "dynamicStates",
          get: function get() {
            return this._dynamicStates;
          }
        }, {
          key: "renderPass",
          get: function get() {
            return this._renderPass;
          }
        }]);
        return PipelineState;
      }(GFXObject);

      var Queue = function (_GFXObject) {
        _inheritsLoose(Queue, _GFXObject);
        function Queue() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.QUEUE) || this;
          _this._type = QueueType.GRAPHICS;
          return _this;
        }
        _createClass(Queue, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Queue;
      }(GFXObject);

      var RenderPass = function (_GFXObject) {
        _inheritsLoose(RenderPass, _GFXObject);
        function RenderPass() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.RENDER_PASS) || this;
          _this._colorInfos = [];
          _this._depthStencilInfo = null;
          _this._subpasses = [];
          _this._hash = 0;
          return _this;
        }
        var _proto = RenderPass.prototype;
        _proto.computeHash = function computeHash() {
          var res = '';
          if (this._subpasses.length) {
            for (var i = 0; i < this._subpasses.length; ++i) {
              var subpass = this._subpasses[i];
              if (subpass.inputs.length) {
                res += 'ia';
                for (var j = 0; j < subpass.inputs.length; ++j) {
                  var ia = this._colorInfos[subpass.inputs[j]];
                  res += "," + ia.format + "," + ia.sampleCount;
                }
              }
              if (subpass.colors.length) {
                res += 'ca';
                for (var _j = 0; _j < subpass.inputs.length; ++_j) {
                  var ca = this._colorInfos[subpass.inputs[_j]];
                  res += "," + ca.format + "," + ca.sampleCount;
                }
              }
              if (subpass.depthStencil >= 0) {
                var ds = this._colorInfos[subpass.depthStencil];
                res += "ds," + ds.format + "," + ds.sampleCount;
              }
            }
          } else {
            res += 'ca';
            for (var _i = 0; _i < this._colorInfos.length; ++_i) {
              var _ca = this._colorInfos[_i];
              res += "," + _ca.format + "," + _ca.sampleCount;
            }
            var _ds = this._depthStencilInfo;
            if (_ds) {
              res += "ds," + _ds.format + "," + _ds.sampleCount;
            }
          }
          return murmurhash2_32_gc(res, 666);
        };
        _createClass(RenderPass, [{
          key: "colorAttachments",
          get: function get() {
            return this._colorInfos;
          }
        }, {
          key: "depthStencilAttachment",
          get: function get() {
            return this._depthStencilInfo;
          }
        }, {
          key: "subPasses",
          get: function get() {
            return this._subpasses;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }]);
        return RenderPass;
      }(GFXObject);

      var Sampler = function (_GFXObject) {
        _inheritsLoose(Sampler, _GFXObject);
        function Sampler(info, hash) {
          var _this;
          _this = _GFXObject.call(this, ObjectType.SAMPLER) || this;
          _this._info = new SamplerInfo();
          _this._hash = 0;
          _this._info.copy(info);
          _this._hash = hash;
          return _this;
        }
        Sampler.computeHash = function computeHash(info) {
          var hash = info.minFilter;
          hash |= info.magFilter << 2;
          hash |= info.mipFilter << 4;
          hash |= info.addressU << 6;
          hash |= info.addressV << 8;
          hash |= info.addressW << 10;
          hash |= info.maxAnisotropy << 12;
          hash |= info.cmpFunc << 16;
          return hash;
        };
        Sampler.unpackFromHash = function unpackFromHash(hash) {
          var info = new SamplerInfo();
          info.minFilter = (hash & (1 << 2) - 1) >> 0;
          info.magFilter = (hash & (1 << 2) - 1) >> 2;
          info.mipFilter = (hash & (1 << 2) - 1) >> 4;
          info.addressU = (hash & (1 << 2) - 1) >> 6;
          info.addressV = (hash & (1 << 2) - 1) >> 8;
          info.addressW = (hash & (1 << 2) - 1) >> 10;
          info.maxAnisotropy = (hash & (1 << 4) - 1) >> 12;
          info.cmpFunc = (hash & (1 << 3) - 1) >> 16;
          return info;
        };
        _createClass(Sampler, [{
          key: "info",
          get: function get() {
            return this._info;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }]);
        return Sampler;
      }(GFXObject);

      var Shader = function (_GFXObject) {
        _inheritsLoose(Shader, _GFXObject);
        function Shader() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.SHADER) || this;
          _this._name = '';
          _this._stages = [];
          _this._attributes = [];
          _this._blocks = [];
          _this._samplers = [];
          return _this;
        }
        _createClass(Shader, [{
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "attributes",
          get: function get() {
            return this._attributes;
          }
        }, {
          key: "blocks",
          get: function get() {
            return this._blocks;
          }
        }, {
          key: "samplers",
          get: function get() {
            return this._samplers;
          }
        }, {
          key: "stages",
          get: function get() {
            return this._stages;
          }
        }]);
        return Shader;
      }(GFXObject);

      var Texture = function (_GFXObject) {
        _inheritsLoose(Texture, _GFXObject);
        function Texture() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.TEXTURE) || this;
          _this._info = new TextureInfo();
          _this._viewInfo = new TextureViewInfo();
          _this._isPowerOf2 = false;
          _this._isTextureView = false;
          _this._size = 0;
          return _this;
        }
        Texture.getLevelCount = function getLevelCount(width, height) {
          return Math.floor(Math.log2(Math.max(width, height)));
        };
        _createClass(Texture, [{
          key: "type",
          get: function get() {
            return this._info.type;
          }
        }, {
          key: "usage",
          get: function get() {
            return this._info.usage;
          }
        }, {
          key: "format",
          get: function get() {
            return this._info.format;
          }
        }, {
          key: "width",
          get: function get() {
            return this._info.width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._info.height;
          }
        }, {
          key: "depth",
          get: function get() {
            return this._info.depth;
          }
        }, {
          key: "layerCount",
          get: function get() {
            return this._info.layerCount;
          }
        }, {
          key: "levelCount",
          get: function get() {
            return this._info.levelCount;
          }
        }, {
          key: "samples",
          get: function get() {
            return this._info.samples;
          }
        }, {
          key: "flags",
          get: function get() {
            return this._info.flags;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          }
        }, {
          key: "info",
          get: function get() {
            return this._info;
          }
        }, {
          key: "viewInfo",
          get: function get() {
            return this._viewInfo;
          }
        }, {
          key: "isTextureView",
          get: function get() {
            return this._isTextureView;
          }
        }]);
        return Texture;
      }(GFXObject);

      var GeneralBarrier = function (_GFXObject) {
        _inheritsLoose(GeneralBarrier, _GFXObject);
        function GeneralBarrier(info, hash) {
          var _this;
          _this = _GFXObject.call(this, ObjectType.GLOBAL_BARRIER) || this;
          _this._info = new GeneralBarrierInfo();
          _this._hash = 0;
          _this._info.copy(info);
          _this._hash = hash;
          return _this;
        }
        GeneralBarrier.computeHash = function computeHash(info) {
          return murmurhash2_32_gc(info.prevAccesses + " " + info.nextAccesses + " " + info.type, 666);
        };
        _createClass(GeneralBarrier, [{
          key: "info",
          get: function get() {
            return this._info;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }]);
        return GeneralBarrier;
      }(GFXObject);

      var TextureBarrier = function (_GFXObject) {
        _inheritsLoose(TextureBarrier, _GFXObject);
        function TextureBarrier(info, hash) {
          var _this;
          _this = _GFXObject.call(this, ObjectType.TEXTURE_BARRIER) || this;
          _this._info = new TextureBarrierInfo();
          _this._hash = 0;
          _this._info.copy(info);
          _this._hash = hash;
          return _this;
        }
        TextureBarrier.computeHash = function computeHash(info) {
          var res = info.prevAccesses + " " + info.nextAccesses;
          res += info.type;
          res += info.baseMipLevel;
          res += info.levelCount;
          res += info.baseSlice;
          res += info.sliceCount;
          res += info.discardContents;
          res += info.srcQueue ? info.srcQueue.type : 0;
          res += info.dstQueue ? info.dstQueue.type : 0;
          return murmurhash2_32_gc(res, 666);
        };
        _createClass(TextureBarrier, [{
          key: "info",
          get: function get() {
            return this._info;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }]);
        return TextureBarrier;
      }(GFXObject);

      var BufferBarrier = function (_GFXObject) {
        _inheritsLoose(BufferBarrier, _GFXObject);
        function BufferBarrier(info, hash) {
          var _this;
          _this = _GFXObject.call(this, ObjectType.BUFFER_BARRIER) || this;
          _this._info = new BufferBarrierInfo();
          _this._hash = 0;
          _this._info.copy(info);
          _this._hash = hash;
          return _this;
        }
        BufferBarrier.computeHash = function computeHash(info) {
          var res = info.prevAccesses + " " + info.nextAccesses;
          res += info.type;
          res += info.offset;
          res += info.size;
          res += info.discardContents;
          res += info.srcQueue ? info.srcQueue.type : 0;
          res += info.dstQueue ? info.dstQueue.type : 0;
          return murmurhash2_32_gc(res, 666);
        };
        _createClass(BufferBarrier, [{
          key: "info",
          get: function get() {
            return this._info;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }]);
        return BufferBarrier;
      }(GFXObject);

      var polyfills$1 = {
        Device: Device,
        Swapchain: Swapchain,
        Buffer: Buffer,
        Texture: Texture,
        Sampler: Sampler,
        Shader: Shader,
        InputAssembler: InputAssembler,
        RenderPass: RenderPass,
        Framebuffer: Framebuffer,
        DescriptorSet: DescriptorSet,
        DescriptorSetLayout: DescriptorSetLayout,
        PipelineLayout: PipelineLayout,
        PipelineState: PipelineState,
        CommandBuffer: CommandBuffer,
        Queue: Queue,
        GeneralBarrier: GeneralBarrier,
        TextureBarrier: TextureBarrier,
        BufferBarrier: BufferBarrier,
        RasterizerState: RasterizerState,
        BlendState: BlendState$1,
        BlendTarget: BlendTarget,
        DepthStencilState: DepthStencilState,
        PipelineStateInfo: PipelineStateInfo
      };
      Object.assign(polyfills$1, defines);
      legacyCC.gfx = polyfills$1;

      var polyfills = {
        GFXDevice: true,
        GFXBuffer: true,
        GFXTexture: true,
        GFXSampler: true,
        GFXShader: true,
        GFXInputAssembler: true,
        GFXRenderPass: true,
        GFXFramebuffer: true,
        GFXPipelineState: true,
        GFXCommandBuffer: true,
        GFXQueue: true,
        GFXObjectType: true,
        GFXObject: false,
        GFXAttributeName: true,
        GFXType: true,
        GFXFormat: true,
        GFXBufferUsageBit: true,
        GFXMemoryUsageBit: true,
        GFXBufferFlagBit: true,
        GFXBufferAccessBit: 'MemoryAccessBit',
        GFXPrimitiveMode: true,
        GFXPolygonMode: true,
        GFXShadeModel: true,
        GFXCullMode: true,
        GFXComparisonFunc: true,
        GFXStencilOp: true,
        GFXBlendOp: true,
        GFXBlendFactor: true,
        GFXColorMask: true,
        GFXFilter: true,
        GFXAddress: true,
        GFXTextureType: true,
        GFXTextureUsageBit: true,
        GFXSampleCount: true,
        GFXTextureFlagBit: true,
        GFXShaderStageFlagBit: true,
        GFXDescriptorType: true,
        GFXCommandBufferType: true,
        GFXLoadOp: true,
        GFXStoreOp: true,
        GFXPipelineBindPoint: true,
        GFXDynamicStateFlagBit: true,
        GFXStencilFace: true,
        GFXQueueType: true,
        GFXRect: true,
        GFXViewport: true,
        GFXColor: true,
        GFXClearFlag: true,
        GFXOffset: true,
        GFXExtent: true,
        GFXTextureSubres: 'TextureSubresLayers',
        GFXTextureCopy: true,
        GFXBufferTextureCopy: true,
        GFXFormatType: true,
        GFXFormatInfo: true,
        GFXMemoryStatus: true,
        GFXFormatInfos: true,
        GFXFormatSize: true,
        GFXFormatSurfaceSize: true,
        GFXGetTypeSize: true,
        getTypedArrayConstructor: false
      };
      for (var name in polyfills) {
        var newName = polyfills[name];
        if (newName === true) {
          newName = name.slice(3);
        } else if (newName === false) {
          newName = name;
        }
        replaceProperty(legacyCC, 'cc', [{
          name: name,
          newName: newName,
          target: legacyCC.gfx,
          targetName: 'cc.gfx'
        }]);
      }
      removeProperty(legacyCC, 'cc', [{
        name: 'GFX_MAX_VERTEX_ATTRIBUTES'
      }, {
        name: 'GFX_MAX_TEXTURE_UNITS'
      }, {
        name: 'GFX_MAX_ATTACHMENTS'
      }, {
        name: 'GFX_MAX_BUFFER_BINDINGS'
      }, {
        name: 'GFXTextureLayout'
      }]);

      removeProperty(Feature, 'Feature', [{
        name: 'COLOR_FLOAT',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.R32F) & FormatFeatureBit.RENDER_TARGET;'
      }, {
        name: 'COLOR_HALF_FLOAT',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.R16F) & FormatFeatureBit.RENDER_TARGET;'
      }, {
        name: 'TEXTURE_FLOAT',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = (device.getFormatFeatures(Format.R32F) & (FormatFeatureBit.RENDER_TARGET' + ' | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE);'
      }, {
        name: 'TEXTURE_HALF_FLOAT',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = (device.getFormatFeatures(Format.R16F) & (FormatFeatureBit.RENDER_TARGET' + ' | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE);'
      }, {
        name: 'TEXTURE_FLOAT_LINEAR',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.R32F) & FormatFeatureBit.LINEAR_FILTER;'
      }, {
        name: 'TEXTURE_HALF_FLOAT_LINEAR',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.R16F) & FormatFeatureBit.LINEAR_FILTER;'
      }, {
        name: 'FORMAT_R11G11B10F',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.R11G11B10F) !== FormatFeatureBit.NONE;'
      }, {
        name: 'FORMAT_SRGB',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.SRGB8) !== FormatFeatureBit.NONE;'
      }, {
        name: 'FORMAT_ETC1',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.ETC_RGB8) !== FormatFeatureBit.NONE;'
      }, {
        name: 'FORMAT_ETC2',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.ETC2_RGB8) !== FormatFeatureBit.NONE;'
      }, {
        name: 'FORMAT_DXT',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.BC1) !== FormatFeatureBit.NONE;'
      }, {
        name: 'FORMAT_PVRTC',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.PVRTC_RGB2) !== FormatFeatureBit.NONE;'
      }, {
        name: 'FORMAT_ASTC',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.ASTC_RGBA_4x4) !== FormatFeatureBit.NONE;'
      }, {
        name: 'FORMAT_RGB8',
        suggest: 'Please use device.getFormatFeatures() instead, like: \n' + 'let isSupported = device.getFormatFeatures(Format.RGB8) !== FormatFeatureBit.NONE;'
      }]);
      removeProperty(ColorAttachment.prototype, 'ColorAttachment', [{
        name: 'beginAccesses',
        suggest: 'Please assign to ColorAttachment.barrier instead'
      }, {
        name: 'endAccesses',
        suggest: 'Please assign to ColorAttachment.barrier instead'
      }]);
      removeProperty(DepthStencilAttachment.prototype, 'DepthStencilAttachment', [{
        name: 'beginAccesses',
        suggest: 'Please assign to DepthStencilAttachment.barrier instead'
      }, {
        name: 'endAccesses',
        suggest: 'Please assign to DepthStencilAttachment.barrier instead'
      }]);
      replaceProperty(Device.prototype, 'Device', [{
        name: 'getGlobalBarrier',
        newName: 'getGeneralBarrier'
      }]);

      var LegacyRenderMode;
      (function (LegacyRenderMode) {
        LegacyRenderMode[LegacyRenderMode["AUTO"] = 0] = "AUTO";
        LegacyRenderMode[LegacyRenderMode["CANVAS"] = 1] = "CANVAS";
        LegacyRenderMode[LegacyRenderMode["WEBGL"] = 2] = "WEBGL";
        LegacyRenderMode[LegacyRenderMode["HEADLESS"] = 3] = "HEADLESS";
      })(LegacyRenderMode || (LegacyRenderMode = {}));
      var RenderType;
      (function (RenderType) {
        RenderType[RenderType["UNKNOWN"] = -1] = "UNKNOWN";
        RenderType[RenderType["CANVAS"] = 0] = "CANVAS";
        RenderType[RenderType["WEBGL"] = 1] = "WEBGL";
        RenderType[RenderType["OPENGL"] = 2] = "OPENGL";
        RenderType[RenderType["HEADLESS"] = 3] = "HEADLESS";
      })(RenderType || (RenderType = {}));
      var DeviceManager = function () {
        function DeviceManager() {
          this.initialized = false;
          this._gfxDevice = void 0;
          this._canvas = null;
          this._swapchain = void 0;
          this._renderType = RenderType.UNKNOWN;
        }
        var _proto = DeviceManager.prototype;
        _proto.init = function init(canvas, bindingMappingInfo) {
          if (this.initialized) {
            return;
          }
          var renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode');
          this._canvas = canvas;
          this._renderType = this._determineRenderType(renderMode);
          if (this._renderType === RenderType.WEBGL) {
            var deviceInfo = new DeviceInfo(bindingMappingInfo);
            {
              var useWebGL2 = !!globalThis.WebGL2RenderingContext;
              globalThis.navigator.userAgent.toLowerCase();
              if (sys.browserType === BrowserType.UC) {
                useWebGL2 = false;
              }
              var deviceCtors = [];
              if (useWebGL2 && legacyCC.WebGL2Device) {
                deviceCtors.push(legacyCC.WebGL2Device);
              }
              if (legacyCC.WebGLDevice) {
                deviceCtors.push(legacyCC.WebGLDevice);
              }
              if (legacyCC.EmptyDevice) {
                deviceCtors.push(legacyCC.EmptyDevice);
              }
              Device.canvas = canvas;
              for (var i = 0; i < deviceCtors.length; i++) {
                this._gfxDevice = new deviceCtors[i]();
                if (this._gfxDevice.initialize(deviceInfo)) {
                  break;
                }
              }
              this._initSwapchain();
            }
          } else if (this._renderType === RenderType.HEADLESS && legacyCC.EmptyDevice) {
            this._gfxDevice = new legacyCC.EmptyDevice();
            this._gfxDevice.initialize(new DeviceInfo(bindingMappingInfo));
            this._initSwapchain();
          }
          if (!this._gfxDevice) {
            error('can not support canvas rendering in 3D');
            this._renderType = RenderType.UNKNOWN;
            return;
          }
          if (this._canvas) {
            this._canvas.oncontextmenu = function () {
              return false;
            };
          }
        };
        _proto._initSwapchain = function _initSwapchain() {
          var swapchainInfo = new SwapchainInfo(1, this._canvas);
          var windowSize = screen$1.windowSize;
          swapchainInfo.width = windowSize.width;
          swapchainInfo.height = windowSize.height;
          this._swapchain = this._gfxDevice.createSwapchain(swapchainInfo);
        };
        _proto._determineRenderType = function _determineRenderType(renderMode) {
          if (typeof renderMode !== 'number' || renderMode > RenderType.HEADLESS || renderMode < LegacyRenderMode.AUTO) {
            renderMode = LegacyRenderMode.AUTO;
          }
          var renderType = RenderType.CANVAS;
          var supportRender = false;
          if (renderMode === LegacyRenderMode.CANVAS) {
            renderType = RenderType.CANVAS;
            supportRender = true;
          } else if (renderMode === LegacyRenderMode.AUTO || renderMode === LegacyRenderMode.WEBGL) {
            renderType = RenderType.WEBGL;
            supportRender = true;
          } else if (renderMode === LegacyRenderMode.HEADLESS) {
            renderType = RenderType.HEADLESS;
            supportRender = true;
          }
          if (!supportRender) {
            throw new Error(getError(3820, renderMode));
          }
          return renderType;
        };
        _createClass(DeviceManager, [{
          key: "gfxDevice",
          get: function get() {
            return this._gfxDevice;
          }
        }, {
          key: "swapchain",
          get: function get() {
            return this._swapchain;
          }
        }]);
        return DeviceManager;
      }();
      var deviceManager = new DeviceManager();

      var index$3 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        DescriptorSet: DescriptorSet,
        Buffer: Buffer,
        CommandBuffer: CommandBuffer,
        get ObjectType () { return ObjectType; },
        get Status () { return Status; },
        get API () { return API; },
        get SurfaceTransform () { return SurfaceTransform; },
        get Feature () { return Feature; },
        get Format () { return Format; },
        get FormatType () { return FormatType; },
        get Type () { return Type$1; },
        get BufferUsageBit () { return BufferUsageBit; },
        get BufferFlagBit () { return BufferFlagBit; },
        get MemoryAccessBit () { return MemoryAccessBit; },
        get MemoryUsageBit () { return MemoryUsageBit; },
        get TextureType () { return TextureType; },
        get TextureUsageBit () { return TextureUsageBit; },
        get TextureFlagBit () { return TextureFlagBit; },
        get FormatFeatureBit () { return FormatFeatureBit; },
        get SampleCount () { return SampleCount; },
        get VsyncMode () { return VsyncMode; },
        get Filter () { return Filter$1; },
        get Address () { return Address; },
        get ComparisonFunc () { return ComparisonFunc; },
        get StencilOp () { return StencilOp; },
        get BlendFactor () { return BlendFactor; },
        get BlendOp () { return BlendOp; },
        get ColorMask () { return ColorMask; },
        get ShaderStageFlagBit () { return ShaderStageFlagBit; },
        get LoadOp () { return LoadOp; },
        get StoreOp () { return StoreOp; },
        get AccessFlagBit () { return AccessFlagBit; },
        get ResolveMode () { return ResolveMode; },
        get PipelineBindPoint () { return PipelineBindPoint; },
        get PrimitiveMode () { return PrimitiveMode; },
        get PolygonMode () { return PolygonMode; },
        get ShadeModel () { return ShadeModel; },
        get CullMode () { return CullMode; },
        get DynamicStateFlagBit () { return DynamicStateFlagBit; },
        get StencilFace () { return StencilFace; },
        get DescriptorType () { return DescriptorType; },
        get QueueType () { return QueueType; },
        get QueryType () { return QueryType; },
        get CommandBufferType () { return CommandBufferType; },
        get ClearFlagBit () { return ClearFlagBit; },
        get BarrierType () { return BarrierType; },
        get PassType () { return PassType; },
        Size: Size,
        DeviceCaps: DeviceCaps,
        DeviceOptions: DeviceOptions,
        Offset: Offset,
        Rect: Rect,
        Extent: Extent,
        TextureSubresLayers: TextureSubresLayers,
        TextureSubresRange: TextureSubresRange,
        TextureCopy: TextureCopy,
        TextureBlit: TextureBlit,
        BufferTextureCopy: BufferTextureCopy,
        Viewport: Viewport,
        Color: Color,
        BindingMappingInfo: BindingMappingInfo,
        SwapchainInfo: SwapchainInfo,
        DeviceInfo: DeviceInfo,
        BufferInfo: BufferInfo,
        BufferViewInfo: BufferViewInfo,
        DrawInfo: DrawInfo,
        DispatchInfo: DispatchInfo,
        IndirectBuffer: IndirectBuffer,
        TextureInfo: TextureInfo,
        TextureViewInfo: TextureViewInfo,
        SamplerInfo: SamplerInfo,
        Uniform: Uniform,
        UniformBlock: UniformBlock,
        UniformSamplerTexture: UniformSamplerTexture,
        UniformSampler: UniformSampler,
        UniformTexture: UniformTexture,
        UniformStorageImage: UniformStorageImage,
        UniformStorageBuffer: UniformStorageBuffer,
        UniformInputAttachment: UniformInputAttachment,
        ShaderStage: ShaderStage,
        Attribute: Attribute,
        ShaderInfo: ShaderInfo,
        InputAssemblerInfo: InputAssemblerInfo,
        ColorAttachment: ColorAttachment,
        DepthStencilAttachment: DepthStencilAttachment,
        SubpassInfo: SubpassInfo,
        SubpassDependency: SubpassDependency,
        RenderPassInfo: RenderPassInfo,
        GeneralBarrierInfo: GeneralBarrierInfo,
        TextureBarrierInfo: TextureBarrierInfo,
        BufferBarrierInfo: BufferBarrierInfo,
        FramebufferInfo: FramebufferInfo,
        DescriptorSetLayoutBinding: DescriptorSetLayoutBinding,
        DescriptorSetLayoutInfo: DescriptorSetLayoutInfo,
        DescriptorSetInfo: DescriptorSetInfo,
        PipelineLayoutInfo: PipelineLayoutInfo,
        InputState: InputState,
        CommandBufferInfo: CommandBufferInfo,
        QueueInfo: QueueInfo,
        QueryPoolInfo: QueryPoolInfo,
        FormatInfo: FormatInfo,
        MemoryStatus: MemoryStatus,
        DynamicStencilStates: DynamicStencilStates,
        DynamicStates: DynamicStates,
        GFXObject: GFXObject,
        get AttributeName () { return AttributeName; },
        FormatInfos: FormatInfos,
        DESCRIPTOR_BUFFER_TYPE: DESCRIPTOR_BUFFER_TYPE,
        DESCRIPTOR_SAMPLER_TYPE: DESCRIPTOR_SAMPLER_TYPE,
        DESCRIPTOR_DYNAMIC_TYPE: DESCRIPTOR_DYNAMIC_TYPE,
        DRAW_INFO_SIZE: DRAW_INFO_SIZE,
        IsPowerOf2: IsPowerOf2,
        FormatSize: FormatSize,
        FormatSurfaceSize: FormatSurfaceSize,
        GetTypeSize: GetTypeSize,
        getTypedArrayConstructor: getTypedArrayConstructor,
        formatAlignment: formatAlignment,
        alignTo: alignTo,
        Device: Device,
        DefaultResource: DefaultResource,
        Swapchain: Swapchain,
        Framebuffer: Framebuffer,
        InputAssembler: InputAssembler,
        DescriptorSetLayout: DescriptorSetLayout,
        PipelineLayout: PipelineLayout,
        BlendState: BlendState$1,
        BlendTarget: BlendTarget,
        RasterizerState: RasterizerState,
        DepthStencilState: DepthStencilState,
        PipelineStateInfo: PipelineStateInfo,
        PipelineState: PipelineState,
        Queue: Queue,
        RenderPass: RenderPass,
        Sampler: Sampler,
        Shader: Shader,
        Texture: Texture,
        GeneralBarrier: GeneralBarrier,
        TextureBarrier: TextureBarrier,
        get LegacyRenderMode () { return LegacyRenderMode; },
        get RenderType () { return RenderType; },
        DeviceManager: DeviceManager,
        deviceManager: deviceManager
      });
      exports('aF', index$3);

      var m$4 = new Mat4();
      function fillMeshVertices3D(node, renderer, renderData, color) {
        var chunk = renderData.chunk;
        var dataList = renderData.data;
        var vData = chunk.vb;
        var vertexCount = renderData.vertexCount;
        node.getWorldMatrix(m$4);
        var vertexOffset = 0;
        for (var i = 0; i < vertexCount; i++) {
          var vert = dataList[i];
          var x = vert.x;
          var y = vert.y;
          var rhw = m$4.m03 * x + m$4.m07 * y + m$4.m15;
          rhw = rhw ? 1 / rhw : 1;
          vData[vertexOffset + 0] = (m$4.m00 * x + m$4.m04 * y + m$4.m12) * rhw;
          vData[vertexOffset + 1] = (m$4.m01 * x + m$4.m05 * y + m$4.m13) * rhw;
          vData[vertexOffset + 2] = (m$4.m02 * x + m$4.m06 * y + m$4.m14) * rhw;
          Color$1.toArray(vData, color, vertexOffset + 5);
          vertexOffset += 9;
        }
        chunk.bufferId;
        var vid = chunk.vertexOffset;
        var meshBuffer = chunk.meshBuffer;
        var ib = chunk.meshBuffer.iData;
        var indexOffset = meshBuffer.indexOffset;
        for (var _i = 0, count = vertexCount / 4; _i < count; _i++) {
          var start = vid + _i * 4;
          ib[indexOffset++] = start;
          ib[indexOffset++] = start + 1;
          ib[indexOffset++] = start + 2;
          ib[indexOffset++] = start + 1;
          ib[indexOffset++] = start + 3;
          ib[indexOffset++] = start + 2;
        }
        meshBuffer.indexOffset += renderData.indexCount;
        meshBuffer.setDirty();
      }
      function updateOpacity(renderData, opacity) {
        var vfmt = renderData.vertexFormat;
        var vb = renderData.chunk.vb;
        var attr;
        var format;
        var stride;
        var offset = 0;
        for (var i = 0; i < vfmt.length; ++i) {
          attr = vfmt[i];
          format = FormatInfos[attr.format];
          if (format.hasAlpha) {
            stride = renderData.floatStride;
            if (format.size / format.count === 1) {
              var alpha = ~~clamp$1(Math.round(opacity * 255), 0, 255);
              for (var color = offset; color < vb.length; color += stride) {
                vb[color] = (vb[color] & 0xffffff00 | alpha) >>> 0;
              }
            } else if (format.size / format.count === 4) {
              for (var _alpha = offset + 3; _alpha < vb.length; _alpha += stride) {
                vb[_alpha] = opacity;
              }
            }
          }
          offset += format.size >> 2;
        }
      }

      var minigame = {};

      var Cache = function () {
        function Cache(map) {
          this._map = null;
          this._count = 0;
          if (map) {
            this._map = map;
            this._count = Object.keys(map).length;
          } else {
            this._map = createMap(true);
            this._count = 0;
          }
        }
        var _proto = Cache.prototype;
        _proto.add = function add(key, val) {
          if (!(key in this._map)) {
            this._count++;
          }
          return this._map[key] = val;
        };
        _proto.get = function get(key) {
          return this._map[key];
        };
        _proto.has = function has(key) {
          return key in this._map;
        };
        _proto.remove = function remove(key) {
          var out = this._map[key];
          if (key in this._map) {
            delete this._map[key];
            this._count--;
          }
          return out;
        };
        _proto.clear = function clear() {
          if (this._count !== 0) {
            this._map = createMap(true);
            this._count = 0;
          }
        };
        _proto.forEach = function forEach(func) {
          for (var _key in this._map) {
            func(this._map[_key], _key);
          }
        };
        _proto.find = function find(predicate) {
          for (var _key2 in this._map) {
            if (predicate(this._map[_key2], _key2)) {
              return this._map[_key2];
            }
          }
          return null;
        };
        _proto.destroy = function destroy() {
          this._map = null;
        };
        _createClass(Cache, [{
          key: "map",
          get: function get() {
            return this._map;
          }
        }, {
          key: "count",
          get: function get() {
            return this._count;
          }
        }]);
        return Cache;
      }();

      var Pipeline = function () {
        function Pipeline(name, funcs) {
          this.id = Pipeline._pipelineId++;
          this.name = '';
          this.pipes = [];
          this.name = name;
          for (var i = 0, l = funcs.length; i < l; i++) {
            this.pipes.push(funcs[i]);
          }
        }
        var _proto = Pipeline.prototype;
        _proto.insert = function insert(func, index) {
          if (index > this.pipes.length) {
            warnID(4921);
            return this;
          }
          this.pipes.splice(index, 0, func);
          return this;
        };
        _proto.append = function append(func) {
          this.pipes.push(func);
          return this;
        };
        _proto.remove = function remove(index) {
          this.pipes.splice(index, 1);
          return this;
        };
        _proto.sync = function sync(task) {
          var pipes = this.pipes;
          if (pipes.length === 0) {
            return null;
          }
          task.isFinished = false;
          for (var i = 0, l = pipes.length; i < l;) {
            var pipe = pipes[i];
            var result = pipe(task);
            if (result) {
              task.isFinished = true;
              return result;
            }
            i++;
            if (i !== l) {
              task.input = task.output;
              task.output = null;
            }
          }
          task.isFinished = true;
          return task.output;
        };
        _proto.async = function async(task) {
          var pipes = this.pipes;
          if (pipes.length === 0) {
            return;
          }
          task.isFinished = false;
          this._flow(0, task);
        };
        _proto._flow = function _flow(index, task) {
          var _this = this;
          var pipe = this.pipes[index];
          pipe(task, function (result) {
            if (result) {
              task.isFinished = true;
              task.dispatch('complete', result);
            } else {
              index++;
              if (index < _this.pipes.length) {
                task.input = task.output;
                task.output = null;
                _this._flow(index, task);
              } else {
                task.isFinished = true;
                task.dispatch('complete', result, task.output);
              }
            }
          });
        };
        return Pipeline;
      }();
      Pipeline._pipelineId = 0;

      (function () {
        function WeakCache(map) {
          this._weakMap = {};
          if (typeof window.WeakRef === 'undefined') throw new Error('this platform does not support WeakRef!');
          if (map) {
            for (var _key in map) {
              this._weakMap[_key] = new WeakRef(map[_key]);
            }
          }
        }
        var _proto = WeakCache.prototype;
        _proto.add = function add(key, val) {
          this._weakMap[key] = new WeakRef(val);
          return val;
        };
        _proto.has = function has(key) {
          return key in this._weakMap && !!this._weakMap[key].deref();
        };
        _proto.get = function get(key) {
          return this._weakMap[key] && this._weakMap[key].deref();
        };
        _proto.remove = function remove(key) {
          var out = this._weakMap[key];
          delete this._weakMap[key];
          return out && out.deref();
        };
        _proto.clear = function clear() {
          this._weakMap = createMap(true);
        };
        _proto.forEach = function forEach(func) {
          for (var _key2 in this._weakMap) {
            var _val = this.get(_key2);
            if (_val) {
              func(_val, _key2);
            }
          }
        };
        _proto.find = function find(predicate) {
          for (var _key3 in this._weakMap) {
            var _val2 = this.get(_key3);
            if (_val2 && predicate(_val2, _key3)) {
              return this._weakMap[_key3].deref();
            }
          }
          return null;
        };
        _proto.destroy = function destroy() {
          this._weakMap = {};
        };
        _createClass(WeakCache, [{
          key: "count",
          get: function get() {
            return Object.values(this._weakMap).filter(function (weakRef) {
              return weakRef.deref();
            }).length;
          }
        }]);
        return WeakCache;
      })();

      var assets = new Cache();
      var files = new Cache();
      var parsed = new Cache();
      var bundles = new Cache();
      var pipeline = new Pipeline('normal load', []);
      var fetchPipeline = new Pipeline('fetch', []);
      var transformPipeline = new Pipeline('transform url', []);
      var references = null;
      var assetsOverrideMap = new Map();
      var RequestType;
      (function (RequestType) {
        RequestType["UUID"] = "uuid";
        RequestType["PATH"] = "path";
        RequestType["DIR"] = "dir";
        RequestType["URL"] = "url";
        RequestType["SCENE"] = "scene";
      })(RequestType || (RequestType = {}));
      var presets = {
        "default": {
          priority: 0
        },
        preload: {
          maxConcurrency: 6,
          maxRequestsPerFrame: 2,
          priority: -1
        },
        scene: {
          maxConcurrency: 20,
          maxRequestsPerFrame: 20,
          priority: 1
        },
        bundle: {
          maxConcurrency: 20,
          maxRequestsPerFrame: 20,
          priority: 2
        },
        remote: {
          maxRetryCount: 4
        }
      };
      var BuiltinBundleName;
      (function (BuiltinBundleName) {
        BuiltinBundleName["INTERNAL"] = "internal";
        BuiltinBundleName["RESOURCES"] = "resources";
        BuiltinBundleName["MAIN"] = "main";
        BuiltinBundleName["START_SCENE"] = "start-scene";
      })(BuiltinBundleName || (BuiltinBundleName = {}));

      var Task = function () {
        Task.create = function create(options) {
          var out;
          if (Task._deadPool.length !== 0) {
            out = Task._deadPool.pop();
            out.set(options);
          } else {
            out = new Task(options);
          }
          return out;
        };
        function Task(options) {
          this.id = Task._taskId++;
          this.onComplete = null;
          this.onProgress = null;
          this.onError = null;
          this.source = null;
          this.output = null;
          this.input = null;
          this.progress = null;
          this.options = null;
          this.isFinished = true;
          this.set(options);
        }
        var _proto = Task.prototype;
        _proto.set = function set(options) {
          if (options === void 0) {
            options = Object.create(null);
          }
          this.onComplete = options.onComplete || null;
          this.onProgress = options.onProgress || null;
          this.onError = options.onError || null;
          this.source = this.input = options.input;
          this.output = null;
          this.progress = options.progress;
          this.options = options.options || Object.create(null);
        };
        _proto.dispatch = function dispatch(event, param1, param2, param3, param4) {
          switch (event) {
            case 'complete':
              if (this.onComplete) {
                this.onComplete(param1, param2);
              }
              break;
            case 'progress':
              if (this.onProgress) {
                this.onProgress(param1, param2, param3, param4);
              }
              break;
            case 'error':
              if (this.onError) {
                this.onError(param1, param2, param3, param4);
              }
              break;
            default:
              {
                var str = "on" + event[0].toUpperCase() + event.substr(1);
                if (typeof this[str] === 'function') {
                  this[str](param1, param2, param3, param4);
                }
                break;
              }
          }
        };
        _proto.recycle = function recycle() {
          if (Task._deadPool.length === Task.MAX_DEAD_NUM) {
            return;
          }
          this.onComplete = null;
          this.onProgress = null;
          this.onError = null;
          this.source = this.output = this.input = null;
          this.progress = null;
          this.options = null;
          Task._deadPool.push(this);
        };
        _createClass(Task, [{
          key: "isFinish",
          get: function get() {
            return this.isFinished;
          },
          set: function set(val) {
            this.isFinished = val;
          }
        }]);
        return Task;
      }();
      Task.MAX_DEAD_NUM = 500;
      Task._taskId = 0;
      Task._deadPool = [];

      var separator = '@';
      var HexChars = '0123456789abcdef'.split('');
      var _t = ['', '', '', ''];
      var UuidTemplate = _t.concat(_t, '-', _t, '-', _t, '-', _t, '-', _t, _t, _t);
      var Indices = UuidTemplate.map(function (x, i) {
        return x === '-' ? NaN : i;
      }).filter(Number.isFinite);
      function decodeUuid(base64) {
        var strs = base64.split(separator);
        var uuid = strs[0];
        if (uuid.length !== 22) {
          return base64;
        }
        UuidTemplate[0] = base64[0];
        UuidTemplate[1] = base64[1];
        for (var i = 2, j = 2; i < 22; i += 2) {
          var lhs = BASE64_VALUES$1[base64.charCodeAt(i)];
          var rhs = BASE64_VALUES$1[base64.charCodeAt(i + 1)];
          UuidTemplate[Indices[j++]] = HexChars[lhs >> 2];
          UuidTemplate[Indices[j++]] = HexChars[(lhs & 3) << 2 | rhs >> 4];
          UuidTemplate[Indices[j++]] = HexChars[rhs & 0xF];
        }
        return base64.replace(uuid, UuidTemplate.join(''));
      }

      var _uuidRegex = /.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,}).*/;
      function getUuidFromURL(url) {
        var matches = _uuidRegex.exec(url);
        if (matches) {
          return matches[1];
        }
        return '';
      }
      function getUrlWithUuid(uuid, options) {
        options = options || Object.create(null);
        options.__isNative__ = options.isNative;
        if (options.nativeExt) {
          options.ext = options.nativeExt;
        }
        var bundle = bundles.find(function (b) {
          return !!b.getAssetInfo(uuid);
        });
        if (bundle) {
          options.bundle = bundle.name;
        }
        return transform(uuid, options);
      }
      function isScene(asset) {
        return !!asset && (asset instanceof legacyCC.SceneAsset || asset instanceof legacyCC.Scene);
      }
      function normalize(url) {
        if (url) {
          if (url.charCodeAt(0) === 46 && url.charCodeAt(1) === 47) {
            url = url.slice(2);
          } else if (url.charCodeAt(0) === 47) {
            url = url.slice(1);
          }
        }
        return url;
      }
      function transform(input, options) {
        var subTask = Task.create({
          input: input,
          options: options
        });
        var urls = [];
        try {
          var result = transformPipeline.sync(subTask);
          for (var _iterator = _createForOfIteratorHelperLoose(result), _step; !(_step = _iterator()).done;) {
            var requestItem = _step.value;
            var url = requestItem.url;
            requestItem.recycle();
            urls.push(url);
          }
        } catch (e) {
          for (var _iterator2 = _createForOfIteratorHelperLoose(subTask.output), _step2; !(_step2 = _iterator2()).done;) {
            var item = _step2.value;
            item.recycle();
          }
          error(e.message, e.stack);
        }
        subTask.recycle();
        return urls.length > 1 ? urls : urls[0];
      }

      var helper = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getUuidFromURL: getUuidFromURL,
        getUrlWithUuid: getUrlWithUuid,
        isScene: isScene,
        normalize: normalize,
        transform: transform,
        decodeUuid: decodeUuid
      });

      var _dec$3G, _class$3C, _class2$3g, _initializer$2Z;
      var ccclass$L = ccclass$M,
        serializable$o = serializable$p,
        property$2 = property$3;
      var Asset = exports('eb', (_dec$3G = ccclass$L('cc.Asset'), _dec$3G(_class$3C = (_class2$3g = function (_Eventify) {
        _inheritsLoose(Asset, _Eventify);
        Asset.deserialize = function deserialize(data) {
          return legacyCC.deserialize(data);
        };
        function Asset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Eventify.call.apply(_Eventify, [this].concat(args)) || this;
          _this.loaded = true;
          _this._native = _initializer$2Z && _initializer$2Z();
          _this._nativeUrl = '';
          _this._file = null;
          _this._ref = 0;
          Object.defineProperty(_assertThisInitialized(_this), '_uuid', {
            value: '',
            writable: true
          });
          return _this;
        }
        var _proto = Asset.prototype;
        _proto.toString = function toString() {
          return this.nativeUrl;
        };
        _proto.serialize = function serialize() {};
        _proto._setRawAsset = function _setRawAsset(filename, inLibrary) {
          if (inLibrary === void 0) {
            inLibrary = true;
          }
          if (inLibrary !== false) {
            this._native = filename || '';
          } else {
            this._native = "/" + filename;
          }
        };
        _proto.addRef = function addRef() {
          this._ref++;
          return this;
        };
        _proto.decRef = function decRef(autoRelease) {
          if (autoRelease === void 0) {
            autoRelease = true;
          }
          if (this._ref > 0) {
            this._ref--;
          }
          if (autoRelease) {
            legacyCC.assetManager._releaseManager.tryRelease(this);
          }
          return this;
        };
        _proto.onLoaded = function onLoaded() {};
        _proto.initDefault = function initDefault(uuid) {
          if (uuid) {
            this._uuid = uuid;
          }
          this.isDefault = true;
        };
        _proto.validate = function validate() {
          return true;
        };
        _proto.destroy = function destroy() {
          debug(getError(12101, this._uuid));
          return _Eventify.prototype.destroy.call(this);
        };
        _createClass(Asset, [{
          key: "nativeUrl",
          get: function get() {
            if (!this._nativeUrl) {
              if (!this._native) return '';
              var name = this._native;
              if (name.charCodeAt(0) === 47) {
                return name.slice(1);
              }
              if (name.charCodeAt(0) === 46) {
                this._nativeUrl = getUrlWithUuid(this._uuid, {
                  nativeExt: name,
                  isNative: true
                });
              } else {
                this._nativeUrl = getUrlWithUuid(this._uuid, {
                  __nativeName__: name,
                  nativeExt: extname(name),
                  isNative: true
                });
              }
            }
            return this._nativeUrl;
          }
        }, {
          key: "uuid",
          get: function get() {
            return this._uuid;
          }
        }, {
          key: "_nativeAsset",
          get: function get() {
            return this._file;
          },
          set: function set(obj) {
            this._file = obj;
          }
        }, {
          key: "nativeAsset",
          get: function get() {
            return this._file;
          }
        }, {
          key: "_nativeDep",
          get: function get() {
            if (this._native) {
              return {
                __isNative__: true,
                uuid: this._uuid,
                ext: this._native
              };
            }
            return undefined;
          }
        }, {
          key: "refCount",
          get: function get() {
            return this._ref;
          }
        }]);
        return Asset;
      }(Eventify(CCObject)), (_initializer$2Z = applyDecoratedInitializer(_class2$3g.prototype, "_native", [serializable$o], function () {
        return '';
      }), _applyDecoratedDescriptor(_class2$3g.prototype, "_nativeAsset", [property$2], Object.getOwnPropertyDescriptor(_class2$3g.prototype, "_nativeAsset"), _class2$3g.prototype)), _class2$3g)) || _class$3C));
      Asset.prototype.createNode = null;
      legacyCC.Asset = Asset;

      var CUSTOM_PIXEL_FORMAT = 1024;
      var PixelFormat;
      (function (PixelFormat) {
        PixelFormat[PixelFormat["RGB565"] = Format.R5G6B5] = "RGB565";
        PixelFormat[PixelFormat["RGB5A1"] = Format.RGB5A1] = "RGB5A1";
        PixelFormat[PixelFormat["RGBA4444"] = Format.RGBA4] = "RGBA4444";
        PixelFormat[PixelFormat["RGB888"] = Format.RGB8] = "RGB888";
        PixelFormat[PixelFormat["RGB32F"] = Format.RGB32F] = "RGB32F";
        PixelFormat[PixelFormat["RGBA8888"] = Format.RGBA8] = "RGBA8888";
        PixelFormat[PixelFormat["RGBA32F"] = Format.RGBA32F] = "RGBA32F";
        PixelFormat[PixelFormat["A8"] = Format.A8] = "A8";
        PixelFormat[PixelFormat["I8"] = Format.L8] = "I8";
        PixelFormat[PixelFormat["AI8"] = Format.LA8] = "AI8";
        PixelFormat[PixelFormat["RGB_PVRTC_2BPPV1"] = Format.PVRTC_RGB2] = "RGB_PVRTC_2BPPV1";
        PixelFormat[PixelFormat["RGBA_PVRTC_2BPPV1"] = Format.PVRTC_RGBA2] = "RGBA_PVRTC_2BPPV1";
        PixelFormat[PixelFormat["RGB_A_PVRTC_2BPPV1"] = CUSTOM_PIXEL_FORMAT] = "RGB_A_PVRTC_2BPPV1";
        PixelFormat[PixelFormat["RGB_PVRTC_4BPPV1"] = Format.PVRTC_RGB4] = "RGB_PVRTC_4BPPV1";
        PixelFormat[PixelFormat["RGBA_PVRTC_4BPPV1"] = Format.PVRTC_RGBA4] = "RGBA_PVRTC_4BPPV1";
        PixelFormat[PixelFormat["RGB_A_PVRTC_4BPPV1"] = CUSTOM_PIXEL_FORMAT + 1] = "RGB_A_PVRTC_4BPPV1";
        PixelFormat[PixelFormat["RGB_ETC1"] = Format.ETC_RGB8] = "RGB_ETC1";
        PixelFormat[PixelFormat["RGBA_ETC1"] = CUSTOM_PIXEL_FORMAT + 2] = "RGBA_ETC1";
        PixelFormat[PixelFormat["RGB_ETC2"] = Format.ETC2_RGB8] = "RGB_ETC2";
        PixelFormat[PixelFormat["RGBA_ETC2"] = Format.ETC2_RGBA8] = "RGBA_ETC2";
        PixelFormat[PixelFormat["RGBA_ASTC_4x4"] = Format.ASTC_RGBA_4X4] = "RGBA_ASTC_4x4";
        PixelFormat[PixelFormat["RGBA_ASTC_5x4"] = Format.ASTC_RGBA_5X4] = "RGBA_ASTC_5x4";
        PixelFormat[PixelFormat["RGBA_ASTC_5x5"] = Format.ASTC_RGBA_5X5] = "RGBA_ASTC_5x5";
        PixelFormat[PixelFormat["RGBA_ASTC_6x5"] = Format.ASTC_RGBA_6X5] = "RGBA_ASTC_6x5";
        PixelFormat[PixelFormat["RGBA_ASTC_6x6"] = Format.ASTC_RGBA_6X6] = "RGBA_ASTC_6x6";
        PixelFormat[PixelFormat["RGBA_ASTC_8x5"] = Format.ASTC_RGBA_8X5] = "RGBA_ASTC_8x5";
        PixelFormat[PixelFormat["RGBA_ASTC_8x6"] = Format.ASTC_RGBA_8X6] = "RGBA_ASTC_8x6";
        PixelFormat[PixelFormat["RGBA_ASTC_8x8"] = Format.ASTC_RGBA_8X8] = "RGBA_ASTC_8x8";
        PixelFormat[PixelFormat["RGBA_ASTC_10x5"] = Format.ASTC_RGBA_10X5] = "RGBA_ASTC_10x5";
        PixelFormat[PixelFormat["RGBA_ASTC_10x6"] = Format.ASTC_RGBA_10X6] = "RGBA_ASTC_10x6";
        PixelFormat[PixelFormat["RGBA_ASTC_10x8"] = Format.ASTC_RGBA_10X8] = "RGBA_ASTC_10x8";
        PixelFormat[PixelFormat["RGBA_ASTC_10x10"] = Format.ASTC_RGBA_10X10] = "RGBA_ASTC_10x10";
        PixelFormat[PixelFormat["RGBA_ASTC_12x10"] = Format.ASTC_RGBA_12X10] = "RGBA_ASTC_12x10";
        PixelFormat[PixelFormat["RGBA_ASTC_12x12"] = Format.ASTC_RGBA_12X12] = "RGBA_ASTC_12x12";
      })(PixelFormat || (PixelFormat = {}));
      var WrapMode$1;
      (function (WrapMode) {
        WrapMode[WrapMode["REPEAT"] = Address.WRAP] = "REPEAT";
        WrapMode[WrapMode["CLAMP_TO_EDGE"] = Address.CLAMP] = "CLAMP_TO_EDGE";
        WrapMode[WrapMode["MIRRORED_REPEAT"] = Address.MIRROR] = "MIRRORED_REPEAT";
        WrapMode[WrapMode["CLAMP_TO_BORDER"] = Address.BORDER] = "CLAMP_TO_BORDER";
      })(WrapMode$1 || (WrapMode$1 = {}));
      var Filter;
      (function (Filter) {
        Filter[Filter["NONE"] = Filter$1.NONE] = "NONE";
        Filter[Filter["LINEAR"] = Filter$1.LINEAR] = "LINEAR";
        Filter[Filter["NEAREST"] = Filter$1.POINT] = "NEAREST";
      })(Filter || (Filter = {}));

      var _dec$3F, _class$3B, _class2$3f, _class3$$;
      var COMPRESSED_HEADER_LENGTH = 4;
      var COMPRESSED_MIPMAP_DATA_SIZE_LENGTH = 4;
      var COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH = 4;
      var COMPRESSED_MIPMAP_MAGIC = 0x50494d43;
      var compressType = Enum({
        PVR: 0,
        PKM: 1,
        ASTC: 2
      });
      var PVR_HEADER_LENGTH = 13;
      var PVR_MAGIC = 0x03525650;
      var PVR_HEADER_MAGIC = 0;
      var PVR_HEADER_HEIGHT = 6;
      var PVR_HEADER_WIDTH = 7;
      var PVR_HEADER_METADATA = 12;
      var ETC_PKM_HEADER_LENGTH = 16;
      var ETC_PKM_FORMAT_OFFSET = 6;
      var ETC_PKM_WIDTH_OFFSET = 12;
      var ETC_PKM_HEIGHT_OFFSET = 14;
      var ETC1_RGB_NO_MIPMAPS = 0;
      var ETC2_RGB_NO_MIPMAPS = 1;
      var ETC2_RGBA_NO_MIPMAPS = 3;
      var ASTC_MAGIC = 0x5CA1AB13;
      var ASTC_HEADER_LENGTH = 16;
      var ASTC_HEADER_MAGIC = 4;
      var ASTC_HEADER_SIZE_X_BEGIN = 7;
      var ASTC_HEADER_SIZE_Y_BEGIN = 10;
      function getASTCFormat(xdim, ydim) {
        if (xdim === 4) {
          return PixelFormat.RGBA_ASTC_4x4;
        }
        if (xdim === 5) {
          if (ydim === 4) {
            return PixelFormat.RGBA_ASTC_5x4;
          }
          return PixelFormat.RGBA_ASTC_5x5;
        }
        if (xdim === 6) {
          if (ydim === 5) {
            return PixelFormat.RGBA_ASTC_6x5;
          }
          return PixelFormat.RGBA_ASTC_6x6;
        }
        if (xdim === 8) {
          if (ydim === 5) {
            return PixelFormat.RGBA_ASTC_8x5;
          }
          if (ydim === 6) {
            return PixelFormat.RGBA_ASTC_8x6;
          }
          return PixelFormat.RGBA_ASTC_8x8;
        }
        if (xdim === 10) {
          if (ydim === 5) {
            return PixelFormat.RGBA_ASTC_10x5;
          }
          if (ydim === 6) {
            return PixelFormat.RGBA_ASTC_10x6;
          }
          if (ydim === 8) {
            return PixelFormat.RGBA_ASTC_10x8;
          }
          return PixelFormat.RGBA_ASTC_10x10;
        }
        if (ydim === 10) {
          return PixelFormat.RGBA_ASTC_12x10;
        }
        return PixelFormat.RGBA_ASTC_12x12;
      }
      function readBEUint16(header, offset) {
        return header[offset] << 8 | header[offset + 1];
      }
      function isImageBitmap(imageSource) {
        return !!(sys.hasFeature(sys.Feature.IMAGE_BITMAP) && imageSource instanceof ImageBitmap);
      }
      function isNativeImage(imageSource) {
        return imageSource instanceof HTMLImageElement || imageSource instanceof HTMLCanvasElement || isImageBitmap(imageSource);
      }
      var ImageAsset = exports('eh', (_dec$3F = ccclass$M('cc.ImageAsset'), _dec$3F(_class$3B = (_class2$3f = (_class3$$ = function (_Asset) {
        _inheritsLoose(ImageAsset, _Asset);
        ImageAsset.mergeCompressedTextureMips = function mergeCompressedTextureMips(files) {
          var out = new Uint8Array(0);
          var err = null;
          try {
            var fileHeaderLength = COMPRESSED_HEADER_LENGTH + COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH + files.length * COMPRESSED_MIPMAP_DATA_SIZE_LENGTH;
            var fileLength = 0;
            for (var _iterator = _createForOfIteratorHelperLoose(files), _step; !(_step = _iterator()).done;) {
              var _file = _step.value;
              fileLength += _file.byteLength;
            }
            fileLength += fileHeaderLength;
            out = new Uint8Array(fileLength);
            var outView = new DataView(out.buffer, out.byteOffset, out.byteLength);
            outView.setUint32(0, COMPRESSED_MIPMAP_MAGIC, true);
            outView.setUint32(COMPRESSED_HEADER_LENGTH, files.length, true);
            var dataOffset = fileHeaderLength;
            for (var i = 0; i < files.length; i++) {
              var file = files[i];
              outView.setUint32(COMPRESSED_HEADER_LENGTH + COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH + i * COMPRESSED_MIPMAP_DATA_SIZE_LENGTH, file.byteLength, true);
              if (file instanceof ArrayBuffer) {
                var srcArray = new Uint8Array(file);
                out.set(srcArray, dataOffset);
              } else {
                var _srcArray = new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
                out.set(_srcArray, dataOffset);
              }
              dataOffset += file.byteLength;
            }
          } catch (e) {
            err = e;
            console.warn(err);
          }
          return out;
        };
        ImageAsset.parseCompressedTextures = function parseCompressedTextures(file, type) {
          var out = {
            _data: new Uint8Array(0),
            _compressed: true,
            width: 0,
            height: 0,
            format: 0,
            mipmapLevelDataSize: []
          };
          var buffer = file instanceof ArrayBuffer ? file : file.buffer;
          var bufferView = new DataView(buffer);
          var magicNumber = bufferView.getUint32(0, true);
          if (magicNumber === COMPRESSED_MIPMAP_MAGIC) {
            var mipmapLevelNumber = bufferView.getUint32(COMPRESSED_HEADER_LENGTH, true);
            var mipmapLevelDataSize = bufferView.getUint32(COMPRESSED_HEADER_LENGTH + COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH, true);
            var fileHeaderByteLength = COMPRESSED_HEADER_LENGTH + COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH + mipmapLevelNumber * COMPRESSED_MIPMAP_DATA_SIZE_LENGTH;
            ImageAsset.parseCompressedTexture(file, 0, fileHeaderByteLength, mipmapLevelDataSize, type, out);
            var beginOffset = fileHeaderByteLength + mipmapLevelDataSize;
            for (var i = 1; i < mipmapLevelNumber; i++) {
              var endOffset = bufferView.getUint32(COMPRESSED_HEADER_LENGTH + COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH + i * COMPRESSED_MIPMAP_DATA_SIZE_LENGTH, true);
              ImageAsset.parseCompressedTexture(file, i, beginOffset, endOffset, type, out);
              beginOffset += endOffset;
            }
          } else {
            ImageAsset.parseCompressedTexture(file, 0, 0, 0, type, out);
          }
          return out;
        };
        ImageAsset.parseCompressedTexture = function parseCompressedTexture(file, levelIndex, beginOffset, endOffset, type, out) {
          switch (type) {
            case compressType.PVR:
              ImageAsset.parsePVRTexture(file, levelIndex, beginOffset, endOffset, out);
              break;
            case compressType.PKM:
              ImageAsset.parsePKMTexture(file, levelIndex, beginOffset, endOffset, out);
              break;
            case compressType.ASTC:
              ImageAsset.parseASTCTexture(file, levelIndex, beginOffset, endOffset, out);
              break;
          }
        };
        ImageAsset.parsePVRTexture = function parsePVRTexture(file, levelIndex, beginOffset, endOffset, out) {
          var buffer = file instanceof ArrayBuffer ? file : file.buffer;
          var header = new Int32Array(buffer, beginOffset, PVR_HEADER_LENGTH);
          if (header[PVR_HEADER_MAGIC] === PVR_MAGIC) {
            var byteOffset = beginOffset + header[PVR_HEADER_METADATA] + 52;
            var length = endOffset - header.byteLength;
            if (endOffset > 0) {
              var srcView = new Uint8Array(buffer, byteOffset, length);
              var dstView = new Uint8Array(out._data.byteLength + srcView.byteLength);
              dstView.set(out._data);
              dstView.set(srcView, out._data.byteLength);
              out._data = dstView;
              out.mipmapLevelDataSize[levelIndex] = length;
            } else {
              out._data = new Uint8Array(buffer, byteOffset);
            }
            out.width = levelIndex > 0 ? out.width : header[PVR_HEADER_WIDTH];
            out.height = levelIndex > 0 ? out.height : header[PVR_HEADER_HEIGHT];
          } else if (header[11] === 0x21525650) {
            var _byteOffset = beginOffset + header[0];
            var _length = endOffset - header.byteLength;
            if (endOffset > 0) {
              var _srcView = new Uint8Array(buffer, _byteOffset, _length);
              var _dstView = new Uint8Array(out._data.byteLength + _srcView.byteLength);
              _dstView.set(out._data);
              _dstView.set(_srcView, out._data.byteLength);
              out._data = _dstView;
              out.mipmapLevelDataSize[levelIndex] = _length;
            } else {
              out._data = new Uint8Array(buffer, _byteOffset);
            }
            out.width = levelIndex > 0 ? out.width : header[1];
            out.height = levelIndex > 0 ? out.height : header[2];
          } else {
            throw new Error('Invalid magic number in PVR header');
          }
        };
        ImageAsset.parsePKMTexture = function parsePKMTexture(file, levelIndex, beginOffset, endOffset, out) {
          var buffer = file instanceof ArrayBuffer ? file : file.buffer;
          var header = new Uint8Array(buffer, beginOffset, ETC_PKM_HEADER_LENGTH);
          var format = readBEUint16(header, ETC_PKM_FORMAT_OFFSET);
          if (format !== ETC1_RGB_NO_MIPMAPS && format !== ETC2_RGB_NO_MIPMAPS && format !== ETC2_RGBA_NO_MIPMAPS) {
            throw new Error('Invalid magic number in ETC header');
          }
          var byteOffset = beginOffset + ETC_PKM_HEADER_LENGTH;
          var length = endOffset - ETC_PKM_HEADER_LENGTH;
          if (endOffset > 0) {
            var srcView = new Uint8Array(buffer, byteOffset, length);
            var dstView = new Uint8Array(out._data.byteLength + srcView.byteLength);
            dstView.set(out._data);
            dstView.set(srcView, out._data.byteLength);
            out._data = dstView;
            out.mipmapLevelDataSize[levelIndex] = length;
          } else {
            out._data = new Uint8Array(buffer, byteOffset);
          }
          out.width = levelIndex > 0 ? out.width : readBEUint16(header, ETC_PKM_WIDTH_OFFSET);
          out.height = levelIndex > 0 ? out.height : readBEUint16(header, ETC_PKM_HEIGHT_OFFSET);
        };
        ImageAsset.parseASTCTexture = function parseASTCTexture(file, levelIndex, beginOffset, endOffset, out) {
          var buffer = file instanceof ArrayBuffer ? file : file.buffer;
          var header = new Uint8Array(buffer, beginOffset, ASTC_HEADER_LENGTH);
          var magicval = header[0] + (header[1] << 8) + (header[2] << 16) + (header[3] << 24);
          if (magicval !== ASTC_MAGIC) {
            throw new Error('Invalid magic number in ASTC header');
          }
          var xdim = header[ASTC_HEADER_MAGIC];
          var ydim = header[ASTC_HEADER_MAGIC + 1];
          var zdim = header[ASTC_HEADER_MAGIC + 2];
          if ((xdim < 3 || xdim > 6 || ydim < 3 || ydim > 6 || zdim < 3 || zdim > 6) && (xdim < 4 || xdim === 7 || xdim === 9 || xdim === 11 || xdim > 12 || ydim < 4 || ydim === 7 || ydim === 9 || ydim === 11 || ydim > 12 || zdim !== 1)) {
            throw new Error('Invalid block number in ASTC header');
          }
          var format = getASTCFormat(xdim, ydim);
          var byteOffset = beginOffset + ASTC_HEADER_LENGTH;
          var length = endOffset - ASTC_HEADER_LENGTH;
          if (endOffset > 0) {
            var srcView = new Uint8Array(buffer, byteOffset, length);
            var dstView = new Uint8Array(out._data.byteLength + srcView.byteLength);
            dstView.set(out._data);
            dstView.set(srcView, out._data.byteLength);
            out._data = dstView;
            out.mipmapLevelDataSize[levelIndex] = length;
          } else {
            out._data = new Uint8Array(buffer, byteOffset);
          }
          out.width = levelIndex > 0 ? out.width : header[ASTC_HEADER_SIZE_X_BEGIN] + (header[ASTC_HEADER_SIZE_X_BEGIN + 1] << 8) + (header[ASTC_HEADER_SIZE_X_BEGIN + 2] << 16);
          out.height = levelIndex > 0 ? out.height : header[ASTC_HEADER_SIZE_Y_BEGIN] + (header[ASTC_HEADER_SIZE_Y_BEGIN + 1] << 8) + (header[ASTC_HEADER_SIZE_Y_BEGIN + 2] << 16);
          out.format = format;
        };
        var _proto = ImageAsset.prototype;
        _proto.extractMipmap0 = function extractMipmap0() {
          if (this.mipmapLevelDataSize && this.mipmapLevelDataSize.length > 0) {
            var mipmapSize = this.mipmapLevelDataSize[0];
            var data = this.data;
            var dataView = new Uint8Array(data.buffer, 0, mipmapSize);
            var mipmap = new ImageAsset({
              _data: dataView,
              _compressed: true,
              width: this.width,
              height: this.height,
              format: this.format,
              mipmapLevelDataSize: []
            });
            mipmap._uuid = "" + this._uuid;
            return mipmap;
          } else {
            return this;
          }
        };
        _proto.extractMipmaps = function extractMipmaps() {
          var images = [];
          if (this.mipmapLevelDataSize && this.mipmapLevelDataSize.length > 0) {
            var mipmapLevelDataSize = this.mipmapLevelDataSize;
            var data = this.data;
            var byteOffset = 0;
            var height = this.height;
            var width = this.width;
            for (var _iterator2 = _createForOfIteratorHelperLoose(mipmapLevelDataSize), _step2; !(_step2 = _iterator2()).done;) {
              var mipmapSize = _step2.value;
              var dataView = new Uint8Array(data.buffer, byteOffset, mipmapSize);
              var mipmap = new ImageAsset({
                _data: dataView,
                _compressed: true,
                width: width,
                height: height,
                format: this.format,
                mipmapLevelDataSize: []
              });
              byteOffset += mipmapSize;
              mipmap._uuid = "" + this._uuid;
              width = Math.max(width >> 1, 1);
              height = Math.max(height >> 1, 1);
              images.push(mipmap);
            }
          } else {
            images.push(this);
          }
          return images;
        };
        function ImageAsset(nativeAsset) {
          var _this;
          _this = _Asset.call(this) || this;
          _this._nativeData = void 0;
          _this._exportedExts = undefined;
          _this._format = PixelFormat.RGBA8888;
          _this._width = 0;
          _this._height = 0;
          _this._nativeData = {
            _data: null,
            width: 0,
            height: 0,
            format: 0,
            _compressed: false,
            mipmapLevelDataSize: []
          };
          if (nativeAsset !== undefined) {
            _this.reset(nativeAsset);
          }
          return _this;
        }
        _proto.reset = function reset(data) {
          if (isImageBitmap(data)) {
            this._nativeData = data;
          } else if (!(data instanceof HTMLElement)) {
            this._nativeData = data;
            this._format = data.format;
          } else {
            this._nativeData = data;
          }
        };
        _proto.destroy = function destroy() {
          if (this.data && this.data instanceof HTMLImageElement) {
            this.data.src = '';
            this._setRawAsset('');
          } else if (isImageBitmap(this.data)) {
            var _this$data;
            (_this$data = this.data) === null || _this$data === void 0 ? void 0 : _this$data.close();
          }
          return _Asset.prototype.destroy.call(this);
        };
        _proto._serialize = function _serialize() {
        };
        _proto._deserialize = function _deserialize(data) {
          var fmtStr = '';
          if (typeof data === 'string') {
            fmtStr = data;
          } else {
            this._width = data.w;
            this._height = data.h;
            fmtStr = data.fmt;
          }
          var device = _getGlobalDevice();
          var extensionIDs = fmtStr.split('_');
          var preferedExtensionIndex = Number.MAX_VALUE;
          var format = this._format;
          var ext = '';
          var SupportTextureFormats = macro.SUPPORT_TEXTURE_FORMATS;
          for (var _iterator4 = _createForOfIteratorHelperLoose(extensionIDs), _step4; !(_step4 = _iterator4()).done;) {
            var extensionID = _step4.value;
            var extFormat = extensionID.split('@');
            var i = parseInt(extFormat[0], undefined);
            var tmpExt = ImageAsset.extnames[i] || extFormat[0];
            var index = SupportTextureFormats.indexOf(tmpExt);
            if (index !== -1 && index < preferedExtensionIndex) {
              var fmt = extFormat[1] ? parseInt(extFormat[1]) : this._format;
              if (tmpExt === '.astc' && (!device || !(device.getFormatFeatures(Format.ASTC_RGBA_4X4) & FormatFeatureBit.SAMPLED_TEXTURE))) {
                continue;
              } else if (tmpExt === '.pvr' && (!device || !(device.getFormatFeatures(Format.PVRTC_RGBA4) & FormatFeatureBit.SAMPLED_TEXTURE))) {
                continue;
              } else if ((fmt === PixelFormat.RGB_ETC1 || fmt === PixelFormat.RGBA_ETC1) && (!device || !(device.getFormatFeatures(Format.ETC_RGB8) & FormatFeatureBit.SAMPLED_TEXTURE))) {
                continue;
              } else if ((fmt === PixelFormat.RGB_ETC2 || fmt === PixelFormat.RGBA_ETC2) && (!device || !(device.getFormatFeatures(Format.ETC2_RGB8) & FormatFeatureBit.SAMPLED_TEXTURE))) {
                continue;
              } else if (tmpExt === '.webp' && !sys.hasFeature(sys.Feature.WEBP)) {
                continue;
              }
              preferedExtensionIndex = index;
              ext = tmpExt;
              format = fmt;
            }
          }
          if (ext) {
            this._setRawAsset(ext);
            this._format = format;
          } else {
            warnID(3121);
          }
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          if (!ImageAsset._sharedPlaceHolderCanvas) {
            var canvas = ccwindow.document.createElement('canvas');
            var context = canvas.getContext('2d');
            var l = canvas.width = canvas.height = 2;
            context.fillStyle = '#ff00ff';
            context.fillRect(0, 0, l, l);
            this.reset(canvas);
            ImageAsset._sharedPlaceHolderCanvas = canvas;
          } else {
            this.reset(ImageAsset._sharedPlaceHolderCanvas);
          }
        };
        _proto.validate = function validate() {
          return !!this.data;
        };
        _createClass(ImageAsset, [{
          key: "_nativeAsset",
          get: function get() {
            return this._nativeData;
          },
          set: function set(value) {
            if (!(value instanceof HTMLElement) && !isImageBitmap(value)) {
              value.format = value.format || this._format;
            }
            this.reset(value);
          }
        }, {
          key: "data",
          get: function get() {
            if (isNativeImage(this._nativeData)) {
              return this._nativeData;
            }
            return this._nativeData && this._nativeData._data;
          }
        }, {
          key: "width",
          get: function get() {
            return this._nativeData.width || this._width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._nativeData.height || this._height;
          }
        }, {
          key: "format",
          get: function get() {
            return this._format;
          }
        }, {
          key: "isCompressed",
          get: function get() {
            return this._format >= PixelFormat.RGB_ETC1 && this._format <= PixelFormat.RGBA_ASTC_12x12 || this._format >= PixelFormat.RGB_A_PVRTC_2BPPV1 && this._format <= PixelFormat.RGBA_ETC1;
          }
        }, {
          key: "mipmapLevelDataSize",
          get: function get() {
            return this._nativeData.mipmapLevelDataSize;
          }
        }, {
          key: "url",
          get: function get() {
            return this.nativeUrl;
          }
        }]);
        return ImageAsset;
      }(Asset), _class3$$.extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.pkm', '.astc'], _class3$$._sharedPlaceHolderCanvas = null, _class3$$), (_applyDecoratedDescriptor(_class2$3f.prototype, "_nativeAsset", [override$1], Object.getOwnPropertyDescriptor(_class2$3f.prototype, "_nativeAsset"), _class2$3f.prototype)), _class2$3f)) || _class$3B));
      function _getGlobalDevice() {
        return deviceManager.gfxDevice;
      }
      legacyCC.ImageAsset = ImageAsset;

      var _dec$3E, _class$3A, _class2$3e, _initializer$2Y, _initializer2$2m, _initializer3$1L, _initializer4$1u, _initializer5$19, _initializer6$X, _initializer7$L, _initializer8$H, _class3$_;
      ccenum(Format);
      var idGenerator$2 = new IDGenerator('Tex');
      var TextureBase = (_dec$3E = ccclass$M('cc.TextureBase'), _dec$3E(_class$3A = (_class2$3e = (_class3$_ = function (_Asset) {
        _inheritsLoose(TextureBase, _Asset);
        function TextureBase() {
          var _this;
          _this = _Asset.call(this) || this;
          _this._format = _initializer$2Y && _initializer$2Y();
          _this._minFilter = _initializer2$2m && _initializer2$2m();
          _this._magFilter = _initializer3$1L && _initializer3$1L();
          _this._mipFilter = _initializer4$1u && _initializer4$1u();
          _this._wrapS = _initializer5$19 && _initializer5$19();
          _this._wrapT = _initializer6$X && _initializer6$X();
          _this._wrapR = _initializer7$L && _initializer7$L();
          _this._anisotropy = _initializer8$H && _initializer8$H();
          _this._width = 1;
          _this._height = 1;
          _this._id = void 0;
          _this._samplerInfo = new SamplerInfo();
          _this._gfxSampler = null;
          _this._gfxDevice = null;
          _this._textureHash = 0;
          _this._id = idGenerator$2.getNewId();
          _this._gfxDevice = _this._getGFXDevice();
          _this._textureHash = murmurhash2_32_gc(_this._id, 666);
          return _this;
        }
        var _proto = TextureBase.prototype;
        _proto.getId = function getId() {
          return this._id;
        };
        _proto.getPixelFormat = function getPixelFormat() {
          return this._format;
        };
        _proto.getAnisotropy = function getAnisotropy() {
          return this._anisotropy;
        };
        _proto.setWrapMode = function setWrapMode(wrapS, wrapT, wrapR) {
          if (wrapR === undefined) wrapR = wrapS;
          this._wrapS = wrapS;
          this._samplerInfo.addressU = wrapS;
          this._wrapT = wrapT;
          this._samplerInfo.addressV = wrapT;
          this._wrapR = wrapR;
          this._samplerInfo.addressW = wrapR;
          if (this._gfxDevice) {
            this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo);
          }
        };
        _proto.setFilters = function setFilters(minFilter, magFilter) {
          this._minFilter = minFilter;
          this._samplerInfo.minFilter = minFilter;
          this._magFilter = magFilter;
          this._samplerInfo.magFilter = magFilter;
          if (this._gfxDevice) {
            this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo);
          }
        };
        _proto.setMipFilter = function setMipFilter(mipFilter) {
          this._mipFilter = mipFilter;
          this._samplerInfo.mipFilter = mipFilter;
          if (this._gfxDevice) {
            this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo);
          }
        };
        _proto.setAnisotropy = function setAnisotropy(anisotropy) {
          this._anisotropy = anisotropy;
          this._samplerInfo.maxAnisotropy = anisotropy;
          if (this._gfxDevice) {
            this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo);
          }
        };
        _proto.destroy = function destroy() {
          var _cclegacy$director$ro;
          var destroyed = _Asset.prototype.destroy.call(this);
          if (destroyed && (_cclegacy$director$ro = legacyCC.director.root) !== null && _cclegacy$director$ro !== void 0 && _cclegacy$director$ro.batcher2D) {
            legacyCC.director.root.batcher2D._releaseDescriptorSetCache(this._textureHash);
          }
          return destroyed;
        };
        _proto.getHash = function getHash() {
          return this._textureHash;
        };
        _proto.getGFXTexture = function getGFXTexture() {
          return null;
        };
        _proto.getSamplerInfo = function getSamplerInfo() {
          return this._samplerInfo;
        };
        _proto.getGFXSampler = function getGFXSampler() {
          if (!this._gfxSampler) {
            if (this._gfxDevice) {
              this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo);
            } else {
              errorID(9302);
            }
          }
          return this._gfxSampler;
        };
        _proto._serialize = function _serialize(ctxForExporting) {
          return '';
        };
        _proto._deserialize = function _deserialize(serializedData, handle) {
          var data = serializedData;
          var fields = data.split(',');
          fields.unshift('');
          if (fields.length >= 5) {
            this.setFilters(parseInt(fields[1]), parseInt(fields[2]));
            this.setWrapMode(parseInt(fields[3]), parseInt(fields[4]));
          }
          if (fields.length >= 7) {
            this.setMipFilter(parseInt(fields[5]));
            this.setAnisotropy(parseInt(fields[6]));
          }
        };
        _proto._getGFXDevice = function _getGFXDevice() {
          return deviceManager.gfxDevice;
        };
        _proto._getGFXFormat = function _getGFXFormat() {
          return this._getGFXPixelFormat(this._format);
        };
        _proto._setGFXFormat = function _setGFXFormat(format) {
          this._format = format === undefined ? PixelFormat.RGBA8888 : format;
        };
        _proto._getGFXPixelFormat = function _getGFXPixelFormat(format) {
          if (format === PixelFormat.RGBA_ETC1) {
            format = PixelFormat.RGB_ETC1;
          } else if (format === PixelFormat.RGB_A_PVRTC_4BPPV1) {
            format = PixelFormat.RGB_PVRTC_4BPPV1;
          } else if (format === PixelFormat.RGB_A_PVRTC_2BPPV1) {
            format = PixelFormat.RGB_PVRTC_2BPPV1;
          }
          return format;
        };
        _createClass(TextureBase, [{
          key: "isCompressed",
          get: function get() {
            return this._format >= PixelFormat.RGB_ETC1 && this._format <= PixelFormat.RGBA_ASTC_12x12 || this._format >= PixelFormat.RGB_A_PVRTC_2BPPV1 && this._format <= PixelFormat.RGBA_ETC1;
          }
        }, {
          key: "width",
          get: function get() {
            return this._width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          }
        }]);
        return TextureBase;
      }(Asset), _class3$_.PixelFormat = PixelFormat, _class3$_.WrapMode = WrapMode$1, _class3$_.Filter = Filter, _class3$_), (_initializer$2Y = applyDecoratedInitializer(_class2$3e.prototype, "_format", [serializable$p], function () {
        return PixelFormat.RGBA8888;
      }), _initializer2$2m = applyDecoratedInitializer(_class2$3e.prototype, "_minFilter", [serializable$p], function () {
        return Filter.LINEAR;
      }), _initializer3$1L = applyDecoratedInitializer(_class2$3e.prototype, "_magFilter", [serializable$p], function () {
        return Filter.LINEAR;
      }), _initializer4$1u = applyDecoratedInitializer(_class2$3e.prototype, "_mipFilter", [serializable$p], function () {
        return Filter.NONE;
      }), _initializer5$19 = applyDecoratedInitializer(_class2$3e.prototype, "_wrapS", [serializable$p], function () {
        return WrapMode$1.REPEAT;
      }), _initializer6$X = applyDecoratedInitializer(_class2$3e.prototype, "_wrapT", [serializable$p], function () {
        return WrapMode$1.REPEAT;
      }), _initializer7$L = applyDecoratedInitializer(_class2$3e.prototype, "_wrapR", [serializable$p], function () {
        return WrapMode$1.REPEAT;
      }), _initializer8$H = applyDecoratedInitializer(_class2$3e.prototype, "_anisotropy", [serializable$p], function () {
        return 0;
      })), _class2$3e)) || _class$3A);
      legacyCC.TextureBase = TextureBase;

      var _dec$3D, _class$3z, _dec2$2A, _class2$3d, _dec3$1N, _class3$Z;
      var Script = exports('en', (_dec$3D = ccclass$M('cc.Script'), _dec$3D(_class$3z = function (_Asset) {
        _inheritsLoose(Script, _Asset);
        function Script() {
          return _Asset.apply(this, arguments) || this;
        }
        return Script;
      }(Asset)) || _class$3z));
      legacyCC._Script = Script;
      var JavaScript = exports('eo', (_dec2$2A = ccclass$M('cc.JavaScript'), _dec2$2A(_class2$3d = function (_Script) {
        _inheritsLoose(JavaScript, _Script);
        function JavaScript() {
          return _Script.apply(this, arguments) || this;
        }
        return JavaScript;
      }(Script)) || _class2$3d));
      legacyCC._JavaScript = JavaScript;
      var TypeScript = exports('ep', (_dec3$1N = ccclass$M('cc.TypeScript'), _dec3$1N(_class3$Z = function (_Script2) {
        _inheritsLoose(TypeScript, _Script2);
        function TypeScript() {
          return _Script2.apply(this, arguments) || this;
        }
        return TypeScript;
      }(Script)) || _class3$Z));
      legacyCC._TypeScript = TypeScript;

      var _dec$3C, _class$3y, _class2$3c, _initializer$2X, _initializer2$2l, _initializer3$1K, _initializer4$1t, _initializer5$18;
      var EventHandler = exports('dG', (_dec$3C = ccclass$M('cc.ClickEvent'), _dec$3C(_class$3y = (_class2$3c = function () {
        function EventHandler() {
          this.target = _initializer$2X && _initializer$2X();
          this.component = _initializer2$2l && _initializer2$2l();
          this._componentId = _initializer3$1K && _initializer3$1K();
          this.handler = _initializer4$1t && _initializer4$1t();
          this.customEventData = _initializer5$18 && _initializer5$18();
        }
        EventHandler.emitEvents = function emitEvents(events) {
          for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            args[_key - 1] = arguments[_key];
          }
          for (var i = 0, l = events.length; i < l; i++) {
            var event = events[i];
            if (!(event instanceof EventHandler)) {
              continue;
            }
            event.emit(args);
          }
        };
        var _proto = EventHandler.prototype;
        _proto.emit = function emit(params) {
          var target = this.target;
          if (!legacyCC.isValid(target)) {
            return;
          }
          this._genCompIdIfNeeded();
          var compType = legacyCC.js.getClassById(this._componentId);
          var comp = target.getComponent(compType);
          if (!legacyCC.isValid(comp)) {
            return;
          }
          var handler = comp[this.handler];
          if (typeof handler !== 'function') {
            return;
          }
          if (this.customEventData != null && this.customEventData !== '') {
            params = params.slice();
            params.push(this.customEventData);
          }
          handler.apply(comp, params);
        };
        _proto._compName2Id = function _compName2Id(compName) {
          var comp = legacyCC.js.getClassByName(compName);
          return legacyCC.js.getClassId(comp);
        };
        _proto._compId2Name = function _compId2Name(compId) {
          var comp = legacyCC.js.getClassById(compId);
          return legacyCC.js.getClassName(comp);
        };
        _proto._genCompIdIfNeeded = function _genCompIdIfNeeded() {
          if (!this._componentId) {
            this._componentName = this.component;
            this.component = '';
          }
        };
        _createClass(EventHandler, [{
          key: "_componentName",
          get: function get() {
            this._genCompIdIfNeeded();
            return this._compId2Name(this._componentId);
          },
          set: function set(value) {
            this._componentId = this._compName2Id(value);
          }
        }]);
        return EventHandler;
      }(), (_initializer$2X = applyDecoratedInitializer(_class2$3c.prototype, "target", [serializable$p], function () {
        return null;
      }), _initializer2$2l = applyDecoratedInitializer(_class2$3c.prototype, "component", [serializable$p], function () {
        return '';
      }), _initializer3$1K = applyDecoratedInitializer(_class2$3c.prototype, "_componentId", [serializable$p], function () {
        return '';
      }), _initializer4$1t = applyDecoratedInitializer(_class2$3c.prototype, "handler", [serializable$p], function () {
        return '';
      }), _initializer5$18 = applyDecoratedInitializer(_class2$3c.prototype, "customEventData", [serializable$p], function () {
        return '';
      })), _class2$3c)) || _class$3y));

      var _dec$3B, _dec2$2z, _class$3x, _class2$3b, _initializer$2W, _initializer2$2k, _initializer3$1J, _class3$Y;
      var idGenerator$1 = new IDGenerator('Comp');
      var IsOnLoadCalled$1 = CCObject.Flags.IsOnLoadCalled;
      var NullNode = null;
      var Component = exports('dH', (_dec$3B = ccclass$M('cc.Component'), _dec2$2z = type$d(Script), _dec$3B(_class$3x = (_class2$3b = (_class3$Y = function (_CCObject) {
        _inheritsLoose(Component, _CCObject);
        function Component() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _CCObject.call.apply(_CCObject, [this].concat(args)) || this;
          _this.node = _initializer$2W && _initializer$2W();
          _this._enabled = _initializer2$2k && _initializer2$2k();
          _this.__prefab = _initializer3$1J && _initializer3$1J();
          _this._sceneGetter = null;
          _this._id = idGenerator$1.getNewId();
          return _this;
        }
        var _proto = Component.prototype;
        _proto._getRenderScene = function _getRenderScene() {
          if (this._sceneGetter) {
            return this._sceneGetter();
          }
          return this.node.scene.renderScene;
        };
        _proto.addComponent = function addComponent(typeOrClassName) {
          return this.node.addComponent(typeOrClassName);
        };
        _proto.getComponent = function getComponent(typeOrClassName) {
          return this.node.getComponent(typeOrClassName);
        };
        _proto.getComponents = function getComponents(typeOrClassName) {
          return this.node.getComponents(typeOrClassName);
        };
        _proto.getComponentInChildren = function getComponentInChildren(typeOrClassName) {
          return this.node.getComponentInChildren(typeOrClassName);
        };
        _proto.getComponentsInChildren = function getComponentsInChildren(typeOrClassName) {
          return this.node.getComponentsInChildren(typeOrClassName);
        };
        _proto.destroy = function destroy() {
          if (_CCObject.prototype.destroy.call(this)) {
            if (this._enabled && this.node.activeInHierarchy) {
              legacyCC.director._compScheduler.disableComp(this);
            }
            return true;
          }
          return false;
        };
        _proto._onPreDestroy = function _onPreDestroy() {
          this.unscheduleAllCallbacks();
          legacyCC.director._nodeActivator.destroyComp(this);
          this.node._removeComponent(this);
        };
        _proto._instantiate = function _instantiate(cloned) {
          if (!cloned) {
            cloned = legacyCC.instantiate._clone(this, this);
          }
          if (cloned) {
            cloned.node = NullNode;
          }
          return cloned;
        };
        _proto.schedule = function schedule(callback, interval, repeat, delay) {
          if (interval === void 0) {
            interval = 0;
          }
          if (repeat === void 0) {
            repeat = legacyCC.macro.REPEAT_FOREVER;
          }
          if (delay === void 0) {
            delay = 0;
          }
          assertID(Boolean(callback), 1619);
          interval = interval || 0;
          assertID(interval >= 0, 1620);
          repeat = Number.isNaN(repeat) ? legacyCC.macro.REPEAT_FOREVER : repeat;
          delay = delay || 0;
          var scheduler = legacyCC.director.getScheduler();
          var paused = scheduler.isTargetPaused(this);
          scheduler.schedule(callback, this, interval, repeat, delay, paused);
        };
        _proto.scheduleOnce = function scheduleOnce(callback, delay) {
          if (delay === void 0) {
            delay = 0;
          }
          this.schedule(callback, 0, 0, delay);
        };
        _proto.unschedule = function unschedule(callback_fn) {
          if (!callback_fn) {
            return;
          }
          legacyCC.director.getScheduler().unschedule(callback_fn, this);
        };
        _proto.unscheduleAllCallbacks = function unscheduleAllCallbacks() {
          legacyCC.director.getScheduler().unscheduleAllForTarget(this);
        };
        _createClass(Component, [{
          key: "name",
          get: function get() {
            if (this._name) {
              return this._name;
            }
            var className = getClassName(this);
            var trimLeft = className.lastIndexOf('.');
            if (trimLeft >= 0) {
              className = className.slice(trimLeft + 1);
            }
            if (this.node) {
              return this.node.name + "<" + className + ">";
            } else {
              return className;
            }
          },
          set: function set(value) {
            this._name = value;
          }
        }, {
          key: "uuid",
          get: function get() {
            return this._id;
          }
        }, {
          key: "__scriptAsset",
          get: function get() {
            return null;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(value) {
            if (this._enabled !== value) {
              this._enabled = value;
              if (this.node.activeInHierarchy) {
                var compScheduler = legacyCC.director._compScheduler;
                if (value) {
                  compScheduler.enableComp(this);
                } else {
                  compScheduler.disableComp(this);
                }
              }
            }
          }
        }, {
          key: "enabledInHierarchy",
          get: function get() {
            return this._enabled && this.node && this.node.activeInHierarchy;
          }
        }, {
          key: "_isOnLoadCalled",
          get: function get() {
            return this._objFlags & IsOnLoadCalled$1;
          }
        }, {
          key: "internalUpdate",
          get: function get() {
            return this.update;
          }
        }, {
          key: "internalLateUpdate",
          get: function get() {
            return this.lateUpdate;
          }
        }, {
          key: "internalPreload",
          get: function get() {
            return this.__preload;
          }
        }, {
          key: "internalOnLoad",
          get: function get() {
            return this.onLoad;
          }
        }, {
          key: "internalStart",
          get: function get() {
            return this.start;
          }
        }, {
          key: "internalOnEnable",
          get: function get() {
            return this.onEnable;
          }
        }, {
          key: "internalOnDisable",
          get: function get() {
            return this.onDisable;
          }
        }, {
          key: "internalOnDestroy",
          get: function get() {
            return this.onDestroy;
          }
        }]);
        return Component;
      }(CCObject), _class3$Y.EventHandler = EventHandler, _class3$Y._executionOrder = 0, _class3$Y._requireComponent = null, _class3$Y.system = null, _class3$Y), (_applyDecoratedDescriptor(_class2$3b.prototype, "__scriptAsset", [_dec2$2z], Object.getOwnPropertyDescriptor(_class2$3b.prototype, "__scriptAsset"), _class2$3b.prototype), _initializer$2W = applyDecoratedInitializer(_class2$3b.prototype, "node", [serializable$p], function () {
        return NullNode;
      }), _initializer2$2k = applyDecoratedInitializer(_class2$3b.prototype, "_enabled", [serializable$p], function () {
        return true;
      }), _initializer3$1J = applyDecoratedInitializer(_class2$3b.prototype, "__prefab", [serializable$p], function () {
        return null;
      })), _class2$3b)) || _class$3x));
      value(Component, '_registerEditorProps', function (cls, props) {
        var reqComp = props.requireComponent;
        if (reqComp) {
          if (Array.isArray(reqComp)) {
            reqComp = reqComp.filter(Boolean);
          }
          cls._requireComponent = reqComp;
        }
        var order = props.executionOrder;
        if (order && typeof order === 'number') {
          cls._executionOrder = order;
        }
      });
      legacyCC.Component = Component;

      var _dec$3A, _class$3w, _class2$3a, _initializer$2V;
      var MissingScript = exports('e2', (_dec$3A = ccclass$M('cc.MissingScript'), _dec$3A(_class$3w = (_class2$3a = function (_Component) {
        _inheritsLoose(MissingScript, _Component);
        MissingScript.safeFindClass = function safeFindClass(id) {
          var cls = getClassById(id);
          if (cls) {
            return cls;
          }
          legacyCC.deserialize.reportMissingClass(id);
          return undefined;
        };
        function MissingScript() {
          var _this;
          _this = _Component.call(this) || this;
          _this._$erialized = _initializer$2V && _initializer$2V();
          return _this;
        }
        var _proto = MissingScript.prototype;
        _proto.onLoad = function onLoad() {
          warnID(4600, this.node.name);
        };
        return MissingScript;
      }(Component), (_initializer$2V = applyDecoratedInitializer(_class2$3a.prototype, "_$erialized", [serializable$p, editorOnly], function () {
        return null;
      })), _class2$3a)) || _class$3w));
      legacyCC._MissingScript = MissingScript;
      try {
        var props = MissingScript.__values__;
        if (props.length === 0 || props[props.length - 1] !== '_$erialized') {
          error("The '_$erialized' prop in MissingScript is missing. Please contact jare.");
          error("    Error props: ['" + props + "']");
        }
      } catch (e) {
        error("Error when checking MissingScript 5, " + e);
      }

      var VERSION = 1;
      var MAGIC = 0x4E4F4343;
      var CHUNK_ALIGN_AS = 8;
      var CCON = function () {
        function CCON(document, chunks) {
          this._document = void 0;
          this._chunks = void 0;
          this._document = document;
          this._chunks = chunks;
        }
        _createClass(CCON, [{
          key: "document",
          get: function get() {
            return this._document;
          }
        }, {
          key: "chunks",
          get: function get() {
            return this._chunks;
          }
        }]);
        return CCON;
      }();
      function parseCCONJson(json) {
        var cconPreface = json;
        return {
          chunks: cconPreface.chunks,
          document: cconPreface.document
        };
      }
      function decodeCCONBinary(bytes) {
        if (bytes.length < 16) {
          throw new InvalidCCONError(getError(13102));
        }
        var dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
        var magic = dataView.getUint32(0, true);
        if (magic !== MAGIC) {
          throw new InvalidCCONError(getError(13100));
        }
        var version = dataView.getUint32(4, true);
        if (version !== VERSION) {
          throw new InvalidCCONError(getError(13101, version));
        }
        var dataByteLength = dataView.getUint32(8, true);
        if (dataByteLength !== dataView.byteLength) {
          throw new InvalidCCONError(getError(13102));
        }
        var chunksStart = 12;
        var jsonDataLength = dataView.getUint32(chunksStart, true);
        chunksStart += 4;
        var jsonData = new Uint8Array(dataView.buffer, chunksStart + dataView.byteOffset, jsonDataLength);
        chunksStart += jsonDataLength;
        var jsonString = decodeJson(jsonData);
        var json;
        try {
          json = JSON.parse(jsonString);
        } catch (err) {
          throw new InvalidCCONError(err);
        }
        var chunks = [];
        while (chunksStart < dataView.byteLength) {
          if (chunksStart % CHUNK_ALIGN_AS !== 0) {
            var padding = CHUNK_ALIGN_AS - chunksStart % CHUNK_ALIGN_AS;
            chunksStart += padding;
          }
          var chunkDataLength = dataView.getUint32(chunksStart, true);
          chunksStart += 4;
          chunks.push(new Uint8Array(dataView.buffer, chunksStart + dataView.byteOffset, chunkDataLength));
          chunksStart += chunkDataLength;
        }
        if (chunksStart !== dataView.byteLength) {
          throw new InvalidCCONError(getError(13102));
        }
        return new CCON(json, chunks);
      }
      function decodeJson(data) {
        if (typeof TextDecoder !== 'undefined') {
          return new TextDecoder().decode(data);
        } else if ('Buffer' in globalThis) {
          var _ref2 = globalThis,
            _Buffer2 = _ref2.Buffer;
          return _Buffer2.from(data.buffer, data.byteOffset, data.byteLength).toString();
        } else {
          throw new Error(getError(13104));
        }
      }
      var InvalidCCONError = function (_Error) {
        _inheritsLoose(InvalidCCONError, _Error);
        function InvalidCCONError() {
          return _Error.apply(this, arguments) || this;
        }
        return InvalidCCONError;
      }(_wrapNativeSuper(Error));
      (function () {
        function BufferBuilder() {
          this._viewOrPaddings = [];
          this._length = 0;
        }
        var _proto = BufferBuilder.prototype;
        _proto.alignAs = function alignAs(align) {
          if (align !== 0) {
            var remainder = this._length % align;
            if (remainder !== 0) {
              var padding = align - remainder;
              this._viewOrPaddings.push(padding);
              this._length += padding;
              return padding;
            }
          }
          return 0;
        };
        _proto.append = function append(view) {
          var result = this._length;
          this._viewOrPaddings.push(view);
          this._length += view.byteLength;
          return result;
        };
        _proto.get = function get() {
          var result = new Uint8Array(this._length);
          var counter = 0;
          this._viewOrPaddings.forEach(function (viewOrPadding) {
            if (typeof viewOrPadding === 'number') {
              counter += viewOrPadding;
            } else {
              result.set(new Uint8Array(viewOrPadding.buffer, viewOrPadding.byteOffset, viewOrPadding.byteLength), counter);
              counter += viewOrPadding.byteLength;
            }
          });
          return result;
        };
        _createClass(BufferBuilder, [{
          key: "byteLength",
          get: function get() {
            return this._length;
          }
        }]);
        return BufferBuilder;
      })();
      legacyCC.internal.parseCCONJson = parseCCONJson;
      legacyCC.internal.decodeCCONBinary = decodeCCONBinary;
      legacyCC.internal.CCON = CCON;

      function compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue) {
        if (defaultValue instanceof legacyCC.ValueType) {
          if (!assumeHavePropIfIsValue) {
            sources.push('if(prop){');
          }
          var ctorCode = getClassName(defaultValue);
          sources.push("s._deserializeFastDefinedObject(o" + accessorToSet + ",prop," + ctorCode + ");");
          if (!assumeHavePropIfIsValue) {
            sources.push("}else o" + accessorToSet + "=null;");
          }
        } else {
          sources.push("\nif (prop) {\n    s._deserializeAndAssignField(o, prop, " + propNameLiteralToSet + ");\n} else {\n    o" + accessorToSet + "=null;\n}\n");
        }
      }
      var compileDeserialize = compileDeserializeJIT ;
      var DELIMITER = CCClass.Attr.DELIMETER;
      var POSTFIX_TYPE = DELIMITER + "type";
      var POSTFIX_DEFAULT = DELIMITER + "default";
      var POSTFIX_FORMERLY_SERIALIZED_AS = DELIMITER + "formerlySerializedAs";
      function compileDeserializeJIT(self, klass) {
        var attrs = CCClass.Attr.getClassAttrs(klass);
        var props = klass.__values__;
        var sources = ['var prop;'];
        var fastMode = canBeDeserializedInFastMode(klass);
        for (var p = 0; p < props.length; p++) {
          var propName = props[p];
          var accessorToSet = void 0;
          var propNameLiteralToSet = void 0;
          if (CCClass.IDENTIFIER_RE.test(propName)) {
            propNameLiteralToSet = "\"" + propName + "\"";
            accessorToSet = "." + propName;
          } else {
            propNameLiteralToSet = CCClass.escapeForJS(propName);
            accessorToSet = "[" + propNameLiteralToSet + "]";
          }
          var accessorToGet = accessorToSet;
          if (attrs[propName + POSTFIX_FORMERLY_SERIALIZED_AS]) {
            var propNameToRead = attrs[propName + POSTFIX_FORMERLY_SERIALIZED_AS];
            if (CCClass.IDENTIFIER_RE.test(propNameToRead)) {
              accessorToGet = "." + propNameToRead;
            } else {
              accessorToGet = "[" + CCClass.escapeForJS(propNameToRead) + "]";
            }
          }
          sources.push("prop=d" + accessorToGet + ";");
          sources.push("if(typeof " + ('prop') + "!==\"undefined\"){");
          var defaultValue = CCClass.getDefault(attrs[propName + POSTFIX_DEFAULT]);
          var userType = attrs[propName + POSTFIX_TYPE];
          if (fastMode && (defaultValue !== undefined || userType)) {
            var isPrimitiveTypeInFastMode = isPrimitivePropertyByDefaultOrType(defaultValue, userType);
            if (isPrimitiveTypeInFastMode) {
              sources.push("o" + accessorToSet + "=prop;");
            } else {
              compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, true);
            }
          } else {
            sources.push("" + ("if(typeof " + ('prop') + "!==\"object\"){" + 'o') + accessorToSet + "=prop;" + "}else{");
            compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, false);
            sources.push('}');
          }
          sources.push('}');
        }
        if (isChildClassOf(klass, legacyCC.Node) || isChildClassOf(klass, legacyCC.Component)) {
          {
            sources.push('d._id&&(o._id=d._id);');
          }
        }
        if (props[props.length - 1] === '_$erialized') {
          sources.push('o._$erialized=JSON.parse(JSON.stringify(d));');
          sources.push('s._fillPlainObject(o._$erialized,d);');
        }
        return Function('s', 'o', 'd', 'k', sources.join(''));
      }
      function canBeDeserializedInFastMode(klass) {
        return BUILTIN_CLASSID_RE.test(getClassId(klass));
      }
      function isPrimitivePropertyByDefaultOrType(defaultValue, userType) {
        if (defaultValue === undefined) {
          return userType instanceof CCClass.Attr.PrimitiveType || userType === ENUM_TAG || userType === BITMASK_TAG;
        } else {
          var defaultType = typeof defaultValue;
          return defaultType === 'string' || defaultType === 'number' || defaultType === 'boolean';
        }
      }
      var DeserializerPool = function (_js$Pool) {
        _inheritsLoose(DeserializerPool, _js$Pool);
        function DeserializerPool() {
          return _js$Pool.call(this, function (deserializer) {
            deserializer.clear();
          }, 1) || this;
        }
        return DeserializerPool;
      }(Pool$1);
      DeserializerPool.prototype.get = function (details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly) {
        var cache = this._get();
        if (cache) {
          cache.reset(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
          return cache;
        } else {
          return new _Deserializer(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
        }
      };
      var _Deserializer = function () {
        function _Deserializer(result, classFinder, reportMissingClass, customEnv, ignoreEditorOnly) {
          this.deserializedList = void 0;
          this.deserializedData = void 0;
          this._ignoreEditorOnly = void 0;
          this.result = result;
          this.customEnv = customEnv;
          this.deserializedList = [];
          this.deserializedData = null;
          this._classFinder = classFinder;
          this._reportMissingClass = reportMissingClass;
          this._onDereferenced = classFinder === null || classFinder === void 0 ? void 0 : classFinder.onDereferenced;
        }
        var _proto = _Deserializer.prototype;
        _proto.reset = function reset(result, classFinder, reportMissingClass, customEnv, ignoreEditorOnly) {
          this.result = result;
          this.customEnv = customEnv;
          this._classFinder = classFinder;
          this._reportMissingClass = reportMissingClass;
          this._onDereferenced = classFinder === null || classFinder === void 0 ? void 0 : classFinder.onDereferenced;
        };
        _proto.clear = function clear() {
          this.result = null;
          this.customEnv = null;
          this.deserializedList.length = 0;
          this.deserializedData = null;
          this._classFinder = null;
          this._reportMissingClass = null;
          this._onDereferenced = null;
        };
        _proto.deserialize = function deserialize(serializedData) {
          var fromCCON = false;
          var jsonObj;
          if (serializedData instanceof CCON) {
            fromCCON = true;
            jsonObj = serializedData.document;
            if (serializedData.chunks.length > 0) {
              assertIsTrue(serializedData.chunks.length === 1);
              this._mainBinChunk = serializedData.chunks[0];
            }
          } else {
            jsonObj = serializedData;
          }
          this._serializedData = jsonObj;
          this._context = {
            fromCCON: fromCCON
          };
          var serializedRootObject = Array.isArray(jsonObj) ? jsonObj[0] : jsonObj;
          {
            this.deserializedData = this._deserializeObject(serializedRootObject, 0);
          }
          this._serializedData = undefined;
          this._mainBinChunk = undefined;
          this._context = undefined;
          return this.deserializedData;
        };
        _proto._deserializeObject = function _deserializeObject(serialized, globalIndex, owner, propName) {
          switch (serialized.__type__) {
            case 'TypedArray':
              return this._deserializeTypedArrayView(serialized);
            case 'TypedArrayRef':
              return this._deserializeTypedArrayViewRef(serialized);
            default:
              if (serialized.__type__) {
                return this._deserializeTypeTaggedObject(serialized, globalIndex, owner, propName);
              } else if (!Array.isArray(serialized)) {
                return this._deserializePlainObject(serialized);
              } else {
                return this._deserializeArray(serialized);
              }
          }
        };
        _proto._deserializeTypedArrayView = function _deserializeTypedArrayView(value) {
          return globalThis[value.ctor].from(value.array);
        };
        _proto._deserializeTypedArrayViewRef = function _deserializeTypedArrayViewRef(value) {
          var offset = value.offset,
            length = value.length,
            constructorName = value.ctor;
          var obj = new globalThis[constructorName](this._mainBinChunk.buffer, this._mainBinChunk.byteOffset + offset, length);
          return obj;
        };
        _proto._deserializeArray = function _deserializeArray(value) {
          var obj = new Array(value.length);
          var prop;
          for (var i = 0; i < value.length; i++) {
            prop = value[i];
            if (typeof prop === 'object' && prop) {
              var isAssetType = this._deserializeAndAssignField(obj, prop, "" + i);
              if (isAssetType) {
                obj[i] = null;
              }
            } else {
              obj[i] = prop;
            }
          }
          return obj;
        };
        _proto._deserializePlainObject = function _deserializePlainObject(value) {
          var obj = {};
          this._fillPlainObject(obj, value);
          return obj;
        };
        _proto._deserializeTypeTaggedObject = function _deserializeTypeTaggedObject(value, globalIndex, owner, propName) {
          var _this = this;
          var type = value.__type__;
          var klass = this._classFinder(type, value, owner, propName);
          if (!klass) {
            var notReported = this._classFinder === getClassById;
            if (notReported) {
              this._reportMissingClass(type);
            }
            return null;
          }
          var createObject = function createObject(constructor) {
            var obj = new constructor();
            if (globalIndex >= 0) {
              _this.deserializedList[globalIndex] = obj;
            }
            return obj;
          };
          {
            var obj = createObject(klass);
            this._deserializeInto(value, obj, klass);
            return obj;
          }
        };
        _proto._deserializeInto = function _deserializeInto(value, object, constructor, skipCustomized) {
          if (skipCustomized === void 0) {
            skipCustomized = false;
          }
          if (!skipCustomized && object[deserializeTag]) {
            this._runCustomizedDeserialize(value, object, constructor);
            return;
          }
          if (object._deserialize) {
            object._deserialize(value.content, this);
            return;
          }
          if (legacyCC.Class._isCCClass(constructor)) {
            this._deserializeFireClass(object, value, constructor);
          } else {
            this._deserializeFastDefinedObject(object, value, constructor);
          }
        };
        _proto._runCustomizedDeserialize = function _runCustomizedDeserialize(value, object, constructor) {
          var _this2 = this;
          var serializationInput = {
            readProperty: function readProperty(name) {
              var serializedField = value[name];
              if (typeof serializedField !== 'object' || !serializedField) {
                return serializedField;
              } else {
                return _this2._deserializeObjectField(serializedField);
              }
            },
            readThis: function readThis() {
              _this2._deserializeInto(value, object, constructor, true);
            },
            readSuper: function readSuper() {
              var superConstructor = getSuper(constructor);
              if (superConstructor) {
                _this2._deserializeInto(value, object, superConstructor);
              }
            }
          };
          object[deserializeTag](serializationInput, this._context);
        };
        _proto._deserializeFireClass = function _deserializeFireClass(obj, serialized, klass) {
          var deserialize;
          if (klass.hasOwnProperty('__deserialize__')) {
            deserialize = klass.__deserialize__;
          } else {
            deserialize = compileDeserialize(this, klass);
            try {
              if (klass === MissingScript) {
                var props = klass.__values__;
                if (props.length === 0 || props[props.length - 1] !== '_$erialized') {
                  error("The '_$erialized' prop of MissingScript is missing. Will force the raw data to be save.");
                  error("    Error props: ['" + props + "']. Please contact jare.");
                }
                var rawDeserialize = deserialize;
                deserialize = function deserialize(deserializer, object, deserialized, constructor) {
                  rawDeserialize(deserializer, object, deserialized, constructor);
                  if (!object._$erialized) {
                    error("Unable to stash previously serialized data. " + JSON.stringify(deserialized));
                  }
                };
              }
            } catch (e) {
              error("Error when checking MissingScript 6, " + e);
            }
            value(klass, '__deserialize__', deserialize, true);
          }
          deserialize(this, obj, serialized, klass);
        };
        _proto._deserializeAndAssignField = function _deserializeAndAssignField(obj, serializedField, propName) {
          var id = serializedField.__id__;
          if (typeof id === 'number') {
            var field = this.deserializedList[id];
            if (field) {
              obj[propName] = field;
            } else {
              var _this$_onDereferenced;
              var source = this._serializedData[id];
              {
                obj[propName] = this._deserializeObject(source, id, undefined, propName);
              }
              (_this$_onDereferenced = this._onDereferenced) === null || _this$_onDereferenced === void 0 ? void 0 : _this$_onDereferenced.call(this, this.deserializedList, id, obj, propName);
            }
          } else {
            var uuid = serializedField.__uuid__;
            if (uuid) {
              var expectedType = serializedField.__expectedType__;
              this.result.push(obj, propName, uuid, expectedType);
            } else {
              obj[propName] = this._deserializeObject(serializedField, -1);
            }
          }
          return false;
        };
        _proto._deserializeObjectField = function _deserializeObjectField(serializedField) {
          var id = serializedField.__id__;
          if (typeof id === 'number') {
            var field = this.deserializedList[id];
            if (field) {
              return field;
            } else {
              var source = this._serializedData[id];
              var _field = this._deserializeObject(source, id, undefined, undefined);
              return _field;
            }
          } else {
            var uuid = serializedField.__uuid__;
            if (uuid) {
              serializedField.__expectedType__;
              throw new Error("Asset reference field serialization is currently not supported in custom serialization.");
            } else {
              return this._deserializeObject(serializedField, -1);
            }
          }
        };
        _proto._fillPlainObject = function _fillPlainObject(instance, serialized) {
          for (var propName in serialized) {
            if (!serialized.hasOwnProperty(propName)) {
              continue;
            }
            var prop = serialized[propName];
            if (typeof prop !== 'object') {
              if (propName !== '__type__') {
                instance[propName] = prop;
              }
            } else if (prop) {
              var isAssetType = this._deserializeAndAssignField(instance, prop, propName);
              if (isAssetType) {
                instance[propName] = null;
              }
            } else {
              instance[propName] = null;
            }
          }
        };
        _proto._deserializeFastDefinedObject = function _deserializeFastDefinedObject(instance, serialized, klass) {
          if (klass === legacyCC.Vec2) {
            instance.x = serialized.x || 0;
            instance.y = serialized.y || 0;
            return;
          } else if (klass === legacyCC.Vec3) {
            instance.x = serialized.x || 0;
            instance.y = serialized.y || 0;
            instance.z = serialized.z || 0;
            return;
          } else if (klass === legacyCC.Color) {
            instance.r = serialized.r || 0;
            instance.g = serialized.g || 0;
            instance.b = serialized.b || 0;
            var a = serialized.a;
            instance.a = a === undefined ? 255 : a;
            return;
          } else if (klass === legacyCC.Size) {
            instance.width = serialized.width || 0;
            instance.height = serialized.height || 0;
            return;
          }
          var attrs = CCClass.Attr.getClassAttrs(klass);
          var props = klass.__values__;
          if (!props) {
            error("Unable to deserialize " + getClassName(klass) + ". " + 'For non-CCClass types, they can only be marked as serializable by `CCClass.fastDefine`.');
          }
          for (var i = 0; i < props.length; i++) {
            var propName = props[i];
            var value = serialized[propName];
            var exists = value !== undefined || serialized.hasOwnProperty(propName);
            if (!exists) {
              value = CCClass.getDefault(attrs[propName + POSTFIX_DEFAULT]);
            }
            if (typeof value !== 'object') {
              instance[propName] = value;
            } else if (value) {
              this._deserializeAndAssignField(instance, value, propName);
            } else {
              instance[propName] = null;
            }
          }
        };
        _createClass(_Deserializer, [{
          key: "ignoreEditorOnly",
          get: function get() {
            return this._ignoreEditorOnly;
          }
        }]);
        return _Deserializer;
      }();
      _Deserializer.pool = new DeserializerPool();
      function deserializeDynamic(data, details, options) {
        var _options$reportMissin;
        options = options || {};
        var classFinder = options.classFinder || getClassById;
        var createAssetRefs = options.createAssetRefs || sys.platform === Platform.EDITOR_CORE;
        var customEnv = options.customEnv;
        var ignoreEditorOnly = options.ignoreEditorOnly;
        var reportMissingClass = (_options$reportMissin = options.reportMissingClass) !== null && _options$reportMissin !== void 0 ? _options$reportMissin : legacyCC.deserialize.reportMissingClass;
        details.init();
        var deserializer = _Deserializer.pool.get(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
        legacyCC.game._isCloning = true;
        var res = deserializer.deserialize(data);
        legacyCC.game._isCloning = false;
        _Deserializer.pool.put(deserializer);
        if (createAssetRefs) {
          details.assignAssetsBy(function (uuid, options) {
            return EditorExtends.serialize.asAsset(uuid, options.type);
          });
        }
        return res;
      }

      function reportMissingClass(id) {
        {
          errorID(5302, id);
        }
      }

      var constructorMap = [Vec2, Vec3, Vec4, Quat, Color$1, Size$1, Rect$1, Mat4];
      function vec4LikeSetter(obj, data) {
        obj.x = data[1];
        obj.y = data[2];
        obj.z = data[3];
        obj.w = data[4];
      }
      var setterMap = [function (obj, data) {
        obj.x = data[1];
        obj.y = data[2];
      }, function (obj, data) {
        obj.x = data[1];
        obj.y = data[2];
        obj.z = data[3];
      }, vec4LikeSetter, vec4LikeSetter, function (obj, data) {
        obj._val = data[1];
      }, function (obj, data) {
        obj.width = data[1];
        obj.height = data[2];
      }, function (obj, data) {
        obj.x = data[1];
        obj.y = data[2];
        obj.width = data[3];
        obj.height = data[4];
      }, function (obj, data) {
        Mat4.fromArray(obj, data, 1);
      }];
      function deserializeBuiltinValueType(data, owner, key, value) {
        var typeIndex = value[0];
        assertIsTrue(typeIndex >= 0 && typeIndex < constructorMap.length);
        var object = new constructorMap[typeIndex]();
        var setter = setterMap[typeIndex];
        setter(object, value);
        owner[key] = object;
      }
      function deserializeBuiltinValueTypeInto(data, owner, key, value) {
        var typeIndex = value[0];
        assertIsTrue(typeIndex >= 0 && typeIndex < constructorMap.length);
        {
          var object = owner[key];
          var _setter = setterMap[typeIndex];
          _setter(object, value);
        }
      }

      var SUPPORT_MIN_FORMAT_VERSION = 1;
      var EMPTY_PLACEHOLDER = 0;
      var DataTypeID = {
        SimpleType: 0,
        InstanceRef: 1,
        Array_InstanceRef: 2,
        Array_AssetRefByInnerObj: 3,
        Class: 4,
        ValueTypeCreated: 5,
        AssetRefByInnerObj: 6,
        TRS: 7,
        ValueType: 8,
        Array_Class: 9,
        CustomizedClass: 10,
        Dict: 11,
        Array: 12,
        ARRAY_LENGTH: 13
      };
      var CLASS_TYPE = 0;
      var CLASS_KEYS = 1;
      var CLASS_PROP_TYPE_OFFSET = 2;
      var MASK_CLASS = 0;
      var OBJ_DATA_MASK = 0;
      var CUSTOM_OBJ_DATA_CLASS = 0;
      var CUSTOM_OBJ_DATA_CONTENT = 1;
      var DICT_JSON_LAYOUT = 0;
      var ARRAY_ITEM_VALUES = 0;
      var Refs = {
        EACH_RECORD_LENGTH: 3,
        OWNER_OFFSET: 0,
        KEY_OFFSET: 1,
        TARGET_OFFSET: 2
      };
      var File = {
        Version: 0,
        Context: 0,
        SharedUuids: 1,
        SharedStrings: 2,
        SharedClasses: 3,
        SharedMasks: 4,
        Instances: 5,
        InstanceTypes: 6,
        Refs: 7,
        DependObjs: 8,
        DependKeys: 9,
        DependUuidIndices: 10,
        ARRAY_LENGTH: 11
      };
      var PACKED_SECTIONS = File.Instances;
      var Details = exports('e9', function () {
        function Details() {
          this.uuidObjList = null;
          this.uuidPropList = null;
          this.uuidList = null;
          this.uuidTypeList = [];
        }
        var _proto = Details.prototype;
        _proto.init = function init(data) {
          if (data) {
            this.uuidObjList = data[File.DependObjs];
            this.uuidPropList = data[File.DependKeys];
            this.uuidList = data[File.DependUuidIndices];
          } else {
            var used = this.uuidList;
            if (!used) {
              this.uuidList = [];
              this.uuidObjList = [];
              this.uuidPropList = [];
              this.uuidTypeList = [];
            }
          }
        };
        _proto.reset = function reset() {
          {
            var used = this.uuidList;
            if (used) {
              this.uuidList.length = 0;
              this.uuidObjList.length = 0;
              this.uuidPropList.length = 0;
              this.uuidTypeList.length = 0;
            }
          }
        };
        _proto.push = function push(obj, propName, uuid, type) {
          this.uuidObjList.push(obj);
          this.uuidPropList.push(propName);
          this.uuidList.push(uuid);
          this.uuidTypeList.push(type || '');
        };
        return Details;
      }());
      Details.pool = new Pool$1(function (obj) {
        obj.reset();
      }, 5);
      Details.pool.get = function () {
        return this._get() || new Details();
      };
      function dereference(refs, instances, strings) {
        var dataLength = refs.length - 1;
        var i = 0;
        var instanceOffset = refs[dataLength] * Refs.EACH_RECORD_LENGTH;
        for (; i < instanceOffset; i += Refs.EACH_RECORD_LENGTH) {
          var _owner = refs[i];
          var target = instances[refs[i + Refs.TARGET_OFFSET]];
          var keyIndex = refs[i + Refs.KEY_OFFSET];
          if (keyIndex >= 0) {
            _owner[strings[keyIndex]] = target;
          } else {
            _owner[~keyIndex] = target;
          }
        }
        for (; i < dataLength; i += Refs.EACH_RECORD_LENGTH) {
          var _owner2 = instances[refs[i]];
          var _target = instances[refs[i + Refs.TARGET_OFFSET]];
          var _keyIndex = refs[i + Refs.KEY_OFFSET];
          if (_keyIndex >= 0) {
            _owner2[strings[_keyIndex]] = _target;
          } else {
            _owner2[~_keyIndex] = _target;
          }
        }
      }
      function deserializeCCObject(data, objectData) {
        var mask = data[File.SharedMasks][objectData[OBJ_DATA_MASK]];
        var clazz = mask[MASK_CLASS];
        var ctor = clazz[CLASS_TYPE];
        var obj = new ctor();
        var keys = clazz[CLASS_KEYS];
        var classTypeOffset = clazz[CLASS_PROP_TYPE_OFFSET];
        var maskTypeOffset = mask[mask.length - 1];
        var i = MASK_CLASS + 1;
        for (; i < maskTypeOffset; ++i) {
          var _key = keys[mask[i]];
          obj[_key] = objectData[i];
        }
        for (; i < objectData.length; ++i) {
          var _key2 = keys[mask[i]];
          var type = clazz[mask[i] + classTypeOffset];
          var op = ASSIGNMENTS[type];
          op(data, obj, _key2, objectData[i]);
        }
        return obj;
      }
      function deserializeCustomCCObject(data, ctor, value) {
        var obj = new ctor();
        if (obj._deserialize) {
          obj._deserialize(value, data[File.Context]);
        } else {
          errorID(5303, getClassName(ctor));
        }
        return obj;
      }
      function assignSimple(data, owner, key, value) {
        owner[key] = value;
      }
      function assignInstanceRef(data, owner, key, value) {
        if (value >= 0) {
          owner[key] = data[File.Instances][value];
        } else {
          data[File.Refs][~value * Refs.EACH_RECORD_LENGTH] = owner;
        }
      }
      function genArrayParser(parser) {
        return function (data, owner, key, value) {
          for (var i = 0; i < value.length; ++i) {
            parser(data, value, i, value[i]);
          }
          owner[key] = value;
        };
      }
      function parseAssetRefByInnerObj(data, owner, key, value) {
        owner[key] = null;
        data[File.DependObjs][value] = owner;
      }
      function parseClass(data, owner, key, value) {
        owner[key] = deserializeCCObject(data, value);
      }
      function parseCustomClass(data, owner, key, value) {
        var ctor = data[File.SharedClasses][value[CUSTOM_OBJ_DATA_CLASS]];
        owner[key] = deserializeCustomCCObject(data, ctor, value[CUSTOM_OBJ_DATA_CONTENT]);
      }
      function parseTRS(data, owner, key, value) {
        var typedArray = owner[key];
        typedArray.set(value);
      }
      function parseDict(data, owner, key, value) {
        var dict = value[DICT_JSON_LAYOUT];
        owner[key] = dict;
        for (var i = DICT_JSON_LAYOUT + 1; i < value.length; i += 3) {
          var subKey = value[i];
          var subType = value[i + 1];
          var subValue = value[i + 2];
          var op = ASSIGNMENTS[subType];
          op(data, dict, subKey, subValue);
        }
      }
      function parseArray(data, owner, key, value) {
        var array = value[ARRAY_ITEM_VALUES];
        for (var i = 0; i < array.length; ++i) {
          var subValue = array[i];
          var type = value[i + 1];
          if (type !== DataTypeID.SimpleType) {
            var op = ASSIGNMENTS[type];
            op(data, array, i, subValue);
          }
        }
        owner[key] = array;
      }
      var ASSIGNMENTS = new Array(DataTypeID.ARRAY_LENGTH);
      ASSIGNMENTS[DataTypeID.SimpleType] = assignSimple;
      ASSIGNMENTS[DataTypeID.InstanceRef] = assignInstanceRef;
      ASSIGNMENTS[DataTypeID.Array_InstanceRef] = genArrayParser(assignInstanceRef);
      ASSIGNMENTS[DataTypeID.Array_AssetRefByInnerObj] = genArrayParser(parseAssetRefByInnerObj);
      ASSIGNMENTS[DataTypeID.Class] = parseClass;
      ASSIGNMENTS[DataTypeID.ValueTypeCreated] = deserializeBuiltinValueTypeInto;
      ASSIGNMENTS[DataTypeID.AssetRefByInnerObj] = parseAssetRefByInnerObj;
      ASSIGNMENTS[DataTypeID.TRS] = parseTRS;
      ASSIGNMENTS[DataTypeID.ValueType] = deserializeBuiltinValueType;
      ASSIGNMENTS[DataTypeID.Array_Class] = genArrayParser(parseClass);
      ASSIGNMENTS[DataTypeID.CustomizedClass] = parseCustomClass;
      ASSIGNMENTS[DataTypeID.Dict] = parseDict;
      ASSIGNMENTS[DataTypeID.Array] = parseArray;
      function parseInstances(data) {
        var instances = data[File.Instances];
        var instanceTypes = data[File.InstanceTypes];
        var instanceTypesLen = instanceTypes === EMPTY_PLACEHOLDER ? 0 : instanceTypes.length;
        var rootIndex = instances[instances.length - 1];
        var normalObjectCount = instances.length - instanceTypesLen;
        if (typeof rootIndex !== 'number') {
          rootIndex = 0;
        } else {
          if (rootIndex < 0) {
            rootIndex = ~rootIndex;
          }
          --normalObjectCount;
        }
        var insIndex = 0;
        for (; insIndex < normalObjectCount; ++insIndex) {
          instances[insIndex] = deserializeCCObject(data, instances[insIndex]);
        }
        var classes = data[File.SharedClasses];
        for (var typeIndex = 0; typeIndex < instanceTypesLen; ++typeIndex, ++insIndex) {
          var type = instanceTypes[typeIndex];
          var eachData = instances[insIndex];
          if (type >= 0) {
            var ctor = classes[type];
            instances[insIndex] = deserializeCustomCCObject(data, ctor, eachData);
          } else {
            type = ~type;
            var op = ASSIGNMENTS[type];
            op(data, instances, insIndex, eachData);
          }
        }
        return rootIndex;
      }
      function getMissingClass(hasCustomFinder, type, reportMissingClass) {
        if (!hasCustomFinder) {
          reportMissingClass(type);
        }
        return Object;
      }
      function doLookupClass(classFinder, type, container, index, silent, hasCustomFinder, reportMissingClass) {
        var klass = classFinder(type);
        if (!klass) {
          if (silent) {
            container[index] = function (c, i, t) {
              return function proxy() {
                var actualClass = classFinder(t) || getMissingClass(hasCustomFinder, t, reportMissingClass);
                c[i] = actualClass;
                return new actualClass();
              };
            }(container, index, type);
            return;
          } else {
            klass = getMissingClass(hasCustomFinder, type, reportMissingClass);
          }
        }
        container[index] = klass;
      }
      function lookupClasses(data, silent, customFinder, reportMissingClass) {
        var classFinder = customFinder || getClassById;
        var classes = data[File.SharedClasses];
        for (var i = 0; i < classes.length; ++i) {
          var klassLayout = classes[i];
          if (typeof klassLayout !== 'string') {
            {
              if (typeof klassLayout[CLASS_TYPE] === 'function') {
                throw new Error('Can not deserialize the same JSON data again.');
              }
            }
            var type = klassLayout[CLASS_TYPE];
            doLookupClass(classFinder, type, klassLayout, CLASS_TYPE, silent, customFinder, reportMissingClass);
          } else {
            doLookupClass(classFinder, klassLayout, classes, i, silent, customFinder, reportMissingClass);
          }
        }
      }
      function cacheMasks(data) {
        var masks = data[File.SharedMasks];
        if (masks) {
          var classes = data[File.SharedClasses];
          for (var i = 0; i < masks.length; ++i) {
            var mask = masks[i];
            mask[MASK_CLASS] = classes[mask[MASK_CLASS]];
          }
        }
      }
      function parseResult(data) {
        var instances = data[File.Instances];
        var sharedStrings = data[File.SharedStrings];
        var dependSharedUuids = data[File.SharedUuids];
        var dependObjs = data[File.DependObjs];
        var dependKeys = data[File.DependKeys];
        var dependUuids = data[File.DependUuidIndices];
        for (var i = 0; i < dependObjs.length; ++i) {
          var obj = dependObjs[i];
          if (typeof obj === 'number') {
            dependObjs[i] = instances[obj];
          }
          var _key3 = dependKeys[i];
          if (typeof _key3 === 'number') {
            if (_key3 >= 0) {
              _key3 = sharedStrings[_key3];
            } else {
              _key3 = ~_key3;
            }
            dependKeys[i] = _key3;
          }
          var _uuid2 = dependUuids[i];
          if (typeof _uuid2 === 'number') {
            dependUuids[i] = dependSharedUuids[_uuid2];
          }
        }
      }
      function isCompiledJson(json) {
        if (Array.isArray(json)) {
          var _version = json[0];
          return typeof _version === 'number' || _version instanceof FileInfo;
        } else {
          return false;
        }
      }
      function initializeDeserializationContext(data, details, options) {
        var _options;
        details.init(data);
        (_options = options) !== null && _options !== void 0 ? _options : options = {};
        var version = data[File.Version];
        var preprocessed = false;
        if (typeof version === 'object') {
          preprocessed = version.preprocessed;
          version = version.version;
        }
        if (version < SUPPORT_MIN_FORMAT_VERSION) {
          throw new Error(getError(5304, version));
        }
        var context = options;
        context._version = version;
        context.result = details;
        data[File.Context] = context;
        if (!preprocessed) {
          var _options$reportMissin;
          lookupClasses(data, false, options.classFinder, (_options$reportMissin = options.reportMissingClass) !== null && _options$reportMissin !== void 0 ? _options$reportMissin : deserialize.reportMissingClass);
          cacheMasks(data);
        }
      }
      function deserialize(data, details, options) {
        if (typeof data === 'string') {
          data = JSON.parse(data);
        }
        var isBorrowedDetails = false;
        if (!details) {
          var borrowedDetails = Details.pool.get();
          assertIsTrue(borrowedDetails, "Can not allocate deserialization details");
          details = borrowedDetails;
          isBorrowedDetails = true;
        }
        var res;
        if (!isCompiledJson(data)) {
          res = deserializeDynamic(data, details, options);
        } else {
          initializeDeserializationContext(data, details, options);
          var runtimeData = data;
          legacyCC.game._isCloning = true;
          var instances = runtimeData[File.Instances];
          var rootIndex = parseInstances(runtimeData);
          legacyCC.game._isCloning = false;
          if (runtimeData[File.Refs]) {
            dereference(runtimeData[File.Refs], instances, runtimeData[File.SharedStrings]);
          }
          parseResult(runtimeData);
          res = instances[rootIndex];
        }
        if (isBorrowedDetails) {
          Details.pool.put(details);
        }
        return res;
      }
      deserialize.Details = Details;
      deserialize.reportMissingClass = reportMissingClass;
      var FileInfo = function FileInfo(version) {
        this.preprocessed = true;
        this.version = version;
      };
      function unpackJSONs(data, classFinder, reportMissingClass) {
        if (data[File.Version] < SUPPORT_MIN_FORMAT_VERSION) {
          throw new Error(getError(5304, data[File.Version]));
        }
        lookupClasses(data, true, classFinder, reportMissingClass !== null && reportMissingClass !== void 0 ? reportMissingClass : deserialize.reportMissingClass);
        cacheMasks(data);
        var version = new FileInfo(data[File.Version]);
        var sharedUuids = data[File.SharedUuids];
        var sharedStrings = data[File.SharedStrings];
        var sharedClasses = data[File.SharedClasses];
        var sharedMasks = data[File.SharedMasks];
        var sections = data[PACKED_SECTIONS];
        for (var i = 0; i < sections.length; ++i) {
          var section = sections[i];
          section.unshift(version, sharedUuids, sharedStrings, sharedClasses, sharedMasks);
        }
        return sections;
      }
      function packCustomObjData(type, data, hasNativeDep) {
        return [SUPPORT_MIN_FORMAT_VERSION, EMPTY_PLACEHOLDER, EMPTY_PLACEHOLDER, [type], EMPTY_PLACEHOLDER, hasNativeDep ? [data, ~0] : [data], [0], EMPTY_PLACEHOLDER, [], [], []];
      }
      function hasNativeDep(data) {
        var instances = data[File.Instances];
        var rootInfo = instances[instances.length - 1];
        if (typeof rootInfo !== 'number') {
          return false;
        } else {
          return rootInfo < 0;
        }
      }
      function getDependUuidList(json) {
        var sharedUuids = json[File.SharedUuids];
        return json[File.DependUuidIndices].map(function (index) {
          return sharedUuids[index];
        });
      }
      function parseUuidDependencies(serialized) {
        {
          return getDependUuidList(serialized);
        }
      }
      legacyCC.deserialize = deserialize;

      var dependMap = new WeakMap();
      var nativeDependMap = new WeakSet();
      var onLoadedInvokedMap = new WeakSet();

      function deserializeAsset(json, options) {
        var classFinder;
        {
          classFinder = MissingScript.safeFindClass;
        }
        var tdInfo = Details.pool.get();
        var asset;
        try {
          asset = deserialize(json, tdInfo, {
            classFinder: classFinder,
            customEnv: options
          });
        } catch (e) {
          error(e);
          Details.pool.put(tdInfo);
          throw e;
        }
        asset._uuid = options.__uuid__ || '';
        var uuidList = tdInfo.uuidList;
        var objList = tdInfo.uuidObjList;
        var propList = tdInfo.uuidPropList;
        var typeList = tdInfo.uuidTypeList || [];
        var depends = [];
        for (var i = 0; i < uuidList.length; i++) {
          var dependUuid = uuidList[i];
          depends[i] = {
            uuid: decodeUuid(dependUuid),
            owner: objList[i],
            prop: propList[i],
            type: getClassById(typeList[i])
          };
        }
        dependMap.set(asset, depends);
        if (asset._native) {
          nativeDependMap.add(asset);
        }
        Details.pool.put(tdInfo);
        return asset;
      }

      var DependUtil = function () {
        function DependUtil() {
          this._depends = new Cache();
        }
        var _proto = DependUtil.prototype;
        _proto.init = function init() {
          this._depends.clear();
        };
        _proto.getNativeDep = function getNativeDep(uuid) {
          var depend = this._depends.get(uuid);
          if (depend && depend.nativeDep) {
            return _extends({}, depend.nativeDep);
          }
          return null;
        };
        _proto.getDeps = function getDeps(uuid) {
          if (this._depends.has(uuid)) {
            return this._depends.get(uuid).deps;
          }
          return [];
        };
        _proto.getDepsRecursively = function getDepsRecursively(uuid) {
          var exclude = Object.create(null);
          var depends = [];
          this._descend(uuid, exclude, depends);
          return depends;
        };
        _proto.remove = function remove(uuid) {
          this._depends.remove(uuid);
        };
        _proto.parse = function parse(uuid, json) {
          var out = null;
          if (Array.isArray(json) || json.__type__ || json instanceof CCON) {
            if (this._depends.has(uuid)) {
              return this._depends.get(uuid);
            }
            if (Array.isArray(json) && (!hasNativeDep(json))) {
              out = {
                deps: this._parseDepsFromJson(json)
              };
            } else {
              try {
                var asset = deserializeAsset(json, {
                  __uuid__: uuid
                });
                out = this._parseDepsFromAsset(asset);
                if (out.nativeDep) {
                  out.nativeDep.uuid = uuid;
                }
                parsed.add(uuid + "@import", asset);
              } catch (e) {
                files.remove(uuid + "@import");
                out = {
                  deps: []
                };
              }
            }
          } else {
            if (this._depends.has(uuid)) {
              out = this._depends.get(uuid);
              if (out.parsedFromExistAsset) {
                return out;
              }
            }
            out = this._parseDepsFromAsset(json);
          }
          this._depends.add(uuid, out);
          return out;
        };
        _proto._parseDepsFromAsset = function _parseDepsFromAsset(asset) {
          var out = {
            deps: [],
            parsedFromExistAsset: true
          };
          var deps = dependMap.get(asset);
          assertIsNonNullable(deps);
          for (var i = 0, l = deps.length; i < l; i++) {
            out.deps.push(deps[i].uuid);
          }
          if (nativeDependMap.has(asset)) {
            out.nativeDep = asset._nativeDep;
          }
          return out;
        };
        _proto._parseDepsFromJson = function _parseDepsFromJson(json) {
          var depends = parseUuidDependencies(json);
          depends.forEach(function (uuid, index) {
            return depends[index] = decodeUuid(uuid);
          });
          return depends;
        };
        _proto._descend = function _descend(uuid, exclude, depends) {
          var deps = this.getDeps(uuid);
          for (var i = 0; i < deps.length; i++) {
            var depend = deps[i];
            if (!exclude[depend]) {
              exclude[depend] = true;
              depends.push(depend);
              this._descend(depend, exclude, depends);
            }
          }
        };
        _createClass(DependUtil, null, [{
          key: "instance",
          get: function get() {
            if (!this._instance) {
              this._instance = new DependUtil();
            }
            return this._instance;
          }
        }]);
        return DependUtil;
      }();
      DependUtil._instance = void 0;
      var dependUtil = DependUtil.instance;

      var _dec$3z, _class$3v;
      var _regions = [new BufferTextureCopy()];
      function getMipLevel(width, height) {
        var size = Math.max(width, height);
        var level = 0;
        while (size) {
          size >>= 1;
          level++;
        }
        return level;
      }
      function isPOT(n) {
        return n && (n & n - 1) === 0;
      }
      function canGenerateMipmap(device, w, h) {
        var needCheckPOT = device.gfxAPI === API.WEBGL;
        if (needCheckPOT) {
          return isPOT(w) && isPOT(h);
        }
        return true;
      }
      var SimpleTexture = (_dec$3z = ccclass$M('cc.SimpleTexture'), _dec$3z(_class$3v = function (_TextureBase) {
        _inheritsLoose(SimpleTexture, _TextureBase);
        function SimpleTexture() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _TextureBase.call.apply(_TextureBase, [this].concat(args)) || this;
          _this._gfxTexture = null;
          _this._gfxTextureView = null;
          _this._mipmapLevel = 1;
          _this._textureWidth = 0;
          _this._textureHeight = 0;
          _this._baseLevel = 0;
          _this._maxLevel = 1000;
          return _this;
        }
        var _proto = SimpleTexture.prototype;
        _proto.getGFXTexture = function getGFXTexture() {
          return this._gfxTextureView;
        };
        _proto.destroy = function destroy() {
          this._tryDestroyTextureView();
          this._tryDestroyTexture();
          return _TextureBase.prototype.destroy.call(this);
        };
        _proto.updateImage = function updateImage() {
          this.updateMipmaps(0);
        };
        _proto.updateMipmaps = function updateMipmaps(firstLevel, count) {
        };
        _proto.uploadData = function uploadData(source, level, arrayIndex) {
          if (level === void 0) {
            level = 0;
          }
          if (arrayIndex === void 0) {
            arrayIndex = 0;
          }
          if (!this._gfxTexture || this._mipmapLevel <= level) {
            return;
          }
          var gfxDevice = this._getGFXDevice();
          if (!gfxDevice) {
            return;
          }
          var region = _regions[0];
          region.texExtent.width = this._textureWidth >> level;
          region.texExtent.height = this._textureHeight >> level;
          region.texSubres.mipLevel = level;
          region.texSubres.baseArrayLayer = arrayIndex;
          if (ArrayBuffer.isView(source)) {
            gfxDevice.copyBuffersToTexture([source], this._gfxTexture, _regions);
          } else {
            gfxDevice.copyTexImagesToTexture([source], this._gfxTexture, _regions);
          }
        };
        _proto._assignImage = function _assignImage(image, level, arrayIndex) {
          var data = image.data;
          if (!data) {
            return;
          }
          this.uploadData(data, level, arrayIndex);
          this._checkTextureLoaded();
          if (macro.CLEANUP_IMAGE_CACHE) {
            var deps = dependUtil.getDeps(this._uuid);
            var index = deps.indexOf(image._uuid);
            if (index !== -1) {
              fastRemoveAt$2(deps, index);
              image.decRef();
            }
          }
        };
        _proto._checkTextureLoaded = function _checkTextureLoaded() {
          this._textureReady();
        };
        _proto._textureReady = function _textureReady() {
          this.loaded = true;
          this.emit('load');
        };
        _proto._setMipmapLevel = function _setMipmapLevel(value) {
          this._mipmapLevel = value < 1 ? 1 : value;
        };
        _proto._setMipRange = function _setMipRange(baseLevel, maxLevel) {
          this._baseLevel = baseLevel < 1 ? 0 : baseLevel;
          this._maxLevel = maxLevel < 1 ? 0 : maxLevel;
        };
        _proto.setMipRange = function setMipRange(baseLevel, maxLevel) {
          assertID(baseLevel <= maxLevel, 3124);
          this._setMipRange(baseLevel, maxLevel);
          var device = this._getGFXDevice();
          if (!device) {
            return;
          }
          var textureView = this._createTextureView(device);
          this._tryDestroyTextureView();
          this._gfxTextureView = textureView;
        };
        _proto._getGfxTextureCreateInfo = function _getGfxTextureCreateInfo(presumed) {
          return null;
        };
        _proto._getGfxTextureViewCreateInfo = function _getGfxTextureViewCreateInfo(presumed) {
          return null;
        };
        _proto._tryReset = function _tryReset() {
          this._tryDestroyTextureView();
          this._tryDestroyTexture();
          if (this._mipmapLevel === 0) {
            return;
          }
          var device = this._getGFXDevice();
          if (!device) {
            return;
          }
          this._createTexture(device);
          this._gfxTextureView = this._createTextureView(device);
        };
        _proto.isUsingOfflineMipmaps = function isUsingOfflineMipmaps() {
          return false;
        };
        _proto._createTexture = function _createTexture(device) {
          if (this._width === 0 || this._height === 0) {
            return;
          }
          var flags = TextureFlagBit.NONE;
          if (this._mipFilter !== Filter.NONE && canGenerateMipmap(device, this._width, this._height)) {
            this._mipmapLevel = getMipLevel(this._width, this._height);
            if (!this.isUsingOfflineMipmaps() && !this.isCompressed) {
              flags = TextureFlagBit.GEN_MIPMAP;
            }
          }
          var textureCreateInfo = this._getGfxTextureCreateInfo({
            usage: TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST | TextureUsageBit.COLOR_ATTACHMENT,
            format: this._getGFXFormat(),
            levelCount: this._mipmapLevel,
            flags: flags
          });
          if (!textureCreateInfo) {
            return;
          }
          var texture = device.createTexture(textureCreateInfo);
          this._textureWidth = textureCreateInfo.width;
          this._textureHeight = textureCreateInfo.height;
          this._gfxTexture = texture;
        };
        _proto._createTextureView = function _createTextureView(device) {
          if (!this._gfxTexture) {
            return null;
          }
          var maxLevel = this._maxLevel < this._mipmapLevel ? this._maxLevel : this._mipmapLevel - 1;
          var textureViewCreateInfo = this._getGfxTextureViewCreateInfo({
            texture: this._gfxTexture,
            format: this._getGFXFormat(),
            baseLevel: this._baseLevel,
            levelCount: maxLevel - this._baseLevel + 1
          });
          if (!textureViewCreateInfo) {
            return null;
          }
          return device.createTexture(textureViewCreateInfo);
        };
        _proto._tryDestroyTexture = function _tryDestroyTexture() {
          if (this._gfxTexture) {
            this._gfxTexture.destroy();
            this._gfxTexture = null;
          }
        };
        _proto._tryDestroyTextureView = function _tryDestroyTextureView() {
          if (this._gfxTextureView) {
            this._gfxTextureView.destroy();
            this._gfxTextureView = null;
          }
        };
        _createClass(SimpleTexture, [{
          key: "mipmapLevel",
          get: function get() {
            return this._mipmapLevel;
          }
        }]);
        return SimpleTexture;
      }(TextureBase)) || _class$3v);
      legacyCC.SimpleTexture = SimpleTexture;

      var _dec$3y, _dec2$2y, _class$3u, _class2$39, _initializer$2U;
      var Texture2D = exports('ei', (_dec$3y = ccclass$M('cc.Texture2D'), _dec2$2y = type$d([ImageAsset]), _dec$3y(_class$3u = (_class2$39 = function (_SimpleTexture) {
        _inheritsLoose(Texture2D, _SimpleTexture);
        function Texture2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _SimpleTexture.call.apply(_SimpleTexture, [this].concat(args)) || this;
          _this._mipmaps = _initializer$2U && _initializer$2U();
          _this._generatedMipmaps = [];
          return _this;
        }
        var _proto = Texture2D.prototype;
        _proto._setMipmapParams = function _setMipmapParams(value) {
          var _this2 = this;
          this._generatedMipmaps = value;
          this._setMipmapLevel(this._generatedMipmaps.length);
          if (this._generatedMipmaps.length > 0) {
            var imageAsset = this._generatedMipmaps[0];
            this.reset({
              width: imageAsset.width,
              height: imageAsset.height,
              format: imageAsset.format,
              mipmapLevel: this._generatedMipmaps.length,
              baseLevel: this._baseLevel,
              maxLevel: this._maxLevel
            });
            this._generatedMipmaps.forEach(function (mipmap, level) {
              _this2._assignImage(mipmap, level);
            });
          } else {
            this.reset({
              width: 0,
              height: 0,
              mipmapLevel: this._generatedMipmaps.length,
              baseLevel: this._baseLevel,
              maxLevel: this._maxLevel
            });
          }
        };
        _proto.initialize = function initialize() {
          this.mipmaps = this._mipmaps;
        };
        _proto.onLoaded = function onLoaded() {
          this.initialize();
        };
        _proto.reset = function reset(info) {
          this._width = info.width;
          this._height = info.height;
          this._setGFXFormat(info.format);
          var mipLevels = info.mipmapLevel === undefined ? 1 : info.mipmapLevel;
          this._setMipmapLevel(mipLevels);
          var minLod = info.baseLevel === undefined ? 0 : info.baseLevel;
          var maxLod = info.maxLevel === undefined ? 1000 : info.maxLevel;
          this._setMipRange(minLod, maxLod);
          this._tryReset();
        };
        _proto.create = function create(width, height, format, mipmapLevel, baseLevel, maxLevel) {
          if (format === void 0) {
            format = PixelFormat.RGBA8888;
          }
          if (mipmapLevel === void 0) {
            mipmapLevel = 1;
          }
          if (baseLevel === void 0) {
            baseLevel = 0;
          }
          if (maxLevel === void 0) {
            maxLevel = 1000;
          }
          this.reset({
            width: width,
            height: height,
            format: format,
            mipmapLevel: mipmapLevel,
            baseLevel: baseLevel,
            maxLevel: maxLevel
          });
        };
        _proto.toString = function toString() {
          return this._mipmaps.length !== 0 ? this._mipmaps[0].url : '';
        };
        _proto.updateMipmaps = function updateMipmaps(firstLevel, count) {
          if (firstLevel === void 0) {
            firstLevel = 0;
          }
          if (firstLevel >= this._generatedMipmaps.length) {
            return;
          }
          var nUpdate = Math.min(count === undefined ? this._generatedMipmaps.length : count, this._generatedMipmaps.length - firstLevel);
          for (var i = 0; i < nUpdate; ++i) {
            var level = firstLevel + i;
            this._assignImage(this._generatedMipmaps[level], level);
          }
        };
        _proto.getHtmlElementObj = function getHtmlElementObj() {
          return this._mipmaps[0] && this._mipmaps[0].data instanceof HTMLElement ? this._mipmaps[0].data : null;
        };
        _proto.destroy = function destroy() {
          this._mipmaps = [];
          this._generatedMipmaps = [];
          return _SimpleTexture.prototype.destroy.call(this);
        };
        _proto.description = function description() {
          var url = this._mipmaps[0] ? this._mipmaps[0].url : '';
          return "<cc.Texture2D | Name = " + url + " | Dimension = " + this.width + " x " + this.height + ">";
        };
        _proto.releaseTexture = function releaseTexture() {
          this.destroy();
        };
        _proto._serialize = function _serialize(ctxForExporting) {
          return null;
        };
        _proto._deserialize = function _deserialize(serializedData, handle) {
          var data = serializedData;
          _SimpleTexture.prototype._deserialize.call(this, data.base, handle);
          this._mipmaps = new Array(data.mipmaps.length);
          for (var i = 0; i < data.mipmaps.length; ++i) {
            this._mipmaps[i] = new ImageAsset();
            if (!data.mipmaps[i]) {
              continue;
            }
            var mipmapUUID = data.mipmaps[i];
            handle.result.push(this._mipmaps, "" + i, mipmapUUID, getClassId(ImageAsset));
          }
        };
        _proto._getGfxTextureCreateInfo = function _getGfxTextureCreateInfo(presumed) {
          var texInfo = new TextureInfo(TextureType.TEX2D);
          texInfo.width = this._width;
          texInfo.height = this._height;
          Object.assign(texInfo, presumed);
          return texInfo;
        };
        _proto._getGfxTextureViewCreateInfo = function _getGfxTextureViewCreateInfo(presumed) {
          var texViewInfo = new TextureViewInfo();
          texViewInfo.type = TextureType.TEX2D;
          Object.assign(texViewInfo, presumed);
          return texViewInfo;
        };
        _proto.initDefault = function initDefault(uuid) {
          _SimpleTexture.prototype.initDefault.call(this, uuid);
          var imageAsset = new ImageAsset();
          imageAsset.initDefault();
          this.image = imageAsset;
        };
        _proto.validate = function validate() {
          return this.mipmaps && this.mipmaps.length !== 0;
        };
        _createClass(Texture2D, [{
          key: "mipmaps",
          get: function get() {
            return this._mipmaps;
          },
          set: function set(value) {
            this._mipmaps = value;
            var mipmaps = [];
            if (value.length === 1) {
              var image = value[0];
              mipmaps.push.apply(mipmaps, image.extractMipmaps());
            } else if (value.length > 1) {
              for (var i = 0; i < value.length; ++i) {
                var _image = value[i];
                mipmaps.push(_image.extractMipmap0());
              }
            }
            this._setMipmapParams(mipmaps);
          }
        }, {
          key: "image",
          get: function get() {
            return this._mipmaps.length === 0 ? null : this._mipmaps[0];
          },
          set: function set(value) {
            this.mipmaps = value ? [value] : [];
          }
        }]);
        return Texture2D;
      }(SimpleTexture), (_initializer$2U = applyDecoratedInitializer(_class2$39.prototype, "_mipmaps", [_dec2$2y], function () {
        return [];
      })), _class2$39)) || _class$3u));
      legacyCC.Texture2D = Texture2D;

      var space$1 = 2;
      var Atlas = function () {
        function Atlas(width, height) {
          this._texture = void 0;
          this._width = void 0;
          this._height = void 0;
          this._x = void 0;
          this._y = void 0;
          this._nexty = void 0;
          this._innerTextureInfos = {};
          this._innerSpriteFrames = void 0;
          this._count = void 0;
          var texture = new DynamicAtlasTexture();
          texture.initWithSize(width, height);
          this._texture = texture;
          this._width = width;
          this._height = height;
          this._x = space$1;
          this._y = space$1;
          this._nexty = space$1;
          this._innerTextureInfos = {};
          this._innerSpriteFrames = [];
          this._count = 0;
        }
        var _proto = Atlas.prototype;
        _proto.insertSpriteFrame = function insertSpriteFrame(spriteFrame) {
          var rect = spriteFrame.rect;
          var texture = spriteFrame.texture;
          var info = this._innerTextureInfos[texture.getId()];
          var sx = rect.x;
          var sy = rect.y;
          if (info) {
            sx += info.x;
            sy += info.y;
          } else {
            var width = texture.width;
            var height = texture.height;
            if (this._x + width + space$1 > this._width) {
              this._x = space$1;
              this._y = this._nexty;
            }
            if (this._y + height + space$1 > this._nexty) {
              this._nexty = this._y + height + space$1;
            }
            if (this._nexty > this._height) {
              return null;
            }
            if (legacyCC.internal.dynamicAtlasManager.textureBleeding) {
              if (width <= 8 || height <= 8) {
                this._texture.drawTextureAt(texture.image, this._x - 1, this._y - 1);
                this._texture.drawTextureAt(texture.image, this._x - 1, this._y + 1);
                this._texture.drawTextureAt(texture.image, this._x + 1, this._y - 1);
                this._texture.drawTextureAt(texture.image, this._x + 1, this._y + 1);
              }
              this._texture.drawTextureAt(texture.image, this._x - 1, this._y);
              this._texture.drawTextureAt(texture.image, this._x + 1, this._y);
              this._texture.drawTextureAt(texture.image, this._x, this._y - 1);
              this._texture.drawTextureAt(texture.image, this._x, this._y + 1);
            }
            this._texture.drawTextureAt(texture.image, this._x, this._y);
            this._innerTextureInfos[texture.getId()] = {
              x: this._x,
              y: this._y,
              texture: texture
            };
            this._count++;
            sx += this._x;
            sy += this._y;
            this._x += width + space$1;
          }
          var frame = {
            x: sx,
            y: sy,
            texture: this._texture
          };
          this._innerSpriteFrames.push(spriteFrame);
          return frame;
        };
        _proto.deleteInnerTexture = function deleteInnerTexture(texture) {
          if (texture && this._innerTextureInfos[texture.getId()]) {
            delete this._innerTextureInfos[texture.getId()];
            this._count--;
          }
        };
        _proto.isEmpty = function isEmpty() {
          return this._count <= 0;
        };
        _proto.reset = function reset() {
          this._x = space$1;
          this._y = space$1;
          this._nexty = space$1;
          var frames = this._innerSpriteFrames;
          for (var i = 0, l = frames.length; i < l; i++) {
            var frame = frames[i];
            if (!frame.isValid) {
              continue;
            }
            frame._resetDynamicAtlasFrame();
          }
          this._innerSpriteFrames.length = 0;
          this._innerTextureInfos = {};
        };
        _proto.destroy = function destroy() {
          this.reset();
          this._texture.destroy();
        };
        return Atlas;
      }();
      var DynamicAtlasTexture = function (_Texture2D) {
        _inheritsLoose(DynamicAtlasTexture, _Texture2D);
        function DynamicAtlasTexture() {
          return _Texture2D.apply(this, arguments) || this;
        }
        var _proto2 = DynamicAtlasTexture.prototype;
        _proto2.initWithSize = function initWithSize(width, height, format) {
          if (format === void 0) {
            format = PixelFormat.RGBA8888;
          }
          this.reset({
            width: width,
            height: height,
            format: format
          });
        };
        _proto2.drawTextureAt = function drawTextureAt(image, x, y) {
          var gfxTexture = this.getGFXTexture();
          if (!image || !gfxTexture) {
            return;
          }
          var gfxDevice = this._getGFXDevice();
          if (!gfxDevice) {
            console.warn('Unable to get device');
            return;
          }
          var region = new BufferTextureCopy();
          region.texOffset.x = x;
          region.texOffset.y = y;
          region.texExtent.width = image.width;
          region.texExtent.height = image.height;
          gfxDevice.copyTexImagesToTexture([image.data], gfxTexture, [region]);
        };
        return DynamicAtlasTexture;
      }(Texture2D);

      var layerList = {
        NONE: 0,
        IGNORE_RAYCAST: 1 << 20,
        GIZMOS: 1 << 21,
        EDITOR: 1 << 22,
        UI_3D: 1 << 23,
        SCENE_GIZMO: 1 << 24,
        UI_2D: 1 << 25,
        PROFILER: 1 << 28,
        DEFAULT: 1 << 30,
        ALL: 0xffffffff
      };
      var Layers = exports('dE', function () {
        function Layers() {}
        Layers.init = function init() {
          var userLayers = settings.querySettings(Settings.Category.ENGINE, 'customLayers');
          if (!userLayers) return;
          for (var i = 0; i < userLayers.length; i++) {
            var layer = userLayers[i];
            Layers.addLayer(layer.name, layer.bit);
          }
        };
        Layers.makeMaskInclude = function makeMaskInclude(includes) {
          var mask = 0;
          for (var _iterator = _createForOfIteratorHelperLoose(includes), _step; !(_step = _iterator()).done;) {
            var inc = _step.value;
            mask |= inc;
          }
          return mask;
        };
        Layers.makeMaskExclude = function makeMaskExclude(excludes) {
          return ~Layers.makeMaskInclude(excludes);
        };
        Layers.addLayer = function addLayer(name, bitNum) {
          if (bitNum === undefined) {
            console.warn('bitNum can\'t be undefined');
            return;
          }
          if (bitNum > 19 || bitNum < 0) {
            console.warn('maximum layers reached.');
            return;
          }
          var val = 1 << bitNum;
          assertIsTrue(!Layers.Enum[name], getError(2104, name));
          Layers.Enum[name] = val;
          value(Layers.Enum, String(val), name);
          Layers.BitMask[name] = val;
          value(Layers.BitMask, String(val), name);
          BitMask.update(Layers.BitMask);
          Enum.update(Layers.Enum);
        };
        Layers.deleteLayer = function deleteLayer(bitNum) {
          if (bitNum > 19 || bitNum < 0) {
            console.warn('do not change buildin layers.');
            return;
          }
          var val = 1 << bitNum;
          delete Layers.Enum[Layers.Enum[val]];
          delete Layers.Enum[val];
          delete Layers.BitMask[Layers.BitMask[val]];
          delete Layers.BitMask[val];
          BitMask.update(Layers.BitMask);
          Enum.update(Layers.Enum);
        };
        Layers.nameToLayer = function nameToLayer(name) {
          if (name === undefined) {
            console.warn('name can\'t be undefined');
            return -1;
          }
          return log2(Layers.Enum[name]);
        };
        Layers.layerToName = function layerToName(bitNum) {
          if (bitNum > 31 || bitNum < 0) {
            console.warn('Unable to access unknown layer.');
            return '';
          }
          return Layers.Enum[1 << bitNum];
        };
        return Layers;
      }());
      Layers.Enum = Enum(layerList);
      Layers.BitMask = BitMask(_extends({}, layerList));
      legacyCC.Layers = Layers;

      var NodeUIProperties = function () {
        var _proto = NodeUIProperties.prototype;
        _proto.setOpacity = function setOpacity(v) {
          this._opacity = v;
        };
        function NodeUIProperties(node) {
          this._uiComp = null;
          this._opacity = 1;
          this._localOpacity = 1;
          this.colorDirty = true;
          this._uiTransformComp = null;
          this._node = void 0;
          this._node = node;
        }
        _proto.applyOpacity = function applyOpacity(effectOpacity) {
          this._opacity = this._localOpacity * effectOpacity;
        };
        NodeUIProperties.markOpacityTree = function markOpacityTree(node, isDirty) {
        };
        _createClass(NodeUIProperties, [{
          key: "uiTransformComp",
          get: function get() {
            if (!this._uiTransformComp) {
              this._uiTransformComp = this._node.getComponent('cc.UITransform');
            }
            return this._uiTransformComp;
          },
          set: function set(value) {
            this._uiTransformComp = value;
          }
        }, {
          key: "uiComp",
          get: function get() {
            return this._uiComp;
          },
          set: function set(comp) {
            if (this._uiComp && comp) {
              warnID(12002);
              return;
            }
            this._uiComp = comp;
          }
        }, {
          key: "opacity",
          get: function get() {
            return this._opacity;
          }
        }, {
          key: "localOpacity",
          get: function get() {
            return this._localOpacity;
          },
          set: function set(val) {
            this._localOpacity = val;
            this.colorDirty = true;
          }
        }]);
        return NodeUIProperties;
      }();

      CCObject.Flags.Destroying;
      !!legacyCC.GAME_VIEW;

      var NodeSpace; exports('dK', NodeSpace);
      (function (NodeSpace) {
        NodeSpace[NodeSpace["LOCAL"] = 0] = "LOCAL";
        NodeSpace[NodeSpace["WORLD"] = 1] = "WORLD";
      })(NodeSpace || (exports('dK', NodeSpace = {})));
      var TransformBit; exports('dL', TransformBit);
      (function (TransformBit) {
        TransformBit[TransformBit["NONE"] = 0] = "NONE";
        TransformBit[TransformBit["POSITION"] = 1] = "POSITION";
        TransformBit[TransformBit["ROTATION"] = 2] = "ROTATION";
        TransformBit[TransformBit["SCALE"] = 4] = "SCALE";
        TransformBit[TransformBit["RS"] = TransformBit.ROTATION | TransformBit.SCALE] = "RS";
        TransformBit[TransformBit["TRS"] = TransformBit.POSITION | TransformBit.ROTATION | TransformBit.SCALE] = "TRS";
        TransformBit[TransformBit["TRS_MASK"] = ~TransformBit.TRS] = "TRS_MASK";
      })(TransformBit || (exports('dL', TransformBit = {})));
      legacyCC.internal.TransformBit = TransformBit;
      var MobilityMode = exports('dM', Enum({
        Static: 0,
        Stationary: 1,
        Movable: 2
      }));

      var NodeEventType; exports('dN', NodeEventType);
      (function (NodeEventType) {
        NodeEventType["TOUCH_START"] = "touch-start";
        NodeEventType["TOUCH_MOVE"] = "touch-move";
        NodeEventType["TOUCH_END"] = "touch-end";
        NodeEventType["TOUCH_CANCEL"] = "touch-cancel";
        NodeEventType["MOUSE_DOWN"] = "mouse-down";
        NodeEventType["MOUSE_MOVE"] = "mouse-move";
        NodeEventType["MOUSE_UP"] = "mouse-up";
        NodeEventType["MOUSE_WHEEL"] = "mouse-wheel";
        NodeEventType["MOUSE_ENTER"] = "mouse-enter";
        NodeEventType["MOUSE_LEAVE"] = "mouse-leave";
        NodeEventType["KEY_DOWN"] = "keydown";
        NodeEventType["KEY_UP"] = "keyup";
        NodeEventType["DEVICEMOTION"] = "devicemotion";
        NodeEventType["TRANSFORM_CHANGED"] = "transform-changed";
        NodeEventType["MOBILITY_CHANGED"] = "mobility-changed";
        NodeEventType["SCENE_CHANGED_FOR_PERSISTS"] = "scene-changed-for-persists";
        NodeEventType["SIZE_CHANGED"] = "size-changed";
        NodeEventType["ANCHOR_CHANGED"] = "anchor-changed";
        NodeEventType["COLOR_CHANGED"] = "color-changed";
        NodeEventType["CHILD_ADDED"] = "child-added";
        NodeEventType["CHILD_REMOVED"] = "child-removed";
        NodeEventType["PARENT_CHANGED"] = "parent-changed";
        NodeEventType["NODE_DESTROYED"] = "node-destroyed";
        NodeEventType["LAYER_CHANGED"] = "layer-changed";
        NodeEventType["SIBLING_ORDER_CHANGED"] = "sibling-order-changed";
        NodeEventType["CHILDREN_ORDER_CHANGED"] = "sibling-order-changed";
        NodeEventType["ACTIVE_IN_HIERARCHY_CHANGED"] = "active-in-hierarchy-changed";
        NodeEventType["COMPONENT_ADDED"] = "component-added";
        NodeEventType["COMPONENT_REMOVED"] = "component-removed";
        NodeEventType["LIGHT_PROBE_CHANGED"] = "light-probe-changed";
        NodeEventType["LIGHT_PROBE_BAKING_CHANGED"] = "light-probe-baking-changed";
      })(NodeEventType || (exports('dN', NodeEventType = {})));

      var _dec$3x, _dec2$2x, _dec3$1M, _class$3t, _class2$38, _initializer$2T, _initializer2$2j, _initializer3$1I, _initializer4$1s, _initializer5$17, _initializer6$W, _initializer7$K, _initializer8$G, _initializer9$B, _initializer10$y, _initializer11$w, _class3$X;
      var Destroying = CCObject.Flags.Destroying;
      var DontDestroy = CCObject.Flags.DontDestroy;
      var Deactivating$1 = CCObject.Flags.Deactivating;
      var TRANSFORM_ON = 1 << 0;
      var idGenerator = new IDGenerator('Node');
      function getConstructor(typeOrClassName) {
        if (!typeOrClassName) {
          errorID(3804);
          return null;
        }
        if (typeof typeOrClassName === 'string') {
          return getClassByName(typeOrClassName);
        }
        return typeOrClassName;
      }
      var v3_a = new Vec3();
      var v3_b = new Vec3();
      var q_a = new Quat();
      var q_b = new Quat();
      var qt_1 = new Quat();
      var m3_1 = new Mat3();
      new Mat3();
      var m4_1$7 = new Mat4();
      var m4_2$3 = new Mat4();
      var dirtyNodes = [];
      var reserveContentsForAllSyncablePrefabTag = Symbol('ReserveContentsForAllSyncablePrefab');
      var globalFlagChangeVersion = 0;
      var Node$1 = exports('dC', (_dec$3x = ccclass$M('cc.Node'), _dec2$2x = type$d(Vec3), _dec3$1M = type$d(MobilityMode), _dec$3x(_class$3t = (_class2$38 = (_class3$X = function (_CCObject) {
        _inheritsLoose(Node, _CCObject);
        var _proto = Node.prototype;
        _proto._setActiveInHierarchy = function _setActiveInHierarchy(v) {
          this._activeInHierarchy = v;
        };
        Node._setScene = function _setScene(node) {
          node._updateScene();
        };
        Node._findComponent = function _findComponent(node, constructor) {
          var cls = constructor;
          var comps = node._components;
          if (cls._sealed) {
            for (var i = 0; i < comps.length; ++i) {
              var comp = comps[i];
              if (comp.constructor === constructor) {
                return comp;
              }
            }
          } else {
            for (var _i = 0; _i < comps.length; ++_i) {
              var _comp = comps[_i];
              if (_comp instanceof constructor) {
                return _comp;
              }
            }
          }
          return null;
        };
        Node._findComponents = function _findComponents(node, constructor, components) {
          var cls = constructor;
          var comps = node._components;
          if (cls._sealed) {
            for (var i = 0; i < comps.length; ++i) {
              var comp = comps[i];
              if (comp.constructor === constructor) {
                components.push(comp);
              }
            }
          } else {
            for (var _i2 = 0; _i2 < comps.length; ++_i2) {
              var _comp2 = comps[_i2];
              if (_comp2 instanceof constructor) {
                components.push(_comp2);
              }
            }
          }
        };
        Node._findChildComponent = function _findChildComponent(children, constructor) {
          for (var i = 0; i < children.length; ++i) {
            var node = children[i];
            var comp = Node._findComponent(node, constructor);
            if (comp) {
              return comp;
            }
            if (node._children.length > 0) {
              comp = Node._findChildComponent(node._children, constructor);
              if (comp) {
                return comp;
              }
            }
          }
          return null;
        };
        Node._findChildComponents = function _findChildComponents(children, constructor, components) {
          for (var i = 0; i < children.length; ++i) {
            var node = children[i];
            Node._findComponents(node, constructor, components);
            if (node._children.length > 0) {
              Node._findChildComponents(node._children, constructor, components);
            }
          }
        };
        _proto.getWritableComponents = function getWritableComponents() {
          return this._components;
        };
        _proto._updateScene = function _updateScene() {
          if (this._parent == null) {
            error('Node %s(%s) has not attached to a scene.', this.name, this.uuid);
          } else {
            this._scene = this._parent._scene;
          }
        };
        _proto.attr = function attr(attrs) {
          mixin(this, attrs);
        };
        _proto.getParent = function getParent() {
          return this._parent;
        };
        _proto.modifyParent = function modifyParent(parent) {
          this._parent = parent;
        };
        _proto.setParent = function setParent(value, keepWorldTransform) {
          if (keepWorldTransform === void 0) {
            keepWorldTransform = false;
          }
          if (keepWorldTransform) {
            this.updateWorldTransform();
          }
          if (this._parent === value) {
            return;
          }
          var oldParent = this._parent;
          var newParent = value;
          if (oldParent && oldParent._objFlags & Deactivating$1) {
            errorID(3821);
          }
          this._parent = newParent;
          this._siblingIndex = 0;
          this._onSetParent(oldParent, keepWorldTransform);
          if (this.emit) {
            this.emit(NodeEventType.PARENT_CHANGED, oldParent);
          }
          if (oldParent) {
            if (!(oldParent._objFlags & Destroying)) {
              var removeAt = oldParent._children.indexOf(this);
              oldParent._children.splice(removeAt, 1);
              oldParent._updateSiblingIndex();
              if (oldParent.emit) {
                oldParent.emit(NodeEventType.CHILD_REMOVED, this);
              }
            }
          }
          if (newParent) {
            if (newParent._objFlags & Deactivating$1) {
              errorID(3821);
            }
            newParent._children.push(this);
            this._siblingIndex = newParent._children.length - 1;
            if (newParent.emit) {
              newParent.emit(NodeEventType.CHILD_ADDED, this);
            }
          }
          this._onHierarchyChanged(oldParent);
        };
        _proto.getChildByUuid = function getChildByUuid(uuid) {
          if (!uuid) {
            log('Invalid uuid');
            return null;
          }
          var locChildren = this._children;
          for (var i = 0, len = locChildren.length; i < len; i++) {
            if (locChildren[i]._id === uuid) {
              return locChildren[i];
            }
          }
          return null;
        };
        _proto.getChildByName = function getChildByName(name) {
          if (!name) {
            log('Invalid name');
            return null;
          }
          var locChildren = this._children;
          for (var i = 0, len = locChildren.length; i < len; i++) {
            if (locChildren[i]._name === name) {
              return locChildren[i];
            }
          }
          return null;
        };
        _proto.getChildByPath = function getChildByPath(path) {
          var segments = path.split('/');
          var lastNode = this;
          var _loop = function _loop() {
              var segment = segments[i];
              if (segment.length === 0) {
                return 0;
              }
              var next = lastNode.children.find(function (childNode) {
                return childNode.name === segment;
              });
              if (!next) {
                return {
                  v: null
                };
              }
              lastNode = next;
            },
            _ret;
          for (var i = 0; i < segments.length; ++i) {
            _ret = _loop();
            if (_ret === 0) continue;
            if (_ret) return _ret.v;
          }
          return lastNode;
        };
        _proto.addChild = function addChild(child) {
          child.setParent(this);
        };
        _proto.insertChild = function insertChild(child, siblingIndex) {
          child.setParent(this);
          child.setSiblingIndex(siblingIndex);
        };
        _proto.getSiblingIndex = function getSiblingIndex() {
          return this._siblingIndex;
        };
        _proto.setSiblingIndex = function setSiblingIndex(index) {
          if (!this._parent) {
            return;
          }
          if (this._parent._objFlags & Deactivating$1) {
            errorID(3821);
            return;
          }
          var siblings = this._parent._children;
          index = index !== -1 ? index : siblings.length - 1;
          var oldIndex = siblings.indexOf(this);
          if (index !== oldIndex) {
            siblings.splice(oldIndex, 1);
            if (index < siblings.length) {
              siblings.splice(index, 0, this);
            } else {
              siblings.push(this);
            }
            this._parent._updateSiblingIndex();
            if (this._onSiblingIndexChanged) {
              this._onSiblingIndexChanged(index);
            }
            this._eventProcessor.onUpdatingSiblingIndex();
          }
        };
        _proto.walk = function walk(preFunc, postFunc) {
          var index = 1;
          var children = null;
          var curr = null;
          var i = 0;
          var stack = Node._stacks[Node._stackId];
          if (!stack) {
            stack = [];
            Node._stacks.push(stack);
          }
          Node._stackId++;
          stack.length = 0;
          stack[0] = this;
          var parent = null;
          var afterChildren = false;
          while (index) {
            index--;
            curr = stack[index];
            if (!curr) {
              continue;
            }
            if (!afterChildren && preFunc) {
              preFunc(curr);
            } else if (afterChildren && postFunc) {
              postFunc(curr);
            }
            stack[index] = null;
            if (afterChildren) {
              if (parent === this._parent) break;
              afterChildren = false;
            } else {
              if (curr._children.length > 0) {
                parent = curr;
                children = curr._children;
                i = 0;
                stack[index] = children[i];
                index++;
              } else {
                stack[index] = curr;
                index++;
                afterChildren = true;
              }
              continue;
            }
            if (children) {
              i++;
              if (children[i]) {
                stack[index] = children[i];
                index++;
              } else if (parent) {
                stack[index] = parent;
                index++;
                afterChildren = true;
                if (parent._parent) {
                  children = parent._parent._children;
                  i = children.indexOf(parent);
                  parent = parent._parent;
                } else {
                  parent = null;
                  children = null;
                }
                if (i < 0) {
                  break;
                }
              }
            }
          }
          stack.length = 0;
          Node._stackId--;
        };
        _proto.removeFromParent = function removeFromParent() {
          if (this._parent) {
            this._parent.removeChild(this);
          }
        };
        _proto.removeChild = function removeChild(child) {
          if (this._children.indexOf(child) > -1) {
            child.parent = null;
          }
        };
        _proto.removeAllChildren = function removeAllChildren() {
          var children = this._children;
          for (var i = children.length - 1; i >= 0; i--) {
            var node = children[i];
            if (node) {
              node.parent = null;
            }
          }
          this._children.length = 0;
        };
        _proto.isChildOf = function isChildOf(parent) {
          var child = this;
          do {
            if (child === parent) {
              return true;
            }
            child = child._parent;
          } while (child);
          return false;
        };
        _proto.getComponent = function getComponent(typeOrClassName) {
          var constructor = getConstructor(typeOrClassName);
          if (constructor) {
            return Node._findComponent(this, constructor);
          }
          return null;
        };
        _proto.getComponents = function getComponents(typeOrClassName) {
          var constructor = getConstructor(typeOrClassName);
          var components = [];
          if (constructor) {
            Node._findComponents(this, constructor, components);
          }
          return components;
        };
        _proto.getComponentInChildren = function getComponentInChildren(typeOrClassName) {
          var constructor = getConstructor(typeOrClassName);
          if (constructor) {
            return Node._findChildComponent(this._children, constructor);
          }
          return null;
        };
        _proto.getComponentsInChildren = function getComponentsInChildren(typeOrClassName) {
          var constructor = getConstructor(typeOrClassName);
          var components = [];
          if (constructor) {
            Node._findComponents(this, constructor, components);
            Node._findChildComponents(this._children, constructor, components);
          }
          return components;
        };
        _proto.addComponent = function addComponent(typeOrClassName) {
          var constructor;
          if (typeof typeOrClassName === 'string') {
            constructor = getClassByName(typeOrClassName);
            if (!constructor) {
              if (legacyCC._RF.peek()) {
                errorID(3808, typeOrClassName);
              }
              throw TypeError(getError(3807, typeOrClassName));
            }
          } else {
            if (!typeOrClassName) {
              throw TypeError(getError(3804));
            }
            constructor = typeOrClassName;
          }
          if (typeof constructor !== 'function') {
            throw TypeError(getError(3809));
          }
          if (!isChildClassOf(constructor, legacyCC.Component)) {
            throw TypeError(getError(3810));
          }
          var reqComps = constructor._requireComponent;
          if (reqComps) {
            if (Array.isArray(reqComps)) {
              for (var i = 0; i < reqComps.length; i++) {
                var reqComp = reqComps[i];
                if (!this.getComponent(reqComp)) {
                  this.addComponent(reqComp);
                }
              }
            } else {
              var _reqComp = reqComps;
              if (!this.getComponent(_reqComp)) {
                this.addComponent(_reqComp);
              }
            }
          }
          var component = new constructor();
          component.node = this;
          this._components.push(component);
          this.emit(NodeEventType.COMPONENT_ADDED, component);
          if (this._activeInHierarchy) {
            legacyCC.director._nodeActivator.activateComp(component);
          }
          return component;
        };
        _proto.removeComponent = function removeComponent(component) {
          if (!component) {
            errorID(3813);
            return;
          }
          var componentInstance = null;
          if (component instanceof Component) {
            componentInstance = component;
          } else {
            componentInstance = this.getComponent(component);
          }
          if (componentInstance) {
            componentInstance.destroy();
          }
        };
        _proto.on = function on(type, callback, target, useCapture) {
          if (useCapture === void 0) {
            useCapture = false;
          }
          switch (type) {
            case NodeEventType.TRANSFORM_CHANGED:
              this._eventMask |= TRANSFORM_ON;
              break;
          }
          this._eventProcessor.on(type, callback, target, useCapture);
        };
        _proto.off = function off(type, callback, target, useCapture) {
          if (useCapture === void 0) {
            useCapture = false;
          }
          this._eventProcessor.off(type, callback, target, useCapture);
          var hasListeners = this._eventProcessor.hasEventListener(type);
          if (!hasListeners) {
            switch (type) {
              case NodeEventType.TRANSFORM_CHANGED:
                this._eventMask &= ~TRANSFORM_ON;
                break;
            }
          }
        };
        _proto.once = function once(type, callback, target, useCapture) {
          this._eventProcessor.once(type, callback, target, useCapture);
        };
        _proto.emit = function emit(type, arg0, arg1, arg2, arg3, arg4) {
          this._eventProcessor.emit(type, arg0, arg1, arg2, arg3, arg4);
        };
        _proto.dispatchEvent = function dispatchEvent(event) {
          this._eventProcessor.dispatchEvent(event);
        };
        _proto.hasEventListener = function hasEventListener(type, callback, target) {
          return this._eventProcessor.hasEventListener(type, callback, target);
        };
        _proto.targetOff = function targetOff(target) {
          this._eventProcessor.targetOff(target);
          if (this._eventMask & TRANSFORM_ON && !this._eventProcessor.hasEventListener(NodeEventType.TRANSFORM_CHANGED)) {
            this._eventMask &= ~TRANSFORM_ON;
          }
        };
        _proto.destroy = function destroy() {
          if (_CCObject.prototype.destroy.call(this)) {
            this.active = false;
            return true;
          }
          return false;
        };
        _proto.destroyAllChildren = function destroyAllChildren() {
          var children = this._children;
          for (var i = 0; i < children.length; ++i) {
            children[i].destroy();
          }
        };
        _proto._removeComponent = function _removeComponent(component) {
          if (!component) {
            errorID(3814);
            return;
          }
          if (!(this._objFlags & Destroying)) {
            var i = this._components.indexOf(component);
            if (i !== -1) {
              this._components.splice(i, 1);
              this.emit(NodeEventType.COMPONENT_REMOVED, component);
            } else if (component.node !== this) {
              errorID(3815);
            }
          }
        };
        _proto._updateSiblingIndex = function _updateSiblingIndex() {
          for (var i = 0; i < this._children.length; ++i) {
            this._children[i]._siblingIndex = i;
          }
          this.emit(NodeEventType.CHILDREN_ORDER_CHANGED);
        };
        _proto._instantiate = function _instantiate(cloned, isSyncedNode) {
          if (!cloned) {
            cloned = legacyCC.instantiate._clone(this, this);
          }
          cloned._prefab;
          cloned._parent = null;
          cloned._onBatchCreated(isSyncedNode);
          return cloned;
        };
        _proto._onHierarchyChangedBase = function _onHierarchyChangedBase(oldParent) {
          var newParent = this._parent;
          if (this._persistNode && !(newParent instanceof legacyCC.Scene)) {
            legacyCC.game.removePersistRootNode(this);
          }
          var shouldActiveNow = this._active && !!(newParent && newParent._activeInHierarchy);
          if (this._activeInHierarchy !== shouldActiveNow) {
            legacyCC.director._nodeActivator.activateNode(this, shouldActiveNow);
          }
        };
        _proto._onPreDestroyBase = function _onPreDestroyBase() {
          this._objFlags |= Destroying;
          var parent = this._parent;
          var destroyByParent = !!parent && (parent._objFlags & Destroying) !== 0;
          if (!destroyByParent && EDITOR) {
            this._registerIfAttached(false);
          }
          if (this._persistNode) {
            legacyCC.game.removePersistRootNode(this);
          }
          if (!destroyByParent) {
            if (parent) {
              this.emit(NodeEventType.PARENT_CHANGED, this);
              var childIndex = parent._children.indexOf(this);
              parent._children.splice(childIndex, 1);
              this._siblingIndex = 0;
              parent._updateSiblingIndex();
              if (parent.emit) {
                parent.emit(NodeEventType.CHILD_REMOVED, this);
              }
            }
          }
          this.emit(NodeEventType.NODE_DESTROYED, this);
          this._eventProcessor.destroy();
          var children = this._children;
          for (var i = 0; i < children.length; ++i) {
            children[i]._destroyImmediate();
          }
          var comps = this._components;
          for (var _i3 = 0; _i3 < comps.length; ++_i3) {
            comps[_i3]._destroyImmediate();
          }
          return destroyByParent;
        };
        function Node(name) {
          var _this;
          _this = _CCObject.call(this, name) || this;
          _this._parent = _initializer$2T && _initializer$2T();
          _this._children = _initializer2$2j && _initializer2$2j();
          _this._active = _initializer3$1I && _initializer3$1I();
          _this._components = _initializer4$1s && _initializer4$1s();
          _this._prefab = _initializer5$17 && _initializer5$17();
          _this._scene = null;
          _this._activeInHierarchy = false;
          _this._id = idGenerator.getNewId();
          _this._name = void 0;
          _this._eventProcessor = new legacyCC.NodeEventProcessor(_assertThisInitialized(_this));
          _this._eventMask = 0;
          _this._siblingIndex = 0;
          _this._originalSceneId = '';
          _this._uiProps = new NodeUIProperties(_assertThisInitialized(_this));
          _this._static = false;
          _this._lpos = _initializer6$W && _initializer6$W();
          _this._lrot = _initializer7$K && _initializer7$K();
          _this._lscale = _initializer8$G && _initializer8$G();
          _this._mobility = _initializer9$B && _initializer9$B();
          _this._layer = _initializer10$y && _initializer10$y();
          _this._euler = _initializer11$w && _initializer11$w();
          _this._transformFlags = TransformBit.TRS;
          _this._eulerDirty = false;
          _this._flagChangeVersion = 0;
          _this._hasChangedFlags = 0;
          _this._name = name !== undefined ? name : 'New Node';
          _this._pos = new Vec3();
          _this._rot = new Quat();
          _this._scale = new Vec3(1, 1, 1);
          _this._mat = new Mat4();
          return _this;
        }
        Node.isNode = function isNode(obj) {
          return obj instanceof Node && (obj.constructor === Node || !(obj instanceof legacyCC.Scene));
        };
        _proto._onPreDestroy = function _onPreDestroy() {
          return this._onPreDestroyBase();
        };
        _proto[serializeTag] = function (serializationOutput, context) {
          {
            serializationOutput.writeThis();
            return;
          }
        };
        _proto._onSetParent = function _onSetParent(oldParent, keepWorldTransform) {
          if (keepWorldTransform === void 0) {
            keepWorldTransform = false;
          }
          if (this._parent) {
            if ((oldParent == null || oldParent._scene !== this._parent._scene) && this._parent._scene != null) {
              this.walk(Node._setScene);
            }
          }
          if (keepWorldTransform) {
            var parent = this._parent;
            if (parent) {
              parent.updateWorldTransform();
              if (approx(Mat4.determinant(parent._mat), 0, EPSILON$3)) {
                warnID(14300);
                this._transformFlags |= TransformBit.TRS;
                this.updateWorldTransform();
              } else {
                Mat4.multiply(m4_1$7, Mat4.invert(m4_1$7, parent._mat), this._mat);
                Mat4.toRTS(m4_1$7, this._lrot, this._lpos, this._lscale);
              }
            } else {
              Vec3.copy(this._lpos, this._pos);
              Quat.copy(this._lrot, this._rot);
              Vec3.copy(this._lscale, this._scale);
            }
            this._eulerDirty = true;
          }
          this.invalidateChildren(TransformBit.TRS);
        };
        _proto._onHierarchyChanged = function _onHierarchyChanged(oldParent) {
          this.eventProcessor.reattach();
          this._onHierarchyChangedBase(oldParent);
        };
        _proto._onBatchCreated = function _onBatchCreated(dontSyncChildPrefab) {
          this.hasChangedFlags = TransformBit.TRS;
          var len = this._children.length;
          for (var i = 0; i < len; ++i) {
            this._children[i]._siblingIndex = i;
            this._children[i]._onBatchCreated(dontSyncChildPrefab);
          }
        };
        _proto._onBeforeSerialize = function _onBeforeSerialize() {
          this.eulerAngles;
        };
        _proto._onPostActivated = function _onPostActivated(active) {
          if (active) {
            this._eventProcessor.setEnabled(true);
            this.invalidateChildren(TransformBit.TRS);
            if (this._uiProps && this._uiProps.uiComp) {
              this._uiProps.uiComp.setNodeDirty();
              this._uiProps.uiComp.setTextureDirty();
              this._uiProps.uiComp.markForUpdateRenderData();
            }
          } else {
            this._eventProcessor.setEnabled(false);
          }
        };
        _proto.translate = function translate(trans, ns) {
          var space = ns || NodeSpace.LOCAL;
          if (space === NodeSpace.LOCAL) {
            Vec3.transformQuat(v3_a, trans, this._lrot);
            this._lpos.x += v3_a.x;
            this._lpos.y += v3_a.y;
            this._lpos.z += v3_a.z;
          } else if (space === NodeSpace.WORLD) {
            if (this._parent) {
              Quat.invert(q_a, this._parent.worldRotation);
              Vec3.transformQuat(v3_a, trans, q_a);
              var _scale = this.worldScale;
              this._lpos.x += v3_a.x / _scale.x;
              this._lpos.y += v3_a.y / _scale.y;
              this._lpos.z += v3_a.z / _scale.z;
            } else {
              this._lpos.x += trans.x;
              this._lpos.y += trans.y;
              this._lpos.z += trans.z;
            }
          }
          this.invalidateChildren(TransformBit.POSITION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
          }
        };
        _proto.rotate = function rotate(rot, ns) {
          var space = ns || NodeSpace.LOCAL;
          Quat.normalize(q_a, rot);
          if (space === NodeSpace.LOCAL) {
            Quat.multiply(this._lrot, this._lrot, q_a);
          } else if (space === NodeSpace.WORLD) {
            var worldRot = this.worldRotation;
            Quat.multiply(q_b, q_a, worldRot);
            Quat.invert(q_a, worldRot);
            Quat.multiply(q_b, q_a, q_b);
            Quat.multiply(this._lrot, this._lrot, q_b);
          }
          this._eulerDirty = true;
          this.invalidateChildren(TransformBit.ROTATION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
          }
        };
        _proto.lookAt = function lookAt(pos, up) {
          this.getWorldPosition(v3_a);
          Vec3.subtract(v3_a, v3_a, pos);
          Vec3.normalize(v3_a, v3_a);
          Quat.fromViewUp(q_a, v3_a, up);
          this.setWorldRotation(q_a);
        };
        _proto.invalidateChildren = function invalidateChildren(dirtyBit) {
          var i = 0;
          var j = 0;
          var l = 0;
          var cur;
          var children;
          var hasChangedFlags = 0;
          var childDirtyBit = dirtyBit | TransformBit.POSITION;
          dirtyNodes[0] = this;
          while (i >= 0) {
            cur = dirtyNodes[i--];
            hasChangedFlags = cur.hasChangedFlags;
            if (cur.isValid && (cur._transformFlags & hasChangedFlags & dirtyBit) !== dirtyBit) {
              cur._transformFlags |= dirtyBit;
              cur.hasChangedFlags = hasChangedFlags | dirtyBit;
              children = cur._children;
              l = children.length;
              for (j = 0; j < l; j++) {
                dirtyNodes[++i] = children[j];
              }
            }
            dirtyBit = childDirtyBit;
          }
        };
        _proto.updateWorldTransform = function updateWorldTransform() {
          if (!this._transformFlags) {
            return;
          }
          var cur = this;
          var i = 0;
          while (cur && cur._transformFlags) {
            dirtyNodes[i++] = cur;
            cur = cur._parent;
          }
          var child;
          var dirtyBits = 0;
          while (i) {
            child = dirtyNodes[--i];
            dirtyBits |= child._transformFlags;
            if (cur) {
              if (dirtyBits & TransformBit.POSITION) {
                Vec3.transformMat4(child._pos, child._lpos, cur._mat);
                child._mat.m12 = child._pos.x;
                child._mat.m13 = child._pos.y;
                child._mat.m14 = child._pos.z;
              }
              if (dirtyBits & TransformBit.RS) {
                Mat4.fromRTS(child._mat, child._lrot, child._lpos, child._lscale);
                Mat4.multiply(child._mat, cur._mat, child._mat);
                var rotTmp = dirtyBits & TransformBit.ROTATION ? child._rot : null;
                Mat4.toRTS(child._mat, rotTmp, null, child._scale);
              }
            } else {
              if (dirtyBits & TransformBit.POSITION) {
                Vec3.copy(child._pos, child._lpos);
                child._mat.m12 = child._pos.x;
                child._mat.m13 = child._pos.y;
                child._mat.m14 = child._pos.z;
              }
              if (dirtyBits & TransformBit.RS) {
                if (dirtyBits & TransformBit.ROTATION) {
                  Quat.copy(child._rot, child._lrot);
                }
                if (dirtyBits & TransformBit.SCALE) {
                  Vec3.copy(child._scale, child._lscale);
                }
                Mat4.fromRTS(child._mat, child._rot, child._pos, child._scale);
              }
            }
            child._transformFlags = TransformBit.NONE;
            cur = child;
          }
        };
        _proto.setPosition = function setPosition(val, y, z) {
          if (y === undefined && z === undefined) {
            Vec3.copy(this._lpos, val);
          } else if (z === undefined) {
            Vec3.set(this._lpos, val, y, this._lpos.z);
          } else {
            Vec3.set(this._lpos, val, y, z);
          }
          this.invalidateChildren(TransformBit.POSITION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
          }
        };
        _proto.getPosition = function getPosition(out) {
          if (out) {
            return Vec3.set(out, this._lpos.x, this._lpos.y, this._lpos.z);
          }
          return Vec3.copy(new Vec3(), this._lpos);
        };
        _proto.setRotation = function setRotation(val, y, z, w) {
          if (y === undefined || z === undefined || w === undefined) {
            Quat.copy(this._lrot, val);
          } else {
            Quat.set(this._lrot, val, y, z, w);
          }
          this._eulerDirty = true;
          this.invalidateChildren(TransformBit.ROTATION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
          }
        };
        _proto.setRotationFromEuler = function setRotationFromEuler(val, y, zOpt) {
          var z = zOpt === undefined ? this._euler.z : zOpt;
          if (y === undefined) {
            Vec3.copy(this._euler, val);
            Quat.fromEuler(this._lrot, val.x, val.y, val.z);
          } else {
            Vec3.set(this._euler, val, y, z);
            Quat.fromEuler(this._lrot, val, y, z);
          }
          this._eulerDirty = false;
          this.invalidateChildren(TransformBit.ROTATION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
          }
        };
        _proto.getRotation = function getRotation(out) {
          if (out) {
            return Quat.set(out, this._lrot.x, this._lrot.y, this._lrot.z, this._lrot.w);
          }
          return Quat.copy(new Quat(), this._lrot);
        };
        _proto.setScale = function setScale(val, y, z) {
          if (y === undefined && z === undefined) {
            Vec3.copy(this._lscale, val);
          } else if (z === undefined) {
            Vec3.set(this._lscale, val, y, this._lscale.z);
          } else {
            Vec3.set(this._lscale, val, y, z);
          }
          this.invalidateChildren(TransformBit.SCALE);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.SCALE);
          }
        };
        _proto.getScale = function getScale(out) {
          if (out) {
            return Vec3.set(out, this._lscale.x, this._lscale.y, this._lscale.z);
          }
          return Vec3.copy(new Vec3(), this._lscale);
        };
        _proto.inverseTransformPoint = function inverseTransformPoint(out, p) {
          Vec3.copy(out, p);
          var cur = this;
          var i = 0;
          while (cur._parent) {
            dirtyNodes[i++] = cur;
            cur = cur._parent;
          }
          while (i >= 0) {
            Vec3.transformInverseRTS(out, out, cur._lrot, cur._lpos, cur._lscale);
            cur = dirtyNodes[--i];
          }
          return out;
        };
        _proto.setWorldPosition = function setWorldPosition(val, y, z) {
          if (y === undefined || z === undefined) {
            Vec3.copy(this._pos, val);
          } else {
            Vec3.set(this._pos, val, y, z);
          }
          var parent = this._parent;
          var local = this._lpos;
          if (parent) {
            parent.updateWorldTransform();
            Vec3.transformMat4(local, this._pos, Mat4.invert(m4_1$7, parent._mat));
          } else {
            Vec3.copy(local, this._pos);
          }
          this.invalidateChildren(TransformBit.POSITION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
          }
        };
        _proto.getWorldPosition = function getWorldPosition(out) {
          this.updateWorldTransform();
          if (out) {
            return Vec3.copy(out, this._pos);
          }
          return Vec3.copy(new Vec3(), this._pos);
        };
        _proto.setWorldRotation = function setWorldRotation(val, y, z, w) {
          if (y === undefined || z === undefined || w === undefined) {
            Quat.copy(this._rot, val);
          } else {
            Quat.set(this._rot, val, y, z, w);
          }
          if (this._parent) {
            this._parent.updateWorldTransform();
            Quat.multiply(this._lrot, Quat.conjugate(this._lrot, this._parent._rot), this._rot);
          } else {
            Quat.copy(this._lrot, this._rot);
          }
          this._eulerDirty = true;
          this.invalidateChildren(TransformBit.ROTATION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
          }
        };
        _proto.setWorldRotationFromEuler = function setWorldRotationFromEuler(x, y, z) {
          Quat.fromEuler(this._rot, x, y, z);
          if (this._parent) {
            this._parent.updateWorldTransform();
            Quat.multiply(this._lrot, Quat.conjugate(this._lrot, this._parent._rot), this._rot);
          } else {
            Quat.copy(this._lrot, this._rot);
          }
          this._eulerDirty = true;
          this.invalidateChildren(TransformBit.ROTATION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
          }
        };
        _proto.getWorldRotation = function getWorldRotation(out) {
          this.updateWorldTransform();
          if (out) {
            return Quat.copy(out, this._rot);
          }
          return Quat.copy(new Quat(), this._rot);
        };
        _proto.setWorldScale = function setWorldScale(val, y, z) {
          var parent = this._parent;
          if (parent) {
            this.updateWorldTransform();
          }
          if (y === undefined || z === undefined) {
            Vec3.copy(this._scale, val);
          } else {
            Vec3.set(this._scale, val, y, z);
          }
          if (parent) {
            v3_a.x = this._scale.x / Vec3.set(v3_b, this._mat.m00, this._mat.m01, this._mat.m02).length();
            v3_a.y = this._scale.y / Vec3.set(v3_b, this._mat.m04, this._mat.m05, this._mat.m06).length();
            v3_a.z = this._scale.z / Vec3.set(v3_b, this._mat.m08, this._mat.m09, this._mat.m10).length();
            Mat4.scale(m4_1$7, this._mat, v3_a);
            Mat4.multiply(m4_2$3, Mat4.invert(m4_2$3, parent._mat), m4_1$7);
            Mat3.fromQuat(m3_1, Quat.conjugate(qt_1, this._lrot));
            Mat3.multiplyMat4(m3_1, m3_1, m4_2$3);
            this._lscale.x = Vec3.set(v3_a, m3_1.m00, m3_1.m01, m3_1.m02).length();
            this._lscale.y = Vec3.set(v3_a, m3_1.m03, m3_1.m04, m3_1.m05).length();
            this._lscale.z = Vec3.set(v3_a, m3_1.m06, m3_1.m07, m3_1.m08).length();
          } else {
            Vec3.copy(this._lscale, this._scale);
          }
          this.invalidateChildren(TransformBit.SCALE);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.SCALE);
          }
        };
        _proto.getWorldScale = function getWorldScale(out) {
          this.updateWorldTransform();
          if (out) {
            return Vec3.copy(out, this._scale);
          }
          return Vec3.copy(new Vec3(), this._scale);
        };
        _proto.getWorldMatrix = function getWorldMatrix(out) {
          this.updateWorldTransform();
          var target = out || new Mat4();
          return Mat4.copy(target, this._mat);
        };
        _proto.getWorldRS = function getWorldRS(out) {
          this.updateWorldTransform();
          var target = out || new Mat4();
          Mat4.copy(target, this._mat);
          target.m12 = 0;
          target.m13 = 0;
          target.m14 = 0;
          return target;
        };
        _proto.getWorldRT = function getWorldRT(out) {
          this.updateWorldTransform();
          var target = out || new Mat4();
          return Mat4.fromRT(target, this._rot, this._pos);
        };
        _proto.setRTS = function setRTS(rot, pos, scale) {
          var dirtyBit = 0;
          if (rot) {
            dirtyBit |= TransformBit.ROTATION;
            if (rot.w !== undefined) {
              Quat.copy(this._lrot, rot);
              this._eulerDirty = true;
            } else {
              Vec3.copy(this._euler, rot);
              Quat.fromEuler(this._lrot, rot.x, rot.y, rot.z);
              this._eulerDirty = false;
            }
          }
          if (pos) {
            Vec3.copy(this._lpos, pos);
            dirtyBit |= TransformBit.POSITION;
          }
          if (scale) {
            Vec3.copy(this._lscale, scale);
            dirtyBit |= TransformBit.SCALE;
          }
          if (dirtyBit) {
            this.invalidateChildren(dirtyBit);
            if (this._eventMask & TRANSFORM_ON) {
              this.emit(NodeEventType.TRANSFORM_CHANGED, dirtyBit);
            }
          }
        };
        _proto.isTransformDirty = function isTransformDirty() {
          return this._transformFlags !== TransformBit.NONE;
        };
        _proto.pauseSystemEvents = function pauseSystemEvents(recursive) {
          this._eventProcessor.setEnabled(false, recursive);
        };
        _proto.resumeSystemEvents = function resumeSystemEvents(recursive) {
          this._eventProcessor.setEnabled(true, recursive);
        };
        Node.resetHasChangedFlags = function resetHasChangedFlags() {
          globalFlagChangeVersion += 1;
        };
        Node.clearNodeArray = function clearNodeArray() {
          if (Node.ClearFrame < Node.ClearRound && !EDITOR) {
            Node.ClearFrame++;
          } else {
            Node.ClearFrame = 0;
            dirtyNodes.length = 0;
          }
        };
        _proto.getPathInHierarchy = function getPathInHierarchy() {
          var result = this.name;
          var curNode = this.parent;
          while (curNode && !(curNode instanceof legacyCC.Scene)) {
            result = curNode.name + "/" + result;
            curNode = curNode.parent;
          }
          return result;
        };
        _createClass(Node, [{
          key: "components",
          get: function get() {
            return this._components;
          }
        }, {
          key: "_persistNode",
          get: function get() {
            return (this._objFlags & DontDestroy) > 0;
          },
          set: function set(value) {
            if (value) {
              this._objFlags |= DontDestroy;
            } else {
              this._objFlags &= ~DontDestroy;
            }
          }
        }, {
          key: "name",
          get: function get() {
            return this._name;
          },
          set: function set(value) {
            this._name = value;
          }
        }, {
          key: "uuid",
          get: function get() {
            return this._id;
          }
        }, {
          key: "children",
          get: function get() {
            return this._children;
          }
        }, {
          key: "active",
          get: function get() {
            return this._active;
          },
          set: function set(isActive) {
            isActive = !!isActive;
            if (this._active !== isActive) {
              this._active = isActive;
              var parent = this._parent;
              if (parent) {
                var couldActiveInScene = parent._activeInHierarchy;
                if (couldActiveInScene) {
                  legacyCC.director._nodeActivator.activateNode(this, isActive);
                }
              }
            }
          }
        }, {
          key: "activeInHierarchy",
          get: function get() {
            return this._activeInHierarchy;
          }
        }, {
          key: "parent",
          get: function get() {
            return this._parent;
          },
          set: function set(value) {
            this.setParent(value);
          }
        }, {
          key: "scene",
          get: function get() {
            return this._scene;
          }
        }, {
          key: "eventProcessor",
          get: function get() {
            return this._eventProcessor;
          }
        }, {
          key: "prefab",
          get: function get() {
            return this._prefab;
          }
        }, {
          key: "id",
          set: function set(v) {
            this._id = v;
          }
        }, {
          key: "siblingIndex",
          get: function get() {
            return this._siblingIndex;
          },
          set: function set(val) {
            this._siblingIndex = val;
          }
        }, {
          key: "position",
          get: function get() {
            return this._lpos;
          },
          set: function set(val) {
            this.setPosition(val);
          }
        }, {
          key: "worldPosition",
          get: function get() {
            this.updateWorldTransform();
            return this._pos;
          },
          set: function set(val) {
            this.setWorldPosition(val);
          }
        }, {
          key: "rotation",
          get: function get() {
            return this._lrot;
          },
          set: function set(val) {
            this.setRotation(val);
          }
        }, {
          key: "eulerAngles",
          get: function get() {
            if (this._eulerDirty) {
              Quat.toEuler(this._euler, this._lrot);
              this._eulerDirty = false;
            }
            return this._euler;
          },
          set: function set(val) {
            this.setRotationFromEuler(val.x, val.y, val.z);
          }
        }, {
          key: "angle",
          get: function get() {
            return this._euler.z;
          },
          set: function set(val) {
            Vec3.set(this._euler, 0, 0, val);
            Quat.fromAngleZ(this._lrot, val);
            this._eulerDirty = false;
            this.invalidateChildren(TransformBit.ROTATION);
            if (this._eventMask & TRANSFORM_ON) {
              this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
            }
          }
        }, {
          key: "worldRotation",
          get: function get() {
            this.updateWorldTransform();
            return this._rot;
          },
          set: function set(val) {
            this.setWorldRotation(val);
          }
        }, {
          key: "scale",
          get: function get() {
            return this._lscale;
          },
          set: function set(val) {
            this.setScale(val);
          }
        }, {
          key: "worldScale",
          get: function get() {
            this.updateWorldTransform();
            return this._scale;
          },
          set: function set(val) {
            this.setWorldScale(val);
          }
        }, {
          key: "matrix",
          set: function set(val) {
            Mat4.toRTS(val, this._lrot, this._lpos, this._lscale);
            this.invalidateChildren(TransformBit.TRS);
            this._eulerDirty = true;
            if (this._eventMask & TRANSFORM_ON) {
              this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.TRS);
            }
          }
        }, {
          key: "worldMatrix",
          get: function get() {
            this.updateWorldTransform();
            return this._mat;
          }
        }, {
          key: "forward",
          get: function get() {
            return Vec3.transformQuat(new Vec3(), Vec3.FORWARD, this.worldRotation);
          },
          set: function set(dir) {
            var len = dir.length();
            Vec3.multiplyScalar(v3_a, dir, -1 / len);
            Quat.fromViewUp(q_a, v3_a);
            this.setWorldRotation(q_a);
          }
        }, {
          key: "up",
          get: function get() {
            return Vec3.transformQuat(new Vec3(), Vec3.UP, this.worldRotation);
          }
        }, {
          key: "right",
          get: function get() {
            return Vec3.transformQuat(new Vec3(), Vec3.RIGHT, this.worldRotation);
          }
        }, {
          key: "mobility",
          get: function get() {
            return this._mobility;
          },
          set: function set(m) {
            this._mobility = m;
            this.emit(NodeEventType.MOBILITY_CHANGED);
          }
        }, {
          key: "layer",
          get: function get() {
            return this._layer;
          },
          set: function set(l) {
            this._layer = l;
            if (this._uiProps && this._uiProps.uiComp) {
              this._uiProps.uiComp.setNodeDirty();
              this._uiProps.uiComp.markForUpdateRenderData();
            }
            this.emit(NodeEventType.LAYER_CHANGED, this._layer);
          }
        }, {
          key: "flagChangedVersion",
          get: function get() {
            return this._flagChangeVersion;
          }
        }, {
          key: "hasChangedFlags",
          get: function get() {
            return this._flagChangeVersion === globalFlagChangeVersion ? this._hasChangedFlags : 0;
          },
          set: function set(val) {
            this._flagChangeVersion = globalFlagChangeVersion;
            this._hasChangedFlags = val;
          }
        }]);
        return Node;
      }(CCObject), _class3$X.idGenerator = idGenerator, _class3$X._stacks = [[]], _class3$X._stackId = 0, _class3$X.EventType = NodeEventType, _class3$X.NodeSpace = NodeSpace, _class3$X.TransformDirtyBit = TransformBit, _class3$X.TransformBit = TransformBit, _class3$X.reserveContentsForAllSyncablePrefabTag = reserveContentsForAllSyncablePrefabTag, _class3$X.ClearFrame = 0, _class3$X.ClearRound = 1000, _class3$X), (_applyDecoratedDescriptor(_class2$38.prototype, "_persistNode", [property$3], Object.getOwnPropertyDescriptor(_class2$38.prototype, "_persistNode"), _class2$38.prototype), _initializer$2T = applyDecoratedInitializer(_class2$38.prototype, "_parent", [serializable$p], function () {
        return null;
      }), _initializer2$2j = applyDecoratedInitializer(_class2$38.prototype, "_children", [serializable$p], function () {
        return [];
      }), _initializer3$1I = applyDecoratedInitializer(_class2$38.prototype, "_active", [serializable$p], function () {
        return true;
      }), _initializer4$1s = applyDecoratedInitializer(_class2$38.prototype, "_components", [serializable$p], function () {
        return [];
      }), _initializer5$17 = applyDecoratedInitializer(_class2$38.prototype, "_prefab", [serializable$p], function () {
        return null;
      }), _initializer6$W = applyDecoratedInitializer(_class2$38.prototype, "_lpos", [serializable$p], function () {
        return new Vec3();
      }), _initializer7$K = applyDecoratedInitializer(_class2$38.prototype, "_lrot", [serializable$p], function () {
        return new Quat();
      }), _initializer8$G = applyDecoratedInitializer(_class2$38.prototype, "_lscale", [serializable$p], function () {
        return new Vec3(1, 1, 1);
      }), _initializer9$B = applyDecoratedInitializer(_class2$38.prototype, "_mobility", [serializable$p], function () {
        return MobilityMode.Static;
      }), _initializer10$y = applyDecoratedInitializer(_class2$38.prototype, "_layer", [serializable$p], function () {
        return Layers.Enum.DEFAULT;
      }), _initializer11$w = applyDecoratedInitializer(_class2$38.prototype, "_euler", [serializable$p], function () {
        return new Vec3();
      }), _applyDecoratedDescriptor(_class2$38.prototype, "eulerAngles", [_dec2$2x], Object.getOwnPropertyDescriptor(_class2$38.prototype, "eulerAngles"), _class2$38.prototype), _applyDecoratedDescriptor(_class2$38.prototype, "mobility", [_dec3$1M], Object.getOwnPropertyDescriptor(_class2$38.prototype, "mobility"), _class2$38.prototype)), _class2$38)) || _class$3t));
      legacyCC.Node = Node$1;

      var _dec$3w, _class$3s, _class2$37, _initializer$2S, _initializer2$2i, _initializer3$1H, _initializer4$1r, _class3$W;
      var FaceIndex;
      (function (FaceIndex) {
        FaceIndex[FaceIndex["right"] = 0] = "right";
        FaceIndex[FaceIndex["left"] = 1] = "left";
        FaceIndex[FaceIndex["top"] = 2] = "top";
        FaceIndex[FaceIndex["bottom"] = 3] = "bottom";
        FaceIndex[FaceIndex["front"] = 4] = "front";
        FaceIndex[FaceIndex["back"] = 5] = "back";
      })(FaceIndex || (FaceIndex = {}));
      var MipmapMode;
      (function (MipmapMode) {
        MipmapMode[MipmapMode["NONE"] = 0] = "NONE";
        MipmapMode[MipmapMode["AUTO"] = 1] = "AUTO";
        MipmapMode[MipmapMode["BAKED_CONVOLUTION_MAP"] = 2] = "BAKED_CONVOLUTION_MAP";
      })(MipmapMode || (MipmapMode = {}));
      var TextureCube = exports('ej', (_dec$3w = ccclass$M('cc.TextureCube'), _dec$3w(_class$3s = (_class2$37 = (_class3$W = function (_SimpleTexture) {
        _inheritsLoose(TextureCube, _SimpleTexture);
        function TextureCube() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _SimpleTexture.call.apply(_SimpleTexture, [this].concat(args)) || this;
          _this.isRGBE = _initializer$2S && _initializer$2S();
          _this._mipmapAtlas = _initializer2$2i && _initializer2$2i();
          _this._mipmapMode = _initializer3$1H && _initializer3$1H();
          _this._mipmaps = _initializer4$1r && _initializer4$1r();
          _this._generatedMipmaps = [];
          return _this;
        }
        var _proto = TextureCube.prototype;
        _proto._setMipmapParams = function _setMipmapParams(value) {
          var _this2 = this;
          this._generatedMipmaps = value;
          this._setMipmapLevel(this._generatedMipmaps.length);
          if (this._generatedMipmaps.length > 0) {
            var imageAsset = this._generatedMipmaps[0].front;
            this.reset({
              width: imageAsset.width,
              height: imageAsset.height,
              format: imageAsset.format,
              mipmapLevel: this._generatedMipmaps.length,
              baseLevel: this._baseLevel,
              maxLevel: this._maxLevel
            });
            this._generatedMipmaps.forEach(function (mipmap, level) {
              _forEachFace(mipmap, function (face, faceIndex) {
                _this2._assignImage(face, level, faceIndex);
              });
            });
          } else {
            this.reset({
              width: 0,
              height: 0,
              mipmapLevel: this._generatedMipmaps.length,
              baseLevel: this._baseLevel,
              maxLevel: this._maxLevel
            });
          }
        };
        _proto.isUsingOfflineMipmaps = function isUsingOfflineMipmaps() {
          return this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP;
        };
        TextureCube.fromTexture2DArray = function fromTexture2DArray(textures, out) {
          var mipmaps = [];
          var nMipmaps = textures.length / 6;
          for (var i = 0; i < nMipmaps; i++) {
            var x = i * 6;
            mipmaps.push({
              front: textures[x + FaceIndex.front].image,
              back: textures[x + FaceIndex.back].image,
              left: textures[x + FaceIndex.left].image,
              right: textures[x + FaceIndex.right].image,
              top: textures[x + FaceIndex.top].image,
              bottom: textures[x + FaceIndex.bottom].image
            });
          }
          out = out || new TextureCube();
          out.mipmaps = mipmaps;
          return out;
        };
        _proto.onLoaded = function onLoaded() {
          if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) {
            this.mipmapAtlas = this._mipmapAtlas;
          } else {
            this.mipmaps = this._mipmaps;
          }
        };
        _proto.reset = function reset(info) {
          this._width = info.width;
          this._height = info.height;
          this._setGFXFormat(info.format);
          var mipLevels = info.mipmapLevel === undefined ? 1 : info.mipmapLevel;
          this._setMipmapLevel(mipLevels);
          var minLod = info.baseLevel === undefined ? 0 : info.baseLevel;
          var maxLod = info.maxLevel === undefined ? 1000 : info.maxLevel;
          this._setMipRange(minLod, maxLod);
          this._tryReset();
        };
        _proto.updateMipmaps = function updateMipmaps(firstLevel, count) {
          var _this3 = this;
          if (firstLevel === void 0) {
            firstLevel = 0;
          }
          if (firstLevel >= this._generatedMipmaps.length) {
            return;
          }
          var nUpdate = Math.min(count === undefined ? this._generatedMipmaps.length : count, this._generatedMipmaps.length - firstLevel);
          var _loop = function _loop() {
            var level = firstLevel + i;
            _forEachFace(_this3._generatedMipmaps[level], function (face, faceIndex) {
              _this3._assignImage(face, level, faceIndex);
            });
          };
          for (var i = 0; i < nUpdate; ++i) {
            _loop();
          }
        };
        _proto.destroy = function destroy() {
          this._mipmaps = [];
          this._generatedMipmaps = [];
          this._mipmapAtlas = null;
          return _SimpleTexture.prototype.destroy.call(this);
        };
        _proto.releaseTexture = function releaseTexture() {
          this.destroy();
        };
        _proto._serialize = function _serialize(ctxForExporting) {
          return null;
        };
        _proto._deserialize = function _deserialize(serializedData, handle) {
          var data = serializedData;
          _SimpleTexture.prototype._deserialize.call(this, data.base, handle);
          this.isRGBE = data.rgbe;
          this._mipmapMode = data.mipmapMode;
          if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) {
            var mipmapAtlas = data.mipmapAtlas;
            var mipmapLayout = data.mipmapLayout;
            this._mipmapAtlas = {
              atlas: {},
              layout: mipmapLayout
            };
            this._mipmapAtlas.atlas = {
              front: new ImageAsset(),
              back: new ImageAsset(),
              left: new ImageAsset(),
              right: new ImageAsset(),
              top: new ImageAsset(),
              bottom: new ImageAsset()
            };
            var imageAssetClassId = getClassId(ImageAsset);
            handle.result.push(this._mipmapAtlas.atlas, "front", mipmapAtlas.front, imageAssetClassId);
            handle.result.push(this._mipmapAtlas.atlas, "back", mipmapAtlas.back, imageAssetClassId);
            handle.result.push(this._mipmapAtlas.atlas, "left", mipmapAtlas.left, imageAssetClassId);
            handle.result.push(this._mipmapAtlas.atlas, "right", mipmapAtlas.right, imageAssetClassId);
            handle.result.push(this._mipmapAtlas.atlas, "top", mipmapAtlas.top, imageAssetClassId);
            handle.result.push(this._mipmapAtlas.atlas, "bottom", mipmapAtlas.bottom, imageAssetClassId);
          } else {
            this._mipmaps = new Array(data.mipmaps.length);
            for (var i = 0; i < data.mipmaps.length; ++i) {
              this._mipmaps[i] = {
                front: new ImageAsset(),
                back: new ImageAsset(),
                left: new ImageAsset(),
                right: new ImageAsset(),
                top: new ImageAsset(),
                bottom: new ImageAsset()
              };
              var mipmap = data.mipmaps[i];
              var _imageAssetClassId = getClassId(ImageAsset);
              handle.result.push(this._mipmaps[i], "front", mipmap.front, _imageAssetClassId);
              handle.result.push(this._mipmaps[i], "back", mipmap.back, _imageAssetClassId);
              handle.result.push(this._mipmaps[i], "left", mipmap.left, _imageAssetClassId);
              handle.result.push(this._mipmaps[i], "right", mipmap.right, _imageAssetClassId);
              handle.result.push(this._mipmaps[i], "top", mipmap.top, _imageAssetClassId);
              handle.result.push(this._mipmaps[i], "bottom", mipmap.bottom, _imageAssetClassId);
            }
          }
        };
        _proto._getGfxTextureCreateInfo = function _getGfxTextureCreateInfo(presumed) {
          var texInfo = new TextureInfo(TextureType.CUBE);
          texInfo.width = this._width;
          texInfo.height = this._height;
          texInfo.layerCount = 6;
          Object.assign(texInfo, presumed);
          return texInfo;
        };
        _proto._getGfxTextureViewCreateInfo = function _getGfxTextureViewCreateInfo(presumed) {
          var texViewInfo = new TextureViewInfo();
          texViewInfo.type = TextureType.CUBE;
          texViewInfo.baseLayer = 0;
          texViewInfo.layerCount = 6;
          Object.assign(texViewInfo, presumed);
          return texViewInfo;
        };
        _proto._uploadAtlas = function _uploadAtlas() {
          var _this4 = this;
          var layout = this._mipmapAtlas.layout;
          var mip0Layout = layout[0];
          this.reset({
            width: mip0Layout.width,
            height: mip0Layout.height,
            format: this._mipmapAtlas.atlas.front.format,
            mipmapLevel: layout.length
          });
          _forEachFace(this._mipmapAtlas.atlas, function (face, faceIndex) {
            var tex = new Texture2D();
            tex.image = face;
            tex.reset({
              width: face.width,
              height: face.height,
              format: face.format
            });
            tex.uploadData(face.data);
            for (var i = 0; i < layout.length; i++) {
              var layoutInfo = layout[i];
              var size = tex.getGFXTexture().size;
              var buffer = new Uint8Array(size);
              var region = new BufferTextureCopy();
              region.texOffset.x = layoutInfo.left;
              region.texOffset.y = layoutInfo.top;
              region.texExtent.width = layoutInfo.width;
              region.texExtent.height = layoutInfo.height;
              _this4._getGFXDevice().copyTextureToBuffers(tex.getGFXTexture(), [buffer], [region]);
              var bufferAsset = new ImageAsset({
                _data: buffer,
                _compressed: face.isCompressed,
                width: layoutInfo.width,
                height: layoutInfo.height,
                format: face.format
              });
              _this4._assignImage(bufferAsset, layoutInfo.level, faceIndex);
            }
          });
        };
        _proto.initDefault = function initDefault(uuid) {
          _SimpleTexture.prototype.initDefault.call(this, uuid);
          var imageAsset = new ImageAsset();
          imageAsset.initDefault();
          this.mipmaps = [{
            front: imageAsset,
            back: imageAsset,
            top: imageAsset,
            bottom: imageAsset,
            left: imageAsset,
            right: imageAsset
          }];
        };
        _proto.validate = function validate() {
          if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) {
            if (this.mipmapAtlas === null || this.mipmapAtlas.layout.length === 0) {
              return false;
            }
            var atlas = this.mipmapAtlas.atlas;
            return !!(atlas.top && atlas.bottom && atlas.front && atlas.back && atlas.left && atlas.right);
          } else {
            return this._mipmaps.length !== 0 && !this._mipmaps.find(function (x) {
              return !(x.top && x.bottom && x.front && x.back && x.left && x.right);
            });
          }
        };
        _createClass(TextureCube, [{
          key: "mipmaps",
          get: function get() {
            return this._mipmaps;
          },
          set: function set(value) {
            this._mipmaps = value;
            var cubeMaps = [];
            if (value.length === 1) {
              var cubeMipmap = value[0];
              var front = cubeMipmap.front.extractMipmaps();
              var back = cubeMipmap.back.extractMipmaps();
              var left = cubeMipmap.left.extractMipmaps();
              var right = cubeMipmap.right.extractMipmaps();
              var top = cubeMipmap.top.extractMipmaps();
              var bottom = cubeMipmap.bottom.extractMipmaps();
              if (front.length !== back.length || front.length !== left.length || front.length !== right.length || front.length !== top.length || front.length !== bottom.length) {
                console.error('The number of mipmaps of each face is different.');
                this._setMipmapParams([]);
                return;
              }
              var level = front.length;
              for (var i = 0; i < level; ++i) {
                var cubeMap = {
                  front: front[i],
                  back: back[i],
                  left: left[i],
                  right: right[i],
                  top: top[i],
                  bottom: bottom[i]
                };
                cubeMaps.push(cubeMap);
              }
            } else if (value.length > 1) {
              value.forEach(function (mipmap) {
                var cubeMap = {
                  front: mipmap.front.extractMipmap0(),
                  back: mipmap.back.extractMipmap0(),
                  left: mipmap.left.extractMipmap0(),
                  right: mipmap.right.extractMipmap0(),
                  top: mipmap.top.extractMipmap0(),
                  bottom: mipmap.bottom.extractMipmap0()
                };
                cubeMaps.push(cubeMap);
              });
            }
            this._setMipmapParams(cubeMaps);
          }
        }, {
          key: "mipmapAtlas",
          get: function get() {
            return this._mipmapAtlas;
          },
          set: function set(value) {
            var _this5 = this;
            this._mipmapAtlas = value;
            if (!this._mipmapAtlas) {
              this.reset({
                width: 0,
                height: 0,
                mipmapLevel: 0
              });
              return;
            }
            var imageAtlasAsset = this._mipmapAtlas.atlas.front;
            if (!imageAtlasAsset.data) {
              return;
            }
            var faceAtlas = this._mipmapAtlas.atlas;
            var layout = this._mipmapAtlas.layout;
            var mip0Layout = layout[0];
            var ctx = Object.assign(ccwindow.document.createElement('canvas'), {
              width: imageAtlasAsset.width,
              height: imageAtlasAsset.height
            }).getContext('2d');
            this.reset({
              width: mip0Layout.width,
              height: mip0Layout.height,
              format: imageAtlasAsset.format,
              mipmapLevel: layout.length
            });
            var _loop2 = function _loop2() {
              var layoutInfo = layout[j];
              _forEachFace(faceAtlas, function (face, faceIndex) {
                ctx.clearRect(0, 0, imageAtlasAsset.width, imageAtlasAsset.height);
                var drawImg = face.data;
                ctx.drawImage(drawImg, 0, 0);
                var rawData = ctx.getImageData(layoutInfo.left, layoutInfo.top, layoutInfo.width, layoutInfo.height);
                var bufferAsset = new ImageAsset({
                  _data: rawData.data,
                  _compressed: face.isCompressed,
                  width: rawData.width,
                  height: rawData.height,
                  format: face.format
                });
                _this5._assignImage(bufferAsset, layoutInfo.level, faceIndex);
              });
            };
            for (var j = 0; j < layout.length; j++) {
              _loop2();
            }
          }
        }, {
          key: "image",
          get: function get() {
            return this._mipmaps.length === 0 ? null : this._mipmaps[0];
          },
          set: function set(value) {
            this.mipmaps = value ? [value] : [];
          }
        }]);
        return TextureCube;
      }(SimpleTexture), _class3$W.FaceIndex = FaceIndex, _class3$W), (_initializer$2S = applyDecoratedInitializer(_class2$37.prototype, "isRGBE", [serializable$p], function () {
        return false;
      }), _initializer2$2i = applyDecoratedInitializer(_class2$37.prototype, "_mipmapAtlas", [serializable$p], function () {
        return null;
      }), _initializer3$1H = applyDecoratedInitializer(_class2$37.prototype, "_mipmapMode", [serializable$p], function () {
        return MipmapMode.NONE;
      }), _initializer4$1r = applyDecoratedInitializer(_class2$37.prototype, "_mipmaps", [serializable$p], function () {
        return [];
      })), _class2$37)) || _class$3s));
      legacyCC.TextureCube = TextureCube;
      function _forEachFace(mipmap, callback) {
        callback(mipmap.front, FaceIndex.front);
        callback(mipmap.back, FaceIndex.back);
        callback(mipmap.left, FaceIndex.left);
        callback(mipmap.right, FaceIndex.right);
        callback(mipmap.top, FaceIndex.top);
        callback(mipmap.bottom, FaceIndex.bottom);
      }

      var Ambient = function () {
        function Ambient() {
          this._groundAlbedoHDR = new Vec4(0.2, 0.2, 0.2, 1.0);
          this._skyColorHDR = new Vec4(0.2, 0.5, 0.8, 1.0);
          this._skyIllumHDR = 0;
          this._groundAlbedoLDR = new Vec4(0.2, 0.2, 0.2, 1.0);
          this._skyColorLDR = new Vec4(0.2, 0.5, 0.8, 1.0);
          this._skyIllumLDR = 0;
          this._mipmapCount = 1;
          this._enabled = false;
        }
        var _proto = Ambient.prototype;
        _proto.initialize = function initialize(ambientInfo) {
          this._skyColorHDR = ambientInfo.skyColorHDR;
          this._groundAlbedoHDR.set(ambientInfo.groundAlbedoHDR);
          this._skyIllumHDR = ambientInfo.skyIllumHDR;
          this._skyColorLDR = ambientInfo.skyColorLDR;
          this._groundAlbedoLDR.set(ambientInfo.groundAlbedoLDR);
          this._skyIllumLDR = ambientInfo.skyIllumLDR;
        };
        _createClass(Ambient, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }, {
          key: "skyColor",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._skyColorHDR;
            } else {
              return this._skyColorLDR;
            }
          },
          set: function set(color) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._skyColorHDR.set(color);
            } else {
              this._skyColorLDR.set(color);
            }
          }
        }, {
          key: "skyIllum",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._skyIllumHDR;
            } else {
              return this._skyIllumLDR;
            }
          },
          set: function set(illum) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._skyIllumHDR = illum;
            } else {
              this._skyIllumLDR = illum;
            }
          }
        }, {
          key: "groundAlbedo",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._groundAlbedoHDR;
            } else {
              return this._groundAlbedoLDR;
            }
          },
          set: function set(color) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._groundAlbedoHDR.set(color);
            } else {
              this._groundAlbedoLDR.set(color);
            }
          }
        }]);
        return Ambient;
      }();
      Ambient.SUN_ILLUM = 65000.0;
      Ambient.SKY_ILLUM = 20000.0;
      legacyCC.Ambient = Ambient;

      var _class$3r, _class2$36, _class3$V, _class4$y, _class5$y, _class6$a, _class7$b, _class8$c, _class10$7, _class11$8, _class12$4, _class13$7, _class14$6, _class15$1;
      var PIPELINE_FLOW_MAIN = 'MainFlow';
      var PIPELINE_FLOW_FORWARD = 'ForwardFlow';
      var PIPELINE_FLOW_SHADOW = 'ShadowFlow';
      var PIPELINE_FLOW_SMAA = 'SMAAFlow';
      var PIPELINE_FLOW_TONEMAP = 'ToneMapFlow';
      var RenderPassStage;
      (function (RenderPassStage) {
        RenderPassStage[RenderPassStage["DEFAULT"] = 100] = "DEFAULT";
        RenderPassStage[RenderPassStage["UI"] = 200] = "UI";
      })(RenderPassStage || (RenderPassStage = {}));
      legacyCC.RenderPassStage = RenderPassStage;
      var RenderPriority;
      (function (RenderPriority) {
        RenderPriority[RenderPriority["MIN"] = 0] = "MIN";
        RenderPriority[RenderPriority["MAX"] = 255] = "MAX";
        RenderPriority[RenderPriority["DEFAULT"] = 128] = "DEFAULT";
      })(RenderPriority || (RenderPriority = {}));
      var globalDescriptorSetLayout = {
        bindings: [],
        layouts: {}
      };
      var localDescriptorSetLayout = {
        bindings: [],
        layouts: {}
      };
      var PipelineGlobalBindings;
      (function (PipelineGlobalBindings) {
        PipelineGlobalBindings[PipelineGlobalBindings["UBO_GLOBAL"] = 0] = "UBO_GLOBAL";
        PipelineGlobalBindings[PipelineGlobalBindings["UBO_CAMERA"] = 1] = "UBO_CAMERA";
        PipelineGlobalBindings[PipelineGlobalBindings["UBO_SHADOW"] = 2] = "UBO_SHADOW";
        PipelineGlobalBindings[PipelineGlobalBindings["UBO_CSM"] = 3] = "UBO_CSM";
        PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_SHADOWMAP"] = 4] = "SAMPLER_SHADOWMAP";
        PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_ENVIRONMENT"] = 5] = "SAMPLER_ENVIRONMENT";
        PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_SPOT_SHADOW_MAP"] = 6] = "SAMPLER_SPOT_SHADOW_MAP";
        PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_DIFFUSEMAP"] = 7] = "SAMPLER_DIFFUSEMAP";
        PipelineGlobalBindings[PipelineGlobalBindings["COUNT"] = 8] = "COUNT";
      })(PipelineGlobalBindings || (PipelineGlobalBindings = {}));
      var GLOBAL_UBO_COUNT = PipelineGlobalBindings.SAMPLER_SHADOWMAP;
      var GLOBAL_SAMPLER_COUNT = PipelineGlobalBindings.COUNT - GLOBAL_UBO_COUNT;
      var ModelLocalBindings;
      (function (ModelLocalBindings) {
        ModelLocalBindings[ModelLocalBindings["UBO_LOCAL"] = 0] = "UBO_LOCAL";
        ModelLocalBindings[ModelLocalBindings["UBO_FORWARD_LIGHTS"] = 1] = "UBO_FORWARD_LIGHTS";
        ModelLocalBindings[ModelLocalBindings["UBO_SKINNING_ANIMATION"] = 2] = "UBO_SKINNING_ANIMATION";
        ModelLocalBindings[ModelLocalBindings["UBO_SKINNING_TEXTURE"] = 3] = "UBO_SKINNING_TEXTURE";
        ModelLocalBindings[ModelLocalBindings["UBO_MORPH"] = 4] = "UBO_MORPH";
        ModelLocalBindings[ModelLocalBindings["UBO_UI_LOCAL"] = 5] = "UBO_UI_LOCAL";
        ModelLocalBindings[ModelLocalBindings["UBO_SH"] = 6] = "UBO_SH";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_JOINTS"] = 7] = "SAMPLER_JOINTS";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_MORPH_POSITION"] = 8] = "SAMPLER_MORPH_POSITION";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_MORPH_NORMAL"] = 9] = "SAMPLER_MORPH_NORMAL";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_MORPH_TANGENT"] = 10] = "SAMPLER_MORPH_TANGENT";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_LIGHTMAP"] = 11] = "SAMPLER_LIGHTMAP";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_SPRITE"] = 12] = "SAMPLER_SPRITE";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_REFLECTION"] = 13] = "SAMPLER_REFLECTION";
        ModelLocalBindings[ModelLocalBindings["STORAGE_REFLECTION"] = 14] = "STORAGE_REFLECTION";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_REFLECTION_PROBE_CUBE"] = 15] = "SAMPLER_REFLECTION_PROBE_CUBE";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_REFLECTION_PROBE_PLANAR"] = 16] = "SAMPLER_REFLECTION_PROBE_PLANAR";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_REFLECTION_PROBE_DATA_MAP"] = 17] = "SAMPLER_REFLECTION_PROBE_DATA_MAP";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_REFLECTION_PROBE_BLEND_CUBE"] = 18] = "SAMPLER_REFLECTION_PROBE_BLEND_CUBE";
        ModelLocalBindings[ModelLocalBindings["COUNT"] = 19] = "COUNT";
      })(ModelLocalBindings || (ModelLocalBindings = {}));
      var LOCAL_UBO_COUNT = ModelLocalBindings.SAMPLER_JOINTS;
      var LOCAL_SAMPLER_COUNT = ModelLocalBindings.STORAGE_REFLECTION - LOCAL_UBO_COUNT;
      var LOCAL_STORAGE_IMAGE_COUNT = ModelLocalBindings.COUNT - LOCAL_UBO_COUNT - LOCAL_SAMPLER_COUNT;
      var SetIndex;
      (function (SetIndex) {
        SetIndex[SetIndex["GLOBAL"] = 0] = "GLOBAL";
        SetIndex[SetIndex["MATERIAL"] = 1] = "MATERIAL";
        SetIndex[SetIndex["LOCAL"] = 2] = "LOCAL";
        SetIndex[SetIndex["COUNT"] = 3] = "COUNT";
      })(SetIndex || (SetIndex = {}));
      var bindingMappingInfo = new BindingMappingInfo([GLOBAL_UBO_COUNT, 0, LOCAL_UBO_COUNT, 0], [GLOBAL_SAMPLER_COUNT, 0, LOCAL_SAMPLER_COUNT, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, LOCAL_STORAGE_IMAGE_COUNT, 0], [0, 0, 0, 0], [0, 2, 1, 3]);
      var UBOGlobal = function UBOGlobal() {};
      _class$3r = UBOGlobal;
      UBOGlobal.TIME_OFFSET = 0;
      UBOGlobal.SCREEN_SIZE_OFFSET = _class$3r.TIME_OFFSET + 4;
      UBOGlobal.NATIVE_SIZE_OFFSET = _class$3r.SCREEN_SIZE_OFFSET + 4;
      UBOGlobal.PROBE_INFO_OFFSET = _class$3r.NATIVE_SIZE_OFFSET + 4;
      UBOGlobal.DEBUG_VIEW_MODE_OFFSET = _class$3r.PROBE_INFO_OFFSET + 4;
      UBOGlobal.COUNT = _class$3r.DEBUG_VIEW_MODE_OFFSET + 4;
      UBOGlobal.SIZE = _class$3r.COUNT * 4;
      UBOGlobal.NAME = 'CCGlobal';
      UBOGlobal.BINDING = PipelineGlobalBindings.UBO_GLOBAL;
      UBOGlobal.DESCRIPTOR = new DescriptorSetLayoutBinding(_class$3r.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL);
      UBOGlobal.LAYOUT = new UniformBlock(SetIndex.GLOBAL, _class$3r.BINDING, _class$3r.NAME, [new Uniform('cc_time', Type$1.FLOAT4, 1), new Uniform('cc_screenSize', Type$1.FLOAT4, 1), new Uniform('cc_nativeSize', Type$1.FLOAT4, 1), new Uniform('cc_probeInfo', Type$1.FLOAT4, 1), new Uniform('cc_debug_view_mode', Type$1.FLOAT4, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOGlobal.NAME] = UBOGlobal.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOGlobal.BINDING] = UBOGlobal.DESCRIPTOR;
      var UBOCamera = function UBOCamera() {};
      _class2$36 = UBOCamera;
      UBOCamera.MAT_VIEW_OFFSET = 0;
      UBOCamera.MAT_VIEW_INV_OFFSET = _class2$36.MAT_VIEW_OFFSET + 16;
      UBOCamera.MAT_PROJ_OFFSET = _class2$36.MAT_VIEW_INV_OFFSET + 16;
      UBOCamera.MAT_PROJ_INV_OFFSET = _class2$36.MAT_PROJ_OFFSET + 16;
      UBOCamera.MAT_VIEW_PROJ_OFFSET = _class2$36.MAT_PROJ_INV_OFFSET + 16;
      UBOCamera.MAT_VIEW_PROJ_INV_OFFSET = _class2$36.MAT_VIEW_PROJ_OFFSET + 16;
      UBOCamera.CAMERA_POS_OFFSET = _class2$36.MAT_VIEW_PROJ_INV_OFFSET + 16;
      UBOCamera.SURFACE_TRANSFORM_OFFSET = _class2$36.CAMERA_POS_OFFSET + 4;
      UBOCamera.SCREEN_SCALE_OFFSET = _class2$36.SURFACE_TRANSFORM_OFFSET + 4;
      UBOCamera.EXPOSURE_OFFSET = _class2$36.SCREEN_SCALE_OFFSET + 4;
      UBOCamera.MAIN_LIT_DIR_OFFSET = _class2$36.EXPOSURE_OFFSET + 4;
      UBOCamera.MAIN_LIT_COLOR_OFFSET = _class2$36.MAIN_LIT_DIR_OFFSET + 4;
      UBOCamera.AMBIENT_SKY_OFFSET = _class2$36.MAIN_LIT_COLOR_OFFSET + 4;
      UBOCamera.AMBIENT_GROUND_OFFSET = _class2$36.AMBIENT_SKY_OFFSET + 4;
      UBOCamera.GLOBAL_FOG_COLOR_OFFSET = _class2$36.AMBIENT_GROUND_OFFSET + 4;
      UBOCamera.GLOBAL_FOG_BASE_OFFSET = _class2$36.GLOBAL_FOG_COLOR_OFFSET + 4;
      UBOCamera.GLOBAL_FOG_ADD_OFFSET = _class2$36.GLOBAL_FOG_BASE_OFFSET + 4;
      UBOCamera.NEAR_FAR_OFFSET = _class2$36.GLOBAL_FOG_ADD_OFFSET + 4;
      UBOCamera.VIEW_PORT_OFFSET = _class2$36.NEAR_FAR_OFFSET + 4;
      UBOCamera.COUNT = _class2$36.VIEW_PORT_OFFSET + 4;
      UBOCamera.SIZE = _class2$36.COUNT * 4;
      UBOCamera.NAME = 'CCCamera';
      UBOCamera.BINDING = PipelineGlobalBindings.UBO_CAMERA;
      UBOCamera.DESCRIPTOR = new DescriptorSetLayoutBinding(_class2$36.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL);
      UBOCamera.LAYOUT = new UniformBlock(SetIndex.GLOBAL, _class2$36.BINDING, _class2$36.NAME, [new Uniform('cc_matView', Type$1.MAT4, 1), new Uniform('cc_matViewInv', Type$1.MAT4, 1), new Uniform('cc_matProj', Type$1.MAT4, 1), new Uniform('cc_matProjInv', Type$1.MAT4, 1), new Uniform('cc_matViewProj', Type$1.MAT4, 1), new Uniform('cc_matViewProjInv', Type$1.MAT4, 1), new Uniform('cc_cameraPos', Type$1.FLOAT4, 1), new Uniform('cc_surfaceTransform', Type$1.FLOAT4, 1), new Uniform('cc_screenScale', Type$1.FLOAT4, 1), new Uniform('cc_exposure', Type$1.FLOAT4, 1), new Uniform('cc_mainLitDir', Type$1.FLOAT4, 1), new Uniform('cc_mainLitColor', Type$1.FLOAT4, 1), new Uniform('cc_ambientSky', Type$1.FLOAT4, 1), new Uniform('cc_ambientGround', Type$1.FLOAT4, 1), new Uniform('cc_fogColor', Type$1.FLOAT4, 1), new Uniform('cc_fogBase', Type$1.FLOAT4, 1), new Uniform('cc_fogAdd', Type$1.FLOAT4, 1), new Uniform('cc_nearFar', Type$1.FLOAT4, 1), new Uniform('cc_viewPort', Type$1.FLOAT4, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOCamera.NAME] = UBOCamera.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOCamera.BINDING] = UBOCamera.DESCRIPTOR;
      var UBOShadow = function UBOShadow() {};
      _class3$V = UBOShadow;
      UBOShadow.MAT_LIGHT_VIEW_OFFSET = 0;
      UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET = _class3$V.MAT_LIGHT_VIEW_OFFSET + 16;
      UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET = _class3$V.MAT_LIGHT_VIEW_PROJ_OFFSET + 16;
      UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET = _class3$V.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 4;
      UBOShadow.SHADOW_PROJ_INFO_OFFSET = _class3$V.SHADOW_PROJ_DEPTH_INFO_OFFSET + 4;
      UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET = _class3$V.SHADOW_PROJ_INFO_OFFSET + 4;
      UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET = _class3$V.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 4;
      UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = _class3$V.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 4;
      UBOShadow.SHADOW_COLOR_OFFSET = _class3$V.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 4;
      UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET = _class3$V.SHADOW_COLOR_OFFSET + 4;
      UBOShadow.COUNT = _class3$V.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4;
      UBOShadow.SIZE = _class3$V.COUNT * 4;
      UBOShadow.NAME = 'CCShadow';
      UBOShadow.BINDING = PipelineGlobalBindings.UBO_SHADOW;
      UBOShadow.DESCRIPTOR = new DescriptorSetLayoutBinding(_class3$V.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL);
      UBOShadow.LAYOUT = new UniformBlock(SetIndex.GLOBAL, _class3$V.BINDING, _class3$V.NAME, [new Uniform('cc_matLightView', Type$1.MAT4, 1), new Uniform('cc_matLightViewProj', Type$1.MAT4, 1), new Uniform('cc_shadowInvProjDepthInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowProjDepthInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowProjInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowNFLSInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowWHPBInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowLPNNInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowColor', Type$1.FLOAT4, 1), new Uniform('cc_planarNDInfo', Type$1.FLOAT4, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOShadow.NAME] = UBOShadow.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOShadow.BINDING] = UBOShadow.DESCRIPTOR;
      var UBOCSM = function UBOCSM() {};
      _class4$y = UBOCSM;
      UBOCSM.CSM_LEVEL_COUNT = 4;
      UBOCSM.CSM_VIEW_DIR_0_OFFSET = 0;
      UBOCSM.CSM_VIEW_DIR_1_OFFSET = _class4$y.CSM_VIEW_DIR_0_OFFSET + 4 * _class4$y.CSM_LEVEL_COUNT;
      UBOCSM.CSM_VIEW_DIR_2_OFFSET = _class4$y.CSM_VIEW_DIR_1_OFFSET + 4 * _class4$y.CSM_LEVEL_COUNT;
      UBOCSM.CSM_ATLAS_OFFSET = _class4$y.CSM_VIEW_DIR_2_OFFSET + 4 * _class4$y.CSM_LEVEL_COUNT;
      UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET = _class4$y.CSM_ATLAS_OFFSET + 4 * _class4$y.CSM_LEVEL_COUNT;
      UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET = _class4$y.MAT_CSM_VIEW_PROJ_OFFSET + 16 * _class4$y.CSM_LEVEL_COUNT;
      UBOCSM.CSM_PROJ_INFO_OFFSET = _class4$y.CSM_PROJ_DEPTH_INFO_OFFSET + 4 * _class4$y.CSM_LEVEL_COUNT;
      UBOCSM.CSM_SPLITS_INFO_OFFSET = _class4$y.CSM_PROJ_INFO_OFFSET + 4 * _class4$y.CSM_LEVEL_COUNT;
      UBOCSM.COUNT = _class4$y.CSM_SPLITS_INFO_OFFSET + 4;
      UBOCSM.SIZE = _class4$y.COUNT * 4;
      UBOCSM.NAME = 'CCCSM';
      UBOCSM.BINDING = PipelineGlobalBindings.UBO_CSM;
      UBOCSM.DESCRIPTOR = new DescriptorSetLayoutBinding(_class4$y.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.FRAGMENT);
      UBOCSM.LAYOUT = new UniformBlock(SetIndex.GLOBAL, _class4$y.BINDING, _class4$y.NAME, [new Uniform('cc_csmViewDir0', Type$1.FLOAT4, _class4$y.CSM_LEVEL_COUNT), new Uniform('cc_csmViewDir1', Type$1.FLOAT4, _class4$y.CSM_LEVEL_COUNT), new Uniform('cc_csmViewDir2', Type$1.FLOAT4, _class4$y.CSM_LEVEL_COUNT), new Uniform('cc_csmAtlas', Type$1.FLOAT4, _class4$y.CSM_LEVEL_COUNT), new Uniform('cc_matCSMViewProj', Type$1.MAT4, _class4$y.CSM_LEVEL_COUNT), new Uniform('cc_csmProjDepthInfo', Type$1.FLOAT4, _class4$y.CSM_LEVEL_COUNT), new Uniform('cc_csmProjInfo', Type$1.FLOAT4, _class4$y.CSM_LEVEL_COUNT), new Uniform('cc_csmSplitsInfo', Type$1.FLOAT4, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOCSM.NAME] = UBOCSM.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOCSM.BINDING] = UBOCSM.DESCRIPTOR;
      var UNIFORM_SHADOWMAP_NAME = 'cc_shadowMap';
      var UNIFORM_SHADOWMAP_BINDING = PipelineGlobalBindings.SAMPLER_SHADOWMAP;
      var UNIFORM_SHADOWMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SHADOWMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_SHADOWMAP_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SHADOWMAP_NAME, Type$1.SAMPLER2D, 1);
      globalDescriptorSetLayout.layouts[UNIFORM_SHADOWMAP_NAME] = UNIFORM_SHADOWMAP_LAYOUT;
      globalDescriptorSetLayout.bindings[UNIFORM_SHADOWMAP_BINDING] = UNIFORM_SHADOWMAP_DESCRIPTOR;
      var UNIFORM_ENVIRONMENT_NAME = 'cc_environment';
      var UNIFORM_ENVIRONMENT_BINDING = PipelineGlobalBindings.SAMPLER_ENVIRONMENT;
      var UNIFORM_ENVIRONMENT_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_ENVIRONMENT_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_ENVIRONMENT_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_ENVIRONMENT_BINDING, UNIFORM_ENVIRONMENT_NAME, Type$1.SAMPLER_CUBE, 1);
      globalDescriptorSetLayout.layouts[UNIFORM_ENVIRONMENT_NAME] = UNIFORM_ENVIRONMENT_LAYOUT;
      globalDescriptorSetLayout.bindings[UNIFORM_ENVIRONMENT_BINDING] = UNIFORM_ENVIRONMENT_DESCRIPTOR;
      var UNIFORM_DIFFUSEMAP_NAME = 'cc_diffuseMap';
      var UNIFORM_DIFFUSEMAP_BINDING = PipelineGlobalBindings.SAMPLER_DIFFUSEMAP;
      var UNIFORM_DIFFUSEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_DIFFUSEMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_DIFFUSEMAP_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_DIFFUSEMAP_BINDING, UNIFORM_DIFFUSEMAP_NAME, Type$1.SAMPLER_CUBE, 1);
      globalDescriptorSetLayout.layouts[UNIFORM_DIFFUSEMAP_NAME] = UNIFORM_DIFFUSEMAP_LAYOUT;
      globalDescriptorSetLayout.bindings[UNIFORM_DIFFUSEMAP_BINDING] = UNIFORM_DIFFUSEMAP_DESCRIPTOR;
      var UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME = 'cc_spotShadowMap';
      var UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING = PipelineGlobalBindings.SAMPLER_SPOT_SHADOW_MAP;
      var UNIFORM_SPOT_SHADOW_MAP_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_SPOT_SHADOW_MAP_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      globalDescriptorSetLayout.layouts[UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME] = UNIFORM_SPOT_SHADOW_MAP_TEXTURE_LAYOUT;
      globalDescriptorSetLayout.bindings[UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING] = UNIFORM_SPOT_SHADOW_MAP_TEXTURE_DESCRIPTOR;
      var UBOLocal = function UBOLocal() {};
      _class5$y = UBOLocal;
      UBOLocal.MAT_WORLD_OFFSET = 0;
      UBOLocal.MAT_WORLD_IT_OFFSET = _class5$y.MAT_WORLD_OFFSET + 16;
      UBOLocal.LIGHTINGMAP_UVPARAM = _class5$y.MAT_WORLD_IT_OFFSET + 16;
      UBOLocal.LOCAL_SHADOW_BIAS = _class5$y.LIGHTINGMAP_UVPARAM + 4;
      UBOLocal.REFLECTION_PROBE_DATA1 = _class5$y.LOCAL_SHADOW_BIAS + 4;
      UBOLocal.REFLECTION_PROBE_DATA2 = _class5$y.REFLECTION_PROBE_DATA1 + 4;
      UBOLocal.REFLECTION_PROBE_BLEND_DATA1 = _class5$y.REFLECTION_PROBE_DATA2 + 4;
      UBOLocal.REFLECTION_PROBE_BLEND_DATA2 = _class5$y.REFLECTION_PROBE_BLEND_DATA1 + 4;
      UBOLocal.COUNT = _class5$y.REFLECTION_PROBE_BLEND_DATA2 + 4;
      UBOLocal.SIZE = _class5$y.COUNT * 4;
      UBOLocal.NAME = 'CCLocal';
      UBOLocal.BINDING = ModelLocalBindings.UBO_LOCAL;
      UBOLocal.DESCRIPTOR = new DescriptorSetLayoutBinding(_class5$y.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX | ShaderStageFlagBit.FRAGMENT | ShaderStageFlagBit.COMPUTE);
      UBOLocal.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class5$y.BINDING, _class5$y.NAME, [new Uniform('cc_matWorld', Type$1.MAT4, 1), new Uniform('cc_matWorldIT', Type$1.MAT4, 1), new Uniform('cc_lightingMapUVParam', Type$1.FLOAT4, 1), new Uniform('cc_localShadowBias', Type$1.FLOAT4, 1), new Uniform('cc_reflectionProbeData1', Type$1.FLOAT4, 1), new Uniform('cc_reflectionProbeData2', Type$1.FLOAT4, 1), new Uniform('cc_reflectionProbeBlendData1', Type$1.FLOAT4, 1), new Uniform('cc_reflectionProbeBlendData2', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOLocal.NAME] = UBOLocal.LAYOUT;
      localDescriptorSetLayout.bindings[UBOLocal.BINDING] = UBOLocal.DESCRIPTOR;
      var UBOWorldBound = function UBOWorldBound() {};
      _class6$a = UBOWorldBound;
      UBOWorldBound.WORLD_BOUND_CENTER = 0;
      UBOWorldBound.WORLD_BOUND_HALF_EXTENTS = _class6$a.WORLD_BOUND_CENTER + 4;
      UBOWorldBound.COUNT = _class6$a.WORLD_BOUND_HALF_EXTENTS + 4;
      UBOWorldBound.SIZE = _class6$a.COUNT * 4;
      UBOWorldBound.NAME = 'CCWorldBound';
      UBOWorldBound.BINDING = ModelLocalBindings.UBO_LOCAL;
      UBOWorldBound.DESCRIPTOR = new DescriptorSetLayoutBinding(_class6$a.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX | ShaderStageFlagBit.COMPUTE);
      UBOWorldBound.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class6$a.BINDING, _class6$a.NAME, [new Uniform('cc_worldBoundCenter', Type$1.FLOAT4, 1), new Uniform('cc_worldBoundHalfExtents', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOWorldBound.NAME] = UBOWorldBound.LAYOUT;
      localDescriptorSetLayout.bindings[UBOWorldBound.BINDING] = UBOWorldBound.DESCRIPTOR;
      var INST_MAT_WORLD = 'a_matWorld0';
      var INST_SH = 'a_sh_linear_const_r';
      var UBOLocalBatched = function UBOLocalBatched() {};
      _class7$b = UBOLocalBatched;
      UBOLocalBatched.BATCHING_COUNT = 10;
      UBOLocalBatched.MAT_WORLDS_OFFSET = 0;
      UBOLocalBatched.COUNT = 16 * _class7$b.BATCHING_COUNT;
      UBOLocalBatched.SIZE = _class7$b.COUNT * 4;
      UBOLocalBatched.NAME = 'CCLocalBatched';
      UBOLocalBatched.BINDING = ModelLocalBindings.UBO_LOCAL;
      UBOLocalBatched.DESCRIPTOR = new DescriptorSetLayoutBinding(_class7$b.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX | ShaderStageFlagBit.COMPUTE);
      UBOLocalBatched.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class7$b.BINDING, _class7$b.NAME, [new Uniform('cc_matWorlds', Type$1.MAT4, _class7$b.BATCHING_COUNT)], 1);
      localDescriptorSetLayout.layouts[UBOLocalBatched.NAME] = UBOLocalBatched.LAYOUT;
      localDescriptorSetLayout.bindings[UBOLocalBatched.BINDING] = UBOLocalBatched.DESCRIPTOR;
      var UBOForwardLight = function UBOForwardLight() {};
      _class8$c = UBOForwardLight;
      UBOForwardLight.LIGHTS_PER_PASS = 1;
      UBOForwardLight.LIGHT_POS_OFFSET = 0;
      UBOForwardLight.LIGHT_COLOR_OFFSET = _class8$c.LIGHT_POS_OFFSET + _class8$c.LIGHTS_PER_PASS * 4;
      UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET = _class8$c.LIGHT_COLOR_OFFSET + _class8$c.LIGHTS_PER_PASS * 4;
      UBOForwardLight.LIGHT_DIR_OFFSET = _class8$c.LIGHT_SIZE_RANGE_ANGLE_OFFSET + _class8$c.LIGHTS_PER_PASS * 4;
      UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET = _class8$c.LIGHT_DIR_OFFSET + _class8$c.LIGHTS_PER_PASS * 4;
      UBOForwardLight.COUNT = _class8$c.LIGHT_BOUNDING_SIZE_VS_OFFSET + _class8$c.LIGHTS_PER_PASS * 4;
      UBOForwardLight.SIZE = _class8$c.COUNT * 4;
      UBOForwardLight.NAME = 'CCForwardLight';
      UBOForwardLight.BINDING = ModelLocalBindings.UBO_FORWARD_LIGHTS;
      UBOForwardLight.DESCRIPTOR = new DescriptorSetLayoutBinding(_class8$c.BINDING, DescriptorType.DYNAMIC_UNIFORM_BUFFER, 1, ShaderStageFlagBit.FRAGMENT);
      UBOForwardLight.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class8$c.BINDING, _class8$c.NAME, [new Uniform('cc_lightPos', Type$1.FLOAT4, _class8$c.LIGHTS_PER_PASS), new Uniform('cc_lightColor', Type$1.FLOAT4, _class8$c.LIGHTS_PER_PASS), new Uniform('cc_lightSizeRangeAngle', Type$1.FLOAT4, _class8$c.LIGHTS_PER_PASS), new Uniform('cc_lightDir', Type$1.FLOAT4, _class8$c.LIGHTS_PER_PASS), new Uniform('cc_lightBoundingSizeVS', Type$1.FLOAT4, _class8$c.LIGHTS_PER_PASS)], 1);
      localDescriptorSetLayout.layouts[UBOForwardLight.NAME] = UBOForwardLight.LAYOUT;
      localDescriptorSetLayout.bindings[UBOForwardLight.BINDING] = UBOForwardLight.DESCRIPTOR;
      var UBODeferredLight = function UBODeferredLight() {};
      UBODeferredLight.LIGHTS_PER_PASS = 10;
      var JOINT_UNIFORM_CAPACITY = 30;
      var UBOSkinningTexture = function UBOSkinningTexture() {};
      _class10$7 = UBOSkinningTexture;
      UBOSkinningTexture.JOINTS_TEXTURE_INFO_OFFSET = 0;
      UBOSkinningTexture.COUNT = _class10$7.JOINTS_TEXTURE_INFO_OFFSET + 4;
      UBOSkinningTexture.SIZE = _class10$7.COUNT * 4;
      UBOSkinningTexture.NAME = 'CCSkinningTexture';
      UBOSkinningTexture.BINDING = ModelLocalBindings.UBO_SKINNING_TEXTURE;
      UBOSkinningTexture.DESCRIPTOR = new DescriptorSetLayoutBinding(_class10$7.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
      UBOSkinningTexture.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class10$7.BINDING, _class10$7.NAME, [new Uniform('cc_jointTextureInfo', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOSkinningTexture.NAME] = UBOSkinningTexture.LAYOUT;
      localDescriptorSetLayout.bindings[UBOSkinningTexture.BINDING] = UBOSkinningTexture.DESCRIPTOR;
      var UBOSkinningAnimation = function UBOSkinningAnimation() {};
      _class11$8 = UBOSkinningAnimation;
      UBOSkinningAnimation.JOINTS_ANIM_INFO_OFFSET = 0;
      UBOSkinningAnimation.COUNT = _class11$8.JOINTS_ANIM_INFO_OFFSET + 4;
      UBOSkinningAnimation.SIZE = _class11$8.COUNT * 4;
      UBOSkinningAnimation.NAME = 'CCSkinningAnimation';
      UBOSkinningAnimation.BINDING = ModelLocalBindings.UBO_SKINNING_ANIMATION;
      UBOSkinningAnimation.DESCRIPTOR = new DescriptorSetLayoutBinding(_class11$8.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
      UBOSkinningAnimation.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class11$8.BINDING, _class11$8.NAME, [new Uniform('cc_jointAnimInfo', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOSkinningAnimation.NAME] = UBOSkinningAnimation.LAYOUT;
      localDescriptorSetLayout.bindings[UBOSkinningAnimation.BINDING] = UBOSkinningAnimation.DESCRIPTOR;
      var INST_JOINT_ANIM_INFO = 'a_jointAnimInfo';
      var UBOSkinning = function () {
        function UBOSkinning() {}
        UBOSkinning.initLayout = function initLayout(capacity) {
          UBOSkinning._jointUniformCapacity = capacity;
          UBOSkinning._count = capacity * 12;
          UBOSkinning._size = UBOSkinning._count * 4;
          UBOSkinning.LAYOUT.members[0].count = capacity * 3;
        };
        _createClass(UBOSkinning, null, [{
          key: "JOINT_UNIFORM_CAPACITY",
          get: function get() {
            return UBOSkinning._jointUniformCapacity;
          }
        }, {
          key: "COUNT",
          get: function get() {
            return UBOSkinning._count;
          }
        }, {
          key: "SIZE",
          get: function get() {
            return UBOSkinning._size;
          }
        }]);
        return UBOSkinning;
      }();
      _class12$4 = UBOSkinning;
      UBOSkinning._jointUniformCapacity = 0;
      UBOSkinning._count = 0;
      UBOSkinning._size = 0;
      UBOSkinning.NAME = 'CCSkinning';
      UBOSkinning.BINDING = ModelLocalBindings.UBO_SKINNING_TEXTURE;
      UBOSkinning.DESCRIPTOR = new DescriptorSetLayoutBinding(_class12$4.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
      UBOSkinning.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class12$4.BINDING, _class12$4.NAME, [new Uniform('cc_joints', Type$1.FLOAT4, 1)], 1);
      function localDescriptorSetLayout_ResizeMaxJoints(maxCount) {
        UBOSkinning.initLayout(maxCount);
        localDescriptorSetLayout.layouts[UBOSkinning.NAME] = UBOSkinning.LAYOUT;
        localDescriptorSetLayout.bindings[UBOSkinning.BINDING] = UBOSkinning.DESCRIPTOR;
      }
      var UBOMorph = function UBOMorph() {};
      _class13$7 = UBOMorph;
      UBOMorph.MAX_MORPH_TARGET_COUNT = 60;
      UBOMorph.OFFSET_OF_WEIGHTS = 0;
      UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH = 4 * _class13$7.MAX_MORPH_TARGET_COUNT;
      UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT = _class13$7.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH + 4;
      UBOMorph.OFFSET_OF_VERTICES_COUNT = _class13$7.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT + 4;
      UBOMorph.COUNT_BASE_4_BYTES = 4 * Math.ceil(_class13$7.MAX_MORPH_TARGET_COUNT / 4) + 4;
      UBOMorph.SIZE = _class13$7.COUNT_BASE_4_BYTES * 4;
      UBOMorph.NAME = 'CCMorph';
      UBOMorph.BINDING = ModelLocalBindings.UBO_MORPH;
      UBOMorph.DESCRIPTOR = new DescriptorSetLayoutBinding(_class13$7.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
      UBOMorph.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class13$7.BINDING, _class13$7.NAME, [new Uniform('cc_displacementWeights', Type$1.FLOAT4, _class13$7.MAX_MORPH_TARGET_COUNT / 4), new Uniform('cc_displacementTextureInfo', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOMorph.NAME] = UBOMorph.LAYOUT;
      localDescriptorSetLayout.bindings[UBOMorph.BINDING] = UBOMorph.DESCRIPTOR;
      var UBOUILocal = function UBOUILocal() {};
      _class14$6 = UBOUILocal;
      UBOUILocal.NAME = 'CCUILocal';
      UBOUILocal.BINDING = ModelLocalBindings.UBO_UI_LOCAL;
      UBOUILocal.DESCRIPTOR = new DescriptorSetLayoutBinding(_class14$6.BINDING, DescriptorType.DYNAMIC_UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
      UBOUILocal.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class14$6.BINDING, _class14$6.NAME, [new Uniform('cc_local_data', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOUILocal.NAME] = UBOUILocal.LAYOUT;
      localDescriptorSetLayout.bindings[UBOUILocal.BINDING] = UBOUILocal.DESCRIPTOR;
      var UBOSH = function UBOSH() {};
      _class15$1 = UBOSH;
      UBOSH.SH_LINEAR_CONST_R_OFFSET = 0;
      UBOSH.SH_LINEAR_CONST_G_OFFSET = _class15$1.SH_LINEAR_CONST_R_OFFSET + 4;
      UBOSH.SH_LINEAR_CONST_B_OFFSET = _class15$1.SH_LINEAR_CONST_G_OFFSET + 4;
      UBOSH.SH_QUADRATIC_R_OFFSET = _class15$1.SH_LINEAR_CONST_B_OFFSET + 4;
      UBOSH.SH_QUADRATIC_G_OFFSET = _class15$1.SH_QUADRATIC_R_OFFSET + 4;
      UBOSH.SH_QUADRATIC_B_OFFSET = _class15$1.SH_QUADRATIC_G_OFFSET + 4;
      UBOSH.SH_QUADRATIC_A_OFFSET = _class15$1.SH_QUADRATIC_B_OFFSET + 4;
      UBOSH.COUNT = _class15$1.SH_QUADRATIC_A_OFFSET + 4;
      UBOSH.SIZE = _class15$1.COUNT * 4;
      UBOSH.NAME = 'CCSH';
      UBOSH.BINDING = ModelLocalBindings.UBO_SH;
      UBOSH.DESCRIPTOR = new DescriptorSetLayoutBinding(_class15$1.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.FRAGMENT);
      UBOSH.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class15$1.BINDING, _class15$1.NAME, [new Uniform('cc_sh_linear_const_r', Type$1.FLOAT4, 1), new Uniform('cc_sh_linear_const_g', Type$1.FLOAT4, 1), new Uniform('cc_sh_linear_const_b', Type$1.FLOAT4, 1), new Uniform('cc_sh_quadratic_r', Type$1.FLOAT4, 1), new Uniform('cc_sh_quadratic_g', Type$1.FLOAT4, 1), new Uniform('cc_sh_quadratic_b', Type$1.FLOAT4, 1), new Uniform('cc_sh_quadratic_a', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOSH.NAME] = UBOSH.LAYOUT;
      localDescriptorSetLayout.bindings[UBOSH.BINDING] = UBOSH.DESCRIPTOR;
      var UNIFORM_JOINT_TEXTURE_NAME = 'cc_jointTexture';
      var UNIFORM_JOINT_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_JOINTS;
      var UNIFORM_JOINT_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_JOINT_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
      var UNIFORM_JOINT_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_JOINT_TEXTURE_BINDING, UNIFORM_JOINT_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_JOINT_TEXTURE_NAME] = UNIFORM_JOINT_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_JOINT_TEXTURE_BINDING] = UNIFORM_JOINT_TEXTURE_DESCRIPTOR;
      var UNIFORM_REALTIME_JOINT_TEXTURE_NAME = 'cc_realtimeJoint';
      var UNIFORM_REALTIME_JOINT_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_JOINTS;
      var UNIFORM_REALTIME_JOINT_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
      var UNIFORM_REALTIME_JOINT_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, UNIFORM_REALTIME_JOINT_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REALTIME_JOINT_TEXTURE_NAME] = UNIFORM_REALTIME_JOINT_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REALTIME_JOINT_TEXTURE_BINDING] = UNIFORM_REALTIME_JOINT_TEXTURE_DESCRIPTOR;
      var UNIFORM_POSITION_MORPH_TEXTURE_NAME = 'cc_PositionDisplacements';
      var UNIFORM_POSITION_MORPH_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_MORPH_POSITION;
      var UNIFORM_POSITION_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_POSITION_MORPH_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
      var UNIFORM_POSITION_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_POSITION_MORPH_TEXTURE_BINDING, UNIFORM_POSITION_MORPH_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_POSITION_MORPH_TEXTURE_NAME] = UNIFORM_POSITION_MORPH_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_POSITION_MORPH_TEXTURE_BINDING] = UNIFORM_POSITION_MORPH_TEXTURE_DESCRIPTOR;
      var UNIFORM_NORMAL_MORPH_TEXTURE_NAME = 'cc_NormalDisplacements';
      var UNIFORM_NORMAL_MORPH_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_MORPH_NORMAL;
      var UNIFORM_NORMAL_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
      var UNIFORM_NORMAL_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, UNIFORM_NORMAL_MORPH_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_NORMAL_MORPH_TEXTURE_NAME] = UNIFORM_NORMAL_MORPH_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_NORMAL_MORPH_TEXTURE_BINDING] = UNIFORM_NORMAL_MORPH_TEXTURE_DESCRIPTOR;
      var UNIFORM_TANGENT_MORPH_TEXTURE_NAME = 'cc_TangentDisplacements';
      var UNIFORM_TANGENT_MORPH_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_MORPH_TANGENT;
      var UNIFORM_TANGENT_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_TANGENT_MORPH_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
      var UNIFORM_TANGENT_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_TANGENT_MORPH_TEXTURE_BINDING, UNIFORM_TANGENT_MORPH_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_TANGENT_MORPH_TEXTURE_NAME] = UNIFORM_TANGENT_MORPH_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_TANGENT_MORPH_TEXTURE_BINDING] = UNIFORM_TANGENT_MORPH_TEXTURE_DESCRIPTOR;
      var UNIFORM_LIGHTMAP_TEXTURE_NAME = 'cc_lightingMap';
      var UNIFORM_LIGHTMAP_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_LIGHTMAP;
      var UNIFORM_LIGHTMAP_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_LIGHTMAP_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_LIGHTMAP_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_LIGHTMAP_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_LIGHTMAP_TEXTURE_NAME] = UNIFORM_LIGHTMAP_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_LIGHTMAP_TEXTURE_BINDING] = UNIFORM_LIGHTMAP_TEXTURE_DESCRIPTOR;
      var UNIFORM_SPRITE_TEXTURE_NAME = 'cc_spriteTexture';
      var UNIFORM_SPRITE_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_SPRITE;
      var UNIFORM_SPRITE_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SPRITE_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_SPRITE_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_SPRITE_TEXTURE_BINDING, UNIFORM_SPRITE_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_SPRITE_TEXTURE_NAME] = UNIFORM_SPRITE_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_SPRITE_TEXTURE_BINDING] = UNIFORM_SPRITE_TEXTURE_DESCRIPTOR;
      var UNIFORM_REFLECTION_TEXTURE_NAME = 'cc_reflectionTexture';
      var UNIFORM_REFLECTION_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_REFLECTION;
      var UNIFORM_REFLECTION_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_REFLECTION_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_TEXTURE_BINDING, UNIFORM_REFLECTION_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_TEXTURE_NAME] = UNIFORM_REFLECTION_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_TEXTURE_BINDING] = UNIFORM_REFLECTION_TEXTURE_DESCRIPTOR;
      var UNIFORM_REFLECTION_STORAGE_NAME = 'cc_reflectionStorage';
      var UNIFORM_REFLECTION_STORAGE_BINDING = ModelLocalBindings.STORAGE_REFLECTION;
      var UNIFORM_REFLECTION_STORAGE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_STORAGE_BINDING, DescriptorType.STORAGE_IMAGE, 1, ShaderStageFlagBit.COMPUTE);
      var UNIFORM_REFLECTION_STORAGE_LAYOUT = new UniformStorageImage(SetIndex.LOCAL, UNIFORM_REFLECTION_STORAGE_BINDING, UNIFORM_REFLECTION_STORAGE_NAME, Type$1.IMAGE2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_STORAGE_NAME] = UNIFORM_REFLECTION_STORAGE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_STORAGE_BINDING] = UNIFORM_REFLECTION_STORAGE_DESCRIPTOR;
      var UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME = 'cc_reflectionProbeCubemap';
      var UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_CUBE;
      var UNIFORM_REFLECTION_PROBE_CUBEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_REFLECTION_PROBE_CUBEMAP_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME, Type$1.SAMPLER_CUBE, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME] = UNIFORM_REFLECTION_PROBE_CUBEMAP_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING] = UNIFORM_REFLECTION_PROBE_CUBEMAP_DESCRIPTOR;
      var UNIFORM_REFLECTION_PROBE_TEXTURE_NAME = 'cc_reflectionProbePlanarMap';
      var UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_PLANAR;
      var UNIFORM_REFLECTION_PROBE_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_REFLECTION_PROBE_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_TEXTURE_NAME] = UNIFORM_REFLECTION_PROBE_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING] = UNIFORM_REFLECTION_PROBE_TEXTURE_DESCRIPTOR;
      var UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME = 'cc_reflectionProbeDataMap';
      var UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_DATA_MAP;
      var UNIFORM_REFLECTION_PROBE_DATA_MAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_REFLECTION_PROBE_DATA_MAP_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME] = UNIFORM_REFLECTION_PROBE_DATA_MAP_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING] = UNIFORM_REFLECTION_PROBE_DATA_MAP_DESCRIPTOR;
      var UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME = 'cc_reflectionProbeBlendCubemap';
      var UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_BLEND_CUBE;
      var UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME, Type$1.SAMPLER_CUBE, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME] = UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING] = UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_DESCRIPTOR;
      var CAMERA_DEFAULT_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.GIZMOS, Layers.BitMask.EDITOR, Layers.BitMask.SCENE_GIZMO, Layers.BitMask.PROFILER]);
      var CAMERA_EDITOR_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.PROFILER]);
      var MODEL_ALWAYS_MASK = Layers.Enum.ALL;
      function supportsR16HalfFloatTexture(device) {
        return (device.getFormatFeatures(Format.R16F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE);
      }
      function supportsR32FloatTexture(device) {
        return (device.getFormatFeatures(Format.R32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) && !(device.gfxAPI === API.WEBGL);
      }
      function supportsRGBA16HalfFloatTexture(device) {
        return (device.getFormatFeatures(Format.RGBA16F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) && !(device.gfxAPI === API.WEBGL);
      }
      function supportsRGBA32FloatTexture(device) {
        return (device.getFormatFeatures(Format.RGBA32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) && !(device.gfxAPI === API.WEBGL);
      }
      function isEnableEffect() {
        return !!(legacyCC.rendering && legacyCC.rendering.enableEffectImport);
      }

      var define$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        PIPELINE_FLOW_MAIN: PIPELINE_FLOW_MAIN,
        PIPELINE_FLOW_FORWARD: PIPELINE_FLOW_FORWARD,
        PIPELINE_FLOW_SHADOW: PIPELINE_FLOW_SHADOW,
        PIPELINE_FLOW_SMAA: PIPELINE_FLOW_SMAA,
        PIPELINE_FLOW_TONEMAP: PIPELINE_FLOW_TONEMAP,
        get RenderPassStage () { return RenderPassStage; },
        get RenderPriority () { return RenderPriority; },
        globalDescriptorSetLayout: globalDescriptorSetLayout,
        localDescriptorSetLayout: localDescriptorSetLayout,
        get PipelineGlobalBindings () { return PipelineGlobalBindings; },
        get ModelLocalBindings () { return ModelLocalBindings; },
        get SetIndex () { return SetIndex; },
        bindingMappingInfo: bindingMappingInfo,
        UBOGlobal: UBOGlobal,
        UBOCamera: UBOCamera,
        UBOShadow: UBOShadow,
        UBOCSM: UBOCSM,
        UNIFORM_SHADOWMAP_BINDING: UNIFORM_SHADOWMAP_BINDING,
        UNIFORM_ENVIRONMENT_BINDING: UNIFORM_ENVIRONMENT_BINDING,
        UNIFORM_DIFFUSEMAP_BINDING: UNIFORM_DIFFUSEMAP_BINDING,
        UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING: UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING,
        UBOLocal: UBOLocal,
        UBOWorldBound: UBOWorldBound,
        INST_MAT_WORLD: INST_MAT_WORLD,
        INST_SH: INST_SH,
        UBOLocalBatched: UBOLocalBatched,
        UBOForwardLight: UBOForwardLight,
        UBODeferredLight: UBODeferredLight,
        JOINT_UNIFORM_CAPACITY: JOINT_UNIFORM_CAPACITY,
        UBOSkinningTexture: UBOSkinningTexture,
        UBOSkinningAnimation: UBOSkinningAnimation,
        INST_JOINT_ANIM_INFO: INST_JOINT_ANIM_INFO,
        UBOSkinning: UBOSkinning,
        localDescriptorSetLayout_ResizeMaxJoints: localDescriptorSetLayout_ResizeMaxJoints,
        UBOMorph: UBOMorph,
        UBOUILocal: UBOUILocal,
        UBOSH: UBOSH,
        UNIFORM_JOINT_TEXTURE_BINDING: UNIFORM_JOINT_TEXTURE_BINDING,
        UNIFORM_REALTIME_JOINT_TEXTURE_BINDING: UNIFORM_REALTIME_JOINT_TEXTURE_BINDING,
        UNIFORM_POSITION_MORPH_TEXTURE_BINDING: UNIFORM_POSITION_MORPH_TEXTURE_BINDING,
        UNIFORM_NORMAL_MORPH_TEXTURE_BINDING: UNIFORM_NORMAL_MORPH_TEXTURE_BINDING,
        UNIFORM_TANGENT_MORPH_TEXTURE_BINDING: UNIFORM_TANGENT_MORPH_TEXTURE_BINDING,
        UNIFORM_LIGHTMAP_TEXTURE_BINDING: UNIFORM_LIGHTMAP_TEXTURE_BINDING,
        UNIFORM_SPRITE_TEXTURE_BINDING: UNIFORM_SPRITE_TEXTURE_BINDING,
        UNIFORM_REFLECTION_TEXTURE_BINDING: UNIFORM_REFLECTION_TEXTURE_BINDING,
        UNIFORM_REFLECTION_STORAGE_BINDING: UNIFORM_REFLECTION_STORAGE_BINDING,
        UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING: UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING,
        UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING: UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING,
        UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING: UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING,
        UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING: UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING,
        CAMERA_DEFAULT_MASK: CAMERA_DEFAULT_MASK,
        CAMERA_EDITOR_MASK: CAMERA_EDITOR_MASK,
        MODEL_ALWAYS_MASK: MODEL_ALWAYS_MASK,
        supportsR16HalfFloatTexture: supportsR16HalfFloatTexture,
        supportsR32FloatTexture: supportsR32FloatTexture,
        supportsRGBA16HalfFloatTexture: supportsRGBA16HalfFloatTexture,
        supportsRGBA32FloatTexture: supportsRGBA32FloatTexture,
        isEnableEffect: isEnableEffect
      });
      exports('da', define$1);

      var _type2reader, _type2writer, _type2validator;
      var typeMask = 0xfc000000;
      var bindingMask = 0x03f00000;
      var countMask = 0x000ff000;
      var offsetMask = 0x00000fff;
      var genHandle = function genHandle(binding, type, count, offset) {
        if (offset === void 0) {
          offset = 0;
        }
        return type << 26 & typeMask | binding << 20 & bindingMask | count << 12 & countMask | offset & offsetMask;
      };
      var getTypeFromHandle = function getTypeFromHandle(handle) {
        return (handle & typeMask) >>> 26;
      };
      var getBindingFromHandle = function getBindingFromHandle(handle) {
        return (handle & bindingMask) >>> 20;
      };
      var getCountFromHandle = function getCountFromHandle(handle) {
        return (handle & countMask) >>> 12;
      };
      var getOffsetFromHandle = function getOffsetFromHandle(handle) {
        return handle & offsetMask;
      };
      var customizeType = function customizeType(handle, type) {
        return handle & ~typeMask | type << 26 & typeMask;
      };
      var type2reader = (_type2reader = {}, _type2reader[Type$1.UNKNOWN] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return warnID(12010, idx);
      }, _type2reader[Type$1.INT] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return a[idx];
      }, _type2reader[Type$1.INT2] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec2.fromArray(v, a, idx);
      }, _type2reader[Type$1.INT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec3.fromArray(v, a, idx);
      }, _type2reader[Type$1.INT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec4.fromArray(v, a, idx);
      }, _type2reader[Type$1.FLOAT] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return a[idx];
      }, _type2reader[Type$1.FLOAT2] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec2.fromArray(v, a, idx);
      }, _type2reader[Type$1.FLOAT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec3.fromArray(v, a, idx);
      }, _type2reader[Type$1.FLOAT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec4.fromArray(v, a, idx);
      }, _type2reader[Type$1.MAT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Mat3.fromArray(v, a, idx);
      }, _type2reader[Type$1.MAT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Mat4.fromArray(v, a, idx);
      }, _type2reader);
      var type2writer = (_type2writer = {}, _type2writer[Type$1.UNKNOWN] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return warnID(12010, idx);
      }, _type2writer[Type$1.INT] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return a[idx] = v;
      }, _type2writer[Type$1.INT2] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec2.toArray(a, v, idx);
      }, _type2writer[Type$1.INT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec3.toArray(a, v, idx);
      }, _type2writer[Type$1.INT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec4.toArray(a, v, idx);
      }, _type2writer[Type$1.FLOAT] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return a[idx] = v;
      }, _type2writer[Type$1.FLOAT2] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec2.toArray(a, v, idx);
      }, _type2writer[Type$1.FLOAT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec3.toArray(a, v, idx);
      }, _type2writer[Type$1.FLOAT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec4.toArray(a, v, idx);
      }, _type2writer[Type$1.MAT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Mat3.toArray(a, v, idx);
      }, _type2writer[Type$1.MAT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Mat4.toArray(a, v, idx);
      }, _type2writer);
      var type2validator = (_type2validator = {}, _type2validator[Type$1.INT] = function (v) {
        return typeof v === 'number';
      }, _type2validator[Type$1.FLOAT] = function (v) {
        return typeof v === 'number';
      }, _type2validator[Type$1.INT2] = function (v) {
        return !!(v instanceof Vec2);
      }, _type2validator[Type$1.FLOAT2] = function (v) {
        return !!(v instanceof Vec2);
      }, _type2validator[Type$1.INT3] = function (v) {
        return !!(v instanceof Vec3);
      }, _type2validator[Type$1.FLOAT3] = function (v) {
        return !!(v instanceof Vec3);
      }, _type2validator[Type$1.INT4] = function (v) {
        return !!(v instanceof Vec4);
      }, _type2validator[Type$1.FLOAT4] = function (v) {
        return !!(v instanceof Vec4 || v instanceof Color$1 || v instanceof Quat);
      }, _type2validator[Type$1.MAT3] = function (v) {
        return !!(v instanceof Mat3);
      }, _type2validator[Type$1.MAT4] = function (v) {
        return !!(v instanceof Mat4);
      }, _type2validator);
      var defaultValues = [Object.freeze([0]), Object.freeze([0, 0]), Object.freeze([0, 0, 0, 0]), Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])];
      function getDefaultFromType(type) {
        switch (type) {
          case Type$1.BOOL:
          case Type$1.INT:
          case Type$1.UINT:
          case Type$1.FLOAT:
            return defaultValues[0];
          case Type$1.BOOL2:
          case Type$1.INT2:
          case Type$1.UINT2:
          case Type$1.FLOAT2:
            return defaultValues[1];
          case Type$1.BOOL4:
          case Type$1.INT4:
          case Type$1.UINT4:
          case Type$1.FLOAT4:
            return defaultValues[2];
          case Type$1.MAT4:
            return defaultValues[3];
          case Type$1.SAMPLER2D:
            return 'default-texture';
          case Type$1.SAMPLER_CUBE:
            return 'default-cube-texture';
          case Type$1.SAMPLER2D_ARRAY:
            return 'default-array-texture';
          case Type$1.SAMPLER3D:
            return 'default-3d-texture';
        }
        return defaultValues[0];
      }
      function getStringFromType(type) {
        switch (type) {
          case Type$1.SAMPLER2D:
            return '-texture';
          case Type$1.SAMPLER_CUBE:
            return '-cube-texture';
          case Type$1.SAMPLER2D_ARRAY:
            return '-array-texture';
          case Type$1.SAMPLER3D:
            return '-3d-texture';
          default:
            return '-unknown';
        }
      }
      function overrideMacros(target, source) {
        var entries = Object.entries(source);
        var isDifferent = false;
        for (var i = 0; i < entries.length; i++) {
          if (target[entries[i][0]] !== entries[i][1]) {
            target[entries[i][0]] = entries[i][1];
            isDifferent = true;
          }
        }
        return isDifferent;
      }

      function mapDefine(info, def) {
        switch (info.type) {
          case 'boolean':
            return typeof def === 'number' ? def.toString() : def ? '1' : '0';
          case 'string':
            return def !== undefined ? def : info.options[0];
          case 'number':
            return def !== undefined ? def.toString() : info.range[0].toString();
          default:
            console.warn("unknown define type '" + info.type + "'");
            return '-1';
        }
      }
      function prepareDefines(defs, tDefs) {
        var macros = [];
        for (var i = 0; i < tDefs.length; i++) {
          var tmpl = tDefs[i];
          var name = tmpl.name;
          var v = defs[name];
          var value = mapDefine(tmpl, v);
          var isDefault = !v || v === '0';
          macros.push({
            name: name,
            value: value,
            isDefault: isDefault
          });
        }
        return macros;
      }
      function getShaderInstanceName(name, macros) {
        return name + macros.reduce(function (acc, cur) {
          return cur.isDefault ? acc : acc + "|" + cur.name + cur.value;
        }, '');
      }
      function dependencyCheck(dependencies, defines) {
        for (var i = 0; i < dependencies.length; i++) {
          var d = dependencies[i];
          if (d[0] === '!') {
            if (defines[d.slice(1)]) {
              return false;
            }
          } else if (!defines[d]) {
            return false;
          }
        }
        return true;
      }
      function getActiveAttributes(tmpl, gfxAttributes, defines) {
        var out = [];
        var attributes = tmpl.attributes;
        for (var i = 0; i < attributes.length; i++) {
          if (!dependencyCheck(attributes[i].defines, defines)) {
            continue;
          }
          out.push(gfxAttributes[i]);
        }
        return out;
      }
      function getVariantKey(programInfo, defines) {
        var tmplDefs = programInfo.defines;
        if (programInfo.uber) {
          var _key = '';
          for (var i = 0; i < tmplDefs.length; i++) {
            var tmplDef = tmplDefs[i];
            var value = defines[tmplDef.name];
            if (!value || !tmplDef._map) {
              continue;
            }
            var mapped = tmplDef._map(value);
            var offset = tmplDef._offset;
            _key += "" + offset + mapped + "|";
          }
          return "" + _key + programInfo.hash;
        }
        var key = 0;
        for (var _i = 0; _i < tmplDefs.length; _i++) {
          var _tmplDef = tmplDefs[_i];
          var _value = defines[_tmplDef.name];
          if (!_value || !_tmplDef._map) {
            continue;
          }
          var _mapped = _tmplDef._map(_value);
          var _offset = _tmplDef._offset;
          key |= _mapped << _offset;
        }
        return key.toString(16) + "|" + programInfo.hash;
      }
      var defaultUniformCounts = new Map();
      defaultUniformCounts.set('cc_joints', UBOSkinning.LAYOUT.members[0].count);
      defaultUniformCounts.set('cc_lightPos', UBOForwardLight.LIGHTS_PER_PASS);
      defaultUniformCounts.set('cc_lightColor', UBOForwardLight.LIGHTS_PER_PASS);
      defaultUniformCounts.set('cc_lightSizeRangeAngle', UBOForwardLight.LIGHTS_PER_PASS);
      defaultUniformCounts.set('cc_lightDir', UBOForwardLight.LIGHTS_PER_PASS);
      defaultUniformCounts.set('cc_lightBoundingSizeVS', UBOForwardLight.LIGHTS_PER_PASS);
      function getUniformSize(prevSize, m) {
        if (m.count) {
          return prevSize + GetTypeSize(m.type) * m.count;
        } else {
          var count = defaultUniformCounts.get(m.name);
          if (count !== undefined) {
            return prevSize + GetTypeSize(m.type) * count;
          }
          console.error("uniform '" + m.name + "' must have a count");
        }
        return prevSize;
      }
      function getSize(blockMembers) {
        return blockMembers.reduce(getUniformSize, 0);
      }
      function genHandles(tmpl) {
        var handleMap = {};
        for (var i = 0; i < tmpl.blocks.length; i++) {
          var block = tmpl.blocks[i];
          var members = block.members;
          var offset = 0;
          for (var j = 0; j < members.length; j++) {
            var uniform = members[j];
            handleMap[uniform.name] = genHandle(block.binding, uniform.type, uniform.count, offset);
            offset += (GetTypeSize(uniform.type) >> 2) * uniform.count;
          }
        }
        for (var _i2 = 0; _i2 < tmpl.samplerTextures.length; _i2++) {
          var samplerTexture = tmpl.samplerTextures[_i2];
          handleMap[samplerTexture.name] = genHandle(samplerTexture.binding, samplerTexture.type, samplerTexture.count);
        }
        return handleMap;
      }
      function getBitCount(cnt) {
        return Math.ceil(Math.log2(Math.max(cnt, 2)));
      }
      function populateMacros(tmpl) {
        var offset = 0;
        var _loop = function _loop() {
          var def = tmpl.defines[i];
          var cnt = 1;
          if (def.type === 'number') {
            var range = def.range;
            cnt = getBitCount(range[1] - range[0] + 1);
            def._map = function (value) {
              return value - range[0];
            };
          } else if (def.type === 'string') {
            cnt = getBitCount(def.options.length);
            def._map = function (value) {
              return Math.max(0, def.options.findIndex(function (s) {
                return s === value;
              }));
            };
          } else if (def.type === 'boolean') {
            def._map = function (value) {
              return value ? 1 : 0;
            };
          }
          def._offset = offset;
          offset += cnt;
        };
        for (var i = 0; i < tmpl.defines.length; i++) {
          _loop();
        }
        if (offset > 31) {
          tmpl.uber = true;
        }
        tmpl.constantMacros = '';
        for (var key in tmpl.builtins.statistics) {
          tmpl.constantMacros += "#define " + key + " " + tmpl.builtins.statistics[key] + "\n";
        }
      }
      function getCombinationDefines(combination) {
        var defines = Object.keys(combination).reduce(function (out, name) {
          return out.reduce(function (acc, cur) {
            var choices = combination[name];
            for (var i = 0; i < choices.length; ++i) {
              var _defines = _extends({}, cur);
              _defines[name] = choices[i];
              acc.push(_defines);
            }
            return acc;
          }, []);
        }, [{}]);
        return defines;
      }
      function addEffectDefaultProperties(effect) {
        for (var i = 0; i < effect.techniques.length; i++) {
          var tech = effect.techniques[i];
          for (var j = 0; j < tech.passes.length; j++) {
            var pass = tech.passes[j];
            if (pass.propertyIndex !== undefined && pass.properties === undefined) {
              pass.properties = tech.passes[pass.propertyIndex].properties;
            }
          }
        }
      }

      var _dsLayoutInfo = new DescriptorSetLayoutInfo();
      function insertBuiltinBindings(tmpl, tmplInfo, source, type, outBindings) {
        var target = tmpl.builtins[type];
        var tempBlocks = [];
        var _loop = function _loop() {
          var b = target.blocks[i];
          var info = source.layouts[b.name];
          var binding = info && source.bindings.find(function (bd) {
            return bd.binding === info.binding;
          });
          if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_BUFFER_TYPE)) {
            console.warn("builtin UBO '" + b.name + "' not available!");
            return 1;
          }
          tempBlocks.push(info);
          if (outBindings && !outBindings.includes(binding)) outBindings.push(binding);
        };
        for (var i = 0; i < target.blocks.length; i++) {
          if (_loop()) continue;
        }
        Array.prototype.unshift.apply(tmplInfo.shaderInfo.blocks, tempBlocks);
        var tempSamplerTextures = [];
        var _loop2 = function _loop2() {
          var s = target.samplerTextures[_i];
          var info = source.layouts[s.name];
          var binding = info && source.bindings.find(function (bd) {
            return bd.binding === info.binding;
          });
          if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_SAMPLER_TYPE)) {
            console.warn("builtin samplerTexture '" + s.name + "' not available!");
            return 1;
          }
          tempSamplerTextures.push(info);
          if (outBindings && !outBindings.includes(binding)) outBindings.push(binding);
        };
        for (var _i = 0; _i < target.samplerTextures.length; _i++) {
          if (_loop2()) continue;
        }
        Array.prototype.unshift.apply(tmplInfo.shaderInfo.samplerTextures, tempSamplerTextures);
        if (outBindings) outBindings.sort(function (a, b) {
          return a.binding - b.binding;
        });
      }
      var ProgramLib = function () {
        function ProgramLib() {
          this._templates = {};
          this._cache = {};
          this._templateInfos = {};
        }
        var _proto = ProgramLib.prototype;
        _proto.register = function register(effect) {
          for (var i = 0; i < effect.shaders.length; i++) {
            var tmpl = this.define(effect.shaders[i]);
            tmpl.effectName = effect.name;
          }
          for (var _i2 = 0; _i2 < effect.techniques.length; _i2++) {
            var tech = effect.techniques[_i2];
            for (var j = 0; j < tech.passes.length; j++) {
              var pass = tech.passes[j];
              if (pass.propertyIndex !== undefined && pass.properties === undefined) {
                pass.properties = tech.passes[pass.propertyIndex].properties;
              }
            }
          }
        };
        _proto.define = function define(shader) {
          var curTmpl = this._templates[shader.name];
          if (curTmpl && curTmpl.hash === shader.hash) {
            return curTmpl;
          }
          var tmpl = _extends({}, shader);
          populateMacros(tmpl);
          this._templates[shader.name] = tmpl;
          if (!this._templateInfos[tmpl.hash]) {
            var tmplInfo = {};
            tmplInfo.samplerStartBinding = tmpl.blocks.length;
            tmplInfo.shaderInfo = new ShaderInfo();
            tmplInfo.blockSizes = [];
            tmplInfo.bindings = [];
            for (var i = 0; i < tmpl.blocks.length; i++) {
              var block = tmpl.blocks[i];
              tmplInfo.blockSizes.push(getSize(block.members));
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(block.binding, DescriptorType.UNIFORM_BUFFER, 1, block.stageFlags));
              tmplInfo.shaderInfo.blocks.push(new UniformBlock(SetIndex.MATERIAL, block.binding, block.name, block.members.map(function (m) {
                return new Uniform(m.name, m.type, m.count);
              }), 1));
            }
            for (var _i3 = 0; _i3 < tmpl.samplerTextures.length; _i3++) {
              var samplerTexture = tmpl.samplerTextures[_i3];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(samplerTexture.binding, DescriptorType.SAMPLER_TEXTURE, samplerTexture.count, samplerTexture.stageFlags));
              tmplInfo.shaderInfo.samplerTextures.push(new UniformSamplerTexture(SetIndex.MATERIAL, samplerTexture.binding, samplerTexture.name, samplerTexture.type, samplerTexture.count));
            }
            for (var _i4 = 0; _i4 < tmpl.samplers.length; _i4++) {
              var sampler = tmpl.samplers[_i4];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(sampler.binding, DescriptorType.SAMPLER, sampler.count, sampler.stageFlags));
              tmplInfo.shaderInfo.samplers.push(new UniformSampler(SetIndex.MATERIAL, sampler.binding, sampler.name, sampler.count));
            }
            for (var _i5 = 0; _i5 < tmpl.textures.length; _i5++) {
              var texture = tmpl.textures[_i5];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(texture.binding, DescriptorType.TEXTURE, texture.count, texture.stageFlags));
              tmplInfo.shaderInfo.textures.push(new UniformTexture(SetIndex.MATERIAL, texture.binding, texture.name, texture.type, texture.count));
            }
            for (var _i6 = 0; _i6 < tmpl.buffers.length; _i6++) {
              var buffer = tmpl.buffers[_i6];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(buffer.binding, DescriptorType.STORAGE_BUFFER, 1, buffer.stageFlags));
              tmplInfo.shaderInfo.buffers.push(new UniformStorageBuffer(SetIndex.MATERIAL, buffer.binding, buffer.name, 1, buffer.memoryAccess));
            }
            for (var _i7 = 0; _i7 < tmpl.images.length; _i7++) {
              var image = tmpl.images[_i7];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(image.binding, DescriptorType.STORAGE_IMAGE, image.count, image.stageFlags));
              tmplInfo.shaderInfo.images.push(new UniformStorageImage(SetIndex.MATERIAL, image.binding, image.name, image.type, image.count, image.memoryAccess));
            }
            for (var _i8 = 0; _i8 < tmpl.subpassInputs.length; _i8++) {
              var subpassInput = tmpl.subpassInputs[_i8];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(subpassInput.binding, DescriptorType.INPUT_ATTACHMENT, subpassInput.count, subpassInput.stageFlags));
              tmplInfo.shaderInfo.subpassInputs.push(new UniformInputAttachment(SetIndex.MATERIAL, subpassInput.binding, subpassInput.name, subpassInput.count));
            }
            tmplInfo.gfxAttributes = [];
            for (var _i9 = 0; _i9 < tmpl.attributes.length; _i9++) {
              var attr = tmpl.attributes[_i9];
              tmplInfo.gfxAttributes.push(new Attribute(attr.name, attr.format, attr.isNormalized, 0, attr.isInstanced, attr.location));
            }
            insertBuiltinBindings(tmpl, tmplInfo, localDescriptorSetLayout, 'locals');
            tmplInfo.shaderInfo.stages.push(new ShaderStage(ShaderStageFlagBit.VERTEX, ''));
            tmplInfo.shaderInfo.stages.push(new ShaderStage(ShaderStageFlagBit.FRAGMENT, ''));
            tmplInfo.handleMap = genHandles(tmpl);
            tmplInfo.setLayouts = [];
            this._templateInfos[tmpl.hash] = tmplInfo;
          }
          return tmpl;
        };
        _proto.getTemplate = function getTemplate(name) {
          return this._templates[name];
        };
        _proto.getTemplateInfo = function getTemplateInfo(name) {
          var hash = this._templates[name].hash;
          return this._templateInfos[hash];
        };
        _proto.getDescriptorSetLayout = function getDescriptorSetLayout(device, name, isLocal) {
          if (isLocal === void 0) {
            isLocal = false;
          }
          var tmpl = this._templates[name];
          var tmplInfo = this._templateInfos[tmpl.hash];
          if (!tmplInfo.setLayouts.length) {
            _dsLayoutInfo.bindings = tmplInfo.bindings;
            tmplInfo.setLayouts[SetIndex.MATERIAL] = device.createDescriptorSetLayout(_dsLayoutInfo);
            _dsLayoutInfo.bindings = localDescriptorSetLayout.bindings;
            tmplInfo.setLayouts[SetIndex.LOCAL] = device.createDescriptorSetLayout(_dsLayoutInfo);
          }
          return tmplInfo.setLayouts[isLocal ? SetIndex.LOCAL : SetIndex.MATERIAL];
        };
        _proto.hasProgram = function hasProgram(name) {
          return this._templates[name] !== undefined;
        };
        _proto.getKey = function getKey(name, defines) {
          var tmpl = this._templates[name];
          return getVariantKey(tmpl, defines);
        };
        _proto.destroyShaderByDefines = function destroyShaderByDefines(defines) {
          var _this = this;
          var names = Object.keys(defines);
          if (!names.length) {
            return;
          }
          var regexes = names.map(function (cur) {
            var val = defines[cur];
            if (typeof val === 'boolean') {
              val = val ? '1' : '0';
            }
            return new RegExp("" + cur + val);
          });
          var keys = Object.keys(this._cache).filter(function (k) {
            return regexes.every(function (re) {
              return re.test(_this._cache[k].name);
            });
          });
          for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var prog = this._cache[k];
            debug("destroyed shader " + prog.name);
            prog.destroy();
            delete this._cache[k];
          }
        };
        _proto.getGFXShader = function getGFXShader(device, name, defines, pipeline, key) {
          Object.assign(defines, pipeline.macros);
          if (!key) key = this.getKey(name, defines);
          var res = this._cache[key];
          if (res) {
            return res;
          }
          var tmpl = this._templates[name];
          var tmplInfo = this._templateInfos[tmpl.hash];
          if (!tmplInfo.pipelineLayout) {
            this.getDescriptorSetLayout(device, name);
            insertBuiltinBindings(tmpl, tmplInfo, globalDescriptorSetLayout, 'globals');
            tmplInfo.setLayouts[SetIndex.GLOBAL] = pipeline.descriptorSetLayout;
            tmplInfo.pipelineLayout = device.createPipelineLayout(new PipelineLayoutInfo(tmplInfo.setLayouts));
          }
          var macroArray = prepareDefines(defines, tmpl.defines);
          var prefix = pipeline.constantMacros + tmpl.constantMacros + macroArray.reduce(function (acc, cur) {
            return acc + "#define " + cur.name + " " + cur.value + "\n";
          }, '');
          var src = tmpl.glsl3;
          var deviceShaderVersion = getDeviceShaderVersion(device);
          if (deviceShaderVersion) {
            src = tmpl[deviceShaderVersion];
          } else {
            console.error('Invalid GFX API!');
          }
          tmplInfo.shaderInfo.stages[0].source = prefix + src.vert;
          tmplInfo.shaderInfo.stages[1].source = prefix + src.frag;
          tmplInfo.shaderInfo.attributes = getActiveAttributes(tmpl, tmplInfo.gfxAttributes, defines);
          tmplInfo.shaderInfo.name = getShaderInstanceName(name, macroArray);
          var shaderInfo = tmplInfo.shaderInfo;
          return this._cache[key] = device.createShader(shaderInfo);
        };
        return ProgramLib;
      }();
      function getDeviceShaderVersion(device) {
        switch (device.gfxAPI) {
          case API.GLES2:
          case API.WEBGL:
            return 'glsl1';
          case API.GLES3:
          case API.WEBGL2:
            return 'glsl3';
          default:
            return 'glsl4';
        }
      }
      var programLib = new ProgramLib();
      legacyCC.programLib = programLib;

      var _dec$3v, _class$3q, _class2$35, _initializer$2R, _initializer2$2h, _initializer3$1G, _initializer4$1q, _class3$U;
      var legacyBuiltinEffectNames = ['planar-shadow', 'skybox', 'deferred-lighting', 'bloom', 'hbao', 'copy-pass', 'post-process', 'profiler', 'splash-screen', 'unlit', 'sprite', 'particle', 'particle-gpu', 'particle-trail', 'billboard', 'terrain', 'graphics', 'clear-stencil', 'spine', 'occlusion-query', 'geometry-renderer', 'debug-renderer', 'ssss-blur', 'float-output-process'];
      var EffectAsset = exports('ek', (_dec$3v = ccclass$M('cc.EffectAsset'), _dec$3v(_class$3q = (_class2$35 = (_class3$U = function (_Asset) {
        _inheritsLoose(EffectAsset, _Asset);
        function EffectAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.techniques = _initializer$2R && _initializer$2R();
          _this.shaders = _initializer2$2h && _initializer2$2h();
          _this.combinations = _initializer3$1G && _initializer3$1G();
          _this.hideInEditor = _initializer4$1q && _initializer4$1q();
          return _this;
        }
        EffectAsset.register = function register(asset) {
          EffectAsset._effects[asset.name] = asset;
          EffectAsset._layoutValid = false;
        };
        EffectAsset.remove = function remove(asset) {
          if (typeof asset !== 'string') {
            if (EffectAsset._effects[asset.name] && EffectAsset._effects[asset.name] === asset) {
              delete EffectAsset._effects[asset.name];
            }
          } else {
            if (EffectAsset._effects[asset]) {
              delete EffectAsset._effects[asset];
              return;
            }
            for (var n in EffectAsset._effects) {
              if (EffectAsset._effects[n]._uuid === asset) {
                delete EffectAsset._effects[n];
                return;
              }
            }
          }
        };
        EffectAsset.get = function get(name) {
          if (EffectAsset._effects[name]) {
            return EffectAsset._effects[name];
          }
          for (var n in EffectAsset._effects) {
            if (EffectAsset._effects[n]._uuid === name) {
              return EffectAsset._effects[n];
            }
          }
          if (legacyBuiltinEffectNames.includes(name)) {
            warnID(16101, name);
          }
          return null;
        };
        EffectAsset.getAll = function getAll() {
          return EffectAsset._effects;
        };
        EffectAsset.isLayoutValid = function isLayoutValid() {
          return EffectAsset._layoutValid;
        };
        EffectAsset.setLayoutValid = function setLayoutValid() {
          EffectAsset._layoutValid = true;
        };
        var _proto = EffectAsset.prototype;
        _proto.onLoaded = function onLoaded() {
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            addEffectDefaultProperties(this);
            var _programLib = legacyCC.rendering.programLib;
            _programLib.addEffect(this);
            _programLib.init(deviceManager.gfxDevice);
          } else {
            programLib.register(this);
          }
          EffectAsset.register(this);
          {
            legacyCC.game.once(legacyCC.Game.EVENT_RENDERER_INITED, this._precompile, this);
          }
        };
        _proto._precompile = function _precompile() {
          var _this2 = this;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            legacyCC.rendering.programLib.precompileEffect(deviceManager.gfxDevice, this);
            return;
          }
          var root = legacyCC.director.root;
          var _loop = function _loop() {
            var shader = _this2.shaders[i];
            var combination = _this2.combinations[i];
            if (!combination) {
              return 1;
            }
            var defines = getCombinationDefines(combination);
            defines.forEach(function (defines) {
              return programLib.getGFXShader(deviceManager.gfxDevice, shader.name, defines, root.pipeline);
            });
          };
          for (var i = 0; i < this.shaders.length; i++) {
            if (_loop()) continue;
          }
        };
        _proto.destroy = function destroy() {
          EffectAsset.remove(this);
          return _Asset.prototype.destroy.call(this);
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          var effect = EffectAsset.get('builtin-unlit');
          this.name = 'builtin-unlit';
          this.shaders = effect.shaders;
          this.combinations = effect.combinations;
          this.techniques = effect.techniques;
        };
        _proto.validate = function validate() {
          return this.techniques.length > 0 && this.shaders.length > 0;
        };
        return EffectAsset;
      }(Asset), _class3$U._effects = {}, _class3$U._layoutValid = true, _class3$U), (_initializer$2R = applyDecoratedInitializer(_class2$35.prototype, "techniques", [serializable$p], function () {
        return [];
      }), _initializer2$2h = applyDecoratedInitializer(_class2$35.prototype, "shaders", [serializable$p], function () {
        return [];
      }), _initializer3$1G = applyDecoratedInitializer(_class2$35.prototype, "combinations", [serializable$p], function () {
        return [];
      }), _initializer4$1q = applyDecoratedInitializer(_class2$35.prototype, "hideInEditor", [serializable$p, editorOnly], function () {
        return false;
      })), _class2$35)) || _class$3q));
      legacyCC.EffectAsset = EffectAsset;

      var isMatchByWord = function isMatchByWord(path, test) {
        if (path.length > test.length) {
          var nextAscii = path.charCodeAt(test.length);
          return nextAscii === 47;
        }
        return true;
      };
      var processOptions = function processOptions(options) {
        var uuids = options.uuids;
        var paths = options.paths;
        var types = options.types;
        var bundles = options.deps;
        var realEntries = options.paths = Object.create(null);
        if (options.debug === false) {
          for (var i = 0, l = uuids.length; i < l; i++) {
            uuids[i] = decodeUuid(uuids[i]);
          }
          for (var id in paths) {
            var entry = paths[id];
            var type = entry[1];
            entry[1] = types[type];
          }
        } else {
          var out = Object.create(null);
          for (var _i = 0, _l = uuids.length; _i < _l; _i++) {
            var uuid = uuids[_i];
            uuids[_i] = out[uuid] = decodeUuid(uuid);
          }
          uuids = out;
        }
        for (var _id in paths) {
          var _entry = paths[_id];
          realEntries[uuids[_id]] = _entry;
        }
        var scenes = options.scenes;
        for (var name in scenes) {
          var _uuid = scenes[name];
          scenes[name] = uuids[_uuid];
        }
        var packs = options.packs;
        for (var packId in packs) {
          var packedIds = packs[packId];
          for (var j = 0; j < packedIds.length; ++j) {
            packedIds[j] = uuids[packedIds[j]];
          }
        }
        var versions = options.versions;
        if (versions) {
          for (var folder in versions) {
            var entries = versions[folder];
            for (var _i2 = 0; _i2 < entries.length; _i2 += 2) {
              var _uuid2 = entries[_i2];
              entries[_i2] = uuids[_uuid2] || _uuid2;
            }
          }
        }
        var redirect = options.redirect;
        if (redirect) {
          for (var _i3 = 0; _i3 < redirect.length; _i3 += 2) {
            redirect[_i3] = uuids[redirect[_i3]];
            redirect[_i3 + 1] = bundles[redirect[_i3 + 1]];
          }
        }
        var extensionMap = options.extensionMap;
        if (extensionMap) {
          var _loop = function _loop(ext) {
            if (!Object.prototype.hasOwnProperty.call(options.extensionMap, ext)) {
              return 1;
            }
            options.extensionMap[ext].forEach(function (uuid, index) {
              options.extensionMap[ext][index] = uuids[uuid] || uuid;
            });
          };
          for (var ext in options.extensionMap) {
            if (_loop(ext)) continue;
          }
        }
      };
      var Config = function () {
        function Config() {
          this.name = '';
          this.base = '';
          this.importBase = '';
          this.nativeBase = '';
          this.deps = null;
          this.assetInfos = new Cache();
          this.scenes = new Cache();
          this.paths = new Cache();
        }
        var _proto = Config.prototype;
        _proto.init = function init(options) {
          var _this = this;
          processOptions(options);
          this.importBase = options.importBase || '';
          this.nativeBase = options.nativeBase || '';
          this.base = options.base || '';
          this.name = options.name || '';
          this.deps = options.deps || [];
          this._initUuid(options.uuids);
          this._initPath(options.paths);
          this._initScene(options.scenes);
          this._initPackage(options.packs);
          this._initVersion(options.versions);
          this._initRedirect(options.redirect);
          var _loop2 = function _loop2(ext) {
            if (!Object.prototype.hasOwnProperty.call(options.extensionMap, ext)) {
              return 1;
            }
            options.extensionMap[ext].forEach(function (uuid) {
              var assetInfo = _this.assetInfos.get(uuid);
              if (assetInfo) {
                assetInfo.extension = ext;
              }
            });
          };
          for (var ext in options.extensionMap) {
            if (_loop2(ext)) continue;
          }
        };
        _proto.getInfoWithPath = function getInfoWithPath(path, type) {
          if (!path) {
            return null;
          }
          path = normalize(path);
          var items = this.paths.get(path);
          if (items) {
            if (type) {
              for (var i = 0, l = items.length; i < l; i++) {
                var assetInfo = items[i];
                if (isChildClassOf(assetInfo.ctor, type)) {
                  return assetInfo;
                }
              }
            } else {
              return items[0];
            }
          }
          return null;
        };
        _proto.getDirWithPath = function getDirWithPath(path, type, out) {
          path = normalize(path);
          if (path[path.length - 1] === '/') {
            path = path.slice(0, -1);
          }
          var infos = out || [];
          this.paths.forEach(function (items, p) {
            if (p.startsWith(path) && isMatchByWord(p, path) || !path) {
              for (var i = 0, l = items.length; i < l; i++) {
                var entry = items[i];
                if (!type || isChildClassOf(entry.ctor, type)) {
                  infos.push(entry);
                }
              }
            }
          });
          return infos;
        };
        _proto.getAssetInfo = function getAssetInfo(uuid) {
          return this.assetInfos.get(uuid) || null;
        };
        _proto.getSceneInfo = function getSceneInfo(name) {
          if (!name.endsWith('.scene')) {
            name += '.scene';
          }
          if (name[0] !== '/' && !name.startsWith('db://')) {
            name = "/" + name;
          }
          var info = this.scenes.find(function (val, key) {
            return key.endsWith(name);
          });
          return info;
        };
        _proto.destroy = function destroy() {
          this.paths.destroy();
          this.scenes.destroy();
          this.assetInfos.destroy();
        };
        _proto._initUuid = function _initUuid(uuidList) {
          if (!uuidList) {
            return;
          }
          this.assetInfos.clear();
          for (var i = 0, l = uuidList.length; i < l; i++) {
            var uuid = uuidList[i];
            this.assetInfos.add(uuid, {
              uuid: uuid
            });
          }
        };
        _proto._initPath = function _initPath(pathList) {
          if (!pathList) {
            return;
          }
          var paths = this.paths;
          paths.clear();
          for (var uuid in pathList) {
            var info = pathList[uuid];
            var path = info[0];
            var type = info[1];
            var isSubAsset = info.length === 3;
            var assetInfo = this.assetInfos.get(uuid);
            assetInfo.path = path;
            assetInfo.ctor = getClassById(type);
            if (paths.has(path)) {
              if (isSubAsset) {
                paths.get(path).push(assetInfo);
              } else {
                paths.get(path).unshift(assetInfo);
              }
            } else {
              paths.add(path, [assetInfo]);
            }
          }
        };
        _proto._initScene = function _initScene(sceneList) {
          if (!sceneList) {
            return;
          }
          var scenes = this.scenes;
          scenes.clear();
          var assetInfos = this.assetInfos;
          for (var sceneName in sceneList) {
            var uuid = sceneList[sceneName];
            var assetInfo = assetInfos.get(uuid);
            assetInfo.url = sceneName;
            scenes.add(sceneName, assetInfo);
          }
        };
        _proto._initPackage = function _initPackage(packageList) {
          if (!packageList) {
            return;
          }
          var assetInfos = this.assetInfos;
          for (var packUuid in packageList) {
            var uuids = packageList[packUuid];
            var pack = {
              uuid: packUuid,
              packedUuids: uuids,
              ext: '.json'
            };
            assetInfos.add(packUuid, pack);
            for (var i = 0, l = uuids.length; i < l; i++) {
              var uuid = uuids[i];
              var assetInfo = assetInfos.get(uuid);
              var assetPacks = assetInfo.packs;
              if (assetPacks) {
                if (l === 1) {
                  assetPacks.unshift(pack);
                } else {
                  assetPacks.push(pack);
                }
              } else {
                assetInfo.packs = [pack];
              }
            }
          }
        };
        _proto._initVersion = function _initVersion(versions) {
          if (!versions) {
            return;
          }
          var assetInfos = this.assetInfos;
          var entries = versions["import"];
          if (entries) {
            for (var i = 0, l = entries.length; i < l; i += 2) {
              var uuid = entries[i];
              var assetInfo = assetInfos.get(uuid);
              assetInfo.ver = entries[i + 1];
            }
          }
          entries = versions["native"];
          if (entries) {
            for (var _i4 = 0, _l2 = entries.length; _i4 < _l2; _i4 += 2) {
              var _uuid3 = entries[_i4];
              var _assetInfo = assetInfos.get(_uuid3);
              _assetInfo.nativeVer = entries[_i4 + 1];
            }
          }
        };
        _proto._initRedirect = function _initRedirect(redirect) {
          if (!redirect) {
            return;
          }
          var assetInfos = this.assetInfos;
          for (var i = 0, l = redirect.length; i < l; i += 2) {
            var uuid = redirect[i];
            var assetInfo = assetInfos.get(uuid);
            assetInfo.redirect = redirect[i + 1];
          }
        };
        return Config;
      }();

      function visitAsset(asset, deps) {
        if (!asset._uuid) {
          return;
        }
        deps.push(asset._uuid);
      }
      function visitComponent(comp, deps) {
        var props = Object.getOwnPropertyNames(comp);
        for (var i = 0; i < props.length; i++) {
          var propName = props[i];
          if (propName === 'node' || propName === '__eventTargets') {
            continue;
          }
          var value = comp[propName];
          if (typeof value === 'object' && value) {
            if (Array.isArray(value)) {
              for (var j = 0; j < value.length; j++) {
                var val = value[j];
                if (val instanceof Asset) {
                  visitAsset(val, deps);
                }
              }
            } else if (!value.constructor || value.constructor === Object) {
              var keys = Object.getOwnPropertyNames(value);
              for (var _j = 0; _j < keys.length; _j++) {
                var _val = value[keys[_j]];
                if (_val instanceof Asset) {
                  visitAsset(_val, deps);
                }
              }
            } else if (value instanceof Asset) {
              visitAsset(value, deps);
            }
          }
        }
      }
      function visitNode$1(node, deps) {
        for (var i = 0; i < node._components.length; i++) {
          visitComponent(node._components[i], deps);
        }
        for (var _i = 0; _i < node._children.length; _i++) {
          visitNode$1(node._children[_i], deps);
        }
      }
      function descendOpRef(asset, refs, exclude, op) {
        exclude.push(asset._uuid);
        var depends = dependUtil.getDeps(asset._uuid);
        for (var i = 0, l = depends.length; i < l; i++) {
          var dependAsset = assets.get(depends[i]);
          if (!dependAsset) {
            continue;
          }
          var uuid = dependAsset._uuid;
          if (!(uuid in refs)) {
            refs[uuid] = dependAsset.refCount + op;
          } else {
            refs[uuid] += op;
          }
          if (exclude.includes(uuid)) {
            continue;
          }
          descendOpRef(dependAsset, refs, exclude, op);
        }
      }
      var _temp = [];
      function checkCircularReference(asset) {
        var refs = Object.create(null);
        refs[asset._uuid] = asset.refCount;
        descendOpRef(asset, refs, _temp, -1);
        _temp.length = 0;
        if (refs[asset._uuid] !== 0) {
          return refs[asset._uuid];
        }
        for (var uuid in refs) {
          if (refs[uuid] !== 0) {
            descendOpRef(assets.get(uuid), refs, _temp, 1);
          }
        }
        _temp.length = 0;
        return refs[asset._uuid];
      }
      var ReleaseManager = function () {
        function ReleaseManager() {
          this._persistNodeDeps = new Cache();
          this._toDelete = new Cache();
          this._eventListener = false;
          this._dontDestroyAssets = [];
        }
        var _proto = ReleaseManager.prototype;
        _proto.addIgnoredAsset = function addIgnoredAsset(asset) {
          this._dontDestroyAssets.push(asset._uuid);
        };
        _proto.init = function init() {
          this._persistNodeDeps.clear();
          this._toDelete.clear();
        };
        _proto._addPersistNodeRef = function _addPersistNodeRef(node) {
          var deps = [];
          visitNode$1(node, deps);
          for (var i = 0, l = deps.length; i < l; i++) {
            var dependAsset = assets.get(deps[i]);
            if (dependAsset) {
              dependAsset.addRef();
            }
          }
          this._persistNodeDeps.add(node.uuid, deps);
        };
        _proto._removePersistNodeRef = function _removePersistNodeRef(node) {
          if (!this._persistNodeDeps.has(node.uuid)) {
            return;
          }
          var deps = this._persistNodeDeps.get(node.uuid);
          for (var i = 0, l = deps.length; i < l; i++) {
            var dependAsset = assets.get(deps[i]);
            if (dependAsset) {
              dependAsset.decRef();
            }
          }
          this._persistNodeDeps.remove(node.uuid);
        };
        _proto._autoRelease = function _autoRelease(oldScene, newScene, persistNodes) {
          if (oldScene) {
            var childs = dependUtil.getDeps(oldScene.uuid);
            for (var i = 0, l = childs.length; i < l; i++) {
              var asset = assets.get(childs[i]);
              if (asset) {
                asset.decRef(oldScene.autoReleaseAssets);
              }
            }
            var dependencies = dependUtil._depends.get(oldScene.uuid);
            if (dependencies && dependencies.persistDeps) {
              var persistDeps = dependencies.persistDeps;
              for (var _i2 = 0, _l = persistDeps.length; _i2 < _l; _i2++) {
                var _asset = assets.get(persistDeps[_i2]);
                if (_asset) {
                  _asset.decRef(oldScene.autoReleaseAssets);
                }
              }
            }
            if (oldScene.uuid !== newScene.uuid) {
              dependUtil.remove(oldScene.uuid);
            }
          }
          var sceneDeps = dependUtil._depends.get(newScene.uuid);
          if (sceneDeps) {
            sceneDeps.persistDeps = [];
          }
          for (var key in persistNodes) {
            var _ref;
            var node = persistNodes[key];
            var deps = this._persistNodeDeps.get(node.uuid);
            for (var _iterator = _createForOfIteratorHelperLoose(deps), _step; !(_step = _iterator()).done;) {
              var dep = _step.value;
              var dependAsset = assets.get(dep);
              if (dependAsset) {
                dependAsset.addRef();
              }
            }
            if (!sceneDeps) {
              continue;
            }
            (_ref = sceneDeps.persistDeps).push.apply(_ref, deps);
          }
        };
        _proto.tryRelease = function tryRelease(asset, force) {
          if (force === void 0) {
            force = false;
          }
          if (!(asset instanceof Asset)) {
            return;
          }
          if (force) {
            this._free(asset, force);
            return;
          }
          this._toDelete.add(asset._uuid, asset);
          if (!this._eventListener) {
            this._eventListener = true;
            callInNextTick(this._freeAssets.bind(this));
          }
        };
        _proto._freeAssets = function _freeAssets() {
          var _this = this;
          this._eventListener = false;
          this._toDelete.forEach(function (asset) {
            _this._free(asset);
          });
          this._toDelete.clear();
        };
        _proto._free = function _free(asset, force) {
          if (force === void 0) {
            force = false;
          }
          var uuid = asset._uuid;
          this._toDelete.remove(uuid);
          if (!isValid(asset, true) || this._dontDestroyAssets.indexOf(uuid) !== -1) {
            return;
          }
          if (!force) {
            if (asset.refCount > 0) {
              if (checkCircularReference(asset) > 0) {
                return;
              }
            }
          }
          assets.remove(uuid);
          var depends = dependUtil.getDeps(uuid);
          for (var i = 0, l = depends.length; i < l; i++) {
            var dependAsset = assets.get(depends[i]);
            if (dependAsset) {
              dependAsset.decRef(false);
              {
                this._free(dependAsset, false);
              }
            }
          }
          {
            asset.destroy();
          }
          dependUtil.remove(uuid);
        };
        return ReleaseManager;
      }();
      var releaseManager = new ReleaseManager();

      var defaultProgressCallback = null;
      function setDefaultProgressCallback(onProgress) {
        defaultProgressCallback = onProgress;
      }
      function clear(task, clearRef) {
        for (var i = 0, l = task.input.length; i < l; i++) {
          var _item = task.input[i];
          if (clearRef) {
            if (!_item.isNative && _item.content instanceof Asset) {
              _item.content.decRef(false);
            }
          }
          _item.recycle();
        }
        task.input = null;
      }
      function urlAppendTimestamp(url, append) {
        if (append) {
          if (/\?/.test(url)) {
            return url + "&_t=" + Date.now();
          }
          return url + "?_t=" + Date.now();
        }
        return url;
      }
      function retry(process, times, wait, onComplete, index) {
        if (index === void 0) {
          index = 0;
        }
        process(index, function (err, result) {
          index++;
          if (!err || index > times) {
            if (onComplete) {
              onComplete(err, result);
            }
          } else {
            setTimeout(function () {
              retry(process, times, wait, onComplete, index);
            }, wait);
          }
        });
      }
      function getDepends(uuid, data, exclude, depends, config) {
        try {
          var info = dependUtil.parse(uuid, data);
          for (var i = 0, l = info.deps.length; i < l; i++) {
            var dep = info.deps[i];
            if (!(dep in exclude)) {
              exclude[dep] = true;
              depends.push({
                uuid: dep,
                bundle: config && config.name
              });
            }
          }
          if (info.nativeDep) {
            if (config) {
              info.nativeDep.bundle = config.name;
            }
            depends.push(_extends({}, info.nativeDep));
          }
        } catch (e) {
          error(e.message, e.stack);
        }
      }
      function cache(id, asset, cacheAsset) {
        if (!asset) {
          return;
        }
        cacheAsset = cacheAsset !== undefined ? cacheAsset : legacyCC.assetManager.cacheAsset;
        if (!isScene(asset) && cacheAsset && !asset.isDefault) {
          assets.add(id, asset);
        }
      }
      function setProperties(uuid, asset, assetsMap) {
        var missingAsset = false;
        var depends = dependMap.get(asset);
        if (depends) {
          var missingAssetReporter = null;
          for (var i = 0, l = depends.length; i < l; i++) {
            var depend = depends[i];
            var dependAsset = assetsMap[depend.uuid + "@import"];
            if (!dependAsset) {
              {
                error("The asset " + depend.uuid + " is missing!");
              }
              legacyCC.assetManager.dispatchAssetMissing(asset, depend.owner, depend.prop, depend.uuid);
              if (depend.type && depend.type !== Asset) {
                var placeHolder = new depend.type();
                placeHolder.initDefault(depend.uuid);
                depend.owner[depend.prop] = placeHolder;
              }
              missingAsset = true;
            } else {
              depend.owner[depend.prop] = dependAsset.addRef();
            }
          }
          if (missingAssetReporter) {
            missingAssetReporter.reportByOwner();
          }
          dependMap["delete"](asset);
        }
        if (nativeDependMap.has(asset)) {
          if (assetsMap[uuid + "@native"]) {
            asset._nativeAsset = assetsMap[uuid + "@native"];
          } else {
            missingAsset = true;
            console.error("the native asset of " + uuid + " is missing!");
          }
          nativeDependMap["delete"](asset);
        }
        return missingAsset;
      }
      function gatherAsset(task) {
        var source = task.source;
        if (!task.options.__outputAsArray__ && source.length === 1) {
          task.output = source[0].content;
        } else {
          var output = task.output = [];
          for (var i = 0, l = source.length; i < l; i++) {
            output.push(source[i].content);
          }
        }
      }
      function forEach(array, process, onComplete) {
        var count = 0;
        var errs = [];
        var length = array.length;
        if (length === 0 && onComplete) {
          onComplete(errs);
        }
        var cb = function cb(err) {
          if (err) {
            errs.push(err);
          }
          count++;
          if (count === length) {
            if (onComplete) {
              onComplete(errs);
            }
          }
        };
        for (var i = 0; i < length; i++) {
          process(array[i], cb);
        }
      }
      function parseParameters(options, onProgress, onComplete) {
        var optionsOut = options;
        var onProgressOut = onProgress;
        var onCompleteOut = onComplete;
        if (onComplete === undefined) {
          var isCallback = typeof options === 'function';
          if (onProgress) {
            onCompleteOut = onProgress;
            if (!isCallback) {
              onProgressOut = null;
            }
          } else if (onProgress === undefined && isCallback) {
            onCompleteOut = options;
            optionsOut = null;
            onProgressOut = null;
          }
          if (onProgress !== undefined && isCallback) {
            onProgressOut = options;
            optionsOut = null;
          }
        }
        return {
          options: optionsOut || Object.create(null),
          onProgress: onProgressOut,
          onComplete: onCompleteOut
        };
      }
      function parseLoadResArgs(type, onProgress, onComplete) {
        var typeOut = type;
        var onProgressOut = onProgress;
        var onCompleteOut = onComplete;
        if (onComplete === undefined) {
          var isValidType = isChildClassOf(type, Asset);
          if (onProgress) {
            onCompleteOut = onProgress;
            if (isValidType) {
              onProgressOut = null;
            }
          } else if (onProgress === undefined && !isValidType) {
            onCompleteOut = type;
            onProgressOut = null;
            typeOut = null;
          }
          if (onProgress !== undefined && !isValidType) {
            onProgressOut = type;
            typeOut = null;
          }
        }
        return {
          type: typeOut,
          onProgress: onProgressOut || defaultProgressCallback,
          onComplete: onCompleteOut
        };
      }
      function checkCircleReference(owner, uuid, map, checked) {
        if (checked === void 0) {
          checked = {};
        }
        var item = map[uuid];
        if (!item || checked[uuid]) {
          return false;
        }
        checked[uuid] = true;
        var result = false;
        var deps = dependUtil.getDeps(uuid);
        if (deps) {
          for (var i = 0, l = deps.length; i < l; i++) {
            var dep = deps[i];
            if (dep === owner || checkCircleReference(owner, dep, map, checked)) {
              result = true;
              break;
            }
          }
        }
        return result;
      }
      function asyncify(cb) {
        return function (p1, p2) {
          if (!cb) {
            return;
          }
          var refs = [];
          if (Array.isArray(p2)) {
            p2.forEach(function (x) {
              return x instanceof Asset && refs.push(x.addRef());
            });
          } else if (p2 instanceof Asset) {
            refs.push(p2.addRef());
          }
          callInNextTick(function () {
            refs.forEach(function (x) {
              return x.decRef(false);
            });
            cb(p1, p2);
          });
        };
      }

      var Bundle = function () {
        function Bundle() {
          this._config = new Config();
        }
        var _proto = Bundle.prototype;
        _proto.getInfoWithPath = function getInfoWithPath(path, type) {
          return this._config.getInfoWithPath(path, type);
        };
        _proto.getDirWithPath = function getDirWithPath(path, type, out) {
          return this._config.getDirWithPath(path, type, out);
        };
        _proto.getAssetInfo = function getAssetInfo(uuid) {
          return this._config.getAssetInfo(uuid);
        };
        _proto.getSceneInfo = function getSceneInfo(name) {
          return this._config.getSceneInfo(name);
        };
        _proto.init = function init(options) {
          this._config.init(options);
          bundles.add(options.name, this);
        };
        _proto.load = function load(paths, type, onProgress, onComplete) {
          var _parseLoadResArgs = parseLoadResArgs(type, onProgress, onComplete),
            _type = _parseLoadResArgs.type,
            onProg = _parseLoadResArgs.onProgress,
            onComp = _parseLoadResArgs.onComplete;
          var options = {
            __requestType__: RequestType.PATH,
            type: _type,
            bundle: this.name,
            __outputAsArray__: Array.isArray(paths)
          };
          legacyCC.assetManager.loadAny(paths, options, onProg, onComp);
        };
        _proto.preload = function preload(paths, type, onProgress, onComplete) {
          var _parseLoadResArgs2 = parseLoadResArgs(type, onProgress, onComplete),
            _type = _parseLoadResArgs2.type,
            onProg = _parseLoadResArgs2.onProgress,
            onComp = _parseLoadResArgs2.onComplete;
          legacyCC.assetManager.preloadAny(paths, {
            __requestType__: RequestType.PATH,
            type: _type,
            bundle: this.name
          }, onProg, onComp);
        };
        _proto.loadDir = function loadDir(dir, type, onProgress, onComplete) {
          var _parseLoadResArgs3 = parseLoadResArgs(type, onProgress, onComplete),
            _type = _parseLoadResArgs3.type,
            onProg = _parseLoadResArgs3.onProgress,
            onComp = _parseLoadResArgs3.onComplete;
          legacyCC.assetManager.loadAny(dir, {
            __requestType__: RequestType.DIR,
            type: _type,
            bundle: this.name,
            __outputAsArray__: true
          }, onProg, onComp);
        };
        _proto.preloadDir = function preloadDir(dir, type, onProgress, onComplete) {
          var _parseLoadResArgs4 = parseLoadResArgs(type, onProgress, onComplete),
            _type = _parseLoadResArgs4.type,
            onProg = _parseLoadResArgs4.onProgress,
            onComp = _parseLoadResArgs4.onComplete;
          legacyCC.assetManager.preloadAny(dir, {
            __requestType__: RequestType.DIR,
            type: _type,
            bundle: this.name
          }, onProg, onComp);
        };
        _proto.loadScene = function loadScene(sceneName, options, onProgress, onComplete) {
          var _parseParameters = parseParameters(options, onProgress, onComplete),
            opts = _parseParameters.options,
            onProg = _parseParameters.onProgress,
            onComp = _parseParameters.onComplete;
          opts.preset = opts.preset || 'scene';
          opts.bundle = this.name;
          legacyCC.assetManager.loadAny({
            scene: sceneName
          }, opts, onProg, function (err, sceneAsset) {
            if (err) {
              error(err.message, err.stack);
            } else if (sceneAsset.scene) {
              var scene = sceneAsset.scene;
              scene._id = sceneAsset._uuid;
              scene.name = sceneAsset.name;
            } else {
              err = new Error("The asset " + sceneAsset._uuid + " is not a scene");
            }
            if (onComp) {
              onComp(err, sceneAsset);
            }
          });
        };
        _proto.preloadScene = function preloadScene(sceneName, options, onProgress, onComplete) {
          var _parseParameters2 = parseParameters(options, onProgress, onComplete),
            opts = _parseParameters2.options,
            onProg = _parseParameters2.onProgress,
            onComp = _parseParameters2.onComplete;
          opts.bundle = this.name;
          legacyCC.assetManager.preloadAny({
            scene: sceneName
          }, opts, onProg, function (err) {
            if (err) {
              errorID(1210, sceneName, err.message);
            }
            if (onComp) {
              onComp(err);
            }
          });
        };
        _proto.get = function get(path, type) {
          var info = this.getInfoWithPath(path, type);
          if (info) {
            return assets.get(info.uuid) || null;
          }
          return null;
        };
        _proto.release = function release(path, type) {
          var asset = this.get(path, type);
          if (asset) {
            releaseManager.tryRelease(asset, true);
          }
        };
        _proto.releaseUnusedAssets = function releaseUnusedAssets() {
          var _this = this;
          assets.forEach(function (asset) {
            var info = _this.getAssetInfo(asset._uuid);
            if (info && !info.redirect) {
              releaseManager.tryRelease(asset);
            }
          });
        };
        _proto.releaseAll = function releaseAll() {
          var _this2 = this;
          assets.forEach(function (asset) {
            var info = _this2.getAssetInfo(asset._uuid);
            if (info && !info.redirect) {
              releaseManager.tryRelease(asset, true);
            }
          });
        };
        _proto._destroy = function _destroy() {
          this._config.destroy();
        };
        _createClass(Bundle, [{
          key: "config",
          get: function get() {
            return this._config;
          }
        }, {
          key: "name",
          get: function get() {
            return this._config.name;
          }
        }, {
          key: "deps",
          get: function get() {
            return this._config.deps;
          }
        }, {
          key: "base",
          get: function get() {
            return this._config.base;
          }
        }]);
        return Bundle;
      }();
      var resources = exports('es', new Bundle());
      legacyCC.resources = resources;

      var CacheManager = function CacheManager() {
        this.cacheDir = void 0;
        this.cacheEnabled = void 0;
        this.autoClear = void 0;
        this.cacheInterval = void 0;
        this.deleteInterval = void 0;
        this.cachedFiles = void 0;
      };

      function downloadDomImage(url, options, onComplete) {
        var img = new ccwindow.Image();
        if (ccwindow.location.protocol !== 'file:' || XIAOMI) {
          img.crossOrigin = 'anonymous';
        }
        function loadCallback() {
          img.removeEventListener('load', loadCallback);
          img.removeEventListener('error', errorCallback);
          if (onComplete) {
            onComplete(null, img);
          }
        }
        function errorCallback() {
          img.removeEventListener('load', loadCallback);
          img.removeEventListener('error', errorCallback);
          if (onComplete) {
            onComplete(new Error(getError(4930, url)));
          }
        }
        img.addEventListener('load', loadCallback);
        img.addEventListener('error', errorCallback);
        img.src = url;
        return img;
      }

      function downloadFile(url, options, onProgress, onComplete) {
        var xhr = new XMLHttpRequest();
        var errInfo = "download failed: " + url + ", status: ";
        xhr.open('GET', url, true);
        if (options.xhrResponseType !== undefined) {
          xhr.responseType = options.xhrResponseType;
        }
        if (options.xhrWithCredentials !== undefined) {
          xhr.withCredentials = options.xhrWithCredentials;
        }
        if (options.xhrMimeType !== undefined && xhr.overrideMimeType) {
          xhr.overrideMimeType(options.xhrMimeType);
        }
        if (options.xhrTimeout !== undefined) {
          xhr.timeout = options.xhrTimeout;
        }
        if (options.xhrHeader) {
          for (var header in options.xhrHeader) {
            xhr.setRequestHeader(header, options.xhrHeader[header]);
          }
        }
        xhr.onload = function () {
          if (xhr.status === 200 || xhr.status === 0) {
            if (onComplete) {
              onComplete(null, xhr.response);
            }
          } else if (onComplete) {
            onComplete(new Error("" + errInfo + xhr.status + "(no response)"));
          }
        };
        if (onProgress) {
          xhr.onprogress = function (e) {
            if (e.lengthComputable) {
              onProgress(e.loaded, e.total);
            }
          };
        }
        xhr.onerror = function () {
          if (onComplete) {
            onComplete(new Error("" + errInfo + xhr.status + "(error)"));
          }
        };
        xhr.ontimeout = function () {
          if (onComplete) {
            onComplete(new Error("" + errInfo + xhr.status + "(time out)"));
          }
        };
        xhr.onabort = function () {
          if (onComplete) {
            onComplete(new Error("" + errInfo + xhr.status + "(abort)"));
          }
        };
        xhr.send(null);
        return xhr;
      }

      var ccdocument$5 = ccwindow.document;
      var downloaded = {};
      function downloadScript(url, options, onComplete) {
        if (downloaded[url]) {
          if (onComplete) {
            onComplete(null);
          }
          return null;
        }
        var script = ccdocument$5.createElement('script');
        if (ccwindow.location.protocol !== 'file:') {
          script.crossOrigin = 'anonymous';
        }
        script.async = options.scriptAsyncLoading || false;
        script.src = url;
        function loadHandler() {
          script.parentNode.removeChild(script);
          script.removeEventListener('load', loadHandler, false);
          script.removeEventListener('error', errorHandler, false);
          downloaded[url] = true;
          if (onComplete) {
            onComplete(null);
          }
        }
        function errorHandler() {
          script.parentNode.removeChild(script);
          script.removeEventListener('load', loadHandler, false);
          script.removeEventListener('error', errorHandler, false);
          if (onComplete) {
            onComplete(new Error(getError(4928, url)));
          }
        }
        script.addEventListener('load', loadHandler, false);
        script.addEventListener('error', errorHandler, false);
        ccdocument$5.body.appendChild(script);
        return script;
      }

      var REGEX = /^(?:\w+:\/\/|\.+\/).+/;
      var downloadImage = function downloadImage(url, options, onComplete) {
        var func = sys.hasFeature(sys.Feature.IMAGE_BITMAP) && legacyCC.assetManager.allowImageBitmap ? downloadBlob : downloadDomImage;
        func(url, options, onComplete);
      };
      var downloadBlob = function downloadBlob(url, options, onComplete) {
        options.xhrResponseType = 'blob';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      var downloadJson = function downloadJson(url, options, onComplete) {
        options.xhrResponseType = 'json';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      var downloadArrayBuffer = function downloadArrayBuffer(url, options, onComplete) {
        options.xhrResponseType = 'arraybuffer';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      var downloadCCON = function downloadCCON(url, options, onComplete) {
        downloader._downloadJson(url, options, function (err, json) {
          if (err) {
            onComplete(err);
            return;
          }
          var cconPreface = parseCCONJson(json);
          var chunkPromises = Promise.all(cconPreface.chunks.map(function (chunk) {
            return new Promise(function (resolve, reject) {
              downloader._downloadArrayBuffer("" + mainFileName(url) + chunk, {}, function (errChunk, chunkBuffer) {
                if (err) {
                  reject(err);
                } else {
                  resolve(new Uint8Array(chunkBuffer));
                }
              });
            });
          }));
          chunkPromises.then(function (chunks) {
            var ccon = new CCON(cconPreface.document, chunks);
            onComplete(null, ccon);
          })["catch"](function (err) {
            onComplete(err);
          });
        });
      };
      var downloadCCONB = function downloadCCONB(url, options, onComplete) {
        downloader._downloadArrayBuffer(url, options, function (err, arrayBuffer) {
          if (err) {
            onComplete(err);
            return;
          }
          try {
            var ccon = decodeCCONBinary(new Uint8Array(arrayBuffer));
            onComplete(null, ccon);
          } catch (err) {
            onComplete(err);
          }
        });
      };
      var downloadText = function downloadText(url, options, onComplete) {
        options.xhrResponseType = 'text';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      var downloadBundle = function downloadBundle(nameOrUrl, options, onComplete) {
        var bundleName = basename(nameOrUrl);
        var url = nameOrUrl;
        if (!REGEX.test(url)) {
          if (downloader.remoteBundles.indexOf(bundleName) !== -1) {
            url = downloader.remoteServerAddress + "remote/" + bundleName;
          } else {
            url = "assets/" + bundleName;
          }
        }
        var version = options.version || downloader.bundleVers[bundleName];
        var count = 0;
        var config = url + "/config." + (version ? version + "." : '') + "json";
        var out = null;
        var error = null;
        downloadJson(config, options, function (err, response) {
          error = err || error;
          out = response;
          if (out) {
            out.base = url + "/";
          }
          if (++count === 2) {
            onComplete(error, out);
          }
        });
        var jspath = url + "/index." + (version ? version + "." : '') + "js";
        downloadScript(jspath, options, function (err) {
          error = err || error;
          if (++count === 2) {
            onComplete(error, out);
          }
        });
      };
      var Downloader = function () {
        var _proto = Downloader.prototype;
        _proto.init = function init(remoteServerAddress, bundleVers, remoteBundles) {
          if (remoteServerAddress === void 0) {
            remoteServerAddress = '';
          }
          if (bundleVers === void 0) {
            bundleVers = {};
          }
          if (remoteBundles === void 0) {
            remoteBundles = [];
          }
          this._downloading.clear();
          this._queue.length = 0;
          this._remoteServerAddress = remoteServerAddress;
          this.bundleVers = bundleVers;
          this.remoteBundles = remoteBundles;
        };
        _proto.register = function register(type, handler) {
          if (typeof type === 'object') {
            mixin(this._downloaders, type);
          } else {
            this._downloaders[type] = handler;
          }
        };
        _proto.download = function download(id, url, type, options, onComplete) {
          var _this = this;
          var file = files.get(id);
          if (file) {
            onComplete(null, file);
            return;
          }
          var downloadCallbacks = this._downloading.get(id);
          if (downloadCallbacks) {
            downloadCallbacks.push(onComplete);
            var request = this._queue.find(function (x) {
              return x.id === id;
            });
            if (!request) {
              return;
            }
            var priority = options.priority || 0;
            if (request.priority < priority) {
              request.priority = priority;
              this._queueDirty = true;
            }
            return;
          }
          var maxRetryCount = typeof options.maxRetryCount !== 'undefined' ? options.maxRetryCount : this.maxRetryCount;
          var maxConcurrency = typeof options.maxConcurrency !== 'undefined' ? options.maxConcurrency : this.maxConcurrency;
          var maxRequestsPerFrame = typeof options.maxRequestsPerFrame !== 'undefined' ? options.maxRequestsPerFrame : this.maxRequestsPerFrame;
          var handler = this._downloaders[type] || this._downloaders["default"];
          var process = function process(index, callback) {
            if (index === 0) {
              _this._downloading.add(id, [onComplete]);
            }
            if (!_this.limited) {
              handler(urlAppendTimestamp(url, _this.appendTimeStamp), options, callback);
              return;
            }
            _this._updateTime();
            var done = function done(err, data) {
              _this._totalNum--;
              _this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame);
              callback(err, data);
            };
            if (_this._totalNum < maxConcurrency && _this._totalNumThisPeriod < maxRequestsPerFrame) {
              handler(urlAppendTimestamp(url, _this.appendTimeStamp), options, done);
              _this._totalNum++;
              _this._totalNumThisPeriod++;
            } else {
              _this._queue.push({
                id: id,
                priority: options.priority || 0,
                url: url,
                options: options,
                done: done,
                handler: handler
              });
              _this._queueDirty = true;
              if (_this._totalNum < maxConcurrency) {
                _this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame);
              }
            }
          };
          var finale = function finale(err, result) {
            if (!err) {
              files.add(id, result);
            }
            var callbacks = _this._downloading.remove(id);
            for (var i = 0, l = callbacks.length; i < l; i++) {
              callbacks[i](err, result);
            }
          };
          retry(process, maxRetryCount, this.retryInterval, finale);
        };
        _proto.loadSubpackage = function loadSubpackage(name, completeCallback) {
          legacyCC.assetManager.loadBundle(name, null, completeCallback);
        };
        function Downloader() {
          this.maxConcurrency = 15;
          this.maxRequestsPerFrame = 15;
          this.maxRetryCount = 3 ;
          this.appendTimeStamp = !!EDITOR_NOT_IN_PREVIEW;
          this.limited = !EDITOR;
          this.retryInterval = 2000;
          this.bundleVers = {};
          this.remoteBundles = [];
          this.downloadDomImage = downloadDomImage;
          this.downloadDomAudio = null;
          this.downloadFile = downloadFile;
          this.downloadScript = downloadScript;
          this._downloadArrayBuffer = downloadArrayBuffer;
          this._downloadJson = downloadJson;
          this._downloaders = {
            '.png': downloadImage,
            '.jpg': downloadImage,
            '.bmp': downloadImage,
            '.jpeg': downloadImage,
            '.gif': downloadImage,
            '.ico': downloadImage,
            '.tiff': downloadImage,
            '.webp': downloadImage,
            '.image': downloadImage,
            '.pvr': downloadArrayBuffer,
            '.pkm': downloadArrayBuffer,
            '.astc': downloadArrayBuffer,
            '.txt': downloadText,
            '.xml': downloadText,
            '.vsh': downloadText,
            '.fsh': downloadText,
            '.atlas': downloadText,
            '.tmx': downloadText,
            '.tsx': downloadText,
            '.json': downloadJson,
            '.ExportJson': downloadJson,
            '.plist': downloadText,
            '.ccon': downloadCCON,
            '.cconb': downloadCCONB,
            '.fnt': downloadText,
            '.binary': downloadArrayBuffer,
            '.bin': downloadArrayBuffer,
            '.dbbin': downloadArrayBuffer,
            '.skel': downloadArrayBuffer,
            '.js': downloadScript,
            bundle: downloadBundle,
            "default": downloadText
          };
          this._downloading = new Cache();
          this._queue = [];
          this._queueDirty = false;
          this._totalNum = 0;
          this._totalNumThisPeriod = 0;
          this._lastDate = -1;
          this._checkNextPeriod = false;
          this._remoteServerAddress = '';
          this._maxInterval = 1 / 30;
        }
        _proto._updateTime = function _updateTime() {
          var now = performance.now();
          var deltaTime = legacyCC.game.deltaTime;
          var interval = deltaTime > this._maxInterval ? this._maxInterval : deltaTime;
          if (now - this._lastDate > interval * 1000) {
            this._totalNumThisPeriod = 0;
            this._lastDate = now;
          }
        };
        _proto._handleQueue = function _handleQueue(maxConcurrency, maxRequestsPerFrame) {
          this._checkNextPeriod = false;
          this._updateTime();
          while (this._queue.length > 0 && this._totalNum < maxConcurrency && this._totalNumThisPeriod < maxRequestsPerFrame) {
            if (this._queueDirty) {
              this._queue.sort(function (a, b) {
                return a.priority - b.priority;
              });
              this._queueDirty = false;
            }
            var request = this._queue.pop();
            if (!request) {
              break;
            }
            this._totalNum++;
            this._totalNumThisPeriod++;
            request.handler(urlAppendTimestamp(request.url, this.appendTimeStamp), request.options, request.done);
          }
          this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame);
        };
        _proto._handleQueueInNextFrame = function _handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame) {
          if (!this._checkNextPeriod && this._queue.length > 0) {
            callInNextTick(this._handleQueue.bind(this), maxConcurrency, maxRequestsPerFrame);
            this._checkNextPeriod = true;
          }
        };
        _createClass(Downloader, [{
          key: "remoteServerAddress",
          get: function get() {
            return this._remoteServerAddress;
          }
        }], [{
          key: "instance",
          get: function get() {
            if (!Downloader._instance) {
              Downloader._instance = new Downloader();
            }
            return Downloader._instance;
          }
        }]);
        return Downloader;
      }();
      Downloader._instance = void 0;
      var downloader = Downloader.instance;
      var downloader$1 = Downloader.instance;

      var _dec$3u, _class$3p, _class2$34, _initializer$2Q;
      var JsonAsset = exports('eg', (_dec$3u = ccclass$M('cc.JsonAsset'), _dec$3u(_class$3p = (_class2$34 = function (_Asset) {
        _inheritsLoose(JsonAsset, _Asset);
        function JsonAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.json = _initializer$2Q && _initializer$2Q();
          return _this;
        }
        return JsonAsset;
      }(Asset), (_initializer$2Q = applyDecoratedInitializer(_class2$34.prototype, "json", [serializable$p], function () {
        return null;
      })), _class2$34)) || _class$3p));
      legacyCC.JsonAsset = JsonAsset;

      var _dec$3t, _class$3o, _class2$33, _initializer$2P;
      var TextAsset = exports('ef', (_dec$3t = ccclass$M('cc.TextAsset'), _dec$3t(_class$3o = (_class2$33 = function (_Asset) {
        _inheritsLoose(TextAsset, _Asset);
        function TextAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.text = _initializer$2P && _initializer$2P();
          return _this;
        }
        var _proto = TextAsset.prototype;
        _proto.toString = function toString() {
          return this.text;
        };
        return TextAsset;
      }(Asset), (_initializer$2P = applyDecoratedInitializer(_class2$33.prototype, "text", [serializable$p], function () {
        return '';
      })), _class2$33)) || _class$3o));
      legacyCC.TextAsset = TextAsset;

      var _dec$3s, _class$3n, _class2$32;
      var BufferAsset = exports('ec', (_dec$3s = ccclass$M('cc.BufferAsset'), _dec$3s(_class$3n = (_class2$32 = function (_Asset) {
        _inheritsLoose(BufferAsset, _Asset);
        function BufferAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this._buffer = null;
          return _this;
        }
        var _proto = BufferAsset.prototype;
        _proto.buffer = function buffer() {
          assertIsNonNullable(this._buffer);
          return this._buffer;
        };
        _proto.validate = function validate() {
          return !!this._buffer;
        };
        _createClass(BufferAsset, [{
          key: "_nativeAsset",
          get: function get() {
            return this._buffer;
          },
          set: function set(bin) {
            if (bin instanceof ArrayBuffer) {
              this._buffer = bin;
            } else {
              this._buffer = bin.buffer;
            }
          }
        }]);
        return BufferAsset;
      }(Asset), (_applyDecoratedDescriptor(_class2$32.prototype, "_nativeAsset", [override$1], Object.getOwnPropertyDescriptor(_class2$32.prototype, "_nativeAsset"), _class2$32.prototype)), _class2$32)) || _class$3n));
      legacyCC.BufferAsset = BufferAsset;

      function createImageAsset(id, data, options, onComplete) {
        var out = null;
        var err = null;
        try {
          out = new ImageAsset();
          out._nativeUrl = id;
          out._nativeAsset = data;
        } catch (e) {
          err = e;
        }
        onComplete(err, out);
      }
      function createJsonAsset(id, data, options, onComplete) {
        var out = new JsonAsset();
        out.json = data;
        onComplete(null, out);
      }
      function createTextAsset(id, data, options, onComplete) {
        var out = new TextAsset();
        out.text = data;
        onComplete(null, out);
      }
      function createBufferAsset(id, data, options, onComplete) {
        var out = new BufferAsset();
        out._nativeUrl = id;
        out._nativeAsset = data;
        onComplete(null, out);
      }
      function createAsset(id, data, options, onComplete) {
        var out = new Asset();
        out._nativeUrl = id;
        out._nativeAsset = data;
        onComplete(null, out);
      }
      function createBundle(id, data, options, onComplete) {
        var bundle = bundles.get(data.name);
        if (!bundle) {
          bundle = data.name === BuiltinBundleName.RESOURCES ? resources : new Bundle();
          data.base = data.base || id + "/";
          bundle.init(data);
        }
        {
          module.import("virtual:///prerequisite-imports/" + bundle.name).then(function () {
            onComplete(null, bundle);
          })["catch"](onComplete);
        }
      }
      var Factory = function () {
        function Factory() {
          this._creating = new Cache();
          this._producers = {
            '.png': createImageAsset,
            '.jpg': createImageAsset,
            '.bmp': createImageAsset,
            '.jpeg': createImageAsset,
            '.gif': createImageAsset,
            '.ico': createImageAsset,
            '.tiff': createImageAsset,
            '.webp': createImageAsset,
            '.image': createImageAsset,
            '.pvr': createImageAsset,
            '.pkm': createImageAsset,
            '.txt': createTextAsset,
            '.xml': createTextAsset,
            '.vsh': createTextAsset,
            '.fsh': createTextAsset,
            '.atlas': createTextAsset,
            '.tmx': createTextAsset,
            '.tsx': createTextAsset,
            '.fnt': createTextAsset,
            '.json': createJsonAsset,
            '.ExportJson': createJsonAsset,
            '.binary': createBufferAsset,
            '.bin': createBufferAsset,
            '.dbbin': createBufferAsset,
            '.skel': createBufferAsset,
            bundle: createBundle,
            "default": createAsset
          };
        }
        var _proto = Factory.prototype;
        _proto.register = function register(type, handler) {
          if (typeof type === 'object') {
            mixin(this._producers, type);
          } else {
            this._producers[type] = handler;
          }
        };
        _proto.create = function create(id, data, type, options, onComplete) {
          var _this = this;
          var handler = this._producers[type] || this._producers["default"];
          var asset = assets.get(id);
          if (!options.reloadAsset && asset) {
            onComplete(null, asset);
            return;
          }
          var creating = this._creating.get(id);
          if (creating) {
            creating.push(onComplete);
            return;
          }
          this._creating.add(id, [onComplete]);
          handler(id, data, options, function (err, result) {
            if (!err && result instanceof Asset) {
              result._uuid = id;
              cache(id, result, options.cacheAsset);
            }
            var callbacks = _this._creating.remove(id);
            for (var i = 0, l = callbacks.length; i < l; i++) {
              callbacks[i](err, result);
            }
          });
        };
        return Factory;
      }();
      var factory = new Factory();

      var PackManager = function () {
        function PackManager() {
          this._loading = new Cache();
          this._unpackers = {
            '.json': this.unpackJson
          };
        }
        var _proto = PackManager.prototype;
        _proto.unpackJson = function unpackJson(pack, json, options, onComplete) {
          var out = createMap(true);
          var err = null;
          if (Array.isArray(json)) {
            json = unpackJSONs(json);
            if (json.length !== pack.length) {
              errorID(4915);
            }
            for (var i = 0; i < pack.length; i++) {
              out[pack[i] + "@import"] = json[i];
            }
          } else {
            var textureType = getClassId(Texture2D);
            var imageAssetType = getClassId(ImageAsset);
            if (json.type === textureType && json.data) {
              var datas = json.data;
              if (datas.length !== pack.length) {
                errorID(4915);
              }
              for (var _i = 0; _i < pack.length; _i++) {
                out[pack[_i] + "@import"] = packCustomObjData(textureType, {
                  base: datas[_i][0],
                  mipmaps: datas[_i][1]
                });
              }
            } else if (json.type === imageAssetType && json.data) {
              var _datas = json.data;
              if (_datas.length !== pack.length) {
                errorID(4915);
              }
              for (var _i2 = 0; _i2 < pack.length; _i2++) {
                out[pack[_i2] + "@import"] = _datas[_i2];
              }
            } else {
              err = new Error('unmatched type pack!');
              onComplete(err, null);
              return;
            }
          }
          onComplete(err, out);
        };
        _proto.init = function init() {
          this._loading.clear();
        };
        _proto.register = function register(type, handler) {
          if (typeof type === 'object') {
            mixin(this._unpackers, type);
          } else {
            this._unpackers[type] = handler;
          }
        };
        _proto.unpack = function unpack(pack, data, type, options, onComplete) {
          if (!data) {
            onComplete(new Error('package data is wrong!'));
            return;
          }
          var unpacker = this._unpackers[type];
          unpacker(pack, data, options, onComplete);
        };
        _proto.load = function load(item, options, onComplete) {
          var _this = this;
          if (item.isNative || !item.info || !item.info.packs) {
            downloader$1.download(item.id, item.url, item.ext, item.options, onComplete);
            return;
          }
          if (files.has(item.id)) {
            onComplete(null, files.get(item.id));
            return;
          }
          var packs = item.info.packs;
          var loadingPack = packs.find(function (val) {
            return _this._loading.has(val.uuid);
          });
          if (loadingPack) {
            var req = this._loading.get(loadingPack.uuid);
            assertIsTrue(req);
            req.push({
              onComplete: onComplete,
              id: item.id
            });
            return;
          }
          var pack = packs[0];
          this._loading.add(pack.uuid, [{
            onComplete: onComplete,
            id: item.id
          }]);
          assertIsTrue(item.config);
          var url = transform(pack.uuid, {
            ext: pack.ext,
            bundle: item.config.name
          });
          downloader$1.download(pack.uuid, url, pack.ext, item.options, function (err, data) {
            files.remove(pack.uuid);
            if (err) {
              error(err.message, err.stack);
            }
            _this.unpack(pack.packedUuids, data, pack.ext, item.options, function (err2, result) {
              if (!err2) {
                for (var id in result) {
                  files.add(id, result[id]);
                }
              }
              var callbacks = _this._loading.remove(pack.uuid);
              assertIsTrue(callbacks);
              for (var i = 0, l = callbacks.length; i < l; i++) {
                var cb = callbacks[i];
                if (err || err2) {
                  cb.onComplete(err || err2);
                  continue;
                }
                var unpackedData = result[cb.id];
                if (!unpackedData) {
                  cb.onComplete(new Error('can not retrieve data from package'));
                } else {
                  cb.onComplete(null, unpackedData);
                }
              }
            });
          });
        };
        return PackManager;
      }();
      var packManager = new PackManager();

      function fetch$1(task, done) {
        var firstTask = false;
        if (!task.progress) {
          task.progress = {
            finish: 0,
            total: task.input.length,
            canInvoke: true
          };
          firstTask = true;
        }
        var options = task.options,
          progress = task.progress;
        var depends = [];
        var total = progress.total;
        var exclude = options.__exclude__ = options.__exclude__ || Object.create(null);
        task.output = [];
        forEach(task.input, function (item, cb) {
          if (!item.isNative && assets.has(item.uuid)) {
            var asset = assets.get(item.uuid);
            item.content = asset.addRef();
            task.output.push(item);
            if (progress.canInvoke) {
              task.dispatch('progress', ++progress.finish, progress.total, item);
            }
            cb();
            return;
          }
          packManager.load(item, task.options, function (err, data) {
            if (err) {
              if (!task.isFinished) {
                if (!legacyCC.assetManager.force || firstTask) {
                  error(err.message, err.stack);
                  progress.canInvoke = false;
                  done(err);
                } else {
                  task.output.push(item);
                  if (progress.canInvoke) {
                    task.dispatch('progress', ++progress.finish, progress.total, item);
                  }
                }
              }
            } else if (!task.isFinished) {
              item.file = data;
              task.output.push(item);
              if (!item.isNative) {
                exclude[item.uuid] = true;
                getDepends(item.uuid, data, exclude, depends, item.config);
                progress.total = total + depends.length;
              }
              if (progress.canInvoke) {
                task.dispatch('progress', ++progress.finish, progress.total, item);
              }
            }
            cb();
          });
        }, function () {
          if (task.isFinished) {
            clear(task, true);
            task.dispatch('error');
            return;
          }
          if (depends.length > 0) {
            var subTask = Task.create({
              input: depends,
              progress: progress,
              options: options,
              onProgress: task.onProgress,
              onError: Task.prototype.recycle,
              onComplete: function onComplete(err) {
                if (!err) {
                  var _task$output;
                  (_task$output = task.output).push.apply(_task$output, subTask.output);
                  subTask.recycle();
                }
                if (firstTask) {
                  decreaseRef(task);
                }
                done(err);
              }
            });
            fetchPipeline.async(subTask);
            return;
          }
          if (firstTask) {
            decreaseRef(task);
          }
          done();
        });
      }
      function decreaseRef(task) {
        var output = task.output;
        for (var i = 0, l = output.length; i < l; i++) {
          if (output[i].content) {
            output[i].content.decRef(false);
          }
        }
      }

      var SAXParser = function () {
        function SAXParser() {
          this._parser = null;
          if (globalThis.DOMParser) {
            this._parser = new DOMParser();
          }
        }
        var _proto = SAXParser.prototype;
        _proto.parse = function parse(xmlTxt) {
          return this._parseXML(xmlTxt);
        };
        _proto._parseXML = function _parseXML(textxml) {
          if (this._parser) {
            return this._parser.parseFromString(textxml, 'text/xml');
          }
          throw new Error('Dom parser is not supported in this platform!');
        };
        return SAXParser;
      }();
      var PlistParser = function (_SAXParser) {
        _inheritsLoose(PlistParser, _SAXParser);
        function PlistParser() {
          return _SAXParser.apply(this, arguments) || this;
        }
        var _proto2 = PlistParser.prototype;
        _proto2.parse = function parse(xmlTxt) {
          var xmlDoc = this._parseXML(xmlTxt);
          var plist = xmlDoc.documentElement;
          if (plist.tagName !== 'plist') {
            warnID(5100);
            return {};
          }
          var node = null;
          for (var i = 0, len = plist.childNodes.length; i < len; i++) {
            node = plist.childNodes[i];
            if (node.nodeType === 1) {
              break;
            }
          }
          return this._parseNode(node);
        };
        _proto2._parseNode = function _parseNode(node) {
          var data = null;
          var tagName = node.tagName;
          if (tagName === 'dict') {
            data = this._parseDict(node);
          } else if (tagName === 'array') {
            data = this._parseArray(node);
          } else if (tagName === 'string') {
            if (node.childNodes.length === 1) {
              data = node.firstChild.nodeValue;
            } else {
              data = '';
              for (var i = 0; i < node.childNodes.length; i++) {
                data += node.childNodes[i].nodeValue;
              }
            }
          } else if (tagName === 'false') {
            data = false;
          } else if (tagName === 'true') {
            data = true;
          } else if (tagName === 'real') {
            data = parseFloat(node.firstChild.nodeValue);
          } else if (tagName === 'integer') {
            data = parseInt(node.firstChild.nodeValue, 10);
          }
          return data;
        };
        _proto2._parseArray = function _parseArray(node) {
          var data = [];
          for (var i = 0, len = node.childNodes.length; i < len; i++) {
            var child = node.childNodes[i];
            if (child.nodeType !== 1) {
              continue;
            }
            data.push(this._parseNode(child));
          }
          return data;
        };
        _proto2._parseDict = function _parseDict(node) {
          var data = {};
          var key = '';
          for (var i = 0, len = node.childNodes.length; i < len; i++) {
            var child = node.childNodes[i];
            if (child.nodeType !== 1) {
              continue;
            }
            if (child.tagName === 'key') {
              key = child.firstChild.nodeValue;
            } else {
              data[key] = this._parseNode(child);
            }
          }
          return data;
        };
        return PlistParser;
      }(SAXParser);
      var plistParser = new PlistParser();

      var Parser$1 = function () {
        function Parser() {
          this._parsing = new Cache();
          this._parsers = {
            '.png': this.parseImage,
            '.jpg': this.parseImage,
            '.bmp': this.parseImage,
            '.jpeg': this.parseImage,
            '.gif': this.parseImage,
            '.ico': this.parseImage,
            '.tiff': this.parseImage,
            '.webp': this.parseImage,
            '.image': this.parseImage,
            '.pvr': this.parsePVRTex,
            '.pkm': this.parsePKMTex,
            '.astc': this.parseASTCTex,
            '.plist': this.parsePlist,
            "import": this.parseImport,
            '.ccon': this.parseImport,
            '.cconb': this.parseImport
          };
        }
        var _proto = Parser.prototype;
        _proto.parseImage = function parseImage(file, options, onComplete) {
          if (file instanceof HTMLImageElement) {
            onComplete(null, file);
            return;
          }
          createImageBitmap(file, {
            premultiplyAlpha: 'none'
          }).then(function (result) {
            onComplete(null, result);
          }, function (err) {
            onComplete(err, null);
          });
        };
        _proto.parsePVRTex = function parsePVRTex(file, options, onComplete) {
          var err = null;
          var out = null;
          try {
            out = ImageAsset.parseCompressedTextures(file, 0);
          } catch (e) {
            err = e;
            console.warn(err);
          }
          onComplete(err, out);
        };
        _proto.parsePKMTex = function parsePKMTex(file, options, onComplete) {
          var err = null;
          var out = null;
          try {
            out = ImageAsset.parseCompressedTextures(file, 1);
          } catch (e) {
            err = e;
            console.warn(err);
          }
          onComplete(err, out);
        };
        _proto.parseASTCTex = function parseASTCTex(file, options, onComplete) {
          var err = null;
          var out = null;
          try {
            out = ImageAsset.parseCompressedTextures(file, 2);
          } catch (e) {
            err = e;
            console.warn(err);
          }
          onComplete(err, out);
        };
        _proto.parsePlist = function parsePlist(file, options, onComplete) {
          var err = null;
          var result = plistParser.parse(file);
          if (!result) {
            err = new Error('parse failed');
          }
          onComplete(err, result);
        };
        _proto.parseImport = function parseImport(file, options, onComplete) {
          if (!file) {
            onComplete(new Error("The json file of asset " + options.__uuid__ + " is empty or missing"));
            return;
          }
          var result = null;
          var err = null;
          try {
            result = deserializeAsset(file, options);
          } catch (e) {
            err = e;
          }
          onComplete(err, result);
        };
        _proto.init = function init() {
          this._parsing.clear();
        };
        _proto.register = function register(type, handler) {
          if (typeof type === 'object') {
            mixin(this._parsers, type);
          } else {
            this._parsers[type] = handler;
          }
        };
        _proto.parse = function parse(id, file, type, options, onComplete) {
          var _this = this;
          var parsedAsset = parsed.get(id);
          if (parsedAsset) {
            onComplete(null, parsedAsset);
            return;
          }
          var parsing = this._parsing.get(id);
          if (parsing) {
            parsing.push(onComplete);
            return;
          }
          var parseHandler = this._parsers[type];
          if (!parseHandler) {
            onComplete(null, file);
            return;
          }
          this._parsing.add(id, [onComplete]);
          parseHandler(file, options, function (err, data) {
            if (err) {
              files.remove(id);
            } else if (!isScene(data)) {
              parsed.add(id, data);
            }
            var callbacks = _this._parsing.remove(id);
            for (var i = 0, l = callbacks.length; i < l; i++) {
              callbacks[i](err, data);
            }
          });
        };
        _createClass(Parser, null, [{
          key: "instance",
          get: function get() {
            if (!this._instance) {
              this._instance = new Parser();
            }
            return this._instance;
          }
        }]);
        return Parser;
      }();
      Parser$1._instance = void 0;
      var parser = Parser$1.instance;

      function load(task, done) {
        var firstTask = false;
        if (!task.progress) {
          task.progress = {
            finish: 0,
            total: task.input.length,
            canInvoke: true
          };
          firstTask = true;
        }
        var options = task.options,
          progress = task.progress;
        options.__exclude__ = options.__exclude__ || Object.create(null);
        task.output = [];
        forEach(task.input, function (item, cb) {
          var subTask = Task.create({
            input: item,
            onProgress: task.onProgress,
            options: options,
            progress: progress,
            onComplete: function onComplete(err, result) {
              if (err && !task.isFinished) {
                if (!legacyCC.assetManager.force || firstTask) {
                  {
                    error(err.message, err.stack);
                  }
                  progress.canInvoke = false;
                  done(err);
                } else if (progress.canInvoke) {
                  task.dispatch('progress', ++progress.finish, progress.total, item);
                }
              }
              task.output.push(result);
              subTask.recycle();
              cb(null);
            }
          });
          loadOneAssetPipeline.async(subTask);
        }, function () {
          options.__exclude__ = null;
          if (task.isFinished) {
            clear(task, true);
            task.dispatch('error');
            return;
          }
          gatherAsset(task);
          clear(task, true);
          done();
        });
      }
      var loadOneAssetPipeline = new Pipeline('loadOneAsset', [function fetch(task, done) {
        var item = task.output = task.input;
        var options = item.options,
          isNative = item.isNative,
          uuid = item.uuid,
          file = item.file;
        var reloadAsset = options.reloadAsset;
        if (file || !reloadAsset && !isNative && assets.has(uuid)) {
          done();
          return;
        }
        packManager.load(item, task.options, function (err, data) {
          item.file = data;
          done(err);
        });
      }, function parse(task, done) {
        var item = task.output = task.input;
        var progress = task.progress;
        var exclude = task.options.__exclude__;
        var id = item.id,
          file = item.file,
          options = item.options;
        if (item.isNative) {
          parser.parse(id, file, item.ext, options, function (err, asset) {
            if (err) {
              done(err);
              return;
            }
            item.content = asset;
            if (progress.canInvoke) {
              task.dispatch('progress', ++progress.finish, progress.total, item);
            }
            files.remove(id);
            parsed.remove(id);
            done();
          });
        } else {
          var uuid = item.uuid;
          if (uuid in exclude) {
            var _exclude$uuid = exclude[uuid],
              finish = _exclude$uuid.finish,
              content = _exclude$uuid.content,
              _err = _exclude$uuid.err,
              callbacks = _exclude$uuid.callbacks;
            if (progress.canInvoke) {
              task.dispatch('progress', ++progress.finish, progress.total, item);
            }
            if (finish || checkCircleReference(uuid, uuid, exclude)) {
              if (content) {
                content.addRef();
              }
              item.content = content;
              done(_err);
            } else {
              callbacks.push({
                done: done,
                item: item
              });
            }
          } else if (!options.reloadAsset && assets.has(uuid)) {
            var asset = assets.get(uuid);
            item.content = asset.addRef();
            if (progress.canInvoke) {
              task.dispatch('progress', ++progress.finish, progress.total, item);
            }
            done();
          } else {
            options.__uuid__ = uuid;
            parser.parse(id, file, 'import', options, function (err, asset) {
              if (err) {
                done(err);
                return;
              }
              loadDepends(task, asset, done);
            });
          }
        }
      }]);
      function loadDepends(task, asset, done) {
        var item = task.input,
          progress = task.progress;
        var _ref = item,
          uuid = _ref.uuid,
          id = _ref.id,
          options = _ref.options,
          config = _ref.config;
        var cacheAsset = options.cacheAsset;
        var depends = [];
        if (asset.addRef) {
          asset.addRef();
        }
        getDepends(uuid, asset, Object.create(null), depends, config);
        if (progress.canInvoke) {
          task.dispatch('progress', ++progress.finish, progress.total += depends.length, item);
        }
        var repeatItem = task.options.__exclude__[uuid] = {
          content: asset,
          finish: false,
          callbacks: [{
            done: done,
            item: item
          }]
        };
        var subTask = Task.create({
          input: depends,
          options: task.options,
          onProgress: task.onProgress,
          onError: Task.prototype.recycle,
          progress: progress,
          onComplete: function onComplete(err) {
            if (asset.decRef) {
              asset.decRef(false);
            }
            repeatItem.finish = true;
            repeatItem.err = err;
            if (!err) {
              var output = Array.isArray(subTask.output) ? subTask.output : [subTask.output];
              var map = Object.create(null);
              for (var _iterator = _createForOfIteratorHelperLoose(output), _step; !(_step = _iterator()).done;) {
                var dependAsset = _step.value;
                if (!dependAsset) {
                  continue;
                }
                map[dependAsset instanceof Asset ? dependAsset._uuid + "@import" : uuid + "@native"] = dependAsset;
              }
              setProperties(uuid, asset, map);
              try {
                if (typeof asset.onLoaded === 'function' && !onLoadedInvokedMap.has(asset) && !nativeDependMap.has(asset)) {
                  asset.onLoaded();
                  onLoadedInvokedMap.add(asset);
                }
              } catch (e) {
                error("The asset " + uuid + " is invalid for some reason, detail message: " + e.message + ", stack: " + e.stack);
              }
              files.remove(id);
              parsed.remove(id);
              cache(uuid, asset, cacheAsset);
              subTask.recycle();
            }
            var callbacks = repeatItem.callbacks;
            for (var i = 0, l = callbacks.length; i < l; i++) {
              var cb = callbacks[i];
              if (asset.addRef) {
                asset.addRef();
              }
              cb.item.content = asset;
              cb.done(err);
            }
            callbacks.length = 0;
          }
        });
        pipeline.async(subTask);
      }

      function preprocess(task, done) {
        var options = task.options;
        var subOptions = Object.create(null);
        var leftOptions = Object.create(null);
        for (var op in options) {
          switch (op) {
            case RequestType.PATH:
            case RequestType.UUID:
            case RequestType.DIR:
            case RequestType.SCENE:
            case RequestType.URL:
              break;
            case '__requestType__':
            case '__isNative__':
            case 'ext':
            case 'type':
            case '__nativeName__':
            case 'audioLoadMode':
            case 'bundle':
              subOptions[op] = options[op];
              break;
            case '__exclude__':
            case '__outputAsArray__':
              leftOptions[op] = options[op];
              break;
            default:
              subOptions[op] = options[op];
              leftOptions[op] = options[op];
              break;
          }
        }
        task.options = leftOptions;
        var subTask = Task.create({
          input: task.input,
          options: subOptions
        });
        var err = null;
        try {
          task.output = task.source = transformPipeline.sync(subTask);
        } catch (e) {
          err = e;
          for (var i = 0, l = subTask.output.length; i < l; i++) {
            subTask.output[i].recycle();
          }
        }
        subTask.recycle();
        done(err);
      }

      var RequestItem = function () {
        function RequestItem() {
          this.uuid = '';
          this.overrideUuid = '';
          this.url = '';
          this.ext = '.json';
          this.content = null;
          this.file = null;
          this.info = null;
          this.config = null;
          this.isNative = false;
          this.options = Object.create(null);
          this._id = '';
        }
        RequestItem.create = function create() {
          var out;
          if (RequestItem._deadPool.length !== 0) {
            out = RequestItem._deadPool.pop();
          } else {
            out = new RequestItem();
          }
          return out;
        };
        var _proto = RequestItem.prototype;
        _proto.recycle = function recycle() {
          if (RequestItem._deadPool.length === RequestItem.MAX_DEAD_NUM) {
            return;
          }
          this._id = '';
          this.uuid = '';
          this.overrideUuid = '';
          this.url = '';
          this.ext = '.json';
          this.content = null;
          this.file = null;
          this.info = null;
          this.config = null;
          this.isNative = false;
          this.options = Object.create(null);
          RequestItem._deadPool.push(this);
        };
        _createClass(RequestItem, [{
          key: "id",
          get: function get() {
            if (!this._id) {
              this._id = (this.overrideUuid || this.uuid) + "@" + (this.isNative ? 'native' : 'import');
            }
            return this._id;
          }
        }]);
        return RequestItem;
      }();
      RequestItem.MAX_DEAD_NUM = 500;
      RequestItem._deadPool = [];

      var infos = [];
      function parse(task) {
        var options = task.options;
        var input = Array.isArray(task.input) ? task.input : [task.input];
        task.output = [];
        var _loop = function _loop() {
          var item = input[i];
          var out = RequestItem.create();
          var config = null;
          var info = null;
          if (typeof item === 'string') {
            item = Object.create(null);
            item[options.__requestType__ || RequestType.UUID] = input[i];
          }
          if (typeof item === 'object') {
            addon(item, options);
            if (item.preset) {
              addon(item, presets[item.preset]);
            }
            var _loop2 = function _loop2() {
              var _info2;
              switch (key) {
                case RequestType.UUID:
                  {
                    var _info;
                    var uuid = out.uuid = decodeUuid(item.uuid);
                    if (!item.bundle) {
                      var bundle = bundles.find(function (bundle) {
                        return !!bundle.getAssetInfo(uuid);
                      });
                      item.bundle = bundle && bundle.name;
                    }
                    if (bundles.has(item.bundle)) {
                      config = bundles.get(item.bundle).config;
                      info = config.getAssetInfo(uuid);
                      if (info && info.redirect) {
                        if (!bundles.has(info.redirect)) {
                          throw new Error("Please load bundle " + info.redirect + " first");
                        }
                        config = bundles.get(info.redirect).config;
                        info = config.getAssetInfo(uuid);
                      }
                      out.config = config;
                      out.info = info;
                    }
                    out.ext = item.ext || ((_info = info) === null || _info === void 0 ? void 0 : _info.extension) || '.json';
                    break;
                  }
                case '__requestType__':
                case 'ext':
                case 'bundle':
                case 'preset':
                case 'type':
                  break;
                case RequestType.DIR:
                  if (bundles.has(item.bundle)) {
                    bundles.get(item.bundle).config.getDirWithPath(item.dir, item.type, infos);
                    for (var _iterator = _createForOfIteratorHelperLoose(infos), _step; !(_step = _iterator()).done;) {
                      var assetInfo = _step.value;
                      input.push({
                        uuid: assetInfo.uuid,
                        __isNative__: false,
                        ext: assetInfo.extension || '.json',
                        bundle: item.bundle
                      });
                    }
                    infos.length = 0;
                  }
                  out.recycle();
                  out = null;
                  break;
                case RequestType.PATH:
                  if (bundles.has(item.bundle)) {
                    config = bundles.get(item.bundle).config;
                    info = config.getInfoWithPath(item.path, item.type);
                    if (info && info.redirect) {
                      if (!bundles.has(info.redirect)) {
                        throw new Error("you need to load bundle " + info.redirect + " first");
                      }
                      config = bundles.get(info.redirect).config;
                      info = config.getAssetInfo(info.uuid);
                    }
                    if (!info) {
                      out.recycle();
                      throw new Error("Bundle " + item.bundle + " doesn't contain " + item.path);
                    }
                    out.config = config;
                    out.uuid = info.uuid;
                    out.info = info;
                  }
                  out.ext = item.ext || ((_info2 = info) === null || _info2 === void 0 ? void 0 : _info2.extension) || '.json';
                  break;
                case RequestType.SCENE:
                  if (!item.bundle) {
                    var _bundle = bundles.find(function (bundle) {
                      return !!bundle.getSceneInfo(item.scene);
                    });
                    item.bundle = _bundle && _bundle.name;
                  }
                  if (bundles.has(item.bundle)) {
                    config = bundles.get(item.bundle).config;
                    info = config.getSceneInfo(item.scene);
                    if (info && info.redirect) {
                      if (!bundles.has(info.redirect)) {
                        throw new Error("you need to load bundle " + info.redirect + " first");
                      }
                      config = bundles.get(info.redirect).config;
                      info = config.getAssetInfo(info.uuid);
                    }
                    if (!info) {
                      out.recycle();
                      throw new Error("Bundle " + config.name + " doesn't contain scene " + item.scene);
                    }
                    out.config = config;
                    out.uuid = info.uuid;
                    out.info = info;
                  }
                  break;
                case '__isNative__':
                  out.isNative = item.__isNative__;
                  break;
                case RequestType.URL:
                  out.url = item.url;
                  out.uuid = item.uuid || item.url;
                  out.ext = item.ext || extname(item.url);
                  out.isNative = item.__isNative__ !== undefined ? item.__isNative__ : true;
                  break;
                default:
                  out.options[key] = item[key];
              }
              if (!out) {
                return 1;
              }
            };
            for (var key in item) {
              if (_loop2()) break;
            }
          }
          if (!out) {
            return 1;
          }
          task.output.push(out);
          if (!out.uuid && !out.url) {
            throw new Error("Can not parse this input:" + JSON.stringify(item));
          }
        };
        for (var i = 0; i < input.length; i++) {
          if (_loop()) continue;
        }
        return null;
      }
      function replaceOverrideAsset(task) {
        var input = task.output = task.input;
        var _loop3 = function _loop3() {
          var item = input[i];
          if (assetsOverrideMap.has(item.uuid)) {
            var uuid = assetsOverrideMap.get(item.uuid);
            var bundle = bundles.find(function (bundle) {
              return !!bundle.getAssetInfo(uuid);
            });
            if (bundle) {
              var _info3;
              item.overrideUuid = uuid;
              var config = bundle.config;
              var info = config.getAssetInfo(uuid);
              if (info && info.redirect) {
                if (!bundles.has(info.redirect)) {
                  throw new Error("Please load bundle " + info.redirect + " first");
                }
                config = bundles.get(info.redirect).config;
                info = config.getAssetInfo(uuid);
              }
              item.config = config;
              item.info = info;
              item.ext = item.isNative ? item.ext : ((_info3 = info) === null || _info3 === void 0 ? void 0 : _info3.extension) || '.json';
            } else {
              warnID(16201, uuid, item.uuid);
            }
          }
        };
        for (var i = 0; i < input.length; i++) {
          if (_loop3()) continue;
        }
      }
      function combine(task) {
        var input = task.output = task.input;
        for (var i = 0; i < input.length; i++) {
          var item = input[i];
          if (item.url) {
            continue;
          }
          var url = '';
          var base = '';
          var config = item.config;
          if (item.isNative) {
            base = config && config.nativeBase ? config.base + config.nativeBase : legacyCC.assetManager.generalNativeBase;
          } else {
            base = config && config.importBase ? config.base + config.importBase : legacyCC.assetManager.generalImportBase;
          }
          var uuid = item.overrideUuid || item.uuid;
          var ver = '';
          if (item.info) {
            if (item.isNative) {
              ver = item.info.nativeVer ? "." + item.info.nativeVer : '';
            } else {
              ver = item.info.ver ? "." + item.info.ver : '';
            }
          }
          if (item.ext === '.ttf') {
            url = base + "/" + uuid.slice(0, 2) + "/" + uuid + ver + "/" + item.options.__nativeName__;
          } else {
            url = base + "/" + uuid.slice(0, 2) + "/" + uuid + ver + item.ext;
          }
          item.url = url;
        }
        return null;
      }

      var EVENT_ASSET_MISSING = 'asset-missing';
      var AssetManager = exports('er', function () {
        function AssetManager() {
          this.pipeline = pipeline.append(preprocess).append(load);
          this.fetchPipeline = fetchPipeline.append(preprocess).append(fetch$1);
          this.transformPipeline = transformPipeline.append(parse).append(replaceOverrideAsset).append(combine);
          this.bundles = bundles;
          this.assets = assets;
          this.assetsOverrideMap = assetsOverrideMap;
          this.generalImportBase = '';
          this.generalNativeBase = '';
          this.dependUtil = dependUtil;
          this.force = PREVIEW;
          this.allowImageBitmap = false;
          this.utils = helper;
          this.downloader = downloader$1;
          this.parser = parser;
          this.packManager = packManager;
          this.cacheAsset = true;
          this.cacheManager = null;
          this.presets = presets;
          this.factory = factory;
          this.preprocessPipe = preprocess;
          this.fetchPipe = fetch$1;
          this.loadPipe = load;
          this.references = references;
          this._releaseManager = releaseManager;
          this._files = files;
          this._parsed = parsed;
          this._parsePipeline = null ;
          this._projectBundles = [];
          this._eventTarget = new EventTarget();
        }
        var _proto = AssetManager.prototype;
        _proto.onAssetMissing = function onAssetMissing(func, target) {
          this._eventTarget.on(EVENT_ASSET_MISSING, func, target);
        };
        _proto.offAssetMissing = function offAssetMissing(func, target) {
          this._eventTarget.off(EVENT_ASSET_MISSING, func, target);
        };
        _proto.dispatchAssetMissing = function dispatchAssetMissing(parentAsset, owner, propName, uuid) {
          this._eventTarget.emit(EVENT_ASSET_MISSING, parentAsset, owner, propName, uuid);
        };
        _proto.init = function init(options) {
          if (options === void 0) {
            options = {};
          }
          var server = options.server || settings.querySettings(Settings.Category.ASSETS, 'server') || '';
          var bundleVers = options.bundleVers || settings.querySettings(Settings.Category.ASSETS, 'bundleVers') || {};
          var remoteBundles = options.remoteBundles || settings.querySettings(Settings.Category.ASSETS, 'remoteBundles') || [];
          var downloadMaxConcurrency = options.downloadMaxConcurrency || settings.querySettings(Settings.Category.ASSETS, 'downloadMaxConcurrency');
          if (downloadMaxConcurrency && downloadMaxConcurrency > 0) {
            this.downloader.maxConcurrency = downloadMaxConcurrency;
          }
          this._files.clear();
          this._parsed.clear();
          this._releaseManager.init();
          this.assets.clear();
          this.bundles.clear();
          this.packManager.init();
          this.downloader.init(server, bundleVers, remoteBundles);
          this.parser.init();
          this.dependUtil.init();
          var importBase = options.importBase || settings.querySettings(Settings.Category.ASSETS, 'importBase') || '';
          if (importBase && importBase.endsWith('/')) {
            importBase = importBase.substr(0, importBase.length - 1);
          }
          var nativeBase = options.nativeBase || settings.querySettings(Settings.Category.ASSETS, 'nativeBase') || '';
          if (nativeBase && nativeBase.endsWith('/')) {
            nativeBase = nativeBase.substr(0, nativeBase.length - 1);
          }
          this.generalImportBase = importBase;
          this.generalNativeBase = nativeBase;
          this._projectBundles = settings.querySettings(Settings.Category.ASSETS, 'projectBundles') || [];
          var assetsOverride = settings.querySettings(Settings.Category.ASSETS, 'assetsOverrides') || {};
          for (var _key in assetsOverride) {
            this.assetsOverrideMap.set(_key, assetsOverride[_key]);
          }
        };
        _proto.getBundle = function getBundle(name) {
          return bundles.get(name) || null;
        };
        _proto.removeBundle = function removeBundle(bundle) {
          bundle._destroy();
          bundles.remove(bundle.name);
        };
        _proto.loadAny = function loadAny(requests, options, onProgress, onComplete) {
          var _parseParameters = parseParameters(options, onProgress, onComplete),
            opts = _parseParameters.options,
            onProg = _parseParameters.onProgress,
            onComp = _parseParameters.onComplete;
          opts.preset = opts.preset || 'default';
          requests = Array.isArray(requests) ? requests.slice() : requests;
          var task = Task.create({
            input: requests,
            onProgress: onProg,
            onComplete: asyncify(onComp),
            options: opts
          });
          pipeline.async(task);
        };
        _proto.preloadAny = function preloadAny(requests, options, onProgress, onComplete) {
          var _parseParameters2 = parseParameters(options, onProgress, onComplete),
            opts = _parseParameters2.options,
            onProg = _parseParameters2.onProgress,
            onComp = _parseParameters2.onComplete;
          opts.preset = opts.preset || 'preload';
          requests = Array.isArray(requests) ? requests.slice() : requests;
          var task = Task.create({
            input: requests,
            onProgress: onProg,
            onComplete: asyncify(onComp),
            options: opts
          });
          fetchPipeline.async(task);
        };
        _proto.loadRemote = function loadRemote(url, options, onComplete) {
          var _parseParameters3 = parseParameters(options, undefined, onComplete),
            opts = _parseParameters3.options,
            onComp = _parseParameters3.onComplete;
          if (!opts.reloadAsset && this.assets.has(url)) {
            asyncify(onComp)(null, this.assets.get(url));
            return;
          }
          opts.__isNative__ = true;
          opts.preset = opts.preset || 'remote';
          this.loadAny({
            url: url
          }, opts, null, function (err, data) {
            if (err) {
              error(err.message, err.stack);
              if (onComp) {
                onComp(err, data);
              }
            } else {
              factory.create(url, data, opts.ext || extname(url), opts, function (p1, p2) {
                if (onComp) {
                  onComp(p1, p2);
                }
              });
            }
          });
        };
        _proto.loadBundle = function loadBundle(nameOrUrl, options, onComplete) {
          var _parseParameters4 = parseParameters(options, undefined, onComplete),
            opts = _parseParameters4.options,
            onComp = _parseParameters4.onComplete;
          var bundleName = basename(nameOrUrl);
          if (this.bundles.has(bundleName)) {
            asyncify(onComp)(null, this.getBundle(bundleName));
            return;
          }
          opts.preset = opts.preset || 'bundle';
          opts.ext = 'bundle';
          opts.__isNative__ = true;
          this.loadAny({
            url: nameOrUrl
          }, opts, null, function (err, data) {
            if (err) {
              error(err.message, err.stack);
              if (onComp) {
                onComp(err, data);
              }
            } else {
              factory.create(nameOrUrl, data, 'bundle', opts, function (p1, p2) {
                if (onComp) {
                  onComp(p1, p2);
                }
              });
            }
          });
        };
        _proto.releaseAsset = function releaseAsset(asset) {
          releaseManager.tryRelease(asset, true);
        };
        _proto.releaseUnusedAssets = function releaseUnusedAssets() {
          assets.forEach(function (asset) {
            releaseManager.tryRelease(asset);
          });
        };
        _proto.releaseAll = function releaseAll() {
          assets.forEach(function (asset) {
            releaseManager.tryRelease(asset, true);
          });
        };
        _proto.loadWithJson = function loadWithJson(json, options, onProgress, onComplete) {
          {
            throw new Error('Only valid in Editor');
          }
        };
        _createClass(AssetManager, [{
          key: "main",
          get: function get() {
            return bundles.get(BuiltinBundleName.MAIN) || null;
          }
        }, {
          key: "resources",
          get: function get() {
            return bundles.get(BuiltinBundleName.RESOURCES) || null;
          }
        }], [{
          key: "instance",
          get: function get() {
            if (!this._instance) {
              this._instance = new AssetManager();
            }
            return this._instance;
          }
        }]);
        return AssetManager;
      }());
      AssetManager._instance = void 0;
      AssetManager.Pipeline = Pipeline;
      AssetManager.Task = Task;
      AssetManager.Cache = Cache;
      AssetManager.RequestItem = RequestItem;
      AssetManager.Bundle = Bundle;
      AssetManager.BuiltinBundleName = BuiltinBundleName;
      AssetManager.CacheManager = CacheManager;
      AssetManager.Downloader = Downloader;
      AssetManager.Parser = Parser$1;
      AssetManager.DependUtil = DependUtil;
      var assetManager = exports('eq', legacyCC.assetManager = AssetManager.instance);
      legacyCC.AssetManager = AssetManager;

      var BuiltinResMgr = exports('ex', function () {
        function BuiltinResMgr() {
          this._resources = {};
          this._materialsToBeCompiled = [];
        }
        var _proto = BuiltinResMgr.prototype;
        _proto.init = function init() {
          var resources = this._resources;
          var len = 2;
          var numChannels = 4;
          var blackValueView = new Uint8Array(len * len * numChannels);
          var emptyValueView = new Uint8Array(len * len * numChannels);
          var greyValueView = new Uint8Array(len * len * numChannels);
          var whiteValueView = new Uint8Array(len * len * numChannels);
          var normalValueView = new Uint8Array(len * len * numChannels);
          var offset = 0;
          for (var i = 0; i < len * len; i++) {
            blackValueView[offset] = 0;
            blackValueView[offset + 1] = 0;
            blackValueView[offset + 2] = 0;
            blackValueView[offset + 3] = 255;
            emptyValueView[offset] = 0;
            emptyValueView[offset + 1] = 0;
            emptyValueView[offset + 2] = 0;
            emptyValueView[offset + 3] = 0;
            greyValueView[offset] = 119;
            greyValueView[offset + 1] = 119;
            greyValueView[offset + 2] = 119;
            greyValueView[offset + 3] = 255;
            whiteValueView[offset] = 255;
            whiteValueView[offset + 1] = 255;
            whiteValueView[offset + 2] = 255;
            whiteValueView[offset + 3] = 255;
            normalValueView[offset] = 127;
            normalValueView[offset + 1] = 127;
            normalValueView[offset + 2] = 255;
            normalValueView[offset + 3] = 255;
            offset += numChannels;
          }
          var defaultSize = 16;
          var halfDefaultSize = defaultSize / 2;
          var defaultValueView = new Uint8Array(defaultSize * defaultSize * numChannels);
          offset = 0;
          for (var _i = 0; _i < defaultSize * defaultSize; _i++) {
            defaultValueView[offset] = 221;
            defaultValueView[offset + 1] = 221;
            defaultValueView[offset + 2] = 221;
            defaultValueView[offset + 3] = 255;
            offset += numChannels;
          }
          offset = 0;
          for (var _i2 = 0; _i2 < halfDefaultSize; _i2++) {
            for (var j = 0; j < halfDefaultSize; j++) {
              defaultValueView[offset] = 85;
              defaultValueView[offset + 1] = 85;
              defaultValueView[offset + 2] = 85;
              defaultValueView[offset + 3] = 255;
              offset += numChannels;
            }
            offset += halfDefaultSize * numChannels;
          }
          offset += halfDefaultSize * numChannels;
          for (var _i3 = 0; _i3 < halfDefaultSize; _i3++) {
            for (var _j = 0; _j < halfDefaultSize; _j++) {
              defaultValueView[offset] = 85;
              defaultValueView[offset + 1] = 85;
              defaultValueView[offset + 2] = 85;
              defaultValueView[offset + 3] = 255;
              offset += numChannels;
            }
            offset += halfDefaultSize * numChannels;
          }
          var blackMemImageSource = {
            width: len,
            height: len,
            _data: blackValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var emptyMemImageSource = {
            width: len,
            height: len,
            _data: emptyValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var greyMemImageSource = {
            width: len,
            height: len,
            _data: greyValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var whiteMemImageSource = {
            width: len,
            height: len,
            _data: whiteValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var normalMemImageSource = {
            width: len,
            height: len,
            _data: normalValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var defaultMemImageSource = {
            width: defaultSize,
            height: defaultSize,
            _data: defaultValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var imgAsset = new ImageAsset(blackMemImageSource);
          var blackTexture = new Texture2D();
          blackTexture._uuid = 'black-texture';
          blackTexture.image = imgAsset;
          resources[blackTexture._uuid] = blackTexture;
          var emptyImgAsset = new ImageAsset(emptyMemImageSource);
          var emptyTexture = new Texture2D();
          emptyTexture._uuid = 'empty-texture';
          emptyTexture.image = emptyImgAsset;
          resources[emptyTexture._uuid] = emptyTexture;
          var blackCubeTexture = new TextureCube();
          blackCubeTexture._uuid = 'black-cube-texture';
          blackCubeTexture.setMipFilter(TextureCube.Filter.NEAREST);
          blackCubeTexture.image = {
            front: new ImageAsset(blackMemImageSource),
            back: new ImageAsset(blackMemImageSource),
            left: new ImageAsset(blackMemImageSource),
            right: new ImageAsset(blackMemImageSource),
            top: new ImageAsset(blackMemImageSource),
            bottom: new ImageAsset(blackMemImageSource)
          };
          resources[blackCubeTexture._uuid] = blackCubeTexture;
          var greyImgAsset = new ImageAsset(greyMemImageSource);
          var greyTexture = new Texture2D();
          greyTexture._uuid = 'grey-texture';
          greyTexture.image = greyImgAsset;
          resources[greyTexture._uuid] = greyTexture;
          var greyCubeTexture = new TextureCube();
          greyCubeTexture._uuid = 'grey-cube-texture';
          greyCubeTexture.setMipFilter(TextureCube.Filter.NEAREST);
          greyCubeTexture.image = {
            front: new ImageAsset(greyMemImageSource),
            back: new ImageAsset(greyMemImageSource),
            left: new ImageAsset(greyMemImageSource),
            right: new ImageAsset(greyMemImageSource),
            top: new ImageAsset(greyMemImageSource),
            bottom: new ImageAsset(greyMemImageSource)
          };
          resources[greyCubeTexture._uuid] = greyCubeTexture;
          var whiteImgAsset = new ImageAsset(whiteMemImageSource);
          var whiteTexture = new Texture2D();
          whiteTexture._uuid = 'white-texture';
          whiteTexture.image = whiteImgAsset;
          resources[whiteTexture._uuid] = whiteTexture;
          var whiteCubeTexture = new TextureCube();
          whiteCubeTexture._uuid = 'white-cube-texture';
          whiteCubeTexture.setMipFilter(TextureCube.Filter.NEAREST);
          whiteCubeTexture.image = {
            front: new ImageAsset(whiteMemImageSource),
            back: new ImageAsset(whiteMemImageSource),
            left: new ImageAsset(whiteMemImageSource),
            right: new ImageAsset(whiteMemImageSource),
            top: new ImageAsset(whiteMemImageSource),
            bottom: new ImageAsset(whiteMemImageSource)
          };
          resources[whiteCubeTexture._uuid] = whiteCubeTexture;
          var normalImgAsset = new ImageAsset(normalMemImageSource);
          var normalTexture = new Texture2D();
          normalTexture._uuid = 'normal-texture';
          normalTexture.image = normalImgAsset;
          resources[normalTexture._uuid] = normalTexture;
          var defaultImgAsset = new ImageAsset(defaultMemImageSource);
          var defaultTexture = new Texture2D();
          defaultTexture._uuid = 'default-texture';
          defaultTexture.image = defaultImgAsset;
          resources[defaultTexture._uuid] = defaultTexture;
          var defaultCubeTexture = new TextureCube();
          defaultCubeTexture.setMipFilter(TextureCube.Filter.NEAREST);
          defaultCubeTexture._uuid = 'default-cube-texture';
          defaultCubeTexture.image = {
            front: new ImageAsset(defaultMemImageSource),
            back: new ImageAsset(defaultMemImageSource),
            left: new ImageAsset(defaultMemImageSource),
            right: new ImageAsset(defaultMemImageSource),
            top: new ImageAsset(defaultMemImageSource),
            bottom: new ImageAsset(defaultMemImageSource)
          };
          resources[defaultCubeTexture._uuid] = defaultCubeTexture;
          if (legacyCC.SpriteFrame) {
            var spriteFrame = new legacyCC.SpriteFrame();
            var image = imgAsset;
            var texture = new Texture2D();
            texture.image = image;
            spriteFrame.texture = texture;
            spriteFrame._uuid = 'default-spriteframe';
            resources[spriteFrame._uuid] = spriteFrame;
          }
        };
        _proto.addAsset = function addAsset(key, asset) {
          this._resources[key] = asset;
        };
        _proto.get = function get(uuid) {
          return this._resources[uuid];
        };
        _proto.loadBuiltinAssets = function loadBuiltinAssets() {
          var _this = this;
          var builtinAssets = settings.querySettings(Settings.Category.ENGINE, 'builtinAssets');
          if (!builtinAssets) return Promise.resolve();
          var resources = this._resources;
          return new Promise(function (resolve, reject) {
            assetManager.loadBundle(BuiltinBundleName.INTERNAL, function (err, bundle) {
              if (err) {
                reject(err);
                return;
              }
              assetManager.loadAny(builtinAssets, function (err, assets) {
                if (err) {
                  reject(err);
                } else {
                  assets.forEach(function (asset) {
                    resources[asset.name] = asset;
                    {
                      releaseManager.addIgnoredAsset(asset);
                    }
                    if (asset instanceof legacyCC.Material) {
                      _this._materialsToBeCompiled.push(asset);
                    }
                  });
                  resolve();
                }
              });
            });
          });
        };
        _proto.compileBuiltinMaterial = function compileBuiltinMaterial() {
          for (var i = 0; i < this._materialsToBeCompiled.length; ++i) {
            var mat = this._materialsToBeCompiled[i];
            for (var j = 0; j < mat.passes.length; ++j) {
              mat.passes[j].tryCompile();
            }
          }
          this._materialsToBeCompiled.length = 0;
        };
        return BuiltinResMgr;
      }());
      var builtinResMgr = exports('ey', legacyCC.builtinResMgr = new BuiltinResMgr());

      var getPhaseID = exports('dz', function () {
        var phases = new Map();
        var phaseNum = 0;
        return function (phaseName) {
          if (typeof phaseName === 'number') {
            return phaseName;
          }
          if (!phases.has(phaseName)) {
            phases.set(phaseName, 1 << phaseNum);
            phaseNum++;
          }
          return phases.get(phaseName);
        };
      }());

      var INITIAL_CAPACITY = 32;
      var MAX_CAPACITY = 1024;
      var InstancedBuffer = exports('ds', function () {
        function InstancedBuffer(pass) {
          this.instances = [];
          this.pass = void 0;
          this.hasPendingModels = false;
          this.dynamicOffsets = [];
          this._device = void 0;
          this._device = pass.device;
          this.pass = pass;
        }
        var _proto = InstancedBuffer.prototype;
        _proto.destroy = function destroy() {
          for (var i = 0; i < this.instances.length; ++i) {
            var instance = this.instances[i];
            instance.vb.destroy();
            instance.ia.destroy();
          }
          this.instances.length = 0;
        };
        _proto.merge = function merge(subModel, passIdx, shaderImplant) {
          if (shaderImplant === void 0) {
            shaderImplant = null;
          }
          var attrs = subModel.instancedAttributeBlock;
          var stride = attrs.buffer.length;
          if (!stride) {
            return;
          }
          var sourceIA = subModel.inputAssembler;
          var lightingMap = subModel.descriptorSet.getTexture(UNIFORM_LIGHTMAP_TEXTURE_BINDING);
          var reflectionProbeCubemap = subModel.descriptorSet.getTexture(UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING);
          var reflectionProbePlanarMap = subModel.descriptorSet.getTexture(UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING);
          var reflectionProbeBlendCubemap = subModel.descriptorSet.getTexture(UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING);
          var useReflectionProbeType = subModel.useReflectionProbeType;
          var shader = shaderImplant;
          if (!shader) {
            shader = subModel.shaders[passIdx];
          }
          var descriptorSet = subModel.descriptorSet;
          for (var i = 0; i < this.instances.length; ++i) {
            var _instance$ia$indexBuf, _sourceIA$indexBuffer;
            var instance = this.instances[i];
            if (((_instance$ia$indexBuf = instance.ia.indexBuffer) === null || _instance$ia$indexBuf === void 0 ? void 0 : _instance$ia$indexBuf.objectID) !== ((_sourceIA$indexBuffer = sourceIA.indexBuffer) === null || _sourceIA$indexBuffer === void 0 ? void 0 : _sourceIA$indexBuffer.objectID) || instance.count >= MAX_CAPACITY) {
              continue;
            }
            if (instance.lightingMap.objectID !== lightingMap.objectID) {
              continue;
            }
            if (instance.useReflectionProbeType !== useReflectionProbeType) {
              continue;
            }
            if (instance.reflectionProbeCubemap.objectID !== reflectionProbeCubemap.objectID) {
              continue;
            }
            if (instance.reflectionProbePlanarMap.objectID !== reflectionProbePlanarMap.objectID) {
              continue;
            }
            if (instance.reflectionProbeBlendCubemap.objectID !== reflectionProbeBlendCubemap.objectID) {
              continue;
            }
            if (instance.stride !== stride) {
              continue;
            }
            if (instance.count >= instance.capacity) {
              instance.capacity <<= 1;
              var newSize = instance.stride * instance.capacity;
              var oldData = instance.data;
              instance.data = new Uint8Array(newSize);
              instance.data.set(oldData);
              instance.vb.resize(newSize);
            }
            instance.shader = shader;
            instance.descriptorSet = descriptorSet;
            instance.data.set(attrs.buffer, instance.stride * instance.count++);
            this.hasPendingModels = true;
            return;
          }
          var vb = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, stride * INITIAL_CAPACITY, stride));
          var data = new Uint8Array(stride * INITIAL_CAPACITY);
          var vertexBuffers = sourceIA.vertexBuffers.slice();
          var attributes = sourceIA.attributes.slice();
          var indexBuffer = sourceIA.indexBuffer;
          for (var _i = 0; _i < attrs.attributes.length; _i++) {
            var attr = attrs.attributes[_i];
            var newAttr = new Attribute(attr.name, attr.format, attr.isNormalized, vertexBuffers.length, true);
            attributes.push(newAttr);
          }
          data.set(attrs.buffer);
          vertexBuffers.push(vb);
          var iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer);
          var ia = this._device.createInputAssembler(iaInfo);
          this.instances.push({
            count: 1,
            capacity: INITIAL_CAPACITY,
            vb: vb,
            data: data,
            ia: ia,
            stride: stride,
            shader: shader,
            descriptorSet: descriptorSet,
            lightingMap: lightingMap,
            reflectionProbeCubemap: reflectionProbeCubemap,
            reflectionProbePlanarMap: reflectionProbePlanarMap,
            useReflectionProbeType: useReflectionProbeType,
            reflectionProbeBlendCubemap: reflectionProbeBlendCubemap
          });
          this.hasPendingModels = true;
        };
        _proto.uploadBuffers = function uploadBuffers(cmdBuff) {
          for (var i = 0; i < this.instances.length; ++i) {
            var instance = this.instances[i];
            if (!instance.count) {
              continue;
            }
            instance.ia.instanceCount = instance.count;
            cmdBuff.updateBuffer(instance.vb, instance.data);
          }
        };
        _proto.clear = function clear() {
          for (var i = 0; i < this.instances.length; ++i) {
            var instance = this.instances[i];
            instance.count = 0;
          }
          this.hasPendingModels = false;
        };
        return InstancedBuffer;
      }());

      var _bufferInfo = new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE);
      var _bufferViewInfo = new BufferViewInfo(null);
      var _dsInfo$2 = new DescriptorSetInfo(null);
      var _materialSet = 1;
      var BatchingSchemes;
      (function (BatchingSchemes) {
        BatchingSchemes[BatchingSchemes["NONE"] = 0] = "NONE";
        BatchingSchemes[BatchingSchemes["INSTANCING"] = 1] = "INSTANCING";
      })(BatchingSchemes || (BatchingSchemes = {}));
      var Pass = function () {
        Pass.fillPipelineInfo = function fillPipelineInfo(pass, info) {
          if (info.priority !== undefined) {
            pass._priority = info.priority;
          }
          if (info.primitive !== undefined) {
            pass._primitive = info.primitive;
          }
          if (info.stage !== undefined) {
            pass._stage = info.stage;
          }
          if (info.dynamicStates !== undefined) {
            pass._dynamicStates = info.dynamicStates;
          }
          if (info.phase !== undefined) {
            pass._phase = getPhaseID(info.phase);
          }
          var bs = pass._bs;
          if (info.blendState) {
            var bsInfo = info.blendState;
            var targets = bsInfo.targets;
            if (targets) {
              targets.forEach(function (t, i) {
                bs.setTarget(i, t);
              });
            }
            if (bsInfo.isA2C !== undefined) {
              bs.isA2C = bsInfo.isA2C;
            }
            if (bsInfo.isIndepend !== undefined) {
              bs.isIndepend = bsInfo.isIndepend;
            }
            if (bsInfo.blendColor !== undefined) {
              bs.blendColor = bsInfo.blendColor;
            }
          }
          pass._rs.assign(info.rasterizerState);
          pass._dss.assign(info.depthStencilState);
        };
        Pass.getPassHash = function getPassHash(pass) {
          var shaderKey = '';
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var key = legacyCC.rendering.programLib.getKey(pass._phaseID, pass.program, pass.defines);
            shaderKey = pass._phaseID.toString() + "," + key;
          } else {
            shaderKey = programLib.getKey(pass.program, pass.defines);
          }
          var res = shaderKey + "," + pass._primitive + "," + pass._dynamicStates;
          res += serializeBlendState(pass._bs);
          res += serializeDepthStencilState(pass._dss);
          res += serializeRasterizerState(pass._rs);
          return murmurhash2_32_gc(res, 666);
        };
        function Pass(root) {
          this._rootBuffer = null;
          this._buffers = [];
          this._descriptorSet = null;
          this._pipelineLayout = null;
          this._passIndex = 0;
          this._propertyIndex = 0;
          this._programName = '';
          this._dynamics = {};
          this._propertyHandleMap = {};
          this._rootBlock = null;
          this._blocksInt = [];
          this._blocks = [];
          this._shaderInfo = null;
          this._defines = {};
          this._properties = {};
          this._shader = null;
          this._bs = new BlendState$1();
          this._dss = new DepthStencilState();
          this._rs = new RasterizerState();
          this._priority = RenderPriority.DEFAULT;
          this._stage = RenderPassStage.DEFAULT;
          this._phase = getPhaseID('default');
          this._passID = 0xFFFFFFFF;
          this._subpassID = 0xFFFFFFFF;
          this._phaseID = 0xFFFFFFFF;
          this._primitive = PrimitiveMode.TRIANGLE_LIST;
          this._batchingScheme = BatchingSchemes.NONE;
          this._dynamicStates = DynamicStateFlagBit.NONE;
          this._instancedBuffers = {};
          this._hash = 0;
          this._root = void 0;
          this._device = void 0;
          this._rootBufferDirty = false;
          this._root = root;
          this._device = deviceManager.gfxDevice;
        }
        var _proto = Pass.prototype;
        _proto.initialize = function initialize(info) {
          this._doInit(info);
          this.resetUBOs();
          this.resetTextures();
          this.tryCompile();
        };
        _proto.getHandle = function getHandle(name, offset, targetType) {
          if (offset === void 0) {
            offset = 0;
          }
          if (targetType === void 0) {
            targetType = Type$1.UNKNOWN;
          }
          var handle = this._propertyHandleMap[name];
          if (!handle) {
            return 0;
          }
          if (targetType) {
            handle = customizeType(handle, targetType);
          } else if (offset) {
            handle = customizeType(handle, getTypeFromHandle(handle) - offset);
          }
          return handle + offset;
        };
        _proto.getBinding = function getBinding(name) {
          var handle = this.getHandle(name);
          if (!handle) {
            return -1;
          }
          return Pass.getBindingFromHandle(handle);
        };
        _proto.setUniform = function setUniform(handle, value) {
          var binding = Pass.getBindingFromHandle(handle);
          var type = Pass.getTypeFromHandle(handle);
          var ofs = Pass.getOffsetFromHandle(handle);
          var block = this._getBlockView(type, binding);
          {
            var validator = type2validator[type];
            assertID(Boolean(validator && validator(value)), 12011, binding, Type$1[type]);
          }
          type2writer[type](block, value, ofs);
          this._rootBufferDirty = true;
        };
        _proto.getUniform = function getUniform(handle, out) {
          var binding = Pass.getBindingFromHandle(handle);
          var type = Pass.getTypeFromHandle(handle);
          var ofs = Pass.getOffsetFromHandle(handle);
          var block = this._getBlockView(type, binding);
          return type2reader[type](block, out, ofs);
        };
        _proto.setUniformArray = function setUniformArray(handle, value) {
          var binding = Pass.getBindingFromHandle(handle);
          var type = Pass.getTypeFromHandle(handle);
          var stride = GetTypeSize(type) >> 2;
          var block = this._getBlockView(type, binding);
          var ofs = Pass.getOffsetFromHandle(handle);
          for (var i = 0; i < value.length; i++, ofs += stride) {
            if (value[i] === null) {
              continue;
            }
            type2writer[type](block, value[i], ofs);
          }
          this._rootBufferDirty = true;
        };
        _proto.bindTexture = function bindTexture(binding, value, index) {
          this._descriptorSet.bindTexture(binding, value, index || 0);
        };
        _proto.bindSampler = function bindSampler(binding, value, index) {
          this._descriptorSet.bindSampler(binding, value, index || 0);
        };
        _proto.setDynamicState = function setDynamicState(state, value) {
          var ds = this._dynamics[state];
          if (ds && ds.value === value) {
            return;
          }
          ds.value = value;
          ds.dirty = true;
        };
        _proto.overridePipelineStates = function overridePipelineStates(original, overrides) {
          warnID(12102);
        };
        _proto.update = function update() {
          if (!this._descriptorSet) {
            errorID(12006);
            return;
          }
          if (this._rootBuffer && this._rootBufferDirty) {
            this._rootBuffer.update(this._rootBlock);
            this._rootBufferDirty = false;
          }
          this._descriptorSet.update();
        };
        _proto.getInstancedBuffer = function getInstancedBuffer(extraKey) {
          if (extraKey === void 0) {
            extraKey = 0;
          }
          return this._instancedBuffers[extraKey] || (this._instancedBuffers[extraKey] = new InstancedBuffer(this));
        };
        _proto.destroy = function destroy() {
          for (var i = 0; i < this._shaderInfo.blocks.length; i++) {
            var u = this._shaderInfo.blocks[i];
            this._buffers[u.binding].destroy();
          }
          this._buffers = [];
          if (this._rootBuffer) {
            this._rootBuffer.destroy();
            this._rootBuffer = null;
          }
          for (var ib in this._instancedBuffers) {
            this._instancedBuffers[ib].destroy();
          }
          this._descriptorSet.destroy();
          this._rs.destroy();
          this._dss.destroy();
          this._bs.destroy();
        };
        _proto.resetUniform = function resetUniform(name) {
          var handle = this.getHandle(name);
          if (!handle) {
            return;
          }
          var type = Pass.getTypeFromHandle(handle);
          var binding = Pass.getBindingFromHandle(handle);
          var ofs = Pass.getOffsetFromHandle(handle);
          var count = Pass.getCountFromHandle(handle);
          var block = this._getBlockView(type, binding);
          var info = this._properties[name];
          var givenDefault = info && info.value;
          var value = givenDefault || getDefaultFromType(type);
          var size = (GetTypeSize(type) >> 2) * count;
          for (var k = 0; k + value.length <= size; k += value.length) {
            block.set(value, ofs + k);
          }
          this._rootBufferDirty = true;
        };
        _proto.resetTexture = function resetTexture(name, index) {
          var handle = this.getHandle(name);
          if (!handle) {
            return;
          }
          var type = Pass.getTypeFromHandle(handle);
          var binding = Pass.getBindingFromHandle(handle);
          var info = this._properties[name];
          var value = info && info.value;
          var textureBase;
          if (typeof value === 'string') {
            textureBase = builtinResMgr.get("" + value + getStringFromType(type));
          } else {
            textureBase = value || builtinResMgr.get(getDefaultFromType(type));
          }
          var texture = textureBase && textureBase.getGFXTexture();
          var samplerInfo = info && info.samplerHash !== undefined ? Sampler.unpackFromHash(info.samplerHash) : textureBase && textureBase.getSamplerInfo();
          var sampler = this._device.getSampler(samplerInfo);
          this._descriptorSet.bindSampler(binding, sampler, index || 0);
          this._descriptorSet.bindTexture(binding, texture, index || 0);
        };
        _proto.resetUBOs = function resetUBOs() {
          for (var i = 0; i < this._shaderInfo.blocks.length; i++) {
            var u = this._shaderInfo.blocks[i];
            var ofs = 0;
            for (var j = 0; j < u.members.length; j++) {
              var cur = u.members[j];
              var block = this._getBlockView(cur.type, u.binding);
              var info = this._properties[cur.name];
              var givenDefault = info && info.value;
              var value = givenDefault || getDefaultFromType(cur.type);
              var size = (GetTypeSize(cur.type) >> 2) * cur.count;
              for (var k = 0; k + value.length <= size; k += value.length) {
                block.set(value, ofs + k);
              }
              ofs += size;
            }
          }
          this._rootBufferDirty = true;
        };
        _proto.resetTextures = function resetTextures() {
          if (legacyCC.rendering) {
            var set = this._shaderInfo.descriptors[SetIndex.MATERIAL];
            for (var _iterator = _createForOfIteratorHelperLoose(set.samplerTextures), _step; !(_step = _iterator()).done;) {
              var combined = _step.value;
              for (var j = 0; j < combined.count; ++j) {
                this.resetTexture(combined.name, j);
              }
            }
          } else {
            for (var i = 0; i < this._shaderInfo.samplerTextures.length; i++) {
              var u = this._shaderInfo.samplerTextures[i];
              for (var _j = 0; _j < u.count; _j++) {
                this.resetTexture(u.name, _j);
              }
            }
          }
        };
        _proto.tryCompile = function tryCompile() {
          var pipeline = this._root.pipeline;
          if (!pipeline) {
            return false;
          }
          this._syncBatchingScheme();
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var _programLib = legacyCC.rendering.programLib;
            var program = _programLib.getProgramVariant(this._device, this._phaseID, this._programName, this._defines);
            if (!program) {
              warnID(12103, this._programName);
              return false;
            }
            this._shader = program.shader;
            this._pipelineLayout = _programLib.getPipelineLayout(this.device, this._phaseID, this._programName);
          } else {
            var shader = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline);
            if (!shader) {
              warnID(12104, this._programName);
              return false;
            }
            this._shader = shader;
            this._pipelineLayout = programLib.getTemplateInfo(this._programName).pipelineLayout;
          }
          this._hash = Pass.getPassHash(this);
          return true;
        };
        _proto.getShaderVariant = function getShaderVariant(patches) {
          if (patches === void 0) {
            patches = null;
          }
          if (!this._shader && !this.tryCompile()) {
            warnID(12105);
            return null;
          }
          if (!patches) {
            return this._shader;
          }
          var pipeline = this._root.pipeline;
          for (var _i = 0; _i < patches.length; _i++) {
            var patch = patches[_i];
            this._defines[patch.name] = patch.value;
          }
          if (this._isBlend) {
            this._defines.CC_IS_TRANSPARENCY_PASS = 1;
          }
          var shader = null;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var program = legacyCC.rendering.programLib.getProgramVariant(this._device, this._phaseID, this._programName, this._defines);
            if (program) {
              shader = program.shader;
            }
          } else {
            shader = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline);
          }
          for (var _i2 = 0; _i2 < patches.length; _i2++) {
            var _patch = patches[_i2];
            delete this._defines[_patch.name];
          }
          return shader;
        };
        _proto.beginChangeStatesSilently = function beginChangeStatesSilently() {};
        _proto.endChangeStatesSilently = function endChangeStatesSilently() {};
        _proto._doInit = function _doInit(info, copyDefines) {
          if (copyDefines === void 0) {
            copyDefines = false;
          }
          this._priority = RenderPriority.DEFAULT;
          this._stage = RenderPassStage.DEFAULT;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var r = legacyCC.rendering;
            if (typeof info.phase === 'number') {
              this._passID = info._passID;
              this._subpassID = info._subpassID;
              this._phaseID = info._phaseID;
            } else {
              this._passID = r.getPassID(info.pass);
              if (this._passID !== r.INVALID_ID) {
                if (info.subpass) {
                  this._subpassID = r.getSubpassID(this._passID, info.subpass);
                  this._phaseID = r.getPhaseID(this._subpassID, info.phase);
                } else {
                  this._phaseID = r.getPhaseID(this._passID, info.phase);
                }
              }
            }
            if (this._passID === r.INVALID_ID) {
              errorID(12107, info.program);
              return;
            }
            if (this._phaseID === r.INVALID_ID) {
              errorID(12108, info.program);
              return;
            }
          }
          this._phase = getPhaseID('default');
          this._primitive = PrimitiveMode.TRIANGLE_LIST;
          this._passIndex = info.passIndex;
          this._propertyIndex = info.propertyIndex !== undefined ? info.propertyIndex : info.passIndex;
          this._programName = info.program;
          this._defines = copyDefines ? _extends({}, info.defines) : info.defines;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            this._shaderInfo = legacyCC.rendering.programLib.getProgramInfo(this._phaseID, this._programName);
          } else {
            this._shaderInfo = programLib.getTemplate(info.program);
          }
          this._properties = info.properties || this._properties;
          var device = this._device;
          Pass.fillPipelineInfo(this, info);
          if (info.stateOverrides) {
            Pass.fillPipelineInfo(this, info.stateOverrides);
          }
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            _dsInfo$2.layout = legacyCC.rendering.programLib.getMaterialDescriptorSetLayout(this._device, this._phaseID, info.program);
          } else {
            _dsInfo$2.layout = programLib.getDescriptorSetLayout(this._device, info.program);
          }
          this._descriptorSet = this._device.createDescriptorSet(_dsInfo$2);
          var blocks = this._shaderInfo.blocks;
          var blockSizes;
          var handleMap;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var _programLib2 = legacyCC.rendering.programLib;
            blockSizes = _programLib2.getBlockSizes(this._phaseID, this._programName);
            handleMap = _programLib2.getHandleMap(this._phaseID, this._programName);
          } else {
            var tmplInfo = programLib.getTemplateInfo(info.program);
            blockSizes = tmplInfo.blockSizes;
            handleMap = tmplInfo.handleMap;
          }
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var _programLib3 = legacyCC.rendering.programLib;
            var shaderInfo = _programLib3.getShaderInfo(this._phaseID, this.program);
            this._buildMaterialUniformBlocks(device, shaderInfo.blocks, blockSizes);
          } else {
            this._buildUniformBlocks(device, blocks, blockSizes);
          }
          var directHandleMap = this._propertyHandleMap = handleMap;
          var indirectHandleMap = {};
          for (var name in this._properties) {
            var prop = this._properties[name];
            if (!prop.handleInfo) {
              continue;
            }
            indirectHandleMap[name] = this.getHandle.apply(this, prop.handleInfo);
          }
          Object.assign(directHandleMap, indirectHandleMap);
        };
        _proto._buildUniformBlocks = function _buildUniformBlocks(device, blocks, blockSizes) {
          var alignment = device.capabilities.uboOffsetAlignment;
          var startOffsets = [];
          var lastSize = 0;
          var lastOffset = 0;
          for (var i = 0; i < blocks.length; i++) {
            var size = blockSizes[i];
            startOffsets.push(lastOffset);
            lastOffset += Math.ceil(size / alignment) * alignment;
            lastSize = size;
          }
          var totalSize = startOffsets[startOffsets.length - 1] + lastSize;
          if (totalSize) {
            _bufferInfo.size = Math.ceil(totalSize / 16) * 16;
            this._rootBuffer = device.createBuffer(_bufferInfo);
            this._rootBlock = new ArrayBuffer(totalSize);
          }
          for (var _i3 = 0, count = 0; _i3 < blocks.length; _i3++) {
            var binding = blocks[_i3].binding;
            var _size = blockSizes[_i3];
            _bufferViewInfo.buffer = this._rootBuffer;
            _bufferViewInfo.offset = startOffsets[count++];
            _bufferViewInfo.range = Math.ceil(_size / 16) * 16;
            var bufferView = this._buffers[binding] = device.createBuffer(_bufferViewInfo);
            this._blocks[binding] = new Float32Array(this._rootBlock, _bufferViewInfo.offset, _size / Float32Array.BYTES_PER_ELEMENT);
            this._blocksInt[binding] = new Int32Array(this._blocks[binding].buffer, this._blocks[binding].byteOffset, this._blocks[binding].length);
            this._descriptorSet.bindBuffer(binding, bufferView);
          }
        };
        _proto._buildMaterialUniformBlocks = function _buildMaterialUniformBlocks(device, blocks, blockSizes) {
          var alignment = device.capabilities.uboOffsetAlignment;
          var startOffsets = [];
          var lastSize = 0;
          var lastOffset = 0;
          for (var i = 0; i < blocks.length; i++) {
            var block = blocks[i];
            if (block.set !== _materialSet) {
              continue;
            }
            var size = blockSizes[i];
            startOffsets.push(lastOffset);
            lastOffset += Math.ceil(size / alignment) * alignment;
            lastSize = size;
          }
          if (lastSize !== 0) {
            var totalSize = startOffsets[startOffsets.length - 1] + lastSize;
            if (totalSize) {
              _bufferInfo.size = Math.ceil(totalSize / 16) * 16;
              this._rootBuffer = device.createBuffer(_bufferInfo);
              this._rootBlock = new ArrayBuffer(totalSize);
            }
          }
          for (var _i4 = 0, count = 0; _i4 < blocks.length; _i4++) {
            var _block = blocks[_i4];
            if (_block.set !== _materialSet) {
              continue;
            }
            var binding = blocks[_i4].binding;
            var _size2 = blockSizes[_i4];
            _bufferViewInfo.buffer = this._rootBuffer;
            _bufferViewInfo.offset = startOffsets[count++];
            _bufferViewInfo.range = Math.ceil(_size2 / 16) * 16;
            var bufferView = this._buffers[binding] = device.createBuffer(_bufferViewInfo);
            this._blocks[binding] = new Float32Array(this._rootBlock, _bufferViewInfo.offset, _size2 / Float32Array.BYTES_PER_ELEMENT);
            this._blocksInt[binding] = new Int32Array(this._blocks[binding].buffer, this._blocks[binding].byteOffset, this._blocks[binding].length);
            this._descriptorSet.bindBuffer(binding, bufferView);
          }
        };
        _proto._syncBatchingScheme = function _syncBatchingScheme() {
          if (this._defines.USE_INSTANCING) {
            if (this._device.hasFeature(Feature.INSTANCED_ARRAYS)) {
              this._batchingScheme = BatchingSchemes.INSTANCING;
            } else {
              this._defines.USE_INSTANCING = false;
              this._batchingScheme = BatchingSchemes.NONE;
            }
          } else {
            this._batchingScheme = BatchingSchemes.NONE;
          }
        };
        _proto._getBlockView = function _getBlockView(type, binding) {
          return type < Type$1.FLOAT ? this._blocksInt[binding] : this._blocks[binding];
        };
        _proto._initPassFromTarget = function _initPassFromTarget(target, dss, hashFactor) {
          this._priority = target.priority;
          this._stage = target.stage;
          this._phase = target.phase;
          this._phaseID = target._phaseID;
          this._passID = target._passID;
          this._batchingScheme = target.batchingScheme;
          this._primitive = target.primitive;
          this._dynamicStates = target.dynamicStates;
          this._bs = target.blendState;
          this._dss = dss;
          this._descriptorSet = target.descriptorSet;
          this._rs = target.rasterizerState;
          this._passIndex = target.passIndex;
          this._propertyIndex = target.propertyIndex;
          this._programName = target.program;
          this._defines = target.defines;
          this._shaderInfo = target._shaderInfo;
          this._properties = target._properties;
          this._blocks = target._blocks;
          this._blocksInt = target._blocksInt;
          this._dynamics = target._dynamics;
          this._shader = target._shader;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            this._pipelineLayout = legacyCC.rendering.programLib.getPipelineLayout(this.device, this._phaseID, this._programName);
          } else {
            this._pipelineLayout = programLib.getTemplateInfo(this._programName).pipelineLayout;
          }
          this._hash = target._hash ^ hashFactor;
        };
        _proto._updatePassHash = function _updatePassHash() {
          this._hash = Pass.getPassHash(this);
        };
        _proto.setRootBufferDirty = function setRootBufferDirty(val) {
          this._rootBufferDirty = val;
        };
        _proto.setPriority = function setPriority(val) {
          this._priority = val;
        };
        _createClass(Pass, [{
          key: "_isBlend",
          get: function get() {
            var bBlend = false;
            for (var _iterator2 = _createForOfIteratorHelperLoose(this.blendState.targets), _step2; !(_step2 = _iterator2()).done;) {
              var target = _step2.value;
              if (target.blend) {
                bBlend = true;
              }
            }
            return bBlend;
          }
        }, {
          key: "root",
          get: function get() {
            return this._root;
          }
        }, {
          key: "device",
          get: function get() {
            return this._device;
          }
        }, {
          key: "shaderInfo",
          get: function get() {
            return this._shaderInfo;
          }
        }, {
          key: "localSetLayout",
          get: function get() {
            if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
              return legacyCC.rendering.programLib.getLocalDescriptorSetLayout(this._device, this._phaseID, this._programName);
            } else {
              return programLib.getDescriptorSetLayout(this._device, this._programName, true);
            }
          }
        }, {
          key: "program",
          get: function get() {
            return this._programName;
          }
        }, {
          key: "properties",
          get: function get() {
            return this._properties;
          }
        }, {
          key: "defines",
          get: function get() {
            return this._defines;
          }
        }, {
          key: "passIndex",
          get: function get() {
            return this._passIndex;
          }
        }, {
          key: "propertyIndex",
          get: function get() {
            return this._propertyIndex;
          }
        }, {
          key: "dynamics",
          get: function get() {
            return this._dynamics;
          }
        }, {
          key: "blocks",
          get: function get() {
            return this._blocks;
          }
        }, {
          key: "blocksInt",
          get: function get() {
            return this._blocksInt;
          }
        }, {
          key: "rootBufferDirty",
          get: function get() {
            return this._rootBufferDirty;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          }
        }, {
          key: "primitive",
          get: function get() {
            return this._primitive;
          }
        }, {
          key: "stage",
          get: function get() {
            return this._stage;
          }
        }, {
          key: "phase",
          get: function get() {
            return this._phase;
          }
        }, {
          key: "passID",
          get: function get() {
            return this._passID;
          }
        }, {
          key: "phaseID",
          get: function get() {
            return this._phaseID;
          }
        }, {
          key: "rasterizerState",
          get: function get() {
            return this._rs;
          }
        }, {
          key: "depthStencilState",
          get: function get() {
            return this._dss;
          }
        }, {
          key: "blendState",
          get: function get() {
            return this._bs;
          }
        }, {
          key: "dynamicStates",
          get: function get() {
            return this._dynamicStates;
          }
        }, {
          key: "batchingScheme",
          get: function get() {
            return this._batchingScheme;
          }
        }, {
          key: "descriptorSet",
          get: function get() {
            return this._descriptorSet;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }, {
          key: "pipelineLayout",
          get: function get() {
            return this._pipelineLayout;
          }
        }]);
        return Pass;
      }();
      Pass.getTypeFromHandle = getTypeFromHandle;
      Pass.getBindingFromHandle = getBindingFromHandle;
      Pass.getCountFromHandle = getCountFromHandle;
      Pass.getOffsetFromHandle = getOffsetFromHandle;
      function serializeBlendState(bs) {
        var res = ",bs," + bs.isA2C;
        for (var _iterator3 = _createForOfIteratorHelperLoose(bs.targets), _step3; !(_step3 = _iterator3()).done;) {
          var t = _step3.value;
          res += ",bt," + t.blend + "," + t.blendEq + "," + t.blendAlphaEq + "," + t.blendColorMask;
          res += "," + t.blendSrc + "," + t.blendDst + "," + t.blendSrcAlpha + "," + t.blendDstAlpha;
        }
        return res;
      }
      function serializeRasterizerState(rs) {
        return ",rs," + rs.cullMode + "," + rs.depthBias + "," + rs.isFrontFaceCCW;
      }
      function serializeDepthStencilState(dss) {
        var res = ",dss," + dss.depthTest + "," + dss.depthWrite + "," + dss.depthFunc;
        res += "," + dss.stencilTestFront + "," + dss.stencilFuncFront + "," + dss.stencilRefFront + "," + dss.stencilReadMaskFront;
        res += "," + dss.stencilFailOpFront + "," + dss.stencilZFailOpFront + "," + dss.stencilPassOpFront + "," + dss.stencilWriteMaskFront;
        res += "," + dss.stencilTestBack + "," + dss.stencilFuncBack + "," + dss.stencilRefBack + "," + dss.stencilReadMaskBack;
        res += "," + dss.stencilFailOpBack + "," + dss.stencilZFailOpBack + "," + dss.stencilPassOpBack + "," + dss.stencilWriteMaskBack;
        return res;
      }

      var PipelineStateManager = exports('dt', function () {
        function PipelineStateManager() {}
        PipelineStateManager.getOrCreatePipelineState = function getOrCreatePipelineState(device, pass, shader, renderPass, ia) {
          var hash1 = pass.hash;
          var hash2 = renderPass.hash;
          var hash3 = ia.attributesHash;
          var hash4 = shader.typedID;
          var newHash = hash1 ^ hash2 ^ hash3 ^ hash4;
          var pso = this._PSOHashMap.get(newHash);
          if (!pso) {
            var pipelineLayout = pass.pipelineLayout;
            var inputState = new InputState(ia.attributes);
            var psoInfo = new PipelineStateInfo(shader, pipelineLayout, renderPass, inputState, pass.rasterizerState, pass.depthStencilState, pass.blendState, pass.primitive, pass.dynamicStates);
            pso = device.createPipelineState(psoInfo);
            this._PSOHashMap.set(newHash, pso);
          }
          return pso;
        };
        return PipelineStateManager;
      }());
      PipelineStateManager._PSOHashMap = new Map();

      var profilerViewport = new Viewport();
      var profilerScissor = new Rect();
      function SRGBToLinear(out, gamma) {
        out.x = gamma.x * gamma.x;
        out.y = gamma.y * gamma.y;
        out.z = gamma.z * gamma.z;
      }
      var profilerCamera = null;
      function getProfilerCamera() {
        return profilerCamera;
      }
      function decideProfilerCamera(cameras) {
        for (var i = cameras.length - 1; i >= 0; --i) {
          var camera = cameras[i];
          if (camera.window.swapchain) {
            profilerCamera = camera;
            return;
          }
        }
        profilerCamera = null;
      }
      function renderProfiler(device, renderPass, cmdBuff, profiler, camera) {
        if (isEnableEffect()) {
          return;
        }
        if (!profiler || !profiler.enabled) {
          return;
        }
        if (camera !== profilerCamera) {
          return;
        }
        var _profiler$subModels$ = profiler.subModels[0],
          inputAssembler = _profiler$subModels$.inputAssembler,
          passes = _profiler$subModels$.passes,
          shaders = _profiler$subModels$.shaders,
          descriptorSet = _profiler$subModels$.descriptorSet;
        profilerViewport.width = profilerScissor.width = camera.window.width;
        profilerViewport.height = profilerScissor.height = camera.window.height;
        var pso = PipelineStateManager.getOrCreatePipelineState(device, passes[0], shaders[0], renderPass, inputAssembler);
        cmdBuff.setViewport(profilerViewport);
        cmdBuff.setScissor(profilerScissor);
        cmdBuff.bindPipelineState(pso);
        cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, passes[0].descriptorSet);
        cmdBuff.bindDescriptorSet(SetIndex.LOCAL, descriptorSet);
        cmdBuff.bindInputAssembler(inputAssembler);
        cmdBuff.draw(inputAssembler);
      }

      var _dec$3r, _dec2$2w, _class$3m, _class2$31, _initializer$2O, _initializer2$2g, _initializer3$1F, _initializer4$1p, _initializer5$16;
      var v4_1 = new Vec4();
      var Material = exports('el', (_dec$3r = ccclass$M('cc.Material'), _dec2$2w = type$d(EffectAsset), _dec$3r(_class$3m = (_class2$31 = function (_Asset) {
        _inheritsLoose(Material, _Asset);
        Material.getHash = function getHash(material) {
          var hash = 0;
          for (var _iterator = _createForOfIteratorHelperLoose(material.passes), _step; !(_step = _iterator()).done;) {
            var pass = _step.value;
            hash ^= pass.hash;
          }
          return hash;
        };
        function Material() {
          var _this;
          _this = _Asset.call(this) || this;
          _this._effectAsset = _initializer$2O && _initializer$2O();
          _this._techIdx = _initializer2$2g && _initializer2$2g();
          _this._defines = _initializer3$1F && _initializer3$1F();
          _this._states = _initializer4$1p && _initializer4$1p();
          _this._props = _initializer5$16 && _initializer5$16();
          _this._passes = [];
          _this._hash = 0;
          return _this;
        }
        var _proto = Material.prototype;
        _proto.initialize = function initialize(info) {
          if (this._passes.length) {
            warnID(12005);
            return;
          }
          if (!this._defines) {
            this._defines = [];
          }
          if (!this._states) {
            this._states = [];
          }
          if (!this._props) {
            this._props = [];
          }
          this._fillInfo(info);
          this._update();
        };
        _proto.reset = function reset(info) {
          this.initialize(info);
        };
        _proto.destroy = function destroy() {
          this._doDestroy();
          return _Asset.prototype.destroy.call(this);
        };
        _proto.recompileShaders = function recompileShaders(overrides, passIdx) {
          console.warn("Shaders in material asset '" + this.name + "' cannot be modified at runtime, please instantiate the material first.");
        };
        _proto.overridePipelineStates = function overridePipelineStates(overrides, passIdx) {
          console.warn("Pipeline states in material asset '" + this.name + "' cannot be modified at runtime, please instantiate the material first.");
        };
        _proto.onLoaded = function onLoaded() {
          this._update();
        };
        _proto.resetUniforms = function resetUniforms(clearPasses) {
          if (clearPasses === void 0) {
            clearPasses = true;
          }
          this._props.length = this._passes.length;
          for (var i = 0; i < this._props.length; i++) {
            this._props[i] = {};
          }
          if (!clearPasses) {
            return;
          }
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._passes), _step2; !(_step2 = _iterator2()).done;) {
            var pass = _step2.value;
            pass.resetUBOs();
            pass.resetTextures();
          }
        };
        _proto.setProperty = function setProperty(name, val, passIdx) {
          var success = false;
          if (passIdx === undefined) {
            var passes = this._passes;
            var len = passes.length;
            for (var i = 0; i < len; i++) {
              var pass = passes[i];
              if (this._uploadProperty(pass, name, val)) {
                this._props[pass.propertyIndex][name] = val;
                success = true;
              }
            }
          } else {
            if (passIdx >= this._passes.length) {
              console.warn("illegal pass index: " + passIdx + ".");
              return;
            }
            var _pass = this._passes[passIdx];
            if (this._uploadProperty(_pass, name, val)) {
              this._props[_pass.propertyIndex][name] = val;
              success = true;
            }
          }
          if (!success) {
            console.warn("illegal property name: " + name + ".");
          }
        };
        _proto.getProperty = function getProperty(name, passIdx) {
          if (passIdx === undefined) {
            var propsArray = this._props;
            var len = propsArray.length;
            for (var i = 0; i < len; i++) {
              var props = propsArray[i];
              if (name in props) {
                return props[name];
              }
            }
          } else {
            if (passIdx >= this._passes.length) {
              console.warn("illegal pass index: " + passIdx + ".");
              return null;
            }
            var _props = this._props[this._passes[passIdx].propertyIndex];
            if (name in _props) {
              return _props[name];
            }
          }
          return null;
        };
        _proto.copy = function copy(mat, overrides) {
          this._techIdx = mat._techIdx;
          this._props.length = mat._props.length;
          for (var i = 0; i < mat._props.length; i++) {
            this._props[i] = _extends({}, mat._props[i]);
          }
          this._defines.length = mat._defines.length;
          for (var _i = 0; _i < mat._defines.length; _i++) {
            this._defines[_i] = _extends({}, mat._defines[_i]);
          }
          this._states.length = mat._states.length;
          for (var _i2 = 0; _i2 < mat._states.length; _i2++) {
            this._states[_i2] = _extends({}, mat._states[_i2]);
          }
          this._effectAsset = mat._effectAsset;
          if (overrides) this._fillInfo(overrides);
          this._update();
        };
        _proto._fillInfo = function _fillInfo(info) {
          if (info.technique !== undefined) {
            this._techIdx = info.technique;
          }
          if (info.effectAsset) {
            this._effectAsset = info.effectAsset;
          } else if (info.effectName) {
            this._effectAsset = EffectAsset.get(info.effectName);
          }
          if (info.defines) {
            this._prepareInfo(info.defines, this._defines);
          }
          if (info.states) {
            this._prepareInfo(info.states, this._states);
          }
        };
        _proto._prepareInfo = function _prepareInfo(patch, cur) {
          var patchArray = patch;
          if (!Array.isArray(patchArray)) {
            var len = this._effectAsset ? this._effectAsset.techniques[this._techIdx].passes.length : 1;
            patchArray = Array(len).fill(patchArray);
          }
          for (var i = 0; i < patchArray.length; ++i) {
            Object.assign(cur[i] || (cur[i] = {}), patchArray[i]);
          }
        };
        _proto._createPasses = function _createPasses() {
          var tech = this._effectAsset.techniques[this._techIdx || 0];
          if (!tech) {
            return [];
          }
          var passNum = tech.passes.length;
          var passes = [];
          for (var k = 0; k < passNum; ++k) {
            var passInfo = tech.passes[k];
            var propIdx = passInfo.passIndex = k;
            var defines = passInfo.defines = this._defines[propIdx] || (this._defines[propIdx] = {});
            passInfo.stateOverrides = this._states[propIdx] || (this._states[propIdx] = {});
            if (passInfo.propertyIndex !== undefined) {
              Object.assign(defines, this._defines[passInfo.propertyIndex]);
            }
            if (passInfo.embeddedMacros !== undefined) {
              Object.assign(defines, passInfo.embeddedMacros);
            }
            if (passInfo["switch"] && !defines[passInfo["switch"]]) {
              continue;
            }
            var pass = new Pass(legacyCC.director.root);
            pass.initialize(passInfo);
            passes.push(pass);
          }
          return passes;
        };
        _proto._update = function _update(keepProps) {
          var _this2 = this;
          if (keepProps === void 0) {
            keepProps = true;
          }
          if (this._effectAsset) {
            this._passes = this._createPasses();
            var totalPasses = this._effectAsset.techniques[this._techIdx].passes.length;
            this._props.length = totalPasses;
            if (keepProps) {
              this._passes.forEach(function (pass, i) {
                var props = _this2._props[i];
                if (!props) {
                  props = _this2._props[i] = {};
                }
                if (pass.propertyIndex !== undefined) {
                  Object.assign(props, _this2._props[pass.propertyIndex]);
                }
                for (var p in props) {
                  _this2._uploadProperty(pass, p, props[p]);
                }
              });
            } else {
              for (var i = 0; i < this._props.length; i++) {
                this._props[i] = {};
              }
            }
          }
          this._hash = Material.getHash(this);
        };
        _proto._uploadProperty = function _uploadProperty(pass, name, val) {
          var handle = pass.getHandle(name);
          if (!handle) {
            return false;
          }
          var type = Pass.getTypeFromHandle(handle);
          if (type < Type$1.SAMPLER1D) {
            if (Array.isArray(val)) {
              pass.setUniformArray(handle, val);
            } else if (val !== null) {
              var _pass$properties$name;
              if ((_pass$properties$name = pass.properties[name]) !== null && _pass$properties$name !== void 0 && _pass$properties$name.linear) {
                var v4 = val;
                SRGBToLinear(v4_1, v4);
                v4_1.w = v4.w;
                val = v4_1;
              }
              pass.setUniform(handle, val);
            } else {
              pass.resetUniform(name);
            }
          } else if (Array.isArray(val)) {
            for (var i = 0; i < val.length; i++) {
              this._bindTexture(pass, handle, val[i], i);
            }
          } else if (val) {
            this._bindTexture(pass, handle, val);
          } else {
            pass.resetTexture(name);
          }
          return true;
        };
        _proto._bindTexture = function _bindTexture(pass, handle, val, index) {
          var binding = Pass.getBindingFromHandle(handle);
          if (val instanceof Texture) {
            pass.bindTexture(binding, val, index);
          } else if (val instanceof TextureBase) {
            var texture = val.getGFXTexture();
            if (!texture || !texture.width || !texture.height) {
              return;
            }
            pass.bindTexture(binding, texture, index);
            pass.bindSampler(binding, val.getGFXSampler(), index);
          }
        };
        _proto._doDestroy = function _doDestroy() {
          if (this._passes && this._passes.length) {
            for (var _iterator3 = _createForOfIteratorHelperLoose(this._passes), _step3; !(_step3 = _iterator3()).done;) {
              var pass = _step3.value;
              pass.destroy();
            }
          }
          this._passes.length = 0;
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          this.initialize({
            effectName: 'builtin-unlit',
            defines: {
              USE_COLOR: true
            },
            technique: 0
          });
          this.setProperty('mainColor', new Color$1('#ff00ff'));
        };
        _proto.validate = function validate() {
          return !!this._effectAsset && !this._effectAsset.isDefault && this.passes.length > 0;
        };
        _createClass(Material, [{
          key: "effectAsset",
          get: function get() {
            return this._effectAsset;
          }
        }, {
          key: "effectName",
          get: function get() {
            return this._effectAsset ? this._effectAsset.name : '';
          }
        }, {
          key: "technique",
          get: function get() {
            return this._techIdx;
          }
        }, {
          key: "passes",
          get: function get() {
            return this._passes;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }, {
          key: "parent",
          get: function get() {
            return null;
          }
        }, {
          key: "owner",
          get: function get() {
            return null;
          }
        }]);
        return Material;
      }(Asset), (_initializer$2O = applyDecoratedInitializer(_class2$31.prototype, "_effectAsset", [_dec2$2w], function () {
        return null;
      }), _initializer2$2g = applyDecoratedInitializer(_class2$31.prototype, "_techIdx", [serializable$p], function () {
        return 0;
      }), _initializer3$1F = applyDecoratedInitializer(_class2$31.prototype, "_defines", [serializable$p], function () {
        return [];
      }), _initializer4$1p = applyDecoratedInitializer(_class2$31.prototype, "_states", [serializable$p], function () {
        return [];
      }), _initializer5$16 = applyDecoratedInitializer(_class2$31.prototype, "_props", [serializable$p], function () {
        return [];
      })), _class2$31)) || _class$3m));
      legacyCC.Material = Material;

      var ShadowSize = Enum({
        Low_256x256: 256,
        Medium_512x512: 512,
        High_1024x1024: 1024,
        Ultra_2048x2048: 2048
      });
      var ShadowType = Enum({
        Planar: 0,
        ShadowMap: 1
      });
      var PCFType = Enum({
        HARD: 0,
        SOFT: 1,
        SOFT_2X: 2,
        SOFT_4X: 3
      });
      var CSMLevel = Enum({
        LEVEL_1: 1,
        LEVEL_2: 2,
        LEVEL_3: 3,
        LEVEL_4: 4
      });
      var CSMOptimizationMode = Enum({
        NONE: 1,
        RemoveDuplicates: 2,
        DisableRotationFix: 3
      });
      var SHADOW_TYPE_NONE = ShadowType.ShadowMap + 1;
      var Shadows = function () {
        function Shadows() {
          this.fixedSphere = new Sphere(0.0, 0.0, 0.0, 0.01);
          this.maxReceived = 4;
          this._matLight = new Mat4();
          this._material = null;
          this._instancingMaterial = null;
          this._enabled = false;
          this._type = SHADOW_TYPE_NONE;
          this._distance = 0;
          this._planeBias = 1.0;
          this._normal = new Vec3(0, 1, 0);
          this._shadowColor = new Color$1(0, 0, 0, 76);
          this._size = new Vec2(1024, 1024);
          this._shadowMapDirty = false;
        }
        var _proto = Shadows.prototype;
        _proto.getPlanarShader = function getPlanarShader(patches) {
          if (!this._material) {
            this._material = new Material();
            this._material.initialize({
              effectName: 'pipeline/planar-shadow'
            });
          }
          var passes = this._material.passes;
          {
            assert(passes.length > 0, 'passes should not be empty!');
          }
          return passes.length > 0 ? passes[0].getShaderVariant(patches) : null;
        };
        _proto.initialize = function initialize(shadowsInfo) {
          this._enabled = shadowsInfo.enabled;
          this._type = this.enabled ? shadowsInfo.type : SHADOW_TYPE_NONE;
          this.normal = shadowsInfo.planeDirection;
          this.distance = shadowsInfo.planeHeight;
          this.planeBias = shadowsInfo.planeBias;
          this.shadowColor = shadowsInfo.shadowColor;
          this.maxReceived = shadowsInfo.maxReceived;
          if (shadowsInfo.shadowMapSize !== this._size.x) {
            this.size.set(shadowsInfo.shadowMapSize, shadowsInfo.shadowMapSize);
            this._shadowMapDirty = true;
          }
        };
        _proto.activate = function activate() {
          if (this._enabled) {
            if (this.type === ShadowType.Planar) {
              this._updatePlanarInfo();
            } else {
              var root = legacyCC.director.root;
              var pipeline = root.pipeline;
              pipeline.macros.CC_SHADOW_TYPE = 2;
              root.onGlobalPipelineStateChanged();
            }
          } else {
            var _root = legacyCC.director.root;
            var _pipeline = _root.pipeline;
            _pipeline.macros.CC_SHADOW_TYPE = 0;
            _root.onGlobalPipelineStateChanged();
          }
        };
        _proto._updatePlanarInfo = function _updatePlanarInfo() {
          if (!this._material) {
            this._material = new Material();
            this._material.initialize({
              effectName: 'pipeline/planar-shadow'
            });
          }
          var root = legacyCC.director.root;
          var pipeline = root.pipeline;
          pipeline.macros.CC_SHADOW_TYPE = 1;
          root.onGlobalPipelineStateChanged();
        };
        _proto.destroy = function destroy() {
          if (this._material) {
            this._material.destroy();
          }
          if (this._instancingMaterial) {
            this._instancingMaterial.destroy();
          }
          this.fixedSphere.destroy();
        };
        _createClass(Shadows, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
            this.activate();
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(val) {
            this._type = this.enabled ? val : SHADOW_TYPE_NONE;
            this.activate();
          }
        }, {
          key: "normal",
          get: function get() {
            return this._normal;
          },
          set: function set(val) {
            Vec3.copy(this._normal, val);
          }
        }, {
          key: "distance",
          get: function get() {
            return this._distance;
          },
          set: function set(val) {
            this._distance = val;
          }
        }, {
          key: "planeBias",
          get: function get() {
            return this._planeBias;
          },
          set: function set(val) {
            this._planeBias = val;
          }
        }, {
          key: "shadowColor",
          get: function get() {
            return this._shadowColor;
          },
          set: function set(color) {
            this._shadowColor = color;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(val) {
            this._size.set(val);
          }
        }, {
          key: "shadowMapDirty",
          get: function get() {
            return this._shadowMapDirty;
          },
          set: function set(val) {
            this._shadowMapDirty = val;
          }
        }, {
          key: "matLight",
          get: function get() {
            return this._matLight;
          }
        }, {
          key: "material",
          get: function get() {
            return this._material;
          }
        }, {
          key: "instancingMaterial",
          get: function get() {
            return this._instancingMaterial;
          }
        }]);
        return Shadows;
      }();
      Shadows.MAX_FAR = 2000.0;
      Shadows.COEFFICIENT_OF_EXPANSION = 2.0 * Math.sqrt(3.0);
      legacyCC.Shadows = Shadows;

      var PassInstance = function (_Pass) {
        _inheritsLoose(PassInstance, _Pass);
        function PassInstance(parent, owner) {
          var _this;
          _this = _Pass.call(this, parent.root) || this;
          _this._parent = void 0;
          _this._owner = void 0;
          _this._dontNotify = false;
          _this._parent = parent;
          _this._owner = owner;
          _this._doInit(_this._parent, true);
          for (var i = 0; i < _this._shaderInfo.blocks.length; i++) {
            var u = _this._shaderInfo.blocks[i];
            var block = _this._blocks[u.binding];
            var parentBlock = _this._parent.blocks[u.binding];
            block.set(parentBlock);
          }
          _this._rootBufferDirty = true;
          var paren = _this._parent;
          for (var _i = 0; _i < _this._shaderInfo.samplerTextures.length; _i++) {
            var _u = _this._shaderInfo.samplerTextures[_i];
            for (var j = 0; j < _u.count; j++) {
              var sampler = paren._descriptorSet.getSampler(_u.binding, j);
              var texture = paren._descriptorSet.getTexture(_u.binding, j);
              _this._descriptorSet.bindSampler(_u.binding, sampler, j);
              _this._descriptorSet.bindTexture(_u.binding, texture, j);
            }
          }
          _Pass.prototype.tryCompile.call(_assertThisInitialized(_this));
          return _this;
        }
        var _proto = PassInstance.prototype;
        _proto.overridePipelineStates = function overridePipelineStates(original, overrides) {
          this._bs.reset();
          this._rs.reset();
          this._dss.reset();
          Pass.fillPipelineInfo(this, original);
          Pass.fillPipelineInfo(this, overrides);
          this._onStateChange();
        };
        _proto.tryCompile = function tryCompile(defineOverrides) {
          if (defineOverrides) {
            if (!overrideMacros(this._defines, defineOverrides)) {
              return false;
            }
          }
          var res = _Pass.prototype.tryCompile.call(this);
          this._onStateChange();
          return res;
        };
        _proto.beginChangeStatesSilently = function beginChangeStatesSilently() {
          this._dontNotify = true;
        };
        _proto.endChangeStatesSilently = function endChangeStatesSilently() {
          this._dontNotify = false;
        };
        _proto._syncBatchingScheme = function _syncBatchingScheme() {
          this._defines.USE_INSTANCING = false;
          this._batchingScheme = BatchingSchemes.NONE;
        };
        _proto._onStateChange = function _onStateChange() {
          this._hash = Pass.getPassHash(this);
          this._owner.onPassStateChange(this._dontNotify);
        };
        _createClass(PassInstance, [{
          key: "parent",
          get: function get() {
            return this._parent;
          }
        }]);
        return PassInstance;
      }(Pass);

      var MaterialInstance = function (_Material) {
        _inheritsLoose(MaterialInstance, _Material);
        function MaterialInstance(info) {
          var _this;
          _this = _Material.call(this) || this;
          _this._passes = [];
          _this._parent = void 0;
          _this._owner = void 0;
          _this._subModelIdx = 0;
          _this._parent = info.parent;
          _this._owner = info.owner || null;
          _this._subModelIdx = info.subModelIdx || 0;
          _this.copy(_this._parent);
          return _this;
        }
        var _proto = MaterialInstance.prototype;
        _proto.recompileShaders = function recompileShaders(overrides, passIdx) {
          if (!this._passes || !this.effectAsset) {
            return;
          }
          if (passIdx === undefined) {
            for (var _iterator = _createForOfIteratorHelperLoose(this._passes), _step; !(_step = _iterator()).done;) {
              var pass = _step.value;
              pass.tryCompile(overrides);
            }
          } else {
            this._passes[passIdx].tryCompile(overrides);
          }
        };
        _proto.overridePipelineStates = function overridePipelineStates(overrides, passIdx) {
          if (!this._passes || !this.effectAsset) {
            return;
          }
          var passInfos = this.effectAsset.techniques[this.technique].passes;
          if (passIdx === undefined) {
            for (var i = 0; i < this._passes.length; i++) {
              var pass = this._passes[i];
              var state = this._states[i] || (this._states[i] = {});
              for (var key in overrides) {
                state[key] = overrides[key];
              }
              pass.overridePipelineStates(passInfos[pass.passIndex], state);
            }
          } else {
            var _state = this._states[passIdx] || (this._states[passIdx] = {});
            for (var _key in overrides) {
              _state[_key] = overrides[_key];
            }
            this._passes[passIdx].overridePipelineStates(passInfos[passIdx], _state);
          }
        };
        _proto.destroy = function destroy() {
          this._doDestroy();
          return true;
        };
        _proto.onPassStateChange = function onPassStateChange(dontNotify) {
          this._hash = Material.getHash(this);
          if (!dontNotify && this._owner) {
            this._owner._onRebuildPSO(this._subModelIdx, this);
          }
        };
        _proto._createPasses = function _createPasses() {
          var passes = [];
          var parentPasses = this._parent.passes;
          if (!parentPasses) {
            return passes;
          }
          for (var k = 0; k < parentPasses.length; ++k) {
            passes.push(new PassInstance(parentPasses[k], this));
          }
          return passes;
        };
        _createClass(MaterialInstance, [{
          key: "parent",
          get: function get() {
            return this._parent;
          }
        }, {
          key: "owner",
          get: function get() {
            return this._owner;
          }
        }]);
        return MaterialInstance;
      }(Material);

      var skybox_mesh = null;
      var skybox_material = null;
      var EnvironmentLightingType = Enum({
        HEMISPHERE_DIFFUSE: 0,
        AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION: 1,
        DIFFUSEMAP_WITH_REFLECTION: 2
      });
      var Skybox = function () {
        function Skybox() {
          this._envmapLDR = null;
          this._envmapHDR = null;
          this._diffuseMapLDR = null;
          this._diffuseMapHDR = null;
          this._globalDSManager = null;
          this._model = null;
          this._default = null;
          this._enabled = false;
          this._useIBL = false;
          this._useHDR = true;
          this._useDiffuseMap = false;
          this._editableMaterial = null;
          this._activated = false;
          this._reflectionHDR = null;
          this._reflectionLDR = null;
          this._rotationAngle = 0;
        }
        var _proto = Skybox.prototype;
        _proto.initialize = function initialize(skyboxInfo) {
          this._activated = false;
          this._enabled = skyboxInfo.enabled;
          this._useIBL = skyboxInfo.useIBL;
          this._useDiffuseMap = skyboxInfo.applyDiffuseMap;
          this._useHDR = skyboxInfo.useHDR;
        };
        _proto.setEnvMaps = function setEnvMaps(envmapHDR, envmapLDR) {
          this._envmapHDR = envmapHDR;
          this._envmapLDR = envmapLDR;
          this._updateGlobalBinding();
          this._updatePipeline();
        };
        _proto.setDiffuseMaps = function setDiffuseMaps(diffuseMapHDR, diffuseMapLDR) {
          this._diffuseMapHDR = diffuseMapHDR;
          this._diffuseMapLDR = diffuseMapLDR;
          this._updateGlobalBinding();
          this._updatePipeline();
        };
        _proto.setSkyboxMaterial = function setSkyboxMaterial(skyboxMat) {
          if (skyboxMat) {
            this._editableMaterial = new MaterialInstance({
              parent: skyboxMat
            });
            this._editableMaterial.recompileShaders({
              USE_RGBE_CUBEMAP: this.isRGBE
            });
          } else {
            this._editableMaterial = null;
          }
          this._updatePipeline();
        };
        _proto.setReflectionMaps = function setReflectionMaps(reflectionHDR, reflectionLDR) {
          this._reflectionHDR = reflectionHDR;
          this._reflectionLDR = reflectionLDR;
          this._updateGlobalBinding();
          this._updatePipeline();
        };
        _proto.setRotationAngle = function setRotationAngle(angle) {
          this._rotationAngle = angle;
        };
        _proto.getRotationAngle = function getRotationAngle() {
          return this._rotationAngle;
        };
        _proto.updateMaterialRenderInfo = function updateMaterialRenderInfo() {
          this._updateGlobalBinding();
          this._updatePipeline();
        };
        _proto.activate = function activate() {
          var pipeline = legacyCC.director.root.pipeline;
          this._globalDSManager = pipeline.globalDSManager;
          this._default = builtinResMgr.get('default-cube-texture');
          if (!this._model) {
            this._model = legacyCC.director.root.createModel(legacyCC.renderer.scene.Model);
          }
          var isRGBE = this._default.isRGBE;
          this._default.isUsingOfflineMipmaps();
          if (this.envmap) {
            isRGBE = this.envmap.isRGBE;
            this.envmap.isUsingOfflineMipmaps();
          }
          if (!skybox_material) {
            var mat = new Material();
            mat.initialize({
              effectName: 'pipeline/skybox',
              defines: {
                USE_RGBE_CUBEMAP: isRGBE
              }
            });
            skybox_material = new MaterialInstance({
              parent: mat
            });
          }
          if (this.enabled) {
            if (!skybox_mesh) {
              skybox_mesh = legacyCC.utils.createMesh(legacyCC.primitives.box({
                width: 2,
                height: 2,
                length: 2
              }));
            }
            if (this._editableMaterial) {
              this._model.initSubModel(0, skybox_mesh.renderingSubMeshes[0], this._editableMaterial);
            } else {
              this._model.initSubModel(0, skybox_mesh.renderingSubMeshes[0], skybox_material);
            }
          }
          if (!this.envmap) {
            this.envmap = this._default;
          }
          if (!this.diffuseMap) {
            this.diffuseMap = this._default;
          }
          this._updateGlobalBinding();
          this._updatePipeline();
          this._activated = true;
        };
        _proto._updatePipeline = function _updatePipeline() {
          var root = legacyCC.director.root;
          var pipeline = root.pipeline;
          var useIBLValue = this.useIBL ? this.isRGBE ? 2 : 1 : 0;
          var useDiffuseMapValue = this.useIBL && this.useDiffuseMap && this.diffuseMap && this.diffuseMap !== this._default ? this.isRGBE ? 2 : 1 : 0;
          var useHDRValue = this.useHDR;
          var useConvMapValue = this.useConvolutionMap;
          if (pipeline.macros.CC_USE_IBL !== useIBLValue || pipeline.macros.CC_USE_DIFFUSEMAP !== useDiffuseMapValue || pipeline.macros.CC_USE_HDR !== useHDRValue || pipeline.macros.CC_IBL_CONVOLUTED !== useConvMapValue) {
            pipeline.macros.CC_USE_IBL = useIBLValue;
            pipeline.macros.CC_USE_DIFFUSEMAP = useDiffuseMapValue;
            pipeline.macros.CC_USE_HDR = useHDRValue;
            pipeline.macros.CC_IBL_CONVOLUTED = useConvMapValue;
            if (this._activated) {
              root.onGlobalPipelineStateChanged();
            }
          }
          if (this.enabled) {
            var envmap = this.envmap ? this.envmap : this._default;
            var skyboxMat = this._editableMaterial ? this._editableMaterial : skybox_material;
            if (skyboxMat) {
              skyboxMat.setProperty('environmentMap', envmap);
              skyboxMat.recompileShaders({
                USE_RGBE_CUBEMAP: this.isRGBE
              });
            }
            if (this._model) {
              this._model.setSubModelMaterial(0, skyboxMat);
              this._updateSubModes();
            }
          }
        };
        _proto._updateGlobalBinding = function _updateGlobalBinding() {
          if (this._globalDSManager) {
            var device = deviceManager.gfxDevice;
            if (this.reflectionMap) {
              var texture = this.reflectionMap.getGFXTexture();
              var sampler = device.getSampler(this.reflectionMap.getSamplerInfo());
              this._globalDSManager.bindSampler(UNIFORM_ENVIRONMENT_BINDING, sampler);
              this._globalDSManager.bindTexture(UNIFORM_ENVIRONMENT_BINDING, texture);
            } else {
              var envmap = this.envmap ? this.envmap : this._default;
              if (envmap) {
                var _texture = envmap.getGFXTexture();
                var _sampler = device.getSampler(envmap.getSamplerInfo());
                this._globalDSManager.bindSampler(UNIFORM_ENVIRONMENT_BINDING, _sampler);
                this._globalDSManager.bindTexture(UNIFORM_ENVIRONMENT_BINDING, _texture);
              }
            }
            var diffuseMap = this.diffuseMap ? this.diffuseMap : this._default;
            if (diffuseMap) {
              var _texture2 = diffuseMap.getGFXTexture();
              var _sampler2 = device.getSampler(diffuseMap.getSamplerInfo());
              this._globalDSManager.bindSampler(UNIFORM_DIFFUSEMAP_BINDING, _sampler2);
              this._globalDSManager.bindTexture(UNIFORM_DIFFUSEMAP_BINDING, _texture2);
            }
            this._globalDSManager.update();
          }
        };
        _proto._updateSubModes = function _updateSubModes() {
          if (this._model) {
            var subModels = this._model.subModels;
            for (var i = 0; i < subModels.length; i++) {
              subModels[i].update();
            }
          }
        };
        _createClass(Skybox, [{
          key: "model",
          get: function get() {
            return this._model;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
            if (val) this.activate();else this._updatePipeline();
          }
        }, {
          key: "useHDR",
          get: function get() {
            return this._useHDR;
          },
          set: function set(val) {
            this._useHDR = val;
            this.setEnvMaps(this._envmapHDR, this._envmapLDR);
          }
        }, {
          key: "useIBL",
          get: function get() {
            return this._useIBL;
          },
          set: function set(val) {
            this._useIBL = val;
            this._updatePipeline();
          }
        }, {
          key: "useDiffuseMap",
          get: function get() {
            return this._useDiffuseMap;
          },
          set: function set(val) {
            this._useDiffuseMap = val;
            this._updatePipeline();
          }
        }, {
          key: "isRGBE",
          get: function get() {
            if (this.envmap) {
              return this.envmap.isRGBE;
            } else {
              return false;
            }
          }
        }, {
          key: "useConvolutionMap",
          get: function get() {
            if (this.reflectionMap) {
              return this.reflectionMap.isUsingOfflineMipmaps();
            }
            if (this.envmap) {
              return this.envmap.isUsingOfflineMipmaps();
            }
            return false;
          }
        }, {
          key: "envmap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._envmapHDR;
            } else {
              return this._envmapLDR;
            }
          },
          set: function set(val) {
            var root = legacyCC.director.root;
            var isHDR = root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.setEnvMaps(val, this._envmapLDR);
            } else {
              this.setEnvMaps(this._envmapHDR, val);
            }
          }
        }, {
          key: "diffuseMap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._diffuseMapHDR;
            } else {
              return this._diffuseMapLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.setDiffuseMaps(val, this._diffuseMapLDR);
            } else {
              this.setDiffuseMaps(this._diffuseMapHDR, val);
            }
          }
        }, {
          key: "reflectionMap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._reflectionHDR;
            } else {
              return this._reflectionLDR;
            }
          }
        }, {
          key: "editableMaterial",
          get: function get() {
            return this._editableMaterial;
          }
        }]);
        return Skybox;
      }();
      legacyCC.Skybox = Skybox;

      var _v4$1 = new Vec4();
      var FogType = Enum({
        LINEAR: 0,
        EXP: 1,
        EXP_SQUARED: 2,
        LAYERED: 3
      });
      var FOG_TYPE_NONE = FogType.LAYERED + 1;
      var Fog = function () {
        function Fog() {
          this._fogColor = new Color$1('#C8C8C8');
          this._colorArray = new Vec4(0.2, 0.2, 0.2, 1.0);
          this._enabled = false;
          this._accurate = false;
          this._type = 0;
          this._fogDensity = 0.3;
          this._fogStart = 0.5;
          this._fogEnd = 300;
          this._fogAtten = 5;
          this._fogTop = 1.5;
          this._fogRange = 1.2;
          this._activated = false;
        }
        var _proto = Fog.prototype;
        _proto.initialize = function initialize(fogInfo) {
          this._activated = false;
          this.fogColor = fogInfo.fogColor;
          this._enabled = fogInfo.enabled;
          this._type = this.enabled ? fogInfo.type : FOG_TYPE_NONE;
          this._accurate = fogInfo.accurate;
          this.fogDensity = fogInfo.fogDensity;
          this.fogStart = fogInfo.fogStart;
          this.fogEnd = fogInfo.fogEnd;
          this.fogAtten = fogInfo.fogAtten;
          this.fogTop = fogInfo.fogTop;
          this.fogRange = fogInfo.fogRange;
        };
        _proto.activate = function activate() {
          this._updatePipeline();
          this._activated = true;
        };
        _proto._updatePipeline = function _updatePipeline() {
          var root = legacyCC.director.root;
          var value = this.enabled ? this.type : FOG_TYPE_NONE;
          var accurateValue = this.accurate ? 1 : 0;
          var pipeline = root.pipeline;
          if (pipeline.macros.CC_USE_FOG === value && pipeline.macros.CC_USE_ACCURATE_FOG === accurateValue) {
            return;
          }
          pipeline.macros.CC_USE_FOG = value;
          pipeline.macros.CC_USE_ACCURATE_FOG = accurateValue;
          if (this._activated) {
            root.onGlobalPipelineStateChanged();
          }
        };
        _createClass(Fog, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
            if (!val) {
              this._type = FOG_TYPE_NONE;
              this._updatePipeline();
            } else {
              this.activate();
            }
          }
        }, {
          key: "accurate",
          get: function get() {
            return this._accurate;
          },
          set: function set(val) {
            this._accurate = val;
            this._updatePipeline();
          }
        }, {
          key: "fogColor",
          get: function get() {
            return this._fogColor;
          },
          set: function set(val) {
            this._fogColor.set(val);
            _v4$1.set(val.x, val.y, val.z, val.w);
            SRGBToLinear(this._colorArray, _v4$1);
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(val) {
            this._type = this.enabled ? val : FOG_TYPE_NONE;
            if (this.enabled) this._updatePipeline();
          }
        }, {
          key: "fogDensity",
          get: function get() {
            return this._fogDensity;
          },
          set: function set(val) {
            this._fogDensity = val;
          }
        }, {
          key: "fogStart",
          get: function get() {
            return this._fogStart;
          },
          set: function set(val) {
            this._fogStart = val;
          }
        }, {
          key: "fogEnd",
          get: function get() {
            return this._fogEnd;
          },
          set: function set(val) {
            this._fogEnd = val;
          }
        }, {
          key: "fogAtten",
          get: function get() {
            return this._fogAtten;
          },
          set: function set(val) {
            this._fogAtten = val;
          }
        }, {
          key: "fogTop",
          get: function get() {
            return this._fogTop;
          },
          set: function set(val) {
            this._fogTop = val;
          }
        }, {
          key: "fogRange",
          get: function get() {
            return this._fogRange;
          },
          set: function set(val) {
            this._fogRange = val;
          }
        }, {
          key: "colorArray",
          get: function get() {
            return this._colorArray;
          }
        }]);
        return Fog;
      }();
      legacyCC.Fog = Fog;

      var ToneMappingType = Enum({
        DEFAULT: 0,
        LINEAR: 1
      });
      var PostSettings = function () {
        function PostSettings() {
          this._toneMappingType = ToneMappingType.DEFAULT;
          this._activated = false;
        }
        var _proto = PostSettings.prototype;
        _proto.initialize = function initialize(postSettingsInfo) {
          this._toneMappingType = postSettingsInfo.toneMappingType;
        };
        _proto.activate = function activate() {
          this._updatePipeline();
          this._activated = true;
        };
        _proto._updatePipeline = function _updatePipeline() {
          var root = legacyCC.director.root;
          var pipeline = root.pipeline;
          pipeline.macros.CC_TONE_MAPPING_TYPE = this._toneMappingType;
          if (this._activated) {
            root.onGlobalPipelineStateChanged();
          }
        };
        _createClass(PostSettings, [{
          key: "toneMappingType",
          get: function get() {
            return this._toneMappingType;
          },
          set: function set(val) {
            this._toneMappingType = val;
            this._updatePipeline();
          }
        }]);
        return PostSettings;
      }();

      var _dec$3q, _dec2$2v, _dec3$1L, _dec4$1e, _dec5$15, _class$3l, _class2$30, _initializer$2N, _initializer2$2f, _initializer3$1E, _initializer4$1o, _initializer5$15, _initializer6$V, _dec6$R, _dec7$G, _dec8$u, _dec9$p, _dec10$h, _dec11$c, _dec12$b, _dec13$9, _dec14$8, _dec15$7, _dec16$6, _dec17$6, _dec18$6, _dec19$6, _dec20$6, _class4$x, _class5$x, _initializer7$J, _initializer8$F, _initializer9$A, _initializer10$x, _initializer11$v, _initializer12$s, _initializer13$p, _initializer14$l, _initializer15$h, _initializer16$h, _initializer17$e, _dec21$6, _dec22$6, _dec23$6, _dec24$6, _dec25$6, _dec26$6, _dec27$6, _dec28$6, _class7$a, _class8$b, _initializer18$e, _initializer19$d, _initializer20$b, _initializer21$b, _initializer22$a, _initializer23$8, _initializer24$8, _initializer25$7, _initializer26$7, _initializer27$5, _class9$2, _dec29$5, _dec30$4, _dec31$4, _dec32$3, _dec33$3, _dec34$3, _class10$6, _class11$7, _initializer28$5, _initializer29$5, _initializer30$5, _initializer31$5, _initializer32$4, _initializer33$4, _initializer34$4, _initializer35$4, _dec35$3, _dec36$3, _class13$6, _class14$5, _initializer36$3, _initializer37$3, _initializer38$3, _initializer39$3, _dec37$3, _dec38$3, _dec39$3, _class16$2, _class17$3, _initializer40$3, _initializer41$3, _initializer42$2, _dec40$2, _dec41$2, _class19$2, _class20$4, _initializer43$2, _dec42$2, _dec43$2, _dec44$2, _dec45$2, _dec46$2, _dec47$2, _class22$2, _class23$3, _initializer44$1, _initializer45$1, _initializer46$1, _initializer47, _initializer48, _initializer49, _initializer50, _initializer51, _initializer52, _dec48$1, _dec49$1, _class25, _class26$1, _initializer53, _initializer54, _initializer55, _initializer56, _initializer57, _initializer58, _initializer59, _initializer60, _initializer61, _initializer62;
      var _up = new Vec3(0, 1, 0);
      var _v3$3 = new Vec3();
      var _v4 = new Vec4();
      var _col = new Color$1();
      var _qt$1 = new Quat();
      var normalizeHDRColor = function normalizeHDRColor(color) {
        var intensity = 1.0 / Math.max(Math.max(Math.max(color.x, color.y), color.z), 0.0001);
        if (intensity < 1.0) {
          color.x *= intensity;
          color.y *= intensity;
          color.z *= intensity;
        }
      };
      var AmbientInfo = exports('dO', (_dec$3q = ccclass$M('cc.AmbientInfo'), _dec2$2v = type$d(CCFloat), _dec3$1L = formerlySerializedAs$4('_skyColor'), _dec4$1e = formerlySerializedAs$4('_skyIllum'), _dec5$15 = formerlySerializedAs$4('_groundAlbedo'), _dec$3q(_class$3l = (_class2$30 = function () {
        function AmbientInfo() {
          this._skyColorHDR = _initializer$2N && _initializer$2N();
          this._skyIllumHDR = _initializer2$2f && _initializer2$2f();
          this._groundAlbedoHDR = _initializer3$1E && _initializer3$1E();
          this._skyColorLDR = _initializer4$1o && _initializer4$1o();
          this._skyIllumLDR = _initializer5$15 && _initializer5$15();
          this._groundAlbedoLDR = _initializer6$V && _initializer6$V();
          this._resource = null;
        }
        var _proto = AmbientInfo.prototype;
        _proto.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
        };
        _createClass(AmbientInfo, [{
          key: "skyColorHDR",
          get: function get() {
            return this._skyColorHDR;
          }
        }, {
          key: "groundAlbedoHDR",
          get: function get() {
            return this._groundAlbedoHDR;
          }
        }, {
          key: "skyIllumHDR",
          get: function get() {
            return this._skyIllumHDR;
          }
        }, {
          key: "skyColorLDR",
          get: function get() {
            return this._skyColorLDR;
          }
        }, {
          key: "groundAlbedoLDR",
          get: function get() {
            return this._groundAlbedoLDR;
          }
        }, {
          key: "skyIllumLDR",
          get: function get() {
            return this._skyIllumLDR;
          }
        }, {
          key: "skyLightingColor",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            _v4.set(isHDR ? this._skyColorHDR : this._skyColorLDR);
            normalizeHDRColor(_v4);
            return _col.set(_v4.x * 255, _v4.y * 255, _v4.z * 255, 255);
          },
          set: function set(val) {
            _v4.set(val.x, val.y, val.z, val.w);
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              this._skyColorHDR.set(_v4);
            } else {
              this._skyColorLDR.set(_v4);
            }
            if (this._resource) {
              this._resource.skyColor.set(_v4);
            }
          }
        }, {
          key: "skyColor",
          set: function set(val) {
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              this._skyColorHDR.set(val);
            } else {
              this._skyColorLDR.set(val);
            }
            if (this._resource) {
              this._resource.skyColor.set(val);
            }
          }
        }, {
          key: "skyIllum",
          get: function get() {
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              return this._skyIllumHDR;
            } else {
              return this._skyIllumLDR;
            }
          },
          set: function set(val) {
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              this._skyIllumHDR = val;
            } else {
              this._skyIllumLDR = val;
            }
            if (this._resource) {
              this._resource.skyIllum = val;
            }
          }
        }, {
          key: "groundLightingColor",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            _v4.set(isHDR ? this._groundAlbedoHDR : this._groundAlbedoLDR);
            normalizeHDRColor(_v4);
            return _col.set(_v4.x * 255, _v4.y * 255, _v4.z * 255, 255);
          },
          set: function set(val) {
            _v4.set(val.x, val.y, val.z, val.w);
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              this._groundAlbedoHDR.set(_v4);
            } else {
              this._groundAlbedoLDR.set(_v4);
            }
            if (this._resource) {
              this._resource.groundAlbedo.set(_v4);
            }
          }
        }, {
          key: "groundAlbedo",
          set: function set(val) {
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              this._groundAlbedoHDR.set(val);
            } else {
              this._groundAlbedoLDR.set(val);
            }
            if (this._resource) {
              this._resource.groundAlbedo.set(val);
            }
          }
        }]);
        return AmbientInfo;
      }(), (_applyDecoratedDescriptor(_class2$30.prototype, "skyIllum", [_dec2$2v], Object.getOwnPropertyDescriptor(_class2$30.prototype, "skyIllum"), _class2$30.prototype), _initializer$2N = applyDecoratedInitializer(_class2$30.prototype, "_skyColorHDR", [serializable$p, _dec3$1L], function () {
        return new Vec4(0.2, 0.5, 0.8, 1.0);
      }), _initializer2$2f = applyDecoratedInitializer(_class2$30.prototype, "_skyIllumHDR", [serializable$p, _dec4$1e], function () {
        return Ambient.SKY_ILLUM;
      }), _initializer3$1E = applyDecoratedInitializer(_class2$30.prototype, "_groundAlbedoHDR", [serializable$p, _dec5$15], function () {
        return new Vec4(0.2, 0.2, 0.2, 1.0);
      }), _initializer4$1o = applyDecoratedInitializer(_class2$30.prototype, "_skyColorLDR", [serializable$p], function () {
        return new Vec4(0.2, 0.5, 0.8, 1.0);
      }), _initializer5$15 = applyDecoratedInitializer(_class2$30.prototype, "_skyIllumLDR", [serializable$p], function () {
        return Ambient.SKY_ILLUM;
      }), _initializer6$V = applyDecoratedInitializer(_class2$30.prototype, "_groundAlbedoLDR", [serializable$p], function () {
        return new Vec4(0.2, 0.2, 0.2, 1.0);
      })), _class2$30)) || _class$3l));
      legacyCC.AmbientInfo = AmbientInfo;
      var SkyboxInfo = exports('dP', (_dec6$R = ccclass$M('cc.SkyboxInfo'), _dec7$G = type$d(EnvironmentLightingType), _dec8$u = type$d(TextureCube), _dec9$p = type$d(CCFloat), _dec10$h = type$d(TextureCube), _dec11$c = type$d(TextureCube), _dec12$b = type$d(Material), _dec13$9 = type$d(TextureCube), _dec14$8 = formerlySerializedAs$4('_envmap'), _dec15$7 = type$d(TextureCube), _dec16$6 = type$d(TextureCube), _dec17$6 = type$d(TextureCube), _dec18$6 = type$d(Material), _dec19$6 = type$d(TextureCube), _dec20$6 = type$d(TextureCube), _dec6$R(_class4$x = (_class5$x = function () {
        function SkyboxInfo() {
          this._envLightingType = _initializer7$J && _initializer7$J();
          this._envmapHDR = _initializer8$F && _initializer8$F();
          this._envmapLDR = _initializer9$A && _initializer9$A();
          this._diffuseMapHDR = _initializer10$x && _initializer10$x();
          this._diffuseMapLDR = _initializer11$v && _initializer11$v();
          this._enabled = _initializer12$s && _initializer12$s();
          this._useHDR = _initializer13$p && _initializer13$p();
          this._editableMaterial = _initializer14$l && _initializer14$l();
          this._reflectionHDR = _initializer15$h && _initializer15$h();
          this._reflectionLDR = _initializer16$h && _initializer16$h();
          this._rotationAngle = _initializer17$e && _initializer17$e();
          this._resource = null;
        }
        var _proto2 = SkyboxInfo.prototype;
        _proto2.activate = function activate(resource) {
          this.envLightingType = this._envLightingType;
          this._resource = resource;
          this._resource.initialize(this);
          this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR);
          this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR);
          this._resource.setSkyboxMaterial(this._editableMaterial);
          this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR);
          this._resource.setRotationAngle(this._rotationAngle);
          this._resource.activate();
        };
        _proto2.updateEnvMap = function updateEnvMap(val) {
          if (!val) {
            this.applyDiffuseMap = false;
            this.useIBL = false;
            this.envLightingType = EnvironmentLightingType.HEMISPHERE_DIFFUSE;
            warnID(15001);
          }
          if (this._resource) {
            this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR);
            this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR);
            this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR);
            this._resource.useDiffuseMap = this.applyDiffuseMap;
            this._resource.envmap = val;
          }
        };
        _proto2.setMaterialProperty = function setMaterialProperty(name, val, passIdx) {
          if (!this._resource) return;
          if (this._resource.enabled && this._resource.editableMaterial) {
            this._resource.editableMaterial.setProperty(name, val, passIdx);
            this._resource.editableMaterial.passes.forEach(function (pass) {
              pass.update();
            });
          }
        };
        _createClass(SkyboxInfo, [{
          key: "applyDiffuseMap",
          get: function get() {
            if (EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION === this._envLightingType) {
              return true;
            }
            return false;
          },
          set: function set(val) {
            if (this._resource) {
              this._resource.useDiffuseMap = val;
            }
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            if (this._enabled === val) return;
            this._enabled = val;
            if (this._resource) {
              this._resource.enabled = this._enabled;
            }
          }
        }, {
          key: "envLightingType",
          get: function get() {
            return this._envLightingType;
          },
          set: function set(val) {
            if (!this.envmap && EnvironmentLightingType.HEMISPHERE_DIFFUSE !== val) {
              this.useIBL = false;
              this.applyDiffuseMap = false;
              this._envLightingType = EnvironmentLightingType.HEMISPHERE_DIFFUSE;
              warnID(15001);
            } else {
              if (EnvironmentLightingType.HEMISPHERE_DIFFUSE === val) {
                this.useIBL = false;
                this.applyDiffuseMap = false;
              } else if (EnvironmentLightingType.AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION === val) {
                this.useIBL = true;
                this.applyDiffuseMap = false;
              } else if (EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION === val) {
                this.useIBL = true;
                this.applyDiffuseMap = true;
              }
              this._envLightingType = val;
            }
          }
        }, {
          key: "useIBL",
          get: function get() {
            if (EnvironmentLightingType.HEMISPHERE_DIFFUSE !== this._envLightingType) {
              return true;
            }
            return false;
          },
          set: function set(val) {
            if (this._resource) {
              this._resource.useIBL = val;
            }
          }
        }, {
          key: "useHDR",
          get: function get() {
            legacyCC.director.root.pipeline.pipelineSceneData.isHDR = this._useHDR;
            return this._useHDR;
          },
          set: function set(val) {
            legacyCC.director.root.pipeline.pipelineSceneData.isHDR = val;
            this._useHDR = val;
            if (this._resource) {
              if (this.envLightingType === EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION) {
                if (this.diffuseMap === null) {
                  this.envLightingType = EnvironmentLightingType.AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION;
                  warnID(15000);
                } else if (this.diffuseMap.isDefault) {
                  warnID(15002);
                }
              }
            }
            if (this._resource) {
              this._resource.useHDR = this._useHDR;
              this._resource.updateMaterialRenderInfo();
            }
          }
        }, {
          key: "envmap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._envmapHDR;
            } else {
              return this._envmapLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._envmapHDR = val;
              this._reflectionHDR = null;
            } else {
              this._envmapLDR = val;
              this._reflectionLDR = null;
            }
            if (!val) {
              if (isHDR) {
                this._diffuseMapHDR = null;
              } else {
                this._diffuseMapLDR = null;
              }
              this.applyDiffuseMap = false;
              this.useIBL = false;
              this.envLightingType = EnvironmentLightingType.HEMISPHERE_DIFFUSE;
              warnID(15001);
            }
            if (this._resource) {
              this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR);
              this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR);
              this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR);
              this._resource.useDiffuseMap = this.applyDiffuseMap;
              this._resource.envmap = val;
            }
          }
        }, {
          key: "rotationAngle",
          get: function get() {
            return this._rotationAngle;
          },
          set: function set(val) {
            this._rotationAngle = val;
            if (this._resource) {
              this._resource.setRotationAngle(this._rotationAngle);
            }
          }
        }, {
          key: "diffuseMap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._diffuseMapHDR;
            } else {
              return this._diffuseMapLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._diffuseMapHDR = val;
            } else {
              this._diffuseMapLDR = val;
            }
            if (this._resource) {
              this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR);
            }
          }
        }, {
          key: "reflectionMap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._reflectionHDR;
            } else {
              return this._reflectionLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._reflectionHDR = val;
            } else {
              this._reflectionLDR = val;
            }
            if (this._resource) {
              this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR);
            }
          }
        }, {
          key: "skyboxMaterial",
          get: function get() {
            return this._editableMaterial;
          },
          set: function set(val) {
            this._editableMaterial = val;
            if (this._resource) {
              this._resource.setSkyboxMaterial(this._editableMaterial);
            }
          }
        }]);
        return SkyboxInfo;
      }(), (_applyDecoratedDescriptor(_class5$x.prototype, "envLightingType", [_dec7$G], Object.getOwnPropertyDescriptor(_class5$x.prototype, "envLightingType"), _class5$x.prototype), _applyDecoratedDescriptor(_class5$x.prototype, "envmap", [_dec8$u], Object.getOwnPropertyDescriptor(_class5$x.prototype, "envmap"), _class5$x.prototype), _applyDecoratedDescriptor(_class5$x.prototype, "rotationAngle", [_dec9$p], Object.getOwnPropertyDescriptor(_class5$x.prototype, "rotationAngle"), _class5$x.prototype), _applyDecoratedDescriptor(_class5$x.prototype, "diffuseMap", [_dec10$h], Object.getOwnPropertyDescriptor(_class5$x.prototype, "diffuseMap"), _class5$x.prototype), _applyDecoratedDescriptor(_class5$x.prototype, "reflectionMap", [_dec11$c], Object.getOwnPropertyDescriptor(_class5$x.prototype, "reflectionMap"), _class5$x.prototype), _applyDecoratedDescriptor(_class5$x.prototype, "skyboxMaterial", [_dec12$b], Object.getOwnPropertyDescriptor(_class5$x.prototype, "skyboxMaterial"), _class5$x.prototype), _initializer7$J = applyDecoratedInitializer(_class5$x.prototype, "_envLightingType", [serializable$p], function () {
        return EnvironmentLightingType.HEMISPHERE_DIFFUSE;
      }), _initializer8$F = applyDecoratedInitializer(_class5$x.prototype, "_envmapHDR", [serializable$p, _dec13$9, _dec14$8], function () {
        return null;
      }), _initializer9$A = applyDecoratedInitializer(_class5$x.prototype, "_envmapLDR", [serializable$p, _dec15$7], function () {
        return null;
      }), _initializer10$x = applyDecoratedInitializer(_class5$x.prototype, "_diffuseMapHDR", [serializable$p, _dec16$6], function () {
        return null;
      }), _initializer11$v = applyDecoratedInitializer(_class5$x.prototype, "_diffuseMapLDR", [serializable$p, _dec17$6], function () {
        return null;
      }), _initializer12$s = applyDecoratedInitializer(_class5$x.prototype, "_enabled", [serializable$p], function () {
        return false;
      }), _initializer13$p = applyDecoratedInitializer(_class5$x.prototype, "_useHDR", [serializable$p], function () {
        return true;
      }), _initializer14$l = applyDecoratedInitializer(_class5$x.prototype, "_editableMaterial", [serializable$p, _dec18$6], function () {
        return null;
      }), _initializer15$h = applyDecoratedInitializer(_class5$x.prototype, "_reflectionHDR", [serializable$p, _dec19$6], function () {
        return null;
      }), _initializer16$h = applyDecoratedInitializer(_class5$x.prototype, "_reflectionLDR", [serializable$p, _dec20$6], function () {
        return null;
      }), _initializer17$e = applyDecoratedInitializer(_class5$x.prototype, "_rotationAngle", [serializable$p], function () {
        return 0;
      })), _class5$x)) || _class4$x));
      legacyCC.SkyboxInfo = SkyboxInfo;
      var FogInfo = exports('dQ', (_dec21$6 = ccclass$M('cc.FogInfo'), _dec22$6 = type$d(FogType), _dec23$6 = type$d(CCFloat), _dec24$6 = type$d(CCFloat), _dec25$6 = type$d(CCFloat), _dec26$6 = type$d(CCFloat), _dec27$6 = type$d(CCFloat), _dec28$6 = type$d(CCFloat), _dec21$6(_class7$a = (_class8$b = (_class9$2 = function () {
        function FogInfo() {
          this._type = _initializer18$e && _initializer18$e();
          this._fogColor = _initializer19$d && _initializer19$d();
          this._enabled = _initializer20$b && _initializer20$b();
          this._fogDensity = _initializer21$b && _initializer21$b();
          this._fogStart = _initializer22$a && _initializer22$a();
          this._fogEnd = _initializer23$8 && _initializer23$8();
          this._fogAtten = _initializer24$8 && _initializer24$8();
          this._fogTop = _initializer25$7 && _initializer25$7();
          this._fogRange = _initializer26$7 && _initializer26$7();
          this._accurate = _initializer27$5 && _initializer27$5();
          this._resource = null;
        }
        var _proto3 = FogInfo.prototype;
        _proto3.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
          this._resource.activate();
        };
        _createClass(FogInfo, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            if (this._enabled === val) return;
            this._enabled = val;
            if (this._resource) {
              this._resource.enabled = val;
              if (val) {
                this._resource.type = this._type;
              }
            }
          }
        }, {
          key: "accurate",
          get: function get() {
            return this._accurate;
          },
          set: function set(val) {
            if (this._accurate === val) return;
            this._accurate = val;
            if (this._resource) {
              this._resource.accurate = val;
              if (val) {
                this._resource.type = this._type;
              }
            }
          }
        }, {
          key: "fogColor",
          get: function get() {
            return this._fogColor;
          },
          set: function set(val) {
            this._fogColor.set(val);
            if (this._resource) {
              this._resource.fogColor = this._fogColor;
            }
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(val) {
            this._type = val;
            if (this._resource) {
              this._resource.type = val;
            }
          }
        }, {
          key: "fogDensity",
          get: function get() {
            return this._fogDensity;
          },
          set: function set(val) {
            this._fogDensity = val;
            if (this._resource) {
              this._resource.fogDensity = val;
            }
          }
        }, {
          key: "fogStart",
          get: function get() {
            return this._fogStart;
          },
          set: function set(val) {
            this._fogStart = val;
            if (this._resource) {
              this._resource.fogStart = val;
            }
          }
        }, {
          key: "fogEnd",
          get: function get() {
            return this._fogEnd;
          },
          set: function set(val) {
            this._fogEnd = val;
            if (this._resource) {
              this._resource.fogEnd = val;
            }
          }
        }, {
          key: "fogAtten",
          get: function get() {
            return this._fogAtten;
          },
          set: function set(val) {
            this._fogAtten = val;
            if (this._resource) {
              this._resource.fogAtten = val;
            }
          }
        }, {
          key: "fogTop",
          get: function get() {
            return this._fogTop;
          },
          set: function set(val) {
            this._fogTop = val;
            if (this._resource) {
              this._resource.fogTop = val;
            }
          }
        }, {
          key: "fogRange",
          get: function get() {
            return this._fogRange;
          },
          set: function set(val) {
            this._fogRange = val;
            if (this._resource) {
              this._resource.fogRange = val;
            }
          }
        }]);
        return FogInfo;
      }(), _class9$2.FogType = FogType, _class9$2), (_applyDecoratedDescriptor(_class8$b.prototype, "type", [_dec22$6], Object.getOwnPropertyDescriptor(_class8$b.prototype, "type"), _class8$b.prototype), _applyDecoratedDescriptor(_class8$b.prototype, "fogDensity", [_dec23$6], Object.getOwnPropertyDescriptor(_class8$b.prototype, "fogDensity"), _class8$b.prototype), _applyDecoratedDescriptor(_class8$b.prototype, "fogStart", [_dec24$6], Object.getOwnPropertyDescriptor(_class8$b.prototype, "fogStart"), _class8$b.prototype), _applyDecoratedDescriptor(_class8$b.prototype, "fogEnd", [_dec25$6], Object.getOwnPropertyDescriptor(_class8$b.prototype, "fogEnd"), _class8$b.prototype), _applyDecoratedDescriptor(_class8$b.prototype, "fogAtten", [_dec26$6], Object.getOwnPropertyDescriptor(_class8$b.prototype, "fogAtten"), _class8$b.prototype), _applyDecoratedDescriptor(_class8$b.prototype, "fogTop", [_dec27$6], Object.getOwnPropertyDescriptor(_class8$b.prototype, "fogTop"), _class8$b.prototype), _applyDecoratedDescriptor(_class8$b.prototype, "fogRange", [_dec28$6], Object.getOwnPropertyDescriptor(_class8$b.prototype, "fogRange"), _class8$b.prototype), _initializer18$e = applyDecoratedInitializer(_class8$b.prototype, "_type", [serializable$p], function () {
        return FogType.LINEAR;
      }), _initializer19$d = applyDecoratedInitializer(_class8$b.prototype, "_fogColor", [serializable$p], function () {
        return new Color$1('#C8C8C8');
      }), _initializer20$b = applyDecoratedInitializer(_class8$b.prototype, "_enabled", [serializable$p], function () {
        return false;
      }), _initializer21$b = applyDecoratedInitializer(_class8$b.prototype, "_fogDensity", [serializable$p], function () {
        return 0.3;
      }), _initializer22$a = applyDecoratedInitializer(_class8$b.prototype, "_fogStart", [serializable$p], function () {
        return 0.5;
      }), _initializer23$8 = applyDecoratedInitializer(_class8$b.prototype, "_fogEnd", [serializable$p], function () {
        return 300;
      }), _initializer24$8 = applyDecoratedInitializer(_class8$b.prototype, "_fogAtten", [serializable$p], function () {
        return 5;
      }), _initializer25$7 = applyDecoratedInitializer(_class8$b.prototype, "_fogTop", [serializable$p], function () {
        return 1.5;
      }), _initializer26$7 = applyDecoratedInitializer(_class8$b.prototype, "_fogRange", [serializable$p], function () {
        return 1.2;
      }), _initializer27$5 = applyDecoratedInitializer(_class8$b.prototype, "_accurate", [serializable$p], function () {
        return false;
      })), _class8$b)) || _class7$a));
      var ShadowsInfo = exports('dR', (_dec29$5 = ccclass$M('cc.ShadowsInfo'), _dec30$4 = type$d(ShadowType), _dec31$4 = type$d(CCFloat), _dec32$3 = type$d(CCFloat), _dec33$3 = type$d(CCInteger), _dec34$3 = type$d(ShadowSize), _dec29$5(_class10$6 = (_class11$7 = function () {
        function ShadowsInfo() {
          this._enabled = _initializer28$5 && _initializer28$5();
          this._type = _initializer29$5 && _initializer29$5();
          this._normal = _initializer30$5 && _initializer30$5();
          this._distance = _initializer31$5 && _initializer31$5();
          this._planeBias = _initializer32$4 && _initializer32$4();
          this._shadowColor = _initializer33$4 && _initializer33$4();
          this._maxReceived = _initializer34$4 && _initializer34$4();
          this._size = _initializer35$4 && _initializer35$4();
          this._resource = null;
        }
        var _proto4 = ShadowsInfo.prototype;
        _proto4.setPlaneFromNode = function setPlaneFromNode(node) {
          node.getWorldRotation(_qt$1);
          this.planeDirection = Vec3.transformQuat(_v3$3, _up, _qt$1);
          node.getWorldPosition(_v3$3);
          this.planeHeight = Vec3.dot(this._normal, _v3$3);
        };
        _proto4.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
          this._resource.activate();
        };
        _createClass(ShadowsInfo, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            if (this._enabled === val) return;
            this._enabled = val;
            if (this._resource) {
              this._resource.enabled = val;
              if (val) {
                this._resource.type = this._type;
              }
            }
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(val) {
            this._type = val;
            if (this._resource) {
              this._resource.type = val;
            }
          }
        }, {
          key: "shadowColor",
          get: function get() {
            return this._shadowColor;
          },
          set: function set(val) {
            this._shadowColor.set(val);
            if (this._resource) {
              this._resource.shadowColor = val;
            }
          }
        }, {
          key: "planeDirection",
          get: function get() {
            return this._normal;
          },
          set: function set(val) {
            Vec3.copy(this._normal, val);
            if (this._resource) {
              this._resource.normal = val;
            }
          }
        }, {
          key: "planeHeight",
          get: function get() {
            return this._distance;
          },
          set: function set(val) {
            this._distance = val;
            if (this._resource) {
              this._resource.distance = val;
            }
          }
        }, {
          key: "planeBias",
          get: function get() {
            return this._planeBias;
          },
          set: function set(val) {
            this._planeBias = val;
            if (this._resource) {
              this._resource.planeBias = val;
            }
          }
        }, {
          key: "maxReceived",
          get: function get() {
            return this._maxReceived;
          },
          set: function set(val) {
            this._maxReceived = val;
            if (this._resource) {
              this._resource.maxReceived = val;
            }
          }
        }, {
          key: "shadowMapSize",
          get: function get() {
            return this._size.x;
          },
          set: function set(value) {
            this._size.set(value, value);
            if (this._resource) {
              this._resource.size.set(value, value);
              this._resource.shadowMapDirty = true;
            }
          }
        }]);
        return ShadowsInfo;
      }(), (_applyDecoratedDescriptor(_class11$7.prototype, "type", [_dec30$4], Object.getOwnPropertyDescriptor(_class11$7.prototype, "type"), _class11$7.prototype), _applyDecoratedDescriptor(_class11$7.prototype, "planeHeight", [_dec31$4], Object.getOwnPropertyDescriptor(_class11$7.prototype, "planeHeight"), _class11$7.prototype), _applyDecoratedDescriptor(_class11$7.prototype, "planeBias", [_dec32$3], Object.getOwnPropertyDescriptor(_class11$7.prototype, "planeBias"), _class11$7.prototype), _applyDecoratedDescriptor(_class11$7.prototype, "maxReceived", [_dec33$3], Object.getOwnPropertyDescriptor(_class11$7.prototype, "maxReceived"), _class11$7.prototype), _applyDecoratedDescriptor(_class11$7.prototype, "shadowMapSize", [_dec34$3], Object.getOwnPropertyDescriptor(_class11$7.prototype, "shadowMapSize"), _class11$7.prototype), _initializer28$5 = applyDecoratedInitializer(_class11$7.prototype, "_enabled", [serializable$p], function () {
        return false;
      }), _initializer29$5 = applyDecoratedInitializer(_class11$7.prototype, "_type", [serializable$p], function () {
        return ShadowType.Planar;
      }), _initializer30$5 = applyDecoratedInitializer(_class11$7.prototype, "_normal", [serializable$p], function () {
        return new Vec3(0, 1, 0);
      }), _initializer31$5 = applyDecoratedInitializer(_class11$7.prototype, "_distance", [serializable$p], function () {
        return 0;
      }), _initializer32$4 = applyDecoratedInitializer(_class11$7.prototype, "_planeBias", [serializable$p], function () {
        return 1.0;
      }), _initializer33$4 = applyDecoratedInitializer(_class11$7.prototype, "_shadowColor", [serializable$p], function () {
        return new Color$1(0, 0, 0, 76);
      }), _initializer34$4 = applyDecoratedInitializer(_class11$7.prototype, "_maxReceived", [serializable$p], function () {
        return 4;
      }), _initializer35$4 = applyDecoratedInitializer(_class11$7.prototype, "_size", [serializable$p], function () {
        return new Vec2(1024, 1024);
      })), _class11$7)) || _class10$6));
      legacyCC.ShadowsInfo = ShadowsInfo;
      var DEFAULT_WORLD_MIN_POS = exports('dS', new Vec3(-1024.0, -1024.0, -1024.0));
      var DEFAULT_WORLD_MAX_POS = exports('dT', new Vec3(1024.0, 1024.0, 1024.0));
      var DEFAULT_OCTREE_DEPTH = exports('dU', 8);
      var OctreeInfo = exports('dV', (_dec35$3 = ccclass$M('cc.OctreeInfo'), _dec36$3 = type$d(CCInteger), _dec35$3(_class13$6 = (_class14$5 = function () {
        function OctreeInfo() {
          this._enabled = _initializer36$3 && _initializer36$3();
          this._minPos = _initializer37$3 && _initializer37$3();
          this._maxPos = _initializer38$3 && _initializer38$3();
          this._depth = _initializer39$3 && _initializer39$3();
          this._resource = null;
        }
        var _proto5 = OctreeInfo.prototype;
        _proto5.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
        };
        _createClass(OctreeInfo, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            if (this._enabled === val) return;
            this._enabled = val;
            if (this._resource) {
              this._resource.enabled = val;
            }
          }
        }, {
          key: "minPos",
          get: function get() {
            return this._minPos;
          },
          set: function set(val) {
            this._minPos = val;
            if (this._resource) {
              this._resource.minPos = val;
            }
          }
        }, {
          key: "maxPos",
          get: function get() {
            return this._maxPos;
          },
          set: function set(val) {
            this._maxPos = val;
            if (this._resource) {
              this._resource.maxPos = val;
            }
          }
        }, {
          key: "depth",
          get: function get() {
            return this._depth;
          },
          set: function set(val) {
            this._depth = val;
            if (this._resource) {
              this._resource.depth = val;
            }
          }
        }]);
        return OctreeInfo;
      }(), (_applyDecoratedDescriptor(_class14$5.prototype, "depth", [_dec36$3], Object.getOwnPropertyDescriptor(_class14$5.prototype, "depth"), _class14$5.prototype), _initializer36$3 = applyDecoratedInitializer(_class14$5.prototype, "_enabled", [serializable$p], function () {
        return false;
      }), _initializer37$3 = applyDecoratedInitializer(_class14$5.prototype, "_minPos", [serializable$p], function () {
        return new Vec3(DEFAULT_WORLD_MIN_POS);
      }), _initializer38$3 = applyDecoratedInitializer(_class14$5.prototype, "_maxPos", [serializable$p], function () {
        return new Vec3(DEFAULT_WORLD_MAX_POS);
      }), _initializer39$3 = applyDecoratedInitializer(_class14$5.prototype, "_depth", [serializable$p], function () {
        return DEFAULT_OCTREE_DEPTH;
      })), _class14$5)) || _class13$6));
      legacyCC.OctreeInfo = OctreeInfo;
      var SkinInfo = exports('dW', (_dec37$3 = ccclass$M('cc.SkinInfo'), _dec38$3 = type$d(CCFloat), _dec39$3 = type$d(CCFloat), _dec37$3(_class16$2 = (_class17$3 = function () {
        function SkinInfo() {
          this._enabled = _initializer40$3 && _initializer40$3();
          this._blurRadius = _initializer41$3 && _initializer41$3();
          this._sssIntensity = _initializer42$2 && _initializer42$2();
          this._resource = null;
        }
        var _proto6 = SkinInfo.prototype;
        _proto6.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
        };
        _createClass(SkinInfo, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            if (this._enabled === val) return;
            this._enabled = val;
            if (this._resource) {
              this._resource.enabled = val;
            }
          }
        }, {
          key: "blurRadius",
          get: function get() {
            return this._blurRadius;
          },
          set: function set(val) {
            this._blurRadius = val;
            if (this._resource) {
              this._resource.blurRadius = val;
            }
          }
        }, {
          key: "sssIntensity",
          get: function get() {
            return this._sssIntensity;
          },
          set: function set(val) {
            this._sssIntensity = val;
            if (this._resource) {
              this._resource.sssIntensity = val;
            }
          }
        }]);
        return SkinInfo;
      }(), (_applyDecoratedDescriptor(_class17$3.prototype, "blurRadius", [_dec38$3], Object.getOwnPropertyDescriptor(_class17$3.prototype, "blurRadius"), _class17$3.prototype), _applyDecoratedDescriptor(_class17$3.prototype, "sssIntensity", [_dec39$3], Object.getOwnPropertyDescriptor(_class17$3.prototype, "sssIntensity"), _class17$3.prototype), _initializer40$3 = applyDecoratedInitializer(_class17$3.prototype, "_enabled", [serializable$p], function () {
        return true;
      }), _initializer41$3 = applyDecoratedInitializer(_class17$3.prototype, "_blurRadius", [serializable$p], function () {
        return 0.01;
      }), _initializer42$2 = applyDecoratedInitializer(_class17$3.prototype, "_sssIntensity", [serializable$p], function () {
        return 3.0;
      })), _class17$3)) || _class16$2));
      legacyCC.SkinInfo = SkinInfo;
      var PostSettingsInfo = exports('dX', (_dec40$2 = ccclass$M('cc.PostSettingsInfo'), _dec41$2 = type$d(ToneMappingType), _dec40$2(_class19$2 = (_class20$4 = function () {
        function PostSettingsInfo() {
          this._toneMappingType = _initializer43$2 && _initializer43$2();
          this._resource = null;
        }
        var _proto7 = PostSettingsInfo.prototype;
        _proto7.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
          this._resource.activate();
        };
        _createClass(PostSettingsInfo, [{
          key: "toneMappingType",
          get: function get() {
            return this._toneMappingType;
          },
          set: function set(val) {
            this._toneMappingType = val;
            if (this._resource) {
              this._resource.toneMappingType = val;
            }
          }
        }]);
        return PostSettingsInfo;
      }(), (_applyDecoratedDescriptor(_class20$4.prototype, "toneMappingType", [_dec41$2], Object.getOwnPropertyDescriptor(_class20$4.prototype, "toneMappingType"), _class20$4.prototype), _initializer43$2 = applyDecoratedInitializer(_class20$4.prototype, "_toneMappingType", [serializable$p], function () {
        return ToneMappingType.DEFAULT;
      })), _class20$4)) || _class19$2));
      legacyCC.PostSettingsInfo = PostSettingsInfo;
      var LightProbeInfo = exports('dY', (_dec42$2 = ccclass$M('cc.LightProbeInfo'), _dec43$2 = type$d(CCFloat), _dec44$2 = type$d(CCInteger), _dec45$2 = type$d(CCInteger), _dec46$2 = type$d(CCFloat), _dec47$2 = type$d(CCFloat), _dec42$2(_class22$2 = (_class23$3 = function () {
        function LightProbeInfo() {
          this._giScale = _initializer44$1 && _initializer44$1();
          this._giSamples = _initializer45$1 && _initializer45$1();
          this._bounces = _initializer46$1 && _initializer46$1();
          this._reduceRinging = _initializer47 && _initializer47();
          this._showProbe = _initializer48 && _initializer48();
          this._showWireframe = _initializer49 && _initializer49();
          this._showConvex = _initializer50 && _initializer50();
          this._data = _initializer51 && _initializer51();
          this._lightProbeSphereVolume = _initializer52 && _initializer52();
          this._nodes = [];
          this._scene = null;
          this._resource = null;
        }
        var _proto8 = LightProbeInfo.prototype;
        _proto8.activate = function activate(scene, resource) {
          this._scene = scene;
          this._resource = resource;
          this._resource.initialize(this);
        };
        _proto8.onProbeBakeFinished = function onProbeBakeFinished() {
          this.onProbeBakingChanged(this._scene);
        };
        _proto8.onProbeBakeCleared = function onProbeBakeCleared() {
          this.clearSHCoefficients();
          this.onProbeBakingChanged(this._scene);
        };
        _proto8.onProbeBakingChanged = function onProbeBakingChanged(node) {
          if (!node) {
            return;
          }
          node.emit(NodeEventType.LIGHT_PROBE_BAKING_CHANGED);
          for (var i = 0; i < node.children.length; i++) {
            var child = node.children[i];
            this.onProbeBakingChanged(child);
          }
        };
        _proto8.clearSHCoefficients = function clearSHCoefficients() {
          if (!this._data) {
            return;
          }
          var probes = this._data.probes;
          for (var i = 0; i < probes.length; i++) {
            probes[i].coefficients.length = 0;
          }
          this.clearAllSHUBOs();
        };
        _proto8.isUniqueNode = function isUniqueNode() {
          return this._nodes.length === 1;
        };
        _proto8.addNode = function addNode(node) {
          if (!node) {
            return false;
          }
          for (var i = 0; i < this._nodes.length; i++) {
            if (this._nodes[i].node === node) {
              return false;
            }
          }
          this._nodes.push({
            node: node,
            probes: null
          });
          return true;
        };
        _proto8.removeNode = function removeNode(node) {
          if (!node) {
            return false;
          }
          var index = this._nodes.findIndex(function (element) {
            return element.node === node;
          });
          if (index === -1) {
            return false;
          }
          this._nodes.splice(index, 1);
          return true;
        };
        _proto8.syncData = function syncData(node, probes) {
          for (var i = 0; i < this._nodes.length; i++) {
            if (this._nodes[i].node === node) {
              this._nodes[i].probes = probes;
              return;
            }
          }
        };
        _proto8.update = function update(updateTet) {
          if (updateTet === void 0) {
            updateTet = true;
          }
          if (!legacyCC.internal.LightProbesData) {
            return;
          }
          if (!this._data) {
            this._data = new legacyCC.internal.LightProbesData();
            if (this._resource) {
              this._resource.data = this._data;
            }
          }
          var points = [];
          for (var i = 0; i < this._nodes.length; i++) {
            var node = this._nodes[i].node;
            var probes = this._nodes[i].probes;
            var worldPosition = node.worldPosition;
            if (!probes) {
              continue;
            }
            for (var j = 0; j < probes.length; j++) {
              var position = new Vec3(0, 0, 0);
              Vec3.add(position, probes[j], worldPosition);
              points.push(position);
            }
          }
          var pointCount = points.length;
          if (pointCount < 4) {
            this.resetAllTetraIndices();
            this._data.reset();
            return;
          }
          this._data.updateProbes(points);
          if (updateTet) {
            this.resetAllTetraIndices();
            this._data.updateTetrahedrons();
          }
        };
        _proto8.clearAllSHUBOs = function clearAllSHUBOs() {
          if (!this._scene) {
            return;
          }
          var renderScene = this._scene.renderScene;
          if (!renderScene) {
            return;
          }
          var models = renderScene.models;
          for (var i = 0; i < models.length; i++) {
            models[i].clearSHUBOs();
          }
        };
        _proto8.resetAllTetraIndices = function resetAllTetraIndices() {
          if (!this._scene) {
            return;
          }
          var renderScene = this._scene.renderScene;
          if (!renderScene) {
            return;
          }
          var models = renderScene.models;
          for (var i = 0; i < models.length; i++) {
            models[i].tetrahedronIndex = -1;
          }
        };
        _createClass(LightProbeInfo, [{
          key: "giScale",
          get: function get() {
            return this._giScale;
          },
          set: function set(val) {
            if (this._giScale === val) return;
            this._giScale = val;
            if (this._resource) {
              this._resource.giScale = val;
            }
          }
        }, {
          key: "giSamples",
          get: function get() {
            return this._giSamples;
          },
          set: function set(val) {
            if (this._giSamples === val) return;
            this._giSamples = val;
            if (this._resource) {
              this._resource.giSamples = val;
            }
          }
        }, {
          key: "bounces",
          get: function get() {
            return this._bounces;
          },
          set: function set(val) {
            if (this._bounces === val) return;
            this._bounces = val;
            if (this._resource) {
              this._resource.bounces = val;
            }
          }
        }, {
          key: "reduceRinging",
          get: function get() {
            return this._reduceRinging;
          },
          set: function set(val) {
            if (this._reduceRinging === val) return;
            this._reduceRinging = val;
            if (this._resource) {
              this._resource.reduceRinging = val;
            }
          }
        }, {
          key: "showProbe",
          get: function get() {
            return this._showProbe;
          },
          set: function set(val) {
            if (this._showProbe === val) return;
            this._showProbe = val;
            if (this._resource) {
              this._resource.showProbe = val;
            }
          }
        }, {
          key: "showWireframe",
          get: function get() {
            return this._showWireframe;
          },
          set: function set(val) {
            if (this._showWireframe === val) return;
            this._showWireframe = val;
            if (this._resource) {
              this._resource.showWireframe = val;
            }
          }
        }, {
          key: "showConvex",
          get: function get() {
            return this._showConvex;
          },
          set: function set(val) {
            if (this._showConvex === val) return;
            this._showConvex = val;
            if (this._resource) {
              this._resource.showConvex = val;
            }
          }
        }, {
          key: "data",
          get: function get() {
            return this._data;
          },
          set: function set(val) {
            if (this._data === val) return;
            this._data = val;
            if (this._resource) {
              this._resource.data = val;
            }
          }
        }, {
          key: "lightProbeSphereVolume",
          get: function get() {
            return this._lightProbeSphereVolume;
          },
          set: function set(val) {
            if (this._lightProbeSphereVolume === val) return;
            this._lightProbeSphereVolume = val;
            if (this._resource) {
              this._resource.lightProbeSphereVolume = val;
            }
          }
        }]);
        return LightProbeInfo;
      }(), (_applyDecoratedDescriptor(_class23$3.prototype, "giScale", [_dec43$2], Object.getOwnPropertyDescriptor(_class23$3.prototype, "giScale"), _class23$3.prototype), _applyDecoratedDescriptor(_class23$3.prototype, "giSamples", [_dec44$2], Object.getOwnPropertyDescriptor(_class23$3.prototype, "giSamples"), _class23$3.prototype), _applyDecoratedDescriptor(_class23$3.prototype, "bounces", [_dec45$2], Object.getOwnPropertyDescriptor(_class23$3.prototype, "bounces"), _class23$3.prototype), _applyDecoratedDescriptor(_class23$3.prototype, "reduceRinging", [_dec46$2], Object.getOwnPropertyDescriptor(_class23$3.prototype, "reduceRinging"), _class23$3.prototype), _applyDecoratedDescriptor(_class23$3.prototype, "lightProbeSphereVolume", [_dec47$2], Object.getOwnPropertyDescriptor(_class23$3.prototype, "lightProbeSphereVolume"), _class23$3.prototype), _initializer44$1 = applyDecoratedInitializer(_class23$3.prototype, "_giScale", [serializable$p], function () {
        return 1.0;
      }), _initializer45$1 = applyDecoratedInitializer(_class23$3.prototype, "_giSamples", [serializable$p], function () {
        return 1024;
      }), _initializer46$1 = applyDecoratedInitializer(_class23$3.prototype, "_bounces", [serializable$p], function () {
        return 2;
      }), _initializer47 = applyDecoratedInitializer(_class23$3.prototype, "_reduceRinging", [serializable$p], function () {
        return 0.0;
      }), _initializer48 = applyDecoratedInitializer(_class23$3.prototype, "_showProbe", [serializable$p], function () {
        return true;
      }), _initializer49 = applyDecoratedInitializer(_class23$3.prototype, "_showWireframe", [serializable$p], function () {
        return true;
      }), _initializer50 = applyDecoratedInitializer(_class23$3.prototype, "_showConvex", [serializable$p], function () {
        return false;
      }), _initializer51 = applyDecoratedInitializer(_class23$3.prototype, "_data", [serializable$p], function () {
        return null;
      }), _initializer52 = applyDecoratedInitializer(_class23$3.prototype, "_lightProbeSphereVolume", [serializable$p], function () {
        return 1.0;
      })), _class23$3)) || _class22$2));
      var SceneGlobals = exports('dZ', (_dec48$1 = ccclass$M('cc.SceneGlobals'), _dec49$1 = type$d(SkyboxInfo), _dec48$1(_class25 = (_class26$1 = function () {
        function SceneGlobals() {
          this.ambient = _initializer53 && _initializer53();
          this.shadows = _initializer54 && _initializer54();
          this._skybox = _initializer55 && _initializer55();
          this.fog = _initializer56 && _initializer56();
          this.octree = _initializer57 && _initializer57();
          this.skin = _initializer58 && _initializer58();
          this.lightProbeInfo = _initializer59 && _initializer59();
          this.postSettings = _initializer60 && _initializer60();
          this.bakedWithStationaryMainLight = _initializer61 && _initializer61();
          this.bakedWithHighpLightmap = _initializer62 && _initializer62();
          this.disableLightmap = false;
        }
        var _proto9 = SceneGlobals.prototype;
        _proto9.activate = function activate(scene) {
          var sceneData = legacyCC.director.root.pipeline.pipelineSceneData;
          this.skybox.activate(sceneData.skybox);
          this.ambient.activate(sceneData.ambient);
          this.shadows.activate(sceneData.shadows);
          this.fog.activate(sceneData.fog);
          this.octree.activate(sceneData.octree);
          this.skin.activate(sceneData.skin);
          this.postSettings.activate(sceneData.postSettings);
          if (this.lightProbeInfo && sceneData.lightProbes) {
            this.lightProbeInfo.activate(scene, sceneData.lightProbes);
          }
          var root = legacyCC.director.root;
          root.onGlobalPipelineStateChanged();
        };
        _createClass(SceneGlobals, [{
          key: "skybox",
          get: function get() {
            return this._skybox;
          },
          set: function set(value) {
            this._skybox = value;
          }
        }]);
        return SceneGlobals;
      }(), (_initializer53 = applyDecoratedInitializer(_class26$1.prototype, "ambient", [serializable$p], function () {
        return new AmbientInfo();
      }), _initializer54 = applyDecoratedInitializer(_class26$1.prototype, "shadows", [serializable$p], function () {
        return new ShadowsInfo();
      }), _initializer55 = applyDecoratedInitializer(_class26$1.prototype, "_skybox", [serializable$p], function () {
        return new SkyboxInfo();
      }), _initializer56 = applyDecoratedInitializer(_class26$1.prototype, "fog", [serializable$p], function () {
        return new FogInfo();
      }), _applyDecoratedDescriptor(_class26$1.prototype, "skybox", [_dec49$1], Object.getOwnPropertyDescriptor(_class26$1.prototype, "skybox"), _class26$1.prototype), _initializer57 = applyDecoratedInitializer(_class26$1.prototype, "octree", [serializable$p], function () {
        return new OctreeInfo();
      }), _initializer58 = applyDecoratedInitializer(_class26$1.prototype, "skin", [serializable$p], function () {
        return new SkinInfo();
      }), _initializer59 = applyDecoratedInitializer(_class26$1.prototype, "lightProbeInfo", [serializable$p], function () {
        return new LightProbeInfo();
      }), _initializer60 = applyDecoratedInitializer(_class26$1.prototype, "postSettings", [serializable$p], function () {
        return new PostSettingsInfo();
      }), _initializer61 = applyDecoratedInitializer(_class26$1.prototype, "bakedWithStationaryMainLight", [serializable$p], function () {
        return false;
      }), _initializer62 = applyDecoratedInitializer(_class26$1.prototype, "bakedWithHighpLightmap", [serializable$p], function () {
        return false;
      })), _class26$1)) || _class25));
      legacyCC.SceneGlobals = SceneGlobals;

      var _dec$3p, _dec2$2u, _class$3k, _class2$2$, _initializer$2M, _dec3$1K, _dec4$1d, _dec5$14, _dec6$Q, _dec7$F, _dec8$t, _class4$w, _class5$w, _initializer2$2e, _initializer3$1D, _initializer4$1n, _initializer5$14, _initializer6$U, _dec9$o, _class7$9, _class8$a, _initializer7$I, _dec10$g, _dec11$b, _dec12$a, _class10$5, _class11$6, _initializer8$E, _initializer9$z, _initializer10$w, _dec13$8, _dec14$7, _dec15$6, _class13$5, _class14$4, _initializer11$u, _initializer12$r, _dec16$5, _dec17$5, _dec18$5, _class16$1, _class17$2, _initializer13$o, _initializer14$k, _dec19$5, _dec20$5, _dec21$5, _dec22$5, _dec23$5, _dec24$5, _class19$1, _class20$3, _initializer15$g, _initializer16$g, _initializer17$d, _initializer18$d, _initializer19$c, _initializer20$a, _dec25$5, _dec26$5, _dec27$5, _dec28$5, _class22$1, _class23$2, _initializer21$a, _initializer22$9, _initializer23$7, _initializer24$7, _initializer25$6, _initializer26$6;
      var TargetInfo = (_dec$3p = ccclass$M('cc.TargetInfo'), _dec2$2u = type$d([CCString]), _dec$3p(_class$3k = (_class2$2$ = function TargetInfo() {
        this.localID = _initializer$2M && _initializer$2M();
      }, (_initializer$2M = applyDecoratedInitializer(_class2$2$.prototype, "localID", [serializable$p, _dec2$2u], function () {
        return [];
      })), _class2$2$)) || _class$3k);
      var TargetOverrideInfo = (_dec3$1K = ccclass$M('cc.TargetOverrideInfo'), _dec4$1d = type$d(CCObject), _dec5$14 = type$d(TargetInfo), _dec6$Q = type$d([CCString]), _dec7$F = type$d(Node$1), _dec8$t = type$d(TargetInfo), _dec3$1K(_class4$w = (_class5$w = function TargetOverrideInfo() {
        this.source = _initializer2$2e && _initializer2$2e();
        this.sourceInfo = _initializer3$1D && _initializer3$1D();
        this.propertyPath = _initializer4$1n && _initializer4$1n();
        this.target = _initializer5$14 && _initializer5$14();
        this.targetInfo = _initializer6$U && _initializer6$U();
      }, (_initializer2$2e = applyDecoratedInitializer(_class5$w.prototype, "source", [serializable$p, _dec4$1d], function () {
        return null;
      }), _initializer3$1D = applyDecoratedInitializer(_class5$w.prototype, "sourceInfo", [serializable$p, _dec5$14], function () {
        return null;
      }), _initializer4$1n = applyDecoratedInitializer(_class5$w.prototype, "propertyPath", [serializable$p, _dec6$Q], function () {
        return [];
      }), _initializer5$14 = applyDecoratedInitializer(_class5$w.prototype, "target", [serializable$p, _dec7$F], function () {
        return null;
      }), _initializer6$U = applyDecoratedInitializer(_class5$w.prototype, "targetInfo", [serializable$p, _dec8$t], function () {
        return null;
      })), _class5$w)) || _class4$w);
      var CompPrefabInfo = (_dec9$o = ccclass$M('cc.CompPrefabInfo'), _dec9$o(_class7$9 = (_class8$a = function CompPrefabInfo() {
        this.fileId = _initializer7$I && _initializer7$I();
      }, (_initializer7$I = applyDecoratedInitializer(_class8$a.prototype, "fileId", [serializable$p], function () {
        return '';
      })), _class8$a)) || _class7$9);
      var PropertyOverrideInfo = (_dec10$g = ccclass$M('CCPropertyOverrideInfo'), _dec11$b = type$d(TargetInfo), _dec12$a = type$d([CCString]), _dec10$g(_class10$5 = (_class11$6 = function () {
        function PropertyOverrideInfo() {
          this.targetInfo = _initializer8$E && _initializer8$E();
          this.propertyPath = _initializer9$z && _initializer9$z();
          this.value = _initializer10$w && _initializer10$w();
        }
        var _proto = PropertyOverrideInfo.prototype;
        _proto.isTarget = function isTarget(localID, propPath) {
        };
        return PropertyOverrideInfo;
      }(), (_initializer8$E = applyDecoratedInitializer(_class11$6.prototype, "targetInfo", [serializable$p, _dec11$b], function () {
        return null;
      }), _initializer9$z = applyDecoratedInitializer(_class11$6.prototype, "propertyPath", [serializable$p, _dec12$a], function () {
        return [];
      }), _initializer10$w = applyDecoratedInitializer(_class11$6.prototype, "value", [serializable$p], null)), _class11$6)) || _class10$5);
      var MountedChildrenInfo = (_dec13$8 = ccclass$M('cc.MountedChildrenInfo'), _dec14$7 = type$d(TargetInfo), _dec15$6 = type$d([Node$1]), _dec13$8(_class13$5 = (_class14$4 = function () {
        function MountedChildrenInfo() {
          this.targetInfo = _initializer11$u && _initializer11$u();
          this.nodes = _initializer12$r && _initializer12$r();
        }
        var _proto2 = MountedChildrenInfo.prototype;
        _proto2.isTarget = function isTarget(localID) {
        };
        return MountedChildrenInfo;
      }(), (_initializer11$u = applyDecoratedInitializer(_class14$4.prototype, "targetInfo", [serializable$p, _dec14$7], function () {
        return null;
      }), _initializer12$r = applyDecoratedInitializer(_class14$4.prototype, "nodes", [serializable$p, _dec15$6], function () {
        return [];
      })), _class14$4)) || _class13$5);
      var MountedComponentsInfo = (_dec16$5 = ccclass$M('cc.MountedComponentsInfo'), _dec17$5 = type$d(TargetInfo), _dec18$5 = type$d([Component]), _dec16$5(_class16$1 = (_class17$2 = function () {
        function MountedComponentsInfo() {
          this.targetInfo = _initializer13$o && _initializer13$o();
          this.components = _initializer14$k && _initializer14$k();
        }
        var _proto3 = MountedComponentsInfo.prototype;
        _proto3.isTarget = function isTarget(localID) {
        };
        return MountedComponentsInfo;
      }(), (_initializer13$o = applyDecoratedInitializer(_class17$2.prototype, "targetInfo", [serializable$p, _dec17$5], function () {
        return null;
      }), _initializer14$k = applyDecoratedInitializer(_class17$2.prototype, "components", [serializable$p, _dec18$5], function () {
        return [];
      })), _class17$2)) || _class16$1);
      var PrefabInstance = (_dec19$5 = ccclass$M('cc.PrefabInstance'), _dec20$5 = type$d(Node$1), _dec21$5 = type$d([MountedChildrenInfo]), _dec22$5 = type$d([MountedComponentsInfo]), _dec23$5 = type$d([PropertyOverrideInfo]), _dec24$5 = type$d([TargetInfo]), _dec19$5(_class19$1 = (_class20$3 = function () {
        function PrefabInstance() {
          this.fileId = _initializer15$g && _initializer15$g();
          this.prefabRootNode = _initializer16$g && _initializer16$g();
          this.mountedChildren = _initializer17$d && _initializer17$d();
          this.mountedComponents = _initializer18$d && _initializer18$d();
          this.propertyOverrides = _initializer19$c && _initializer19$c();
          this.removedComponents = _initializer20$a && _initializer20$a();
          this.targetMap = {};
          this.expanded = false;
        }
        var _proto4 = PrefabInstance.prototype;
        _proto4.findPropertyOverride = function findPropertyOverride(localID, propPath) {
        };
        _proto4.removePropertyOverride = function removePropertyOverride(localID, propPath) {
        };
        return PrefabInstance;
      }(), (_initializer15$g = applyDecoratedInitializer(_class20$3.prototype, "fileId", [serializable$p], function () {
        return '';
      }), _initializer16$g = applyDecoratedInitializer(_class20$3.prototype, "prefabRootNode", [serializable$p, _dec20$5], null), _initializer17$d = applyDecoratedInitializer(_class20$3.prototype, "mountedChildren", [serializable$p, _dec21$5], function () {
        return [];
      }), _initializer18$d = applyDecoratedInitializer(_class20$3.prototype, "mountedComponents", [serializable$p, _dec22$5], function () {
        return [];
      }), _initializer19$c = applyDecoratedInitializer(_class20$3.prototype, "propertyOverrides", [serializable$p, _dec23$5], function () {
        return [];
      }), _initializer20$a = applyDecoratedInitializer(_class20$3.prototype, "removedComponents", [serializable$p, _dec24$5], function () {
        return [];
      })), _class20$3)) || _class19$1);
      var PrefabInfo = (_dec25$5 = ccclass$M('cc.PrefabInfo'), _dec26$5 = type$d(Node$1), _dec27$5 = type$d(PrefabInstance), _dec28$5 = type$d([TargetOverrideInfo]), _dec25$5(_class22$1 = (_class23$2 = function PrefabInfo() {
        this.root = _initializer21$a && _initializer21$a();
        this.asset = _initializer22$9 && _initializer22$9();
        this.fileId = _initializer23$7 && _initializer23$7();
        this.instance = _initializer24$7 && _initializer24$7();
        this.targetOverrides = _initializer25$6 && _initializer25$6();
        this.nestedPrefabInstanceRoots = _initializer26$6 && _initializer26$6();
      }, (_initializer21$a = applyDecoratedInitializer(_class23$2.prototype, "root", [serializable$p, _dec26$5], null), _initializer22$9 = applyDecoratedInitializer(_class23$2.prototype, "asset", [serializable$p], null), _initializer23$7 = applyDecoratedInitializer(_class23$2.prototype, "fileId", [serializable$p], function () {
        return '';
      }), _initializer24$7 = applyDecoratedInitializer(_class23$2.prototype, "instance", [serializable$p, _dec27$5], null), _initializer25$6 = applyDecoratedInitializer(_class23$2.prototype, "targetOverrides", [serializable$p, _dec28$5], null), _initializer26$6 = applyDecoratedInitializer(_class23$2.prototype, "nestedPrefabInstanceRoots", [serializable$p], null)), _class23$2)) || _class22$1);
      legacyCC._PrefabInfo = PrefabInfo;

      function createNodeWithPrefab(node) {
        var prefabInfo = node === null || node === void 0 ? void 0 : node.prefab;
        if (!prefabInfo) {
          return;
        }
        var prefabInstance = prefabInfo.instance;
        if (!prefabInstance) {
          return;
        }
        if (!prefabInfo.asset) {
          {
            errorID(3701, node.name);
          }
          prefabInfo.instance = undefined;
          return;
        }
        var _objFlags = node._objFlags;
        var _parent = node.getParent();
        var _id = node.uuid;
        node[editorExtrasTag];
        legacyCC.game._isCloning = true;
        {
          prefabInfo.asset._doInstantiate(node);
        }
        legacyCC.game._isCloning = false;
        node._objFlags = _objFlags;
        node.modifyParent(_parent);
        node.id = _id;
        if (node.prefab) {
          node.prefab.instance = prefabInfo.instance;
        }
      }
      function generateTargetMap(node, targetMap, isRoot) {
        var _node$prefab;
        if (!targetMap) {
          return;
        }
        if (!node) {
          return;
        }
        var curTargetMap = targetMap;
        var prefabInstance = (_node$prefab = node.prefab) === null || _node$prefab === void 0 ? void 0 : _node$prefab.instance;
        if (!isRoot && prefabInstance) {
          targetMap[prefabInstance.fileId] = {};
          curTargetMap = targetMap[prefabInstance.fileId];
        }
        var prefabInfo = node.prefab;
        if (prefabInfo) {
          curTargetMap[prefabInfo.fileId] = node;
        }
        var components = node.components;
        for (var i = 0; i < components.length; i++) {
          var comp = components[i];
          if (comp.__prefab) {
            curTargetMap[comp.__prefab.fileId] = comp;
          }
        }
        for (var _i = 0; _i < node.children.length; _i++) {
          var childNode = node.children[_i];
          generateTargetMap(childNode, curTargetMap, false);
        }
      }
      function getTarget(localID, targetMap) {
        if (!localID) {
          return null;
        }
        var target = null;
        var targetIter = targetMap;
        for (var i = 0; i < localID.length; i++) {
          if (!targetIter) {
            return null;
          }
          targetIter = targetIter[localID[i]];
        }
        target = targetIter;
        return target;
      }
      function applyMountedChildren(node, mountedChildren, targetMap) {
        if (!mountedChildren) {
          return;
        }
        for (var i = 0; i < mountedChildren.length; i++) {
          var childInfo = mountedChildren[i];
          if (childInfo && childInfo.targetInfo) {
            var target = getTarget(childInfo.targetInfo.localID, targetMap);
            if (!target) {
              continue;
            }
            var curTargetMap = targetMap;
            var localID = childInfo.targetInfo.localID;
            if (localID.length > 0) {
              for (var _i2 = 0; _i2 < localID.length - 1; _i2++) {
                curTargetMap = curTargetMap[localID[_i2]];
              }
            }
            if (childInfo.nodes) {
              for (var _i3 = 0; _i3 < childInfo.nodes.length; _i3++) {
                var childNode = childInfo.nodes[_i3];
                if (!childNode || target.children.includes(childNode)) {
                  continue;
                }
                target.children.push(childNode);
                childNode.modifyParent(target);
                generateTargetMap(childNode, curTargetMap, false);
                childNode.siblingIndex = target.children.length - 1;
                expandPrefabInstanceNode(childNode, true);
              }
            }
          }
        }
      }
      function applyMountedComponents(node, mountedComponents, targetMap) {
        if (!mountedComponents) {
          return;
        }
        for (var i = 0; i < mountedComponents.length; i++) {
          var componentsInfo = mountedComponents[i];
          if (componentsInfo && componentsInfo.targetInfo) {
            var target = getTarget(componentsInfo.targetInfo.localID, targetMap);
            if (!target) {
              continue;
            }
            if (componentsInfo.components) {
              for (var _i4 = 0; _i4 < componentsInfo.components.length; _i4++) {
                var comp = componentsInfo.components[_i4];
                if (!comp) {
                  continue;
                }
                comp.node = target;
                target.getWritableComponents().push(comp);
              }
            }
          }
        }
      }
      function applyRemovedComponents(node, removedComponents, targetMap) {
        if (!removedComponents) {
          return;
        }
        for (var i = 0; i < removedComponents.length; i++) {
          var targetInfo = removedComponents[i];
          if (targetInfo) {
            var target = getTarget(targetInfo.localID, targetMap);
            if (!target || !target.node) {
              continue;
            }
            var index = target.node.components.indexOf(target);
            if (index >= 0) {
              target.node.getWritableComponents().splice(index, 1);
            }
          }
        }
      }
      function applyPropertyOverrides(node, propertyOverrides, targetMap) {
        if (propertyOverrides.length <= 0) {
          return;
        }
        var target = null;
        for (var i = 0; i < propertyOverrides.length; i++) {
          var propOverride = propertyOverrides[i];
          if (propOverride && propOverride.targetInfo) {
            var targetInfo = propOverride.targetInfo;
            target = getTarget(targetInfo.localID, targetMap);
            if (!target) {
              continue;
            }
            var targetPropOwner = target;
            var propertyPath = propOverride.propertyPath.slice();
            if (propertyPath.length > 0) {
              var targetPropName = propertyPath.pop();
              if (!targetPropName) {
                continue;
              }
              for (var _i5 = 0; _i5 < propertyPath.length; _i5++) {
                var propName = propertyPath[_i5];
                targetPropOwner = targetPropOwner[propName];
                if (!targetPropOwner) {
                  break;
                }
              }
              if (!targetPropOwner) {
                continue;
              }
              if (Array.isArray(targetPropOwner)) {
                if (targetPropName === 'length') {
                  targetPropOwner[targetPropName] = propOverride.value;
                } else {
                  var index = Number.parseInt(targetPropName);
                  if (Number.isInteger(index) && index < targetPropOwner.length) {
                    targetPropOwner[targetPropName] = propOverride.value;
                  }
                }
              } else if (targetPropOwner[targetPropName] instanceof ValueType) {
                targetPropOwner[targetPropName].set(propOverride.value);
              } else {
                targetPropOwner[targetPropName] = propOverride.value;
              }
            }
          }
        }
      }
      function applyTargetOverrides(node) {
        var _node$prefab2;
        var targetOverrides = (_node$prefab2 = node.prefab) === null || _node$prefab2 === void 0 ? void 0 : _node$prefab2.targetOverrides;
        if (targetOverrides) {
          for (var i = 0; i < targetOverrides.length; i++) {
            var _targetAsNode$prefab;
            var targetOverride = targetOverrides[i];
            var source = targetOverride.source;
            var sourceInfo = targetOverride.sourceInfo;
            if (sourceInfo) {
              var _src$prefab;
              var src = targetOverride.source;
              var sourceInstance = src === null || src === void 0 ? void 0 : (_src$prefab = src.prefab) === null || _src$prefab === void 0 ? void 0 : _src$prefab.instance;
              if (sourceInstance && sourceInstance.targetMap) {
                source = getTarget(sourceInfo.localID, sourceInstance.targetMap);
              }
            }
            if (!source) {
              continue;
            }
            var target = null;
            var targetInfo = targetOverride.targetInfo;
            if (!targetInfo) {
              continue;
            }
            var targetAsNode = targetOverride.target;
            var targetInstance = targetAsNode === null || targetAsNode === void 0 ? void 0 : (_targetAsNode$prefab = targetAsNode.prefab) === null || _targetAsNode$prefab === void 0 ? void 0 : _targetAsNode$prefab.instance;
            if (!targetInstance || !targetInstance.targetMap) {
              continue;
            }
            target = getTarget(targetInfo.localID, targetInstance.targetMap);
            if (!target) {
              continue;
            }
            var propertyPath = targetOverride.propertyPath.slice();
            var targetPropOwner = source;
            if (propertyPath.length > 0) {
              var targetPropName = propertyPath.pop();
              if (!targetPropName) {
                return;
              }
              for (var _i6 = 0; _i6 < propertyPath.length; _i6++) {
                var propName = propertyPath[_i6];
                targetPropOwner = targetPropOwner[propName];
                if (!targetPropOwner) {
                  break;
                }
              }
              if (!targetPropOwner) {
                continue;
              }
              targetPropOwner[targetPropName] = target;
            }
          }
        }
      }
      function expandPrefabInstanceNode(node, recursively) {
        var _node$prefab3;
        if (recursively === void 0) {
          recursively = false;
        }
        var prefabInstance = node === null || node === void 0 ? void 0 : (_node$prefab3 = node.prefab) === null || _node$prefab3 === void 0 ? void 0 : _node$prefab3.instance;
        if (prefabInstance && !prefabInstance.expanded) {
          createNodeWithPrefab(node);
          if (recursively) {
            if (node && node.children) {
              node.children.forEach(function (child) {
                expandPrefabInstanceNode(child, true);
              });
            }
          }
          var targetMap = {};
          prefabInstance.targetMap = targetMap;
          generateTargetMap(node, targetMap, true);
          applyMountedChildren(node, prefabInstance.mountedChildren, targetMap);
          applyRemovedComponents(node, prefabInstance.removedComponents, targetMap);
          applyMountedComponents(node, prefabInstance.mountedComponents, targetMap);
          applyPropertyOverrides(node, prefabInstance.propertyOverrides, targetMap);
          prefabInstance.expanded = true;
        } else if (recursively) {
          if (node && node.children) {
            node.children.forEach(function (child) {
              expandPrefabInstanceNode(child, true);
            });
          }
        }
      }
      function expandNestedPrefabInstanceNode(node) {
        var prefabInfo = node.prefab;
        if (prefabInfo && prefabInfo.nestedPrefabInstanceRoots) {
          prefabInfo.nestedPrefabInstanceRoots.forEach(function (instanceNode) {
            expandPrefabInstanceNode(instanceNode);
          });
        }
      }
      function applyNodeAndComponentId(prefabInstanceNode, rootId) {
        var components = prefabInstanceNode.components,
          children = prefabInstanceNode.children;
        for (var i = 0; i < components.length; i++) {
          var _comp$__prefab$fileId, _comp$__prefab;
          var comp = components[i];
          var fileID = (_comp$__prefab$fileId = (_comp$__prefab = comp.__prefab) === null || _comp$__prefab === void 0 ? void 0 : _comp$__prefab.fileId) !== null && _comp$__prefab$fileId !== void 0 ? _comp$__prefab$fileId : '';
          comp._id = "" + rootId + fileID;
        }
        for (var _i7 = 0; _i7 < children.length; _i7++) {
          var child = children[_i7];
          var prefabInfo = child.prefab;
          var fileId = prefabInfo !== null && prefabInfo !== void 0 && prefabInfo.instance ? prefabInfo.instance.fileId : prefabInfo === null || prefabInfo === void 0 ? void 0 : prefabInfo.fileId;
          if (!fileId) continue;
          child.id = "" + rootId + fileId;
          if (!(prefabInfo !== null && prefabInfo !== void 0 && prefabInfo.instance)) {
            applyNodeAndComponentId(child, rootId);
          }
        }
      }

      var utils$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        createNodeWithPrefab: createNodeWithPrefab,
        generateTargetMap: generateTargetMap,
        getTarget: getTarget,
        applyMountedChildren: applyMountedChildren,
        applyMountedComponents: applyMountedComponents,
        applyRemovedComponents: applyRemovedComponents,
        applyPropertyOverrides: applyPropertyOverrides,
        applyTargetOverrides: applyTargetOverrides,
        expandPrefabInstanceNode: expandPrefabInstanceNode,
        expandNestedPrefabInstanceNode: expandNestedPrefabInstanceNode,
        applyNodeAndComponentId: applyNodeAndComponentId,
        TargetInfo: TargetInfo,
        TargetOverrideInfo: TargetOverrideInfo,
        CompPrefabInfo: CompPrefabInfo,
        PropertyOverrideInfo: PropertyOverrideInfo,
        MountedChildrenInfo: MountedChildrenInfo,
        MountedComponentsInfo: MountedComponentsInfo,
        PrefabInstance: PrefabInstance,
        PrefabInfo: PrefabInfo
      });

      var _dec$3o, _class$3j, _class2$2_, _initializer$2L, _initializer2$2d;
      var Scene = exports('dD', (_dec$3o = ccclass$M('cc.Scene'), _dec$3o(_class$3j = (_class2$2_ = function (_Node) {
        _inheritsLoose(Scene, _Node);
        var _proto = Scene.prototype;
        _proto._updateScene = function _updateScene() {
          this._scene = this;
        };
        function Scene(name) {
          var _this;
          _this = _Node.call(this, name) || this;
          _this.autoReleaseAssets = _initializer$2L && _initializer$2L();
          _this._globals = _initializer2$2d && _initializer2$2d();
          _this.dependAssets = null;
          _this._renderScene = null;
          _this._inited = void 0;
          _this._prefabSyncedInLiveReload = false;
          _this._activeInHierarchy = false;
          if (legacyCC.director && legacyCC.director.root) {
            _this._renderScene = legacyCC.director.root.createScene({});
          }
          _this._inited = legacyCC.game ? !legacyCC.game._isCloning : true;
          return _this;
        }
        _proto.destroy = function destroy() {
          var success = CCObject.prototype.destroy.call(this);
          if (success) {
            var children = this._children;
            for (var i = 0; i < children.length; ++i) {
              children[i].active = false;
            }
          }
          if (this._renderScene) legacyCC.director.root.destroyScene(this._renderScene);
          this._active = false;
          this._activeInHierarchy = false;
          return success;
        };
        _proto.addComponent = function addComponent() {
          throw new Error(getError(3822));
        };
        _proto._onHierarchyChanged = function _onHierarchyChanged() {};
        _proto._onPostActivated = function _onPostActivated(active) {};
        _proto._onBatchCreated = function _onBatchCreated(dontSyncChildPrefab) {
          var len = this._children.length;
          for (var i = 0; i < len; ++i) {
            this._children[i]._siblingIndex = i;
            this._children[i]._onBatchCreated(dontSyncChildPrefab);
          }
        };
        _proto.updateWorldTransform = function updateWorldTransform() {};
        _proto._instantiate = function _instantiate() {};
        _proto._load = function _load() {
          if (!this._inited) {
            expandNestedPrefabInstanceNode(this);
            applyTargetOverrides(this);
            this._onBatchCreated(EDITOR );
            this._inited = true;
          }
          this.walk(Node$1._setScene);
        };
        _proto._activate = function _activate(active) {
          if (active === void 0) {
            active = true;
          }
          legacyCC.director._nodeActivator.activateNode(this, active);
          {
            this._globals.activate(this);
          }
        };
        _createClass(Scene, [{
          key: "renderScene",
          get: function get() {
            return this._renderScene;
          }
        }, {
          key: "globals",
          get: function get() {
            return this._globals;
          }
        }]);
        return Scene;
      }(Node$1), (_initializer$2L = applyDecoratedInitializer(_class2$2_.prototype, "autoReleaseAssets", [serializable$p], function () {
        return false;
      }), _initializer2$2d = applyDecoratedInitializer(_class2$2_.prototype, "_globals", [serializable$p], function () {
        return new SceneGlobals();
      })), _class2$2_)) || _class$3j));
      legacyCC.Scene = Scene;

      var _dec$3n, _class$3i, _class2$2Z, _initializer$2K;
      var SceneAsset = exports('ee', (_dec$3n = ccclass$M('cc.SceneAsset'), _dec$3n(_class$3i = (_class2$2Z = function (_Asset) {
        _inheritsLoose(SceneAsset, _Asset);
        function SceneAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.scene = _initializer$2K && _initializer$2K();
          return _this;
        }
        var _proto = SceneAsset.prototype;
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          this.scene = new Scene('New Scene');
        };
        _proto.validate = function validate() {
          return !!this.scene;
        };
        return SceneAsset;
      }(Asset), (_initializer$2K = applyDecoratedInitializer(_class2$2Z.prototype, "scene", [serializable$p], function () {
        return null;
      })), _class2$2Z)) || _class$3i));
      legacyCC.SceneAsset = SceneAsset;

      deprecateModuleExportedName({
        SystemEventType: {
          newName: 'Input.EventType',
          since: '3.3.0',
          removed: false
        }
      });

      deprecateModuleExportedName({
        SystemEvent: {
          newName: 'Input',
          since: '3.4.0',
          removed: false
        },
        systemEvent: {
          newName: 'input',
          since: '3.4.0',
          removed: false
        }
      });

      var Event = exports('eB', function () {
        function Event(type, bubbles) {
          this.type = void 0;
          this.bubbles = void 0;
          this.target = null;
          this.currentTarget = null;
          this.eventPhase = 0;
          this.propagationStopped = false;
          this.propagationImmediateStopped = false;
          this.type = type;
          this.bubbles = !!bubbles;
        }
        var _proto = Event.prototype;
        _proto.unuse = function unuse() {
          this.type = Event.NO_TYPE;
          this.target = null;
          this.currentTarget = null;
          this.eventPhase = Event.NONE;
          this.propagationStopped = false;
          this.propagationImmediateStopped = false;
        };
        _proto.reuse = function reuse(type, bubbles) {
          this.type = type;
          this.bubbles = bubbles || false;
        };
        _proto.isStopped = function isStopped() {
          return this.propagationStopped || this.propagationImmediateStopped;
        };
        _proto.getCurrentTarget = function getCurrentTarget() {
          return this.currentTarget;
        };
        _proto.getType = function getType() {
          return this.type;
        };
        return Event;
      }());
      Event.NO_TYPE = 'no_type';
      Event.TOUCH = 'touch';
      Event.MOUSE = 'mouse';
      Event.KEYBOARD = 'keyboard';
      Event.ACCELERATION = 'acceleration';
      Event.NONE = 0;
      Event.CAPTURING_PHASE = 1;
      Event.AT_TARGET = 2;
      Event.BUBBLING_PHASE = 3;
      legacyCC.Event = Event;

      var SystemEventType; exports('eA', SystemEventType);
      (function (SystemEventType) {
        SystemEventType["TOUCH_START"] = "touch-start";
        SystemEventType["TOUCH_MOVE"] = "touch-move";
        SystemEventType["TOUCH_END"] = "touch-end";
        SystemEventType["TOUCH_CANCEL"] = "touch-cancel";
        SystemEventType["MOUSE_DOWN"] = "mouse-down";
        SystemEventType["MOUSE_MOVE"] = "mouse-move";
        SystemEventType["MOUSE_UP"] = "mouse-up";
        SystemEventType["MOUSE_WHEEL"] = "mouse-wheel";
        SystemEventType["MOUSE_ENTER"] = "mouse-enter";
        SystemEventType["MOUSE_LEAVE"] = "mouse-leave";
        SystemEventType["KEY_DOWN"] = "keydown";
        SystemEventType["KEY_UP"] = "keyup";
        SystemEventType["DEVICEMOTION"] = "devicemotion";
        SystemEventType["TRANSFORM_CHANGED"] = "transform-changed";
        SystemEventType["SCENE_CHANGED_FOR_PERSISTS"] = "scene-changed-for-persists";
        SystemEventType["SIZE_CHANGED"] = "size-changed";
        SystemEventType["ANCHOR_CHANGED"] = "anchor-changed";
        SystemEventType["COLOR_CHANGED"] = "color-changed";
        SystemEventType["CHILD_ADDED"] = "child-added";
        SystemEventType["CHILD_REMOVED"] = "child-removed";
        SystemEventType["PARENT_CHANGED"] = "parent-changed";
        SystemEventType["NODE_DESTROYED"] = "node-destroyed";
        SystemEventType["LAYER_CHANGED"] = "layer-changed";
        SystemEventType["SIBLING_ORDER_CHANGED"] = "sibling-order-changed";
      })(SystemEventType || (exports('eA', SystemEventType = {})));
      var InputEventType;
      (function (InputEventType) {
        InputEventType["TOUCH_START"] = "touch-start";
        InputEventType["TOUCH_MOVE"] = "touch-move";
        InputEventType["TOUCH_END"] = "touch-end";
        InputEventType["TOUCH_CANCEL"] = "touch-cancel";
        InputEventType["MOUSE_DOWN"] = "mouse-down";
        InputEventType["MOUSE_MOVE"] = "mouse-move";
        InputEventType["MOUSE_UP"] = "mouse-up";
        InputEventType["MOUSE_WHEEL"] = "mouse-wheel";
        InputEventType["KEY_DOWN"] = "keydown";
        InputEventType["KEY_PRESSING"] = "key-pressing";
        InputEventType["KEY_UP"] = "keyup";
        InputEventType["DEVICEMOTION"] = "devicemotion";
        InputEventType["GAMEPAD_INPUT"] = "gamepad-input";
        InputEventType["GAMEPAD_CHANGE"] = "gamepad-change";
        InputEventType["HANDLE_INPUT"] = "handle-input";
        InputEventType["HANDLE_POSE_INPUT"] = "handle-pose-input";
        InputEventType["HMD_POSE_INPUT"] = "hmd-pose-input";
        InputEventType["HANDHELD_POSE_INPUT"] = "handheld-pose-input";
      })(InputEventType || (InputEventType = {}));
      legacyCC.SystemEventType = SystemEventType;

      var EventAcceleration = exports('eC', function (_Event) {
        _inheritsLoose(EventAcceleration, _Event);
        function EventAcceleration(acc, bubbles) {
          var _this;
          _this = _Event.call(this, SystemEventType.DEVICEMOTION, bubbles) || this;
          _this.acc = void 0;
          _this.acc = acc;
          return _this;
        }
        return EventAcceleration;
      }(Event));
      Event.EventAcceleration = EventAcceleration;

      var EventKeyboard = exports('eD', function (_Event) {
        _inheritsLoose(EventKeyboard, _Event);
        function EventKeyboard(keyCode, eventType, bubbles) {
          var _this;
          if (typeof eventType === 'boolean') {
            var _isPressed = eventType;
            eventType = _isPressed ? SystemEventType.KEY_DOWN : SystemEventType.KEY_UP;
          }
          _this = _Event.call(this, eventType, bubbles) || this;
          _this.windowId = void 0;
          _this.keyCode = void 0;
          _this.rawEvent = void 0;
          _this._isPressed = void 0;
          _this._isPressed = eventType !== SystemEventType.KEY_UP;
          if (typeof keyCode === 'number') {
            _this.keyCode = keyCode;
          } else {
            _this.keyCode = keyCode.keyCode;
            _this.rawEvent = keyCode;
          }
          _this.windowId = 0;
          return _this;
        }
        _createClass(EventKeyboard, [{
          key: "isPressed",
          get: function get() {
            return this._isPressed;
          }
        }]);
        return EventKeyboard;
      }(Event));
      Event.EventKeyboard = EventKeyboard;

      var EventMouse = exports('eE', function (_Event) {
        _inheritsLoose(EventMouse, _Event);
        function EventMouse(eventType, bubbles, prevLoc, windowId) {
          var _this;
          _this = _Event.call(this, eventType, bubbles) || this;
          _this.movementX = 0;
          _this.movementY = 0;
          _this.windowId = 0;
          _this.preventSwallow = false;
          _this._eventType = void 0;
          _this._button = EventMouse.BUTTON_MISSING;
          _this._x = 0;
          _this._y = 0;
          _this._prevX = 0;
          _this._prevY = 0;
          _this._scrollX = 0;
          _this._scrollY = 0;
          _this._eventType = eventType;
          if (prevLoc) {
            _this._prevX = prevLoc.x;
            _this._prevY = prevLoc.y;
          }
          _this.windowId = windowId !== null && windowId !== void 0 ? windowId : _this.windowId;
          return _this;
        }
        var _proto = EventMouse.prototype;
        _proto.setScrollData = function setScrollData(scrollX, scrollY) {
          this._scrollX = scrollX;
          this._scrollY = scrollY;
        };
        _proto.getScrollX = function getScrollX() {
          return this._scrollX;
        };
        _proto.getScrollY = function getScrollY() {
          return this._scrollY;
        };
        _proto.setLocation = function setLocation(x, y) {
          this._x = x;
          this._y = y;
        };
        _proto.getLocation = function getLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x, this._y);
          return out;
        };
        _proto.getLocationInView = function getLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x, legacyCC.view._designResolutionSize.height - this._y);
          return out;
        };
        _proto.getUILocation = function getUILocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x, this._y);
          legacyCC.view._convertToUISpace(out);
          return out;
        };
        _proto.getPreviousLocation = function getPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._prevX, this._prevY);
          return out;
        };
        _proto.getUIPreviousLocation = function getUIPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._prevX, this._prevY);
          legacyCC.view._convertToUISpace(out);
          return out;
        };
        _proto.getDelta = function getDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x - this._prevX, this._y - this._prevY);
          return out;
        };
        _proto.getDeltaX = function getDeltaX() {
          return this._x - this._prevX;
        };
        _proto.getDeltaY = function getDeltaY() {
          return this._y - this._prevY;
        };
        _proto.getUIDelta = function getUIDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, (this._x - this._prevX) / legacyCC.view.getScaleX(), (this._y - this._prevY) / legacyCC.view.getScaleY());
          return out;
        };
        _proto.getUIDeltaX = function getUIDeltaX() {
          return (this._x - this._prevX) / legacyCC.view.getScaleX();
        };
        _proto.getUIDeltaY = function getUIDeltaY() {
          return (this._y - this._prevY) / legacyCC.view.getScaleY();
        };
        _proto.setButton = function setButton(button) {
          this._button = button;
        };
        _proto.getButton = function getButton() {
          return this._button;
        };
        _proto.getLocationX = function getLocationX() {
          return this._x;
        };
        _proto.getLocationY = function getLocationY() {
          return this._y;
        };
        _proto.getUILocationX = function getUILocationX() {
          var viewport = legacyCC.view.getViewportRect();
          return (this._x - viewport.x) / legacyCC.view.getScaleX();
        };
        _proto.getUILocationY = function getUILocationY() {
          var viewport = legacyCC.view.getViewportRect();
          return (this._y - viewport.y) / legacyCC.view.getScaleY();
        };
        _createClass(EventMouse, [{
          key: "eventType",
          get: function get() {
            return this._eventType;
          }
        }]);
        return EventMouse;
      }(Event));
      EventMouse.BUTTON_MISSING = -1;
      EventMouse.BUTTON_LEFT = 0;
      EventMouse.BUTTON_RIGHT = 2;
      EventMouse.BUTTON_MIDDLE = 1;
      EventMouse.BUTTON_4 = 3;
      EventMouse.BUTTON_5 = 4;
      EventMouse.BUTTON_6 = 5;
      EventMouse.BUTTON_7 = 6;
      EventMouse.BUTTON_8 = 7;
      Event.EventMouse = EventMouse;

      var _vec2$2 = new Vec2();
      var EventTouch = exports('eF', function (_Event) {
        _inheritsLoose(EventTouch, _Event);
        function EventTouch(changedTouches, bubbles, eventType, touches) {
          var _this;
          if (touches === void 0) {
            touches = [];
          }
          _this = _Event.call(this, eventType, bubbles) || this;
          _this.touch = null;
          _this.simulate = false;
          _this.windowId = 0;
          _this.preventSwallow = false;
          _this._eventCode = void 0;
          _this._touches = void 0;
          _this._allTouches = void 0;
          _this._eventCode = eventType;
          _this._touches = changedTouches || [];
          _this._allTouches = touches;
          return _this;
        }
        var _proto = EventTouch.prototype;
        _proto.getEventCode = function getEventCode() {
          return this._eventCode;
        };
        _proto.getTouches = function getTouches() {
          return this._touches;
        };
        _proto.getAllTouches = function getAllTouches() {
          return this._allTouches;
        };
        _proto.setLocation = function setLocation(x, y) {
          if (this.touch) {
            this.touch.setTouchInfo(this.touch.getID(), x, y);
          }
        };
        _proto.getLocation = function getLocation(out) {
          return this.touch ? this.touch.getLocation(out) : new Vec2();
        };
        _proto.getUILocation = function getUILocation(out) {
          return this.touch ? this.touch.getUILocation(out) : new Vec2();
        };
        _proto.getLocationInView = function getLocationInView(out) {
          return this.touch ? this.touch.getLocationInView(out) : new Vec2();
        };
        _proto.getPreviousLocation = function getPreviousLocation(out) {
          return this.touch ? this.touch.getPreviousLocation(out) : new Vec2();
        };
        _proto.getStartLocation = function getStartLocation(out) {
          return this.touch ? this.touch.getStartLocation(out) : new Vec2();
        };
        _proto.getUIStartLocation = function getUIStartLocation(out) {
          return this.touch ? this.touch.getUIStartLocation(out) : new Vec2();
        };
        _proto.getID = function getID() {
          return this.touch ? this.touch.getID() : null;
        };
        _proto.getDelta = function getDelta(out) {
          return this.touch ? this.touch.getDelta(out) : new Vec2();
        };
        _proto.getUIDelta = function getUIDelta(out) {
          return this.touch ? this.touch.getUIDelta(out) : new Vec2();
        };
        _proto.getDeltaX = function getDeltaX() {
          return this.touch ? this.touch.getDelta(_vec2$2).x : 0;
        };
        _proto.getDeltaY = function getDeltaY() {
          return this.touch ? this.touch.getDelta(_vec2$2).y : 0;
        };
        _proto.getLocationX = function getLocationX() {
          return this.touch ? this.touch.getLocationX() : 0;
        };
        _proto.getLocationY = function getLocationY() {
          return this.touch ? this.touch.getLocationY() : 0;
        };
        return EventTouch;
      }(Event));
      EventTouch.MAX_TOUCHES = 5;
      Event.EventTouch = EventTouch;

      var EventGamepad = exports('eG', function (_Event) {
        _inheritsLoose(EventGamepad, _Event);
        function EventGamepad(type, gamepad) {
          var _this;
          _this = _Event.call(this, type, false) || this;
          _this.gamepad = void 0;
          _this.gamepad = gamepad;
          return _this;
        }
        return EventGamepad;
      }(Event));

      var EventHandle = exports('eH', function (_Event) {
        _inheritsLoose(EventHandle, _Event);
        function EventHandle(eventType, handleInputDevice) {
          var _this;
          _this = _Event.call(this, eventType, false) || this;
          _this.handleInputDevice = void 0;
          _this.handleInputDevice = handleInputDevice;
          return _this;
        }
        return EventHandle;
      }(Event));

      var EventHMD = exports('eI', function (_Event) {
        _inheritsLoose(EventHMD, _Event);
        function EventHMD(eventType, hmdInputDevice) {
          var _this;
          _this = _Event.call(this, eventType, false) || this;
          _this.hmdInputDevice = void 0;
          _this.hmdInputDevice = hmdInputDevice;
          return _this;
        }
        return EventHMD;
      }(Event));

      var EventHandheld = exports('eJ', function (_Event) {
        _inheritsLoose(EventHandheld, _Event);
        function EventHandheld(eventType, handheldInputDevice) {
          var _this;
          _this = _Event.call(this, eventType, false) || this;
          _this.handheldInputDevice = void 0;
          _this.handheldInputDevice = handheldInputDevice;
          return _this;
        }
        return EventHandheld;
      }(Event));

      var Acceleration = exports('eK', function Acceleration(x, y, z, timestamp) {
        if (x === void 0) {
          x = 0;
        }
        if (y === void 0) {
          y = 0;
        }
        if (z === void 0) {
          z = 0;
        }
        if (timestamp === void 0) {
          timestamp = 0;
        }
        this.x = void 0;
        this.y = void 0;
        this.z = void 0;
        this.timestamp = void 0;
        this.x = x;
        this.y = y;
        this.z = z;
        this.timestamp = timestamp;
      });

      var KeyCode; exports('eL', KeyCode);
      (function (KeyCode) {
        KeyCode[KeyCode["NONE"] = 0] = "NONE";
        KeyCode[KeyCode["MOBILE_BACK"] = 6] = "MOBILE_BACK";
        KeyCode[KeyCode["BACKSPACE"] = 8] = "BACKSPACE";
        KeyCode[KeyCode["TAB"] = 9] = "TAB";
        KeyCode[KeyCode["ENTER"] = 13] = "ENTER";
        KeyCode[KeyCode["SHIFT_LEFT"] = 16] = "SHIFT_LEFT";
        KeyCode[KeyCode["CTRL_LEFT"] = 17] = "CTRL_LEFT";
        KeyCode[KeyCode["ALT_LEFT"] = 18] = "ALT_LEFT";
        KeyCode[KeyCode["PAUSE"] = 19] = "PAUSE";
        KeyCode[KeyCode["CAPS_LOCK"] = 20] = "CAPS_LOCK";
        KeyCode[KeyCode["ESCAPE"] = 27] = "ESCAPE";
        KeyCode[KeyCode["SPACE"] = 32] = "SPACE";
        KeyCode[KeyCode["PAGE_UP"] = 33] = "PAGE_UP";
        KeyCode[KeyCode["PAGE_DOWN"] = 34] = "PAGE_DOWN";
        KeyCode[KeyCode["END"] = 35] = "END";
        KeyCode[KeyCode["HOME"] = 36] = "HOME";
        KeyCode[KeyCode["ARROW_LEFT"] = 37] = "ARROW_LEFT";
        KeyCode[KeyCode["ARROW_UP"] = 38] = "ARROW_UP";
        KeyCode[KeyCode["ARROW_RIGHT"] = 39] = "ARROW_RIGHT";
        KeyCode[KeyCode["ARROW_DOWN"] = 40] = "ARROW_DOWN";
        KeyCode[KeyCode["INSERT"] = 45] = "INSERT";
        KeyCode[KeyCode["DELETE"] = 46] = "DELETE";
        KeyCode[KeyCode["DIGIT_0"] = 48] = "DIGIT_0";
        KeyCode[KeyCode["DIGIT_1"] = 49] = "DIGIT_1";
        KeyCode[KeyCode["DIGIT_2"] = 50] = "DIGIT_2";
        KeyCode[KeyCode["DIGIT_3"] = 51] = "DIGIT_3";
        KeyCode[KeyCode["DIGIT_4"] = 52] = "DIGIT_4";
        KeyCode[KeyCode["DIGIT_5"] = 53] = "DIGIT_5";
        KeyCode[KeyCode["DIGIT_6"] = 54] = "DIGIT_6";
        KeyCode[KeyCode["DIGIT_7"] = 55] = "DIGIT_7";
        KeyCode[KeyCode["DIGIT_8"] = 56] = "DIGIT_8";
        KeyCode[KeyCode["DIGIT_9"] = 57] = "DIGIT_9";
        KeyCode[KeyCode["KEY_A"] = 65] = "KEY_A";
        KeyCode[KeyCode["KEY_B"] = 66] = "KEY_B";
        KeyCode[KeyCode["KEY_C"] = 67] = "KEY_C";
        KeyCode[KeyCode["KEY_D"] = 68] = "KEY_D";
        KeyCode[KeyCode["KEY_E"] = 69] = "KEY_E";
        KeyCode[KeyCode["KEY_F"] = 70] = "KEY_F";
        KeyCode[KeyCode["KEY_G"] = 71] = "KEY_G";
        KeyCode[KeyCode["KEY_H"] = 72] = "KEY_H";
        KeyCode[KeyCode["KEY_I"] = 73] = "KEY_I";
        KeyCode[KeyCode["KEY_J"] = 74] = "KEY_J";
        KeyCode[KeyCode["KEY_K"] = 75] = "KEY_K";
        KeyCode[KeyCode["KEY_L"] = 76] = "KEY_L";
        KeyCode[KeyCode["KEY_M"] = 77] = "KEY_M";
        KeyCode[KeyCode["KEY_N"] = 78] = "KEY_N";
        KeyCode[KeyCode["KEY_O"] = 79] = "KEY_O";
        KeyCode[KeyCode["KEY_P"] = 80] = "KEY_P";
        KeyCode[KeyCode["KEY_Q"] = 81] = "KEY_Q";
        KeyCode[KeyCode["KEY_R"] = 82] = "KEY_R";
        KeyCode[KeyCode["KEY_S"] = 83] = "KEY_S";
        KeyCode[KeyCode["KEY_T"] = 84] = "KEY_T";
        KeyCode[KeyCode["KEY_U"] = 85] = "KEY_U";
        KeyCode[KeyCode["KEY_V"] = 86] = "KEY_V";
        KeyCode[KeyCode["KEY_W"] = 87] = "KEY_W";
        KeyCode[KeyCode["KEY_X"] = 88] = "KEY_X";
        KeyCode[KeyCode["KEY_Y"] = 89] = "KEY_Y";
        KeyCode[KeyCode["KEY_Z"] = 90] = "KEY_Z";
        KeyCode[KeyCode["NUM_0"] = 96] = "NUM_0";
        KeyCode[KeyCode["NUM_1"] = 97] = "NUM_1";
        KeyCode[KeyCode["NUM_2"] = 98] = "NUM_2";
        KeyCode[KeyCode["NUM_3"] = 99] = "NUM_3";
        KeyCode[KeyCode["NUM_4"] = 100] = "NUM_4";
        KeyCode[KeyCode["NUM_5"] = 101] = "NUM_5";
        KeyCode[KeyCode["NUM_6"] = 102] = "NUM_6";
        KeyCode[KeyCode["NUM_7"] = 103] = "NUM_7";
        KeyCode[KeyCode["NUM_8"] = 104] = "NUM_8";
        KeyCode[KeyCode["NUM_9"] = 105] = "NUM_9";
        KeyCode[KeyCode["NUM_MULTIPLY"] = 106] = "NUM_MULTIPLY";
        KeyCode[KeyCode["NUM_PLUS"] = 107] = "NUM_PLUS";
        KeyCode[KeyCode["NUM_SUBTRACT"] = 109] = "NUM_SUBTRACT";
        KeyCode[KeyCode["NUM_DECIMAL"] = 110] = "NUM_DECIMAL";
        KeyCode[KeyCode["NUM_DIVIDE"] = 111] = "NUM_DIVIDE";
        KeyCode[KeyCode["F1"] = 112] = "F1";
        KeyCode[KeyCode["F2"] = 113] = "F2";
        KeyCode[KeyCode["F3"] = 114] = "F3";
        KeyCode[KeyCode["F4"] = 115] = "F4";
        KeyCode[KeyCode["F5"] = 116] = "F5";
        KeyCode[KeyCode["F6"] = 117] = "F6";
        KeyCode[KeyCode["F7"] = 118] = "F7";
        KeyCode[KeyCode["F8"] = 119] = "F8";
        KeyCode[KeyCode["F9"] = 120] = "F9";
        KeyCode[KeyCode["F10"] = 121] = "F10";
        KeyCode[KeyCode["F11"] = 122] = "F11";
        KeyCode[KeyCode["F12"] = 123] = "F12";
        KeyCode[KeyCode["NUM_LOCK"] = 144] = "NUM_LOCK";
        KeyCode[KeyCode["SCROLL_LOCK"] = 145] = "SCROLL_LOCK";
        KeyCode[KeyCode["SEMICOLON"] = 186] = "SEMICOLON";
        KeyCode[KeyCode["EQUAL"] = 187] = "EQUAL";
        KeyCode[KeyCode["COMMA"] = 188] = "COMMA";
        KeyCode[KeyCode["DASH"] = 189] = "DASH";
        KeyCode[KeyCode["PERIOD"] = 190] = "PERIOD";
        KeyCode[KeyCode["SLASH"] = 191] = "SLASH";
        KeyCode[KeyCode["BACK_QUOTE"] = 192] = "BACK_QUOTE";
        KeyCode[KeyCode["BRACKET_LEFT"] = 219] = "BRACKET_LEFT";
        KeyCode[KeyCode["BACKSLASH"] = 220] = "BACKSLASH";
        KeyCode[KeyCode["BRACKET_RIGHT"] = 221] = "BRACKET_RIGHT";
        KeyCode[KeyCode["QUOTE"] = 222] = "QUOTE";
        KeyCode[KeyCode["SHIFT_RIGHT"] = 2000] = "SHIFT_RIGHT";
        KeyCode[KeyCode["CTRL_RIGHT"] = 2001] = "CTRL_RIGHT";
        KeyCode[KeyCode["ALT_RIGHT"] = 2002] = "ALT_RIGHT";
        KeyCode[KeyCode["NUM_ENTER"] = 2003] = "NUM_ENTER";
      })(KeyCode || (exports('eL', KeyCode = {})));

      var _vec2$1 = new Vec2();
      var Touch = exports('eM', function () {
        function Touch(x, y, id) {
          if (id === void 0) {
            id = 0;
          }
          this._point = new Vec2();
          this._prevPoint = new Vec2();
          this._lastModified = 0;
          this._id = 0;
          this._startPoint = new Vec2();
          this._startPointCaptured = false;
          this.setTouchInfo(id, x, y);
        }
        var _proto = Touch.prototype;
        _proto.getLocation = function getLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point.x, this._point.y);
          return out;
        };
        _proto.getLocationX = function getLocationX() {
          return this._point.x;
        };
        _proto.getLocationY = function getLocationY() {
          return this._point.y;
        };
        _proto.getUILocation = function getUILocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point.x, this._point.y);
          legacyCC.view._convertToUISpace(out);
          return out;
        };
        _proto.getUILocationX = function getUILocationX() {
          var viewport = legacyCC.view.getViewportRect();
          return (this._point.x - viewport.x) / legacyCC.view.getScaleX();
        };
        _proto.getUILocationY = function getUILocationY() {
          var viewport = legacyCC.view.getViewportRect();
          return (this._point.y - viewport.y) / legacyCC.view.getScaleY();
        };
        _proto.getPreviousLocation = function getPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._prevPoint.x, this._prevPoint.y);
          return out;
        };
        _proto.getUIPreviousLocation = function getUIPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._prevPoint.x, this._prevPoint.y);
          legacyCC.view._convertToUISpace(out);
          return out;
        };
        _proto.getStartLocation = function getStartLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._startPoint.x, this._startPoint.y);
          return out;
        };
        _proto.getUIStartLocation = function getUIStartLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._startPoint.x, this._startPoint.y);
          legacyCC.view._convertToUISpace(out);
          return out;
        };
        _proto.getDelta = function getDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point);
          out.subtract(this._prevPoint);
          return out;
        };
        _proto.getUIDelta = function getUIDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          _vec2$1.set(this._point);
          _vec2$1.subtract(this._prevPoint);
          out.set(legacyCC.view.getScaleX(), legacyCC.view.getScaleY());
          Vec2.divide(out, _vec2$1, out);
          return out;
        };
        _proto.getLocationInView = function getLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point.x, legacyCC.view._designResolutionSize.height - this._point.y);
          return out;
        };
        _proto.getPreviousLocationInView = function getPreviousLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._prevPoint.x, legacyCC.view._designResolutionSize.height - this._prevPoint.y);
          return out;
        };
        _proto.getStartLocationInView = function getStartLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._startPoint.x, legacyCC.view._designResolutionSize.height - this._startPoint.y);
          return out;
        };
        _proto.getID = function getID() {
          return this._id;
        };
        _proto.setTouchInfo = function setTouchInfo(id, x, y) {
          if (id === void 0) {
            id = 0;
          }
          if (x === void 0) {
            x = 0;
          }
          if (y === void 0) {
            y = 0;
          }
          this._prevPoint = this._point;
          this._point = new Vec2(x || 0, y || 0);
          this._id = id;
          if (!this._startPointCaptured) {
            this._startPoint = new Vec2(this._point);
            this._startPointCaptured = true;
          }
        };
        _proto.setPoint = function setPoint(x, y) {
          if (typeof x === 'object') {
            this._point.x = x.x;
            this._point.y = x.y;
          } else {
            this._point.x = x || 0;
            this._point.y = y || 0;
          }
          this._lastModified = legacyCC.game.frameStartTime;
        };
        _proto.setPrevPoint = function setPrevPoint(x, y) {
          if (typeof x === 'object') {
            this._prevPoint = new Vec2(x.x, x.y);
          } else {
            this._prevPoint = new Vec2(x || 0, y || 0);
          }
          this._lastModified = legacyCC.game.frameStartTime;
        };
        _proto.clone = function clone() {
          var touchID = this.getID();
          this.getStartLocation(_vec2$1);
          var clonedTouch = new Touch(_vec2$1.x, _vec2$1.y, touchID);
          this.getLocation(_vec2$1);
          clonedTouch.setPoint(_vec2$1.x, _vec2$1.y);
          this.getPreviousLocation(_vec2$1);
          clonedTouch.setPrevPoint(_vec2$1);
          return clonedTouch;
        };
        _createClass(Touch, [{
          key: "lastModified",
          get: function get() {
            return this._lastModified;
          }
        }]);
        return Touch;
      }());
      legacyCC.Touch = Touch;

      var AccelerometerInputSource = function () {
        function AccelerometerInputSource() {
          this._intervalInMileSeconds = 200;
          this._accelTimer = 0;
          this._eventTarget = new EventTarget();
          this._deviceEventName = void 0;
          this._globalEventClass = void 0;
          this._didAccelerateFunc = void 0;
          this._globalEventClass = window.DeviceMotionEvent || window.DeviceOrientationEvent;
          if (systemInfo.browserType === BrowserType.MOBILE_QQ) {
            this._globalEventClass = window.DeviceOrientationEvent;
          }
          this._deviceEventName = this._globalEventClass === window.DeviceMotionEvent ? 'devicemotion' : 'deviceorientation';
          this._didAccelerateFunc = this._didAccelerate.bind(this);
        }
        var _proto = AccelerometerInputSource.prototype;
        _proto._registerEvent = function _registerEvent() {
          this._accelTimer = performance.now();
          window.addEventListener(this._deviceEventName, this._didAccelerateFunc, false);
        };
        _proto._unregisterEvent = function _unregisterEvent() {
          this._accelTimer = 0;
          window.removeEventListener(this._deviceEventName, this._didAccelerateFunc, false);
        };
        _proto._didAccelerate = function _didAccelerate(event) {
          var now = performance.now();
          if (now - this._accelTimer < this._intervalInMileSeconds) {
            return;
          }
          this._accelTimer = now;
          var x = 0;
          var y = 0;
          var z = 0;
          if (this._globalEventClass === window.DeviceMotionEvent) {
            var deviceMotionEvent = event;
            var _eventAcceleration = deviceMotionEvent.accelerationIncludingGravity;
            x = ((_eventAcceleration === null || _eventAcceleration === void 0 ? void 0 : _eventAcceleration.x) || 0) * 0.1;
            y = ((_eventAcceleration === null || _eventAcceleration === void 0 ? void 0 : _eventAcceleration.y) || 0) * 0.1;
            z = ((_eventAcceleration === null || _eventAcceleration === void 0 ? void 0 : _eventAcceleration.z) || 0) * 0.1;
          } else {
            var deviceOrientationEvent = event;
            x = (deviceOrientationEvent.gamma || 0) / 90 * 0.981;
            y = -((deviceOrientationEvent.beta || 0) / 90) * 0.981;
            z = (deviceOrientationEvent.alpha || 0) / 90 * 0.981;
          }
          if (screenAdapter.isFrameRotated) {
            var tmp = x;
            x = -y;
            y = tmp;
          }
          var LANDSCAPE_LEFT = -90;
          var PORTRAIT_UPSIDE_DOWN = 180;
          var LANDSCAPE_RIGHT = 90;
          var tmpX = x;
          if (window.orientation === LANDSCAPE_RIGHT) {
            x = -y;
            y = tmpX;
          } else if (window.orientation === LANDSCAPE_LEFT) {
            x = y;
            y = -tmpX;
          } else if (window.orientation === PORTRAIT_UPSIDE_DOWN) {
            x = -x;
            y = -y;
          }
          if (systemInfo.os === OS.ANDROID && systemInfo.browserType !== BrowserType.MOBILE_QQ) {
            x = -x;
            y = -y;
          }
          var timestamp = performance.now();
          var acceleration = new Acceleration(x, y, z, timestamp);
          var eventAcceleration = new EventAcceleration(acceleration);
          this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration);
        };
        _proto.start = function start() {
          var _this = this;
          if (window.DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === 'function') {
            DeviceMotionEvent.requestPermission().then(function (response) {
              if (response === 'granted') {
                _this._registerEvent();
              }
            })["catch"](function (e) {
              warn(e);
            });
          } else {
            this._registerEvent();
          }
        };
        _proto.stop = function stop() {
          this._unregisterEvent();
        };
        _proto.setInterval = function setInterval(intervalInMileSeconds) {
          this._intervalInMileSeconds = intervalInMileSeconds;
        };
        _proto.on = function on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        return AccelerometerInputSource;
      }();

      var InputSource = function InputSource() {};
      var InputSourceAxis1D = function (_InputSource) {
        _inheritsLoose(InputSourceAxis1D, _InputSource);
        function InputSourceAxis1D() {
          return _InputSource.apply(this, arguments) || this;
        }
        var _proto = InputSourceAxis1D.prototype;
        _proto.getValue = function getValue() {
          throw new Error('Method not implemented.');
        };
        return InputSourceAxis1D;
      }(InputSource);
      var InputSourceAxis2D = function (_InputSource2) {
        _inheritsLoose(InputSourceAxis2D, _InputSource2);
        function InputSourceAxis2D() {
          return _InputSource2.apply(this, arguments) || this;
        }
        var _proto2 = InputSourceAxis2D.prototype;
        _proto2.getValue = function getValue() {
          throw new Error('Method not implemented.');
        };
        return InputSourceAxis2D;
      }(InputSource);
      var InputSourceAxis3D = function (_InputSource3) {
        _inheritsLoose(InputSourceAxis3D, _InputSource3);
        function InputSourceAxis3D() {
          return _InputSource3.apply(this, arguments) || this;
        }
        var _proto3 = InputSourceAxis3D.prototype;
        _proto3.getValue = function getValue() {
          throw new Error('Method not implemented.');
        };
        return InputSourceAxis3D;
      }(InputSource);
      var InputSourceQuat = function (_InputSource4) {
        _inheritsLoose(InputSourceQuat, _InputSource4);
        function InputSourceQuat() {
          return _InputSource4.apply(this, arguments) || this;
        }
        var _proto4 = InputSourceQuat.prototype;
        _proto4.getValue = function getValue() {
          throw new Error('Method not implemented.');
        };
        return InputSourceQuat;
      }(InputSource);
      var CompositeInputSourceAxis1D = function (_InputSourceAxis1D) {
        _inheritsLoose(CompositeInputSourceAxis1D, _InputSourceAxis1D);
        function CompositeInputSourceAxis1D(options) {
          var _this;
          _this = _InputSourceAxis1D.call(this) || this;
          _this.positive = void 0;
          _this.negative = void 0;
          _this.positive = options.positive;
          _this.negative = options.negative;
          return _this;
        }
        var _proto5 = CompositeInputSourceAxis1D.prototype;
        _proto5.getValue = function getValue() {
          var positiveValue = this.positive.getValue();
          var negativeValue = this.negative.getValue();
          if (Math.abs(positiveValue) > Math.abs(negativeValue)) {
            return positiveValue;
          }
          return -negativeValue;
        };
        return CompositeInputSourceAxis1D;
      }(InputSourceAxis1D);
      var CompositeInputSourceAxis2D = function (_InputSourceAxis2D) {
        _inheritsLoose(CompositeInputSourceAxis2D, _InputSourceAxis2D);
        function CompositeInputSourceAxis2D(options) {
          var _this2;
          _this2 = _InputSourceAxis2D.call(this) || this;
          _this2.up = void 0;
          _this2.down = void 0;
          _this2.left = void 0;
          _this2.right = void 0;
          _this2.xAxis = void 0;
          _this2.yAxis = void 0;
          _this2.up = options.up;
          _this2.down = options.down;
          _this2.left = options.left;
          _this2.right = options.right;
          _this2.xAxis = new CompositeInputSourceAxis1D({
            positive: _this2.right,
            negative: _this2.left
          });
          _this2.yAxis = new CompositeInputSourceAxis1D({
            positive: _this2.up,
            negative: _this2.down
          });
          return _this2;
        }
        var _proto6 = CompositeInputSourceAxis2D.prototype;
        _proto6.getValue = function getValue() {
          return new Vec2(this.xAxis.getValue(), this.yAxis.getValue());
        };
        return CompositeInputSourceAxis2D;
      }(InputSourceAxis2D);
      (function (_InputSourceAxis3D) {
        _inheritsLoose(CompositeInputSourceAxis3D, _InputSourceAxis3D);
        function CompositeInputSourceAxis3D(options) {
          var _this3;
          _this3 = _InputSourceAxis3D.call(this) || this;
          _this3.up = void 0;
          _this3.down = void 0;
          _this3.left = void 0;
          _this3.right = void 0;
          _this3.forward = void 0;
          _this3.backward = void 0;
          _this3.xAxis = void 0;
          _this3.yAxis = void 0;
          _this3.zAxis = void 0;
          _this3.up = options.up;
          _this3.down = options.down;
          _this3.left = options.left;
          _this3.right = options.right;
          _this3.forward = options.forward;
          _this3.backward = options.backward;
          _this3.xAxis = new CompositeInputSourceAxis1D({
            positive: _this3.right,
            negative: _this3.left
          });
          _this3.yAxis = new CompositeInputSourceAxis1D({
            positive: _this3.up,
            negative: _this3.down
          });
          _this3.zAxis = new CompositeInputSourceAxis1D({
            positive: _this3.forward,
            negative: _this3.backward
          });
          return _this3;
        }
        var _proto7 = CompositeInputSourceAxis3D.prototype;
        _proto7.getValue = function getValue() {
          return new Vec3(this.xAxis.getValue(), this.yAxis.getValue(), this.zAxis.getValue());
        };
        return CompositeInputSourceAxis3D;
      })(InputSourceAxis3D);
      var InputSourceButton = function (_InputSourceAxis1D2) {
        _inheritsLoose(InputSourceButton, _InputSourceAxis1D2);
        function InputSourceButton() {
          return _InputSourceAxis1D2.apply(this, arguments) || this;
        }
        var _proto8 = InputSourceButton.prototype;
        _proto8.getValue = function getValue() {
          return _InputSourceAxis1D2.prototype.getValue.call(this);
        };
        return InputSourceButton;
      }(InputSourceAxis1D);
      var InputSourceDpad = function (_CompositeInputSource) {
        _inheritsLoose(InputSourceDpad, _CompositeInputSource);
        function InputSourceDpad() {
          return _CompositeInputSource.apply(this, arguments) || this;
        }
        return InputSourceDpad;
      }(CompositeInputSourceAxis2D);
      var InputSourceStick = function (_CompositeInputSource2) {
        _inheritsLoose(InputSourceStick, _CompositeInputSource2);
        function InputSourceStick() {
          return _CompositeInputSource2.apply(this, arguments) || this;
        }
        return InputSourceStick;
      }(CompositeInputSourceAxis2D);
      var InputSourceOrientation = function (_InputSourceQuat) {
        _inheritsLoose(InputSourceOrientation, _InputSourceQuat);
        function InputSourceOrientation() {
          return _InputSourceQuat.apply(this, arguments) || this;
        }
        var _proto9 = InputSourceOrientation.prototype;
        _proto9.getValue = function getValue() {
          return _InputSourceQuat.prototype.getValue.call(this);
        };
        return InputSourceOrientation;
      }(InputSourceQuat);
      var InputSourcePosition = function (_InputSourceAxis3D2) {
        _inheritsLoose(InputSourcePosition, _InputSourceAxis3D2);
        function InputSourcePosition() {
          return _InputSourceAxis3D2.apply(this, arguments) || this;
        }
        var _proto10 = InputSourcePosition.prototype;
        _proto10.getValue = function getValue() {
          return _InputSourceAxis3D2.prototype.getValue.call(this);
        };
        return InputSourcePosition;
      }(InputSourceAxis3D);
      var InputSourceTouch = function (_InputSourceAxis1D3) {
        _inheritsLoose(InputSourceTouch, _InputSourceAxis1D3);
        function InputSourceTouch() {
          return _InputSourceAxis1D3.apply(this, arguments) || this;
        }
        var _proto11 = InputSourceTouch.prototype;
        _proto11.getValue = function getValue() {
          return _InputSourceAxis1D3.prototype.getValue.call(this);
        };
        return InputSourceTouch;
      }(InputSourceAxis1D);

      var BUTTON_SOUTH = 0;
      var BUTTON_EAST = 1;
      var BUTTON_WEST = 2;
      var BUTTON_NORTH = 3;
      var BUTTON_L1 = 4;
      var BUTTON_R1 = 5;
      var BUTTON_L2 = 6;
      var BUTTON_R2 = 7;
      var BUTTON_SHARE = 8;
      var BUTTON_OPTIONS = 9;
      var BUTTON_L3 = 10;
      var BUTTON_R3 = 11;
      var BUTTON_DPAD_UP = 12;
      var BUTTON_DPAD_DOWN = 13;
      var BUTTON_DPAD_LEFT = 14;
      var BUTTON_DPAD_RIGHT = 15;
      var AXIS_LEFT_STICK_X = 0;
      var AXIS_LEFT_STICK_Y = 1;
      var AXIS_RIGHT_STICK_X = 2;
      var AXIS_RIGHT_STICK_Y = 3;
      var XR_TRIGGER = 0;
      var XR_GRIP = 1;
      var XR_TOUCHPAD = 2;
      var XR_STICK = 3;
      var XR_BUTTON_1 = 4;
      var XR_BUTTON_2 = 5;
      var XR_AXIS_TOUCHPAD_X = 0;
      var XR_AXIS_TOUCHPAD_Y = 1;
      var XR_AXIS_STICK_X = 2;
      var XR_AXIS_STICK_Y = 3;
      var EPSILON$2 = 0.01;
      var XRLeftHandedness = 'left';
      var XRRightHandedness = 'right';
      var devicesTmp = [];
      var Pose$2;
      (function (Pose) {
        Pose[Pose["HAND_LEFT"] = 1] = "HAND_LEFT";
        Pose[Pose["HAND_RIGHT"] = 4] = "HAND_RIGHT";
        Pose[Pose["AIM_LEFT"] = 2] = "AIM_LEFT";
        Pose[Pose["AIM_RIGHT"] = 5] = "AIM_RIGHT";
      })(Pose$2 || (Pose$2 = {}));
      var GamepadInputDevice = function () {
        function GamepadInputDevice(deviceId) {
          var _this$_webPoseState;
          this._buttonNorth = void 0;
          this._buttonEast = void 0;
          this._buttonWest = void 0;
          this._buttonSouth = void 0;
          this._buttonL1 = void 0;
          this._buttonL2 = void 0;
          this._buttonL3 = void 0;
          this._buttonR1 = void 0;
          this._buttonR2 = void 0;
          this._buttonR3 = void 0;
          this._buttonShare = void 0;
          this._buttonOptions = void 0;
          this._dpad = void 0;
          this._leftStick = void 0;
          this._rightStick = void 0;
          this._buttonStart = void 0;
          this._gripLeft = void 0;
          this._gripRight = void 0;
          this._handLeftPosition = void 0;
          this._handLeftOrientation = void 0;
          this._handRightPosition = void 0;
          this._handRightOrientation = void 0;
          this._aimLeftPosition = void 0;
          this._aimLeftOrientation = void 0;
          this._aimRightPosition = void 0;
          this._aimRightOrientation = void 0;
          this._deviceId = -1;
          this._connected = false;
          this._webPoseState = (_this$_webPoseState = {}, _this$_webPoseState[Pose$2.HAND_LEFT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState[Pose$2.HAND_RIGHT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState[Pose$2.AIM_LEFT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState[Pose$2.AIM_RIGHT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState);
          this._deviceId = deviceId;
          this._initInputSource();
        }
        GamepadInputDevice._init = function _init() {
          if (!systemInfo.hasFeature(Feature$1.EVENT_GAMEPAD)) {
            return;
          }
          GamepadInputDevice._registerEvent();
        };
        GamepadInputDevice._on = function _on(eventType, cb, target) {
          GamepadInputDevice._eventTarget.on(eventType, cb, target);
        };
        GamepadInputDevice._removeInputDevice = function _removeInputDevice(id) {
          var removeIndex = GamepadInputDevice.all.findIndex(function (device) {
            return device.deviceId === id;
          });
          if (removeIndex === -1) {
            return;
          }
          fastRemoveAt$2(GamepadInputDevice.all, removeIndex);
        };
        GamepadInputDevice._getOrCreateInputDevice = function _getOrCreateInputDevice(id, connected) {
          var device = GamepadInputDevice.all.find(function (device) {
            return device.deviceId === id;
          });
          if (!device) {
            device = new GamepadInputDevice(id);
            GamepadInputDevice.all.push(device);
          }
          device._connected = connected;
          return device;
        };
        GamepadInputDevice._ensureDirectorDefined = function _ensureDirectorDefined(callback) {
          GamepadInputDevice._intervalId = setInterval(function () {
            if (legacyCC.director && legacyCC.Director) {
              clearInterval(GamepadInputDevice._intervalId);
              GamepadInputDevice._intervalId = -1;
              callback();
            }
          }, 50);
        };
        GamepadInputDevice._updateGamepadCnt = function _updateGamepadCnt() {
          var cnt = 0;
          for (var i = 0, l = GamepadInputDevice._cachedWebGamepads.length; i < l; i++) {
            if (GamepadInputDevice._cachedWebGamepads[i]) cnt++;
          }
          GamepadInputDevice._totalGamepadCnt = cnt;
        };
        GamepadInputDevice._registerEvent = function _registerEvent() {
          GamepadInputDevice._ensureDirectorDefined(function () {
            GamepadInputDevice._cachedWebGamepads = GamepadInputDevice._getWebGamePads();
            GamepadInputDevice._updateGamepadCnt();
            legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, GamepadInputDevice._scanGamepads);
          });
          window.addEventListener('gamepadconnected', function (e) {
            GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = e.gamepad;
            GamepadInputDevice._updateGamepadCnt();
            var device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, true);
            GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device));
          });
          window.addEventListener('gamepaddisconnected', function (e) {
            GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = null;
            GamepadInputDevice._updateGamepadCnt();
            var device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, false);
            GamepadInputDevice._removeInputDevice(e.gamepad.index);
            GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device));
          });
        };
        GamepadInputDevice._scanWebGamepads = function _scanWebGamepads(devices) {
          var allDisconnected = GamepadInputDevice._totalGamepadCnt === 0;
          if (allDisconnected) return;
          var webGamepads = GamepadInputDevice._getWebGamePads();
          if (!webGamepads) {
            return;
          }
          for (var i = 0; i < webGamepads.length; ++i) {
            var webGamepad = webGamepads[i];
            if (!webGamepad) {
              continue;
            }
            var cachedWebGamepad = GamepadInputDevice._cachedWebGamepads[webGamepad.index];
            if (cachedWebGamepad) {
              var device = void 0;
              var cachedButtons = cachedWebGamepad.buttons;
              for (var j = 0; j < cachedButtons.length; ++j) {
                var cachedButton = cachedButtons[j];
                var button = webGamepad.buttons[j];
                if (Math.abs(cachedButton.value - button.value) > EPSILON$2) {
                  device = GamepadInputDevice._getOrCreateInputDevice(webGamepad.index, true);
                  break;
                }
              }
              if (device) {
                devices.push(device);
                continue;
              }
              var cachedAxes = cachedWebGamepad.axes;
              for (var _j = 0; _j < cachedAxes.length; ++_j) {
                var cachedAxisValue = cachedAxes[_j];
                var axisValue = webGamepad.axes[_j];
                if (Math.abs(cachedAxisValue - axisValue) > EPSILON$2) {
                  device = GamepadInputDevice._getOrCreateInputDevice(webGamepad.index, true);
                  break;
                }
              }
              if (device) {
                devices.push(device);
                continue;
              }
            }
          }
          GamepadInputDevice._cachedWebGamepads = webGamepads;
        };
        GamepadInputDevice._scanGamepads = function _scanGamepads() {
          devicesTmp.length = 0;
          GamepadInputDevice._scanWebGamepads(devicesTmp);
          GamepadInputDevice._scanWebXRGamepads(devicesTmp);
          for (var i = 0; i < devicesTmp.length; ++i) {
            var device = devicesTmp[i];
            GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_INPUT, new EventGamepad(InputEventType.GAMEPAD_INPUT, device));
          }
          GamepadInputDevice._scanWebXRGamepadsPose();
        };
        GamepadInputDevice._scanWebXRGamepads = function _scanWebXRGamepads(devices) {
          var _GamepadInputDevice$_, _GamepadInputDevice$_2;
          var webxrGamepadMap = GamepadInputDevice._getWebXRGamepadMap();
          if (!webxrGamepadMap) {
            GamepadInputDevice._cachedWebXRGamepadMap = null;
            if (GamepadInputDevice.xr && GamepadInputDevice.xr._connected) {
              GamepadInputDevice.xr._connected = false;
              GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr));
              devices.push(GamepadInputDevice.xr);
            }
            return;
          }
          if (!GamepadInputDevice.xr) {
            GamepadInputDevice.xr = new GamepadInputDevice(-1);
          }
          var left = webxrGamepadMap.get(XRLeftHandedness);
          var right = webxrGamepadMap.get(XRRightHandedness);
          if (!left && !right) {
            if (GamepadInputDevice.xr._connected) {
              GamepadInputDevice.xr._connected = false;
              GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr));
            }
          } else if (!GamepadInputDevice.xr._connected) {
            GamepadInputDevice.xr._connected = true;
            GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr));
          }
          if (GamepadInputDevice.checkGamepadChanged(left, (_GamepadInputDevice$_ = GamepadInputDevice._cachedWebXRGamepadMap) === null || _GamepadInputDevice$_ === void 0 ? void 0 : _GamepadInputDevice$_.get(XRLeftHandedness))) {
            devices.push(GamepadInputDevice.xr);
          } else if (GamepadInputDevice.checkGamepadChanged(right, (_GamepadInputDevice$_2 = GamepadInputDevice._cachedWebXRGamepadMap) === null || _GamepadInputDevice$_2 === void 0 ? void 0 : _GamepadInputDevice$_2.get(XRRightHandedness))) {
            devices.push(GamepadInputDevice.xr);
          }
          if (!GamepadInputDevice._cachedWebXRGamepadMap) {
            GamepadInputDevice._cachedWebXRGamepadMap = new Map();
          }
          GamepadInputDevice._cachedWebXRGamepadMap.set(XRLeftHandedness, GamepadInputDevice._copyCacheGamepadValue(left));
          GamepadInputDevice._cachedWebXRGamepadMap.set(XRRightHandedness, GamepadInputDevice._copyCacheGamepadValue(right));
        };
        GamepadInputDevice.checkGamepadChanged = function checkGamepadChanged(currGamepad, cachedGamepad) {
          if (!currGamepad && !cachedGamepad) {
            return false;
          } else if (!currGamepad || !cachedGamepad) {
            return true;
          }
          var cachedButtons = cachedGamepad.buttons;
          for (var j = 0; j < cachedButtons.length; ++j) {
            var cachedButton = cachedButtons[j];
            var button = currGamepad.buttons[j];
            if (button.value !== 0 || cachedButton !== 0) {
              return true;
            }
          }
          var cachedAxes = cachedGamepad.axes;
          for (var _j2 = 0; _j2 < cachedAxes.length; ++_j2) {
            var cachedAxisValue = cachedAxes[_j2];
            var axisValue = currGamepad.axes[_j2];
            if (axisValue !== 0 || cachedAxisValue !== 0) {
              return true;
            }
          }
          return false;
        };
        GamepadInputDevice._copyCacheGamepadValue = function _copyCacheGamepadValue(gamepad) {
          if (!gamepad) {
            return undefined;
          }
          var cacheGamepad = {
            buttons: new Array(gamepad.buttons.length),
            axes: new Array(gamepad.axes.length)
          };
          for (var j = 0; j < gamepad.buttons.length; ++j) {
            cacheGamepad.buttons[j] = gamepad.buttons[j].value;
          }
          for (var _j3 = 0; _j3 < gamepad.axes.length; ++_j3) {
            cacheGamepad.axes[_j3] = gamepad.axes[_j3];
          }
          return cacheGamepad;
        };
        GamepadInputDevice._scanWebXRGamepadsPose = function _scanWebXRGamepadsPose() {
          var _globalThis$__globalX;
          var infoList = (_globalThis$__globalX = globalThis.__globalXR) === null || _globalThis$__globalX === void 0 ? void 0 : _globalThis$__globalX.webxrHandlePoseInfos;
          if (!infoList || !GamepadInputDevice.xr) {
            return;
          }
          for (var i = 0; i < infoList.length; ++i) {
            var info = infoList[i];
            GamepadInputDevice.xr._updateWebPoseState(info);
          }
          GamepadInputDevice._eventTarget.emit(InputEventType.HANDLE_POSE_INPUT, new EventGamepad(InputEventType.HANDLE_POSE_INPUT, GamepadInputDevice.xr));
        };
        GamepadInputDevice._getWebXRGamepadMap = function _getWebXRGamepadMap() {
          var _globalThis$__globalX2;
          return (_globalThis$__globalX2 = globalThis.__globalXR) === null || _globalThis$__globalX2 === void 0 ? void 0 : _globalThis$__globalX2.webxrGamepadMap;
        };
        GamepadInputDevice._getWebGamePads = function _getWebGamePads() {
          if (typeof navigator.getGamepads === 'function') {
            return navigator.getGamepads();
          } else if (typeof navigator.webkitGetGamepads === 'function') {
            return navigator.webkitGetGamepads();
          }
          return [];
        };
        GamepadInputDevice._getWebGamepad = function _getWebGamepad(deviceId) {
          var webGamepads = GamepadInputDevice._getWebGamePads();
          for (var i = 0; i < webGamepads.length; ++i) {
            var webGamepad = webGamepads[i];
            if (webGamepad && webGamepad.index === deviceId) {
              return webGamepad;
            }
          }
          return undefined;
        };
        var _proto = GamepadInputDevice.prototype;
        _proto._axisToButtons = function _axisToButtons(axisValue) {
          var value = Math.abs(axisValue);
          if (axisValue > 0) {
            return {
              negative: 0,
              positive: value
            };
          } else if (axisValue < 0) {
            return {
              negative: value,
              positive: 0
            };
          } else {
            return {
              negative: 0,
              positive: 0
            };
          }
        };
        _proto._updateWebPoseState = function _updateWebPoseState(info) {
          if (info.code !== Pose$2.HAND_LEFT && info.code !== Pose$2.AIM_LEFT && info.code !== Pose$2.HAND_RIGHT && info.code !== Pose$2.AIM_RIGHT) {
            return;
          }
          this._webPoseState[info.code] = {
            position: new Vec3(info.position.x, info.position.y, info.position.z),
            orientation: new Quat(info.orientation.x, info.orientation.y, info.orientation.z, info.orientation.w)
          };
        };
        _proto._initInputSource = function _initInputSource() {
          var _this = this;
          this._buttonNorth = new InputSourceButton();
          this._buttonNorth.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_3;
              var webxrGamepad = (_GamepadInputDevice$_3 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_3 === void 0 ? void 0 : _GamepadInputDevice$_3.get(XRLeftHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_2) {
                return webxrGamepad.buttons[XR_BUTTON_2].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_NORTH].value;
            }
            return 0;
          };
          this._buttonEast = new InputSourceButton();
          this._buttonEast.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_4;
              var webxrGamepad = (_GamepadInputDevice$_4 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_4 === void 0 ? void 0 : _GamepadInputDevice$_4.get(XRRightHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_2) {
                return webxrGamepad.buttons[XR_BUTTON_2].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_EAST].value;
            }
            return 0;
          };
          this._buttonWest = new InputSourceButton();
          this._buttonWest.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_5;
              var webxrGamepad = (_GamepadInputDevice$_5 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_5 === void 0 ? void 0 : _GamepadInputDevice$_5.get(XRLeftHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_1) {
                return webxrGamepad.buttons[XR_BUTTON_1].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_WEST].value;
            }
            return 0;
          };
          this._buttonSouth = new InputSourceButton();
          this._buttonSouth.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_6;
              var webxrGamepad = (_GamepadInputDevice$_6 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_6 === void 0 ? void 0 : _GamepadInputDevice$_6.get(XRRightHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_1) {
                return webxrGamepad.buttons[XR_BUTTON_1].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_SOUTH].value;
            }
            return 0;
          };
          this._buttonL1 = new InputSourceButton();
          this._buttonL1.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_L1].value;
            }
            return 0;
          };
          this._buttonL2 = new InputSourceButton();
          this._buttonL2.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_7;
              var webxrGamepad = (_GamepadInputDevice$_7 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_7 === void 0 ? void 0 : _GamepadInputDevice$_7.get(XRLeftHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_TRIGGER) {
                return webxrGamepad.buttons[XR_TRIGGER].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_L2].value;
            }
            return 0;
          };
          this._buttonL3 = new InputSourceButton();
          this._buttonL3.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_8;
              var webxrGamepad = (_GamepadInputDevice$_8 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_8 === void 0 ? void 0 : _GamepadInputDevice$_8.get(XRLeftHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.buttons.length > XR_STICK && webxrGamepad.buttons[XR_STICK].value !== 0) {
                  return webxrGamepad.buttons[XR_STICK].value;
                } else if (webxrGamepad.buttons.length > XR_TOUCHPAD && webxrGamepad.buttons[XR_TOUCHPAD].value !== 0) {
                  return webxrGamepad.buttons[XR_TOUCHPAD].value;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_L3].value;
            }
            return 0;
          };
          this._buttonR1 = new InputSourceButton();
          this._buttonR1.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_R1].value;
            }
            return 0;
          };
          this._buttonR2 = new InputSourceButton();
          this._buttonR2.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_9;
              var webxrGamepad = (_GamepadInputDevice$_9 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_9 === void 0 ? void 0 : _GamepadInputDevice$_9.get(XRRightHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_TRIGGER) {
                return webxrGamepad.buttons[XR_TRIGGER].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_R2].value;
            }
            return 0;
          };
          this._buttonR3 = new InputSourceButton();
          this._buttonR3.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_10;
              var webxrGamepad = (_GamepadInputDevice$_10 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_10 === void 0 ? void 0 : _GamepadInputDevice$_10.get(XRRightHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.buttons.length > XR_STICK && webxrGamepad.buttons[XR_STICK].value !== 0) {
                  return webxrGamepad.buttons[XR_STICK].value;
                } else if (webxrGamepad.buttons.length > XR_TOUCHPAD && webxrGamepad.buttons[XR_TOUCHPAD].value !== 0) {
                  return webxrGamepad.buttons[XR_TOUCHPAD].value;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_R3].value;
            }
            return 0;
          };
          this._buttonShare = new InputSourceButton();
          this._buttonShare.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_SHARE].value;
            }
            return 0;
          };
          this._buttonOptions = new InputSourceButton();
          this._buttonOptions.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_OPTIONS].value;
            }
            return 0;
          };
          var dpadUp = new InputSourceButton();
          dpadUp.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_DPAD_UP].value;
            }
            return 0;
          };
          var dpadDown = new InputSourceButton();
          dpadDown.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_DPAD_DOWN].value;
            }
            return 0;
          };
          var dpadLeft = new InputSourceButton();
          dpadLeft.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_DPAD_LEFT].value;
            }
            return 0;
          };
          var dpadRight = new InputSourceButton();
          dpadRight.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_DPAD_RIGHT].value;
            }
            return 0;
          };
          this._dpad = new InputSourceDpad({
            up: dpadUp,
            down: dpadDown,
            left: dpadLeft,
            right: dpadRight
          });
          var leftStickUp = new InputSourceButton();
          leftStickUp.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_11;
              var webxrGamepad = (_GamepadInputDevice$_11 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_11 === void 0 ? void 0 : _GamepadInputDevice$_11.get(XRLeftHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).negative;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).negative;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_Y]).negative;
            }
            return 0;
          };
          var leftStickDown = new InputSourceButton();
          leftStickDown.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_12;
              var webxrGamepad = (_GamepadInputDevice$_12 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_12 === void 0 ? void 0 : _GamepadInputDevice$_12.get(XRLeftHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).positive;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).positive;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_Y]).positive;
            }
            return 0;
          };
          var leftStickLeft = new InputSourceButton();
          leftStickLeft.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_13;
              var webxrGamepad = (_GamepadInputDevice$_13 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_13 === void 0 ? void 0 : _GamepadInputDevice$_13.get(XRLeftHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).negative;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).negative;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_X]).negative;
            }
            return 0;
          };
          var leftStickRight = new InputSourceButton();
          leftStickRight.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_14;
              var webxrGamepad = (_GamepadInputDevice$_14 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_14 === void 0 ? void 0 : _GamepadInputDevice$_14.get(XRLeftHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).positive;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).positive;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_X]).positive;
            }
            return 0;
          };
          this._leftStick = new InputSourceStick({
            up: leftStickUp,
            down: leftStickDown,
            left: leftStickLeft,
            right: leftStickRight
          });
          var rightStickUp = new InputSourceButton();
          rightStickUp.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_15;
              var webxrGamepad = (_GamepadInputDevice$_15 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_15 === void 0 ? void 0 : _GamepadInputDevice$_15.get(XRRightHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).negative;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).negative;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_Y]).negative;
            }
            return 0;
          };
          var rightStickDown = new InputSourceButton();
          rightStickDown.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_16;
              var webxrGamepad = (_GamepadInputDevice$_16 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_16 === void 0 ? void 0 : _GamepadInputDevice$_16.get(XRRightHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).positive;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).positive;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_Y]).positive;
            }
            return 0;
          };
          var rightStickLeft = new InputSourceButton();
          rightStickLeft.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_17;
              var webxrGamepad = (_GamepadInputDevice$_17 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_17 === void 0 ? void 0 : _GamepadInputDevice$_17.get(XRRightHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).negative;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).negative;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_X]).negative;
            }
            return 0;
          };
          var rightStickRight = new InputSourceButton();
          rightStickRight.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_18;
              var webxrGamepad = (_GamepadInputDevice$_18 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_18 === void 0 ? void 0 : _GamepadInputDevice$_18.get(XRRightHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).positive;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).positive;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_X]).positive;
            }
            return 0;
          };
          this._rightStick = new InputSourceStick({
            up: rightStickUp,
            down: rightStickDown,
            left: rightStickLeft,
            right: rightStickRight
          });
          this._buttonStart = new InputSourceButton();
          this._buttonStart.getValue = function () {
            return 0;
          };
          this._gripLeft = new InputSourceButton();
          this._gripLeft.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_19;
              var webxrGamepad = (_GamepadInputDevice$_19 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_19 === void 0 ? void 0 : _GamepadInputDevice$_19.get(XRLeftHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_GRIP) {
                return webxrGamepad.buttons[XR_GRIP].value;
              }
            }
            return 0;
          };
          this._gripRight = new InputSourceButton();
          this._gripRight.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_20;
              var webxrGamepad = (_GamepadInputDevice$_20 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_20 === void 0 ? void 0 : _GamepadInputDevice$_20.get(XRRightHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_GRIP) {
                return webxrGamepad.buttons[XR_GRIP].value;
              }
            }
            return 0;
          };
          this._handLeftPosition = new InputSourcePosition();
          this._handLeftPosition.getValue = function () {
            return _this._webPoseState[Pose$2.HAND_LEFT].position;
          };
          this._handLeftOrientation = new InputSourceOrientation();
          this._handLeftOrientation.getValue = function () {
            return _this._webPoseState[Pose$2.HAND_LEFT].orientation;
          };
          this._handRightPosition = new InputSourcePosition();
          this._handRightPosition.getValue = function () {
            return _this._webPoseState[Pose$2.HAND_RIGHT].position;
          };
          this._handRightOrientation = new InputSourceOrientation();
          this._handRightOrientation.getValue = function () {
            return _this._webPoseState[Pose$2.HAND_RIGHT].orientation;
          };
          this._aimLeftPosition = new InputSourcePosition();
          this._aimLeftPosition.getValue = function () {
            return _this._webPoseState[Pose$2.AIM_LEFT].position;
          };
          this._aimLeftOrientation = new InputSourceOrientation();
          this._aimLeftOrientation.getValue = function () {
            return _this._webPoseState[Pose$2.AIM_LEFT].orientation;
          };
          this._aimRightPosition = new InputSourcePosition();
          this._aimRightPosition.getValue = function () {
            return _this._webPoseState[Pose$2.AIM_RIGHT].position;
          };
          this._aimRightOrientation = new InputSourceOrientation();
          this._aimRightOrientation.getValue = function () {
            return _this._webPoseState[Pose$2.AIM_RIGHT].orientation;
          };
        };
        _createClass(GamepadInputDevice, [{
          key: "buttonNorth",
          get: function get() {
            return this._buttonNorth;
          }
        }, {
          key: "buttonEast",
          get: function get() {
            return this._buttonEast;
          }
        }, {
          key: "buttonWest",
          get: function get() {
            return this._buttonWest;
          }
        }, {
          key: "buttonSouth",
          get: function get() {
            return this._buttonSouth;
          }
        }, {
          key: "buttonL1",
          get: function get() {
            return this._buttonL1;
          }
        }, {
          key: "buttonL2",
          get: function get() {
            return this._buttonL2;
          }
        }, {
          key: "buttonL3",
          get: function get() {
            return this._buttonL3;
          }
        }, {
          key: "buttonR1",
          get: function get() {
            return this._buttonR1;
          }
        }, {
          key: "buttonR2",
          get: function get() {
            return this._buttonR2;
          }
        }, {
          key: "buttonR3",
          get: function get() {
            return this._buttonR3;
          }
        }, {
          key: "buttonShare",
          get: function get() {
            return this._buttonShare;
          }
        }, {
          key: "buttonOptions",
          get: function get() {
            return this._buttonOptions;
          }
        }, {
          key: "dpad",
          get: function get() {
            return this._dpad;
          }
        }, {
          key: "leftStick",
          get: function get() {
            return this._leftStick;
          }
        }, {
          key: "rightStick",
          get: function get() {
            return this._rightStick;
          }
        }, {
          key: "buttonStart",
          get: function get() {
            return this._buttonStart;
          }
        }, {
          key: "gripLeft",
          get: function get() {
            return this._gripLeft;
          }
        }, {
          key: "gripRight",
          get: function get() {
            return this._gripRight;
          }
        }, {
          key: "handLeftPosition",
          get: function get() {
            return this._handLeftPosition;
          }
        }, {
          key: "handLeftOrientation",
          get: function get() {
            return this._handLeftOrientation;
          }
        }, {
          key: "handRightPosition",
          get: function get() {
            return this._handRightPosition;
          }
        }, {
          key: "handRightOrientation",
          get: function get() {
            return this._handRightOrientation;
          }
        }, {
          key: "aimLeftPosition",
          get: function get() {
            return this._aimLeftPosition;
          }
        }, {
          key: "aimLeftOrientation",
          get: function get() {
            return this._aimLeftOrientation;
          }
        }, {
          key: "aimRightPosition",
          get: function get() {
            return this._aimRightPosition;
          }
        }, {
          key: "aimRightOrientation",
          get: function get() {
            return this._aimRightOrientation;
          }
        }, {
          key: "deviceId",
          get: function get() {
            return this._deviceId;
          }
        }, {
          key: "connected",
          get: function get() {
            return this._connected;
          }
        }]);
        return GamepadInputDevice;
      }();
      GamepadInputDevice.all = [];
      GamepadInputDevice.xr = null;
      GamepadInputDevice._eventTarget = new EventTarget();
      GamepadInputDevice._cachedWebGamepads = [];
      GamepadInputDevice._cachedWebXRGamepadMap = null;
      GamepadInputDevice._intervalId = -1;
      GamepadInputDevice._totalGamepadCnt = 0;

      var Button$1;
      (function (Button) {
        Button[Button["BUTTON_EAST"] = 0] = "BUTTON_EAST";
        Button[Button["BUTTON_SOUTH"] = 1] = "BUTTON_SOUTH";
        Button[Button["BUTTON_WEST"] = 2] = "BUTTON_WEST";
        Button[Button["BUTTON_NORTH"] = 3] = "BUTTON_NORTH";
        Button[Button["BUTTON_TRIGGER_LEFT"] = 4] = "BUTTON_TRIGGER_LEFT";
        Button[Button["BUTTON_TRIGGER_RIGHT"] = 5] = "BUTTON_TRIGGER_RIGHT";
        Button[Button["TRIGGER_LEFT"] = 6] = "TRIGGER_LEFT";
        Button[Button["TRIGGER_RIGHT"] = 7] = "TRIGGER_RIGHT";
        Button[Button["GRIP_LEFT"] = 8] = "GRIP_LEFT";
        Button[Button["GRIP_RIGHT"] = 9] = "GRIP_RIGHT";
        Button[Button["BUTTON_LEFT_STICK"] = 10] = "BUTTON_LEFT_STICK";
        Button[Button["LEFT_STICK_UP"] = 11] = "LEFT_STICK_UP";
        Button[Button["LEFT_STICK_DOWN"] = 12] = "LEFT_STICK_DOWN";
        Button[Button["LEFT_STICK_LEFT"] = 13] = "LEFT_STICK_LEFT";
        Button[Button["LEFT_STICK_RIGHT"] = 14] = "LEFT_STICK_RIGHT";
        Button[Button["BUTTON_RIGHT_STICK"] = 15] = "BUTTON_RIGHT_STICK";
        Button[Button["RIGHT_STICK_UP"] = 16] = "RIGHT_STICK_UP";
        Button[Button["RIGHT_STICK_DOWN"] = 17] = "RIGHT_STICK_DOWN";
        Button[Button["RIGHT_STICK_LEFT"] = 18] = "RIGHT_STICK_LEFT";
        Button[Button["RIGHT_STICK_RIGHT"] = 19] = "RIGHT_STICK_RIGHT";
        Button[Button["ROKID_MENU"] = 20] = "ROKID_MENU";
        Button[Button["ROKID_START"] = 21] = "ROKID_START";
      })(Button$1 || (Button$1 = {}));
      var KeyEventType;
      (function (KeyEventType) {
        KeyEventType[KeyEventType["KET_CLICK"] = 0] = "KET_CLICK";
        KeyEventType[KeyEventType["KET_STICK"] = 1] = "KET_STICK";
        KeyEventType[KeyEventType["KET_GRAB"] = 2] = "KET_GRAB";
        KeyEventType[KeyEventType["KET_TOUCH"] = 3] = "KET_TOUCH";
      })(KeyEventType || (KeyEventType = {}));
      var StickKeyCode;
      (function (StickKeyCode) {
        StickKeyCode[StickKeyCode["UNDEFINE"] = 0] = "UNDEFINE";
        StickKeyCode[StickKeyCode["A"] = 1] = "A";
        StickKeyCode[StickKeyCode["B"] = 2] = "B";
        StickKeyCode[StickKeyCode["X"] = 3] = "X";
        StickKeyCode[StickKeyCode["Y"] = 4] = "Y";
        StickKeyCode[StickKeyCode["L1"] = 5] = "L1";
        StickKeyCode[StickKeyCode["R1"] = 6] = "R1";
        StickKeyCode[StickKeyCode["MINUS"] = 7] = "MINUS";
        StickKeyCode[StickKeyCode["PLUS"] = 8] = "PLUS";
        StickKeyCode[StickKeyCode["L3"] = 9] = "L3";
        StickKeyCode[StickKeyCode["R3"] = 10] = "R3";
        StickKeyCode[StickKeyCode["MENU"] = 11] = "MENU";
        StickKeyCode[StickKeyCode["START"] = 12] = "START";
        StickKeyCode[StickKeyCode["TRIGGER_LEFT"] = 13] = "TRIGGER_LEFT";
        StickKeyCode[StickKeyCode["TRIGGER_RIGHT"] = 14] = "TRIGGER_RIGHT";
      })(StickKeyCode || (StickKeyCode = {}));
      var StickAxisCode;
      (function (StickAxisCode) {
        StickAxisCode[StickAxisCode["UNDEFINE"] = 0] = "UNDEFINE";
        StickAxisCode[StickAxisCode["X"] = 1] = "X";
        StickAxisCode[StickAxisCode["Y"] = 2] = "Y";
        StickAxisCode[StickAxisCode["LEFT_STICK_X"] = 3] = "LEFT_STICK_X";
        StickAxisCode[StickAxisCode["LEFT_STICK_Y"] = 4] = "LEFT_STICK_Y";
        StickAxisCode[StickAxisCode["RIGHT_STICK_X"] = 5] = "RIGHT_STICK_X";
        StickAxisCode[StickAxisCode["RIGHT_STICK_Y"] = 6] = "RIGHT_STICK_Y";
        StickAxisCode[StickAxisCode["L2"] = 7] = "L2";
        StickAxisCode[StickAxisCode["R2"] = 8] = "R2";
        StickAxisCode[StickAxisCode["LEFT_GRIP"] = 9] = "LEFT_GRIP";
        StickAxisCode[StickAxisCode["RIGHT_GRIP"] = 10] = "RIGHT_GRIP";
      })(StickAxisCode || (StickAxisCode = {}));
      var StickTouchCode;
      (function (StickTouchCode) {
        StickTouchCode[StickTouchCode["UNDEFINE"] = 0] = "UNDEFINE";
        StickTouchCode[StickTouchCode["A"] = 1] = "A";
        StickTouchCode[StickTouchCode["B"] = 2] = "B";
        StickTouchCode[StickTouchCode["X"] = 3] = "X";
        StickTouchCode[StickTouchCode["Y"] = 4] = "Y";
        StickTouchCode[StickTouchCode["LEFT_TRIGGER"] = 5] = "LEFT_TRIGGER";
        StickTouchCode[StickTouchCode["RIGHT_TRIGGER"] = 6] = "RIGHT_TRIGGER";
        StickTouchCode[StickTouchCode["LEFT_THUMBSTICK"] = 7] = "LEFT_THUMBSTICK";
        StickTouchCode[StickTouchCode["RIGHT_THUMBSTICK"] = 8] = "RIGHT_THUMBSTICK";
      })(StickTouchCode || (StickTouchCode = {}));
      var _nativeButtonMap = {
        1: Button$1.BUTTON_EAST,
        2: Button$1.BUTTON_SOUTH,
        3: Button$1.BUTTON_NORTH,
        4: Button$1.BUTTON_WEST,
        9: Button$1.BUTTON_LEFT_STICK,
        10: Button$1.BUTTON_RIGHT_STICK,
        11: Button$1.ROKID_MENU,
        12: Button$1.ROKID_START,
        13: Button$1.BUTTON_TRIGGER_LEFT,
        14: Button$1.BUTTON_TRIGGER_RIGHT
      };
      var HandleInputDevice = function () {
        function HandleInputDevice() {
          var _this$_nativeButtonSt,
            _this$_nativeTouchSta,
            _this = this;
          this._eventTarget = new EventTarget();
          this._buttonNorth = void 0;
          this._buttonEast = void 0;
          this._buttonWest = void 0;
          this._buttonSouth = void 0;
          this._buttonTriggerLeft = void 0;
          this._buttonTriggerRight = void 0;
          this._triggerLeft = void 0;
          this._triggerRight = void 0;
          this._gripLeft = void 0;
          this._gripRight = void 0;
          this._leftStick = void 0;
          this._rightStick = void 0;
          this._buttonLeftStick = void 0;
          this._buttonRightStick = void 0;
          this._buttonOptions = void 0;
          this._buttonStart = void 0;
          this._handLeftPosition = void 0;
          this._handLeftOrientation = void 0;
          this._handRightPosition = void 0;
          this._handRightOrientation = void 0;
          this._aimLeftPosition = void 0;
          this._aimLeftOrientation = void 0;
          this._aimRightPosition = void 0;
          this._aimRightOrientation = void 0;
          this._touchButtonA = void 0;
          this._touchButtonB = void 0;
          this._touchButtonX = void 0;
          this._touchButtonY = void 0;
          this._touchButtonTriggerLeft = void 0;
          this._touchButtonTriggerRight = void 0;
          this._touchButtonThumbStickLeft = void 0;
          this._touchButtonThumbStickRight = void 0;
          this._nativeButtonState = (_this$_nativeButtonSt = {}, _this$_nativeButtonSt[Button$1.BUTTON_SOUTH] = 0, _this$_nativeButtonSt[Button$1.BUTTON_EAST] = 0, _this$_nativeButtonSt[Button$1.BUTTON_WEST] = 0, _this$_nativeButtonSt[Button$1.BUTTON_NORTH] = 0, _this$_nativeButtonSt[Button$1.BUTTON_TRIGGER_LEFT] = 0, _this$_nativeButtonSt[Button$1.BUTTON_TRIGGER_RIGHT] = 0, _this$_nativeButtonSt[Button$1.TRIGGER_LEFT] = 0, _this$_nativeButtonSt[Button$1.TRIGGER_RIGHT] = 0, _this$_nativeButtonSt[Button$1.GRIP_LEFT] = 0, _this$_nativeButtonSt[Button$1.GRIP_RIGHT] = 0, _this$_nativeButtonSt[Button$1.LEFT_STICK_UP] = 0, _this$_nativeButtonSt[Button$1.LEFT_STICK_DOWN] = 0, _this$_nativeButtonSt[Button$1.LEFT_STICK_LEFT] = 0, _this$_nativeButtonSt[Button$1.LEFT_STICK_RIGHT] = 0, _this$_nativeButtonSt[Button$1.RIGHT_STICK_UP] = 0, _this$_nativeButtonSt[Button$1.RIGHT_STICK_DOWN] = 0, _this$_nativeButtonSt[Button$1.RIGHT_STICK_LEFT] = 0, _this$_nativeButtonSt[Button$1.RIGHT_STICK_RIGHT] = 0, _this$_nativeButtonSt[Button$1.BUTTON_LEFT_STICK] = 0, _this$_nativeButtonSt[Button$1.BUTTON_RIGHT_STICK] = 0, _this$_nativeButtonSt[Button$1.ROKID_MENU] = 0, _this$_nativeButtonSt[Button$1.ROKID_START] = 0, _this$_nativeButtonSt);
          this._nativeTouchState = (_this$_nativeTouchSta = {}, _this$_nativeTouchSta[StickTouchCode.UNDEFINE] = 0, _this$_nativeTouchSta[StickTouchCode.A] = 0, _this$_nativeTouchSta[StickTouchCode.B] = 0, _this$_nativeTouchSta[StickTouchCode.X] = 0, _this$_nativeTouchSta[StickTouchCode.Y] = 0, _this$_nativeTouchSta[StickTouchCode.LEFT_TRIGGER] = 0, _this$_nativeTouchSta[StickTouchCode.RIGHT_TRIGGER] = 0, _this$_nativeTouchSta[StickTouchCode.LEFT_THUMBSTICK] = 0, _this$_nativeTouchSta[StickTouchCode.RIGHT_THUMBSTICK] = 0, _this$_nativeTouchSta);
          this._initInputSource();
          window.addEventListener('xr-remote-input', function (evt) {
            var remoteInputEvent = evt;
            var keyEventType = remoteInputEvent.detail.keyEventType;
            var stickAxisCode = remoteInputEvent.detail.stickAxisCode;
            var stickAxisValue = remoteInputEvent.detail.stickAxisValue;
            var stickKeyCode = remoteInputEvent.detail.stickKeyCode;
            var isButtonPressed = remoteInputEvent.detail.isButtonPressed;
            var touchCode = remoteInputEvent.detail.touchCode;
            var touchValue = remoteInputEvent.detail.touchValue;
            if (keyEventType === KeyEventType.KET_CLICK) {
              var button = _nativeButtonMap[stickKeyCode];
              _this._nativeButtonState[button] = isButtonPressed ? 1 : 0;
            } else if (keyEventType === KeyEventType.KET_STICK || keyEventType === KeyEventType.KET_GRAB) {
              var negativeButton;
              var positiveButton;
              var axisValue;
              switch (stickAxisCode) {
                case StickAxisCode.LEFT_STICK_X:
                  negativeButton = Button$1.LEFT_STICK_LEFT;
                  positiveButton = Button$1.LEFT_STICK_RIGHT;
                  axisValue = _this._axisToButtons(stickAxisValue);
                  break;
                case StickAxisCode.LEFT_STICK_Y:
                  negativeButton = Button$1.LEFT_STICK_DOWN;
                  positiveButton = Button$1.LEFT_STICK_UP;
                  axisValue = _this._axisToButtons(stickAxisValue);
                  break;
                case StickAxisCode.RIGHT_STICK_X:
                  negativeButton = Button$1.RIGHT_STICK_LEFT;
                  positiveButton = Button$1.RIGHT_STICK_RIGHT;
                  axisValue = _this._axisToButtons(stickAxisValue);
                  break;
                case StickAxisCode.RIGHT_STICK_Y:
                  negativeButton = Button$1.RIGHT_STICK_DOWN;
                  positiveButton = Button$1.RIGHT_STICK_UP;
                  axisValue = _this._axisToButtons(stickAxisValue);
                  break;
                case StickAxisCode.L2:
                  _this._nativeButtonState[Button$1.TRIGGER_LEFT] = stickAxisValue;
                  break;
                case StickAxisCode.R2:
                  _this._nativeButtonState[Button$1.TRIGGER_RIGHT] = stickAxisValue;
                  break;
                case StickAxisCode.LEFT_GRIP:
                  _this._nativeButtonState[Button$1.GRIP_LEFT] = stickAxisValue;
                  break;
                case StickAxisCode.RIGHT_GRIP:
                  _this._nativeButtonState[Button$1.GRIP_RIGHT] = stickAxisValue;
                  break;
              }
              if (negativeButton && positiveButton && axisValue) {
                _this._nativeButtonState[negativeButton] = axisValue.negative;
                _this._nativeButtonState[positiveButton] = axisValue.positive;
              }
            } else if (keyEventType === KeyEventType.KET_TOUCH) {
              switch (touchCode) {
                case StickTouchCode.A:
                case StickTouchCode.B:
                case StickTouchCode.X:
                case StickTouchCode.Y:
                case StickTouchCode.LEFT_TRIGGER:
                case StickTouchCode.RIGHT_TRIGGER:
                case StickTouchCode.LEFT_THUMBSTICK:
                case StickTouchCode.RIGHT_THUMBSTICK:
                  _this._nativeTouchState[touchCode] = touchValue;
                  break;
              }
            }
            _this._eventTarget.emit(InputEventType.HANDLE_INPUT, new EventHandle(InputEventType.HANDLE_INPUT, _this));
          });
        }
        var _proto = HandleInputDevice.prototype;
        _proto._axisToButtons = function _axisToButtons(axisValue) {
          var value = Math.abs(axisValue);
          if (axisValue > 0) {
            return {
              negative: 0,
              positive: value
            };
          } else if (axisValue < 0) {
            return {
              negative: value,
              positive: 0
            };
          } else {
            return {
              negative: 0,
              positive: 0
            };
          }
        };
        _proto._on = function _on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        _proto._initInputSource = function _initInputSource() {
          var _this2 = this;
          this._buttonNorth = new InputSourceButton();
          this._buttonNorth.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_NORTH];
          };
          this._buttonEast = new InputSourceButton();
          this._buttonEast.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_EAST];
          };
          this._buttonWest = new InputSourceButton();
          this._buttonWest.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_WEST];
          };
          this._buttonSouth = new InputSourceButton();
          this._buttonSouth.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_SOUTH];
          };
          this._buttonTriggerLeft = new InputSourceButton();
          this._buttonTriggerLeft.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_TRIGGER_LEFT];
          };
          this._buttonTriggerRight = new InputSourceButton();
          this._buttonTriggerRight.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_TRIGGER_RIGHT];
          };
          this._triggerLeft = new InputSourceButton();
          this._triggerLeft.getValue = function () {
            return _this2._nativeButtonState[Button$1.TRIGGER_LEFT];
          };
          this._triggerRight = new InputSourceButton();
          this._triggerRight.getValue = function () {
            return _this2._nativeButtonState[Button$1.TRIGGER_RIGHT];
          };
          this._gripLeft = new InputSourceButton();
          this._gripLeft.getValue = function () {
            return _this2._nativeButtonState[Button$1.GRIP_LEFT];
          };
          this._gripRight = new InputSourceButton();
          this._gripRight.getValue = function () {
            return _this2._nativeButtonState[Button$1.GRIP_RIGHT];
          };
          this._buttonLeftStick = new InputSourceButton();
          this._buttonLeftStick.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_LEFT_STICK];
          };
          var leftStickUp = new InputSourceButton();
          leftStickUp.getValue = function () {
            return _this2._nativeButtonState[Button$1.LEFT_STICK_UP];
          };
          var leftStickDown = new InputSourceButton();
          leftStickDown.getValue = function () {
            return _this2._nativeButtonState[Button$1.LEFT_STICK_DOWN];
          };
          var leftStickLeft = new InputSourceButton();
          leftStickLeft.getValue = function () {
            return _this2._nativeButtonState[Button$1.LEFT_STICK_LEFT];
          };
          var leftStickRight = new InputSourceButton();
          leftStickRight.getValue = function () {
            return _this2._nativeButtonState[Button$1.LEFT_STICK_RIGHT];
          };
          this._leftStick = new InputSourceStick({
            up: leftStickUp,
            down: leftStickDown,
            left: leftStickLeft,
            right: leftStickRight
          });
          this._buttonRightStick = new InputSourceButton();
          this._buttonRightStick.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_RIGHT_STICK];
          };
          var rightStickUp = new InputSourceButton();
          rightStickUp.getValue = function () {
            return _this2._nativeButtonState[Button$1.RIGHT_STICK_UP];
          };
          var rightStickDown = new InputSourceButton();
          rightStickDown.getValue = function () {
            return _this2._nativeButtonState[Button$1.RIGHT_STICK_DOWN];
          };
          var rightStickLeft = new InputSourceButton();
          rightStickLeft.getValue = function () {
            return _this2._nativeButtonState[Button$1.RIGHT_STICK_LEFT];
          };
          var rightStickRight = new InputSourceButton();
          rightStickRight.getValue = function () {
            return _this2._nativeButtonState[Button$1.RIGHT_STICK_RIGHT];
          };
          this._rightStick = new InputSourceStick({
            up: rightStickUp,
            down: rightStickDown,
            left: rightStickLeft,
            right: rightStickRight
          });
          this._buttonOptions = new InputSourceButton();
          this._buttonOptions.getValue = function () {
            return _this2._nativeButtonState[Button$1.ROKID_MENU];
          };
          this._buttonStart = new InputSourceButton();
          this._buttonStart.getValue = function () {
            return _this2._nativeButtonState[Button$1.ROKID_START];
          };
          this._handLeftPosition = new InputSourcePosition();
          this._handLeftPosition.getValue = function () {
            return Vec3.ZERO;
          };
          this._handLeftOrientation = new InputSourceOrientation();
          this._handLeftOrientation.getValue = function () {
            return Quat.IDENTITY;
          };
          this._handRightPosition = new InputSourcePosition();
          this._handRightPosition.getValue = function () {
            return Vec3.ZERO;
          };
          this._handRightOrientation = new InputSourceOrientation();
          this._handRightOrientation.getValue = function () {
            return Quat.IDENTITY;
          };
          this._aimLeftPosition = new InputSourcePosition();
          this._aimLeftPosition.getValue = function () {
            return Vec3.ZERO;
          };
          this._aimLeftOrientation = new InputSourceOrientation();
          this._aimLeftOrientation.getValue = function () {
            return Quat.IDENTITY;
          };
          this._aimRightPosition = new InputSourcePosition();
          this._aimRightPosition.getValue = function () {
            return Vec3.ZERO;
          };
          this._aimRightOrientation = new InputSourceOrientation();
          this._aimRightOrientation.getValue = function () {
            return Quat.IDENTITY;
          };
          this._touchButtonA = new InputSourceTouch();
          this._touchButtonA.getValue = function () {
            return _this2._nativeTouchState[StickTouchCode.A];
          };
          this._touchButtonB = new InputSourceTouch();
          this._touchButtonB.getValue = function () {
            return _this2._nativeTouchState[StickTouchCode.B];
          };
          this._touchButtonX = new InputSourceTouch();
          this._touchButtonX.getValue = function () {
            return _this2._nativeTouchState[StickTouchCode.X];
          };
          this._touchButtonY = new InputSourceTouch();
          this._touchButtonY.getValue = function () {
            return _this2._nativeTouchState[StickTouchCode.Y];
          };
          this._touchButtonTriggerLeft = new InputSourceTouch();
          this._touchButtonTriggerLeft.getValue = function () {
            return _this2._nativeTouchState[StickTouchCode.LEFT_TRIGGER];
          };
          this._touchButtonTriggerRight = new InputSourceTouch();
          this._touchButtonTriggerRight.getValue = function () {
            return _this2._nativeTouchState[StickTouchCode.RIGHT_TRIGGER];
          };
          this._touchButtonThumbStickLeft = new InputSourceTouch();
          this._touchButtonThumbStickLeft.getValue = function () {
            return _this2._nativeTouchState[StickTouchCode.LEFT_THUMBSTICK];
          };
          this._touchButtonThumbStickRight = new InputSourceTouch();
          this._touchButtonThumbStickRight.getValue = function () {
            return _this2._nativeTouchState[StickTouchCode.RIGHT_THUMBSTICK];
          };
        };
        _createClass(HandleInputDevice, [{
          key: "buttonNorth",
          get: function get() {
            return this._buttonNorth;
          }
        }, {
          key: "buttonEast",
          get: function get() {
            return this._buttonEast;
          }
        }, {
          key: "buttonWest",
          get: function get() {
            return this._buttonWest;
          }
        }, {
          key: "buttonSouth",
          get: function get() {
            return this._buttonSouth;
          }
        }, {
          key: "buttonTriggerLeft",
          get: function get() {
            return this._buttonTriggerLeft;
          }
        }, {
          key: "buttonTriggerRight",
          get: function get() {
            return this._buttonTriggerRight;
          }
        }, {
          key: "triggerLeft",
          get: function get() {
            return this._triggerLeft;
          }
        }, {
          key: "triggerRight",
          get: function get() {
            return this._triggerRight;
          }
        }, {
          key: "gripLeft",
          get: function get() {
            return this._gripLeft;
          }
        }, {
          key: "gripRight",
          get: function get() {
            return this._gripRight;
          }
        }, {
          key: "leftStick",
          get: function get() {
            return this._leftStick;
          }
        }, {
          key: "rightStick",
          get: function get() {
            return this._rightStick;
          }
        }, {
          key: "buttonLeftStick",
          get: function get() {
            return this._buttonLeftStick;
          }
        }, {
          key: "buttonRightStick",
          get: function get() {
            return this._buttonRightStick;
          }
        }, {
          key: "buttonOptions",
          get: function get() {
            return this._buttonOptions;
          }
        }, {
          key: "buttonStart",
          get: function get() {
            return this._buttonStart;
          }
        }, {
          key: "handLeftPosition",
          get: function get() {
            return this._handLeftPosition;
          }
        }, {
          key: "handLeftOrientation",
          get: function get() {
            return this._handLeftOrientation;
          }
        }, {
          key: "handRightPosition",
          get: function get() {
            return this._handRightPosition;
          }
        }, {
          key: "handRightOrientation",
          get: function get() {
            return this._handRightOrientation;
          }
        }, {
          key: "aimLeftPosition",
          get: function get() {
            return this._aimLeftPosition;
          }
        }, {
          key: "aimLeftOrientation",
          get: function get() {
            return this._aimLeftOrientation;
          }
        }, {
          key: "aimRightPosition",
          get: function get() {
            return this._aimRightPosition;
          }
        }, {
          key: "aimRightOrientation",
          get: function get() {
            return this._aimRightOrientation;
          }
        }, {
          key: "touchButtonA",
          get: function get() {
            return this._touchButtonA;
          }
        }, {
          key: "touchButtonB",
          get: function get() {
            return this._touchButtonB;
          }
        }, {
          key: "touchButtonX",
          get: function get() {
            return this._touchButtonX;
          }
        }, {
          key: "touchButtonY",
          get: function get() {
            return this._touchButtonY;
          }
        }, {
          key: "touchButtonTriggerLeft",
          get: function get() {
            return this._touchButtonTriggerLeft;
          }
        }, {
          key: "touchButtonTriggerRight",
          get: function get() {
            return this._touchButtonTriggerRight;
          }
        }, {
          key: "touchButtonThumbStickLeft",
          get: function get() {
            return this._touchButtonThumbStickLeft;
          }
        }, {
          key: "touchButtonThumbStickRight",
          get: function get() {
            return this._touchButtonThumbStickRight;
          }
        }]);
        return HandleInputDevice;
      }();

      var Pose$1;
      (function (Pose) {
        Pose[Pose["VIEW_LEFT"] = 0] = "VIEW_LEFT";
        Pose[Pose["VIEW_RIGHT"] = 3] = "VIEW_RIGHT";
        Pose[Pose["HEAD_MIDDLE"] = 6] = "HEAD_MIDDLE";
      })(Pose$1 || (Pose$1 = {}));
      var HMDInputDevice = function () {
        function HMDInputDevice() {
          var _this$_webPoseState;
          this._eventTarget = new EventTarget();
          this._intervalId = -1;
          this._viewLeftPosition = void 0;
          this._viewLeftOrientation = void 0;
          this._viewRightPosition = void 0;
          this._viewRightOrientation = void 0;
          this._headMiddlePosition = void 0;
          this._headMiddleOrientation = void 0;
          this._webPoseState = (_this$_webPoseState = {}, _this$_webPoseState[Pose$1.VIEW_LEFT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState[Pose$1.VIEW_RIGHT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState[Pose$1.HEAD_MIDDLE] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState);
          this._initInputSource();
          this._registerEvent();
        }
        var _proto = HMDInputDevice.prototype;
        _proto._ensureDirectorDefined = function _ensureDirectorDefined() {
          var _this = this;
          return new Promise(function (resolve) {
            _this._intervalId = setInterval(function () {
              if (legacyCC.director && legacyCC.Director) {
                clearInterval(_this._intervalId);
                _this._intervalId = -1;
                resolve();
              }
            }, 50);
          });
        };
        _proto._registerEvent = function _registerEvent() {
          var _this2 = this;
          this._ensureDirectorDefined().then(function () {
            legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, _this2._scanHmd, _this2);
          })["catch"](function (e) {});
        };
        _proto._scanHmd = function _scanHmd() {
          var _globalThis$__globalX;
          var infoList = (_globalThis$__globalX = globalThis.__globalXR) === null || _globalThis$__globalX === void 0 ? void 0 : _globalThis$__globalX.webxrHmdPoseInfos;
          if (!infoList) {
            return;
          }
          for (var i = 0; i < infoList.length; ++i) {
            var info = infoList[i];
            this._updateWebPoseState(info);
          }
          this._eventTarget.emit(InputEventType.HMD_POSE_INPUT, new EventHMD(InputEventType.HMD_POSE_INPUT, this));
        };
        _proto._on = function _on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        _proto._updateWebPoseState = function _updateWebPoseState(info) {
          if (info.code !== Pose$1.VIEW_LEFT && info.code !== Pose$1.VIEW_RIGHT && info.code !== Pose$1.HEAD_MIDDLE) {
            return;
          }
          this._webPoseState[info.code] = {
            position: new Vec3(info.position.x, info.position.y, info.position.z),
            orientation: new Quat(info.orientation.x, info.orientation.y, info.orientation.z, info.orientation.w)
          };
        };
        _proto._initInputSource = function _initInputSource() {
          var _this3 = this;
          this._viewLeftPosition = new InputSourcePosition();
          this._viewLeftPosition.getValue = function () {
            return _this3._webPoseState[Pose$1.VIEW_LEFT].position;
          };
          this._viewLeftOrientation = new InputSourceOrientation();
          this._viewLeftOrientation.getValue = function () {
            return _this3._webPoseState[Pose$1.VIEW_LEFT].orientation;
          };
          this._viewRightPosition = new InputSourcePosition();
          this._viewRightPosition.getValue = function () {
            return _this3._webPoseState[Pose$1.VIEW_RIGHT].position;
          };
          this._viewRightOrientation = new InputSourceOrientation();
          this._viewRightOrientation.getValue = function () {
            return _this3._webPoseState[Pose$1.VIEW_RIGHT].orientation;
          };
          this._headMiddlePosition = new InputSourcePosition();
          this._headMiddlePosition.getValue = function () {
            return _this3._webPoseState[Pose$1.HEAD_MIDDLE].position;
          };
          this._headMiddleOrientation = new InputSourceOrientation();
          this._headMiddleOrientation.getValue = function () {
            return _this3._webPoseState[Pose$1.HEAD_MIDDLE].orientation;
          };
        };
        _createClass(HMDInputDevice, [{
          key: "viewLeftPosition",
          get: function get() {
            return this._viewLeftPosition;
          }
        }, {
          key: "viewLeftOrientation",
          get: function get() {
            return this._viewLeftOrientation;
          }
        }, {
          key: "viewRightPosition",
          get: function get() {
            return this._viewRightPosition;
          }
        }, {
          key: "viewRightOrientation",
          get: function get() {
            return this._viewRightOrientation;
          }
        }, {
          key: "headMiddlePosition",
          get: function get() {
            return this._headMiddlePosition;
          }
        }, {
          key: "headMiddleOrientation",
          get: function get() {
            return this._headMiddleOrientation;
          }
        }]);
        return HMDInputDevice;
      }();

      var HandheldInputDevice = function () {
        function HandheldInputDevice() {
          this._eventTarget = new EventTarget();
          this._handheldPosition = void 0;
          this._handheldOrientation = void 0;
          this._initInputSource();
        }
        var _proto = HandheldInputDevice.prototype;
        _proto._on = function _on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        _proto._initInputSource = function _initInputSource() {
          this._handheldPosition = new InputSourcePosition();
          this._handheldPosition.getValue = function () {
            return Vec3.ZERO;
          };
          this._handheldOrientation = new InputSourceOrientation();
          this._handheldOrientation.getValue = function () {
            return Quat.IDENTITY;
          };
        };
        _createClass(HandheldInputDevice, [{
          key: "handheldPosition",
          get: function get() {
            return this._handheldPosition;
          }
        }, {
          key: "handheldOrientation",
          get: function get() {
            return this._handheldOrientation;
          }
        }]);
        return HandheldInputDevice;
      }();

      var code2KeyCode = {
        Backspace: KeyCode.BACKSPACE,
        Tab: KeyCode.TAB,
        Enter: KeyCode.ENTER,
        ShiftLeft: KeyCode.SHIFT_LEFT,
        ControlLeft: KeyCode.CTRL_LEFT,
        AltLeft: KeyCode.ALT_LEFT,
        ShiftRight: KeyCode.SHIFT_RIGHT,
        ControlRight: KeyCode.CTRL_RIGHT,
        AltRight: KeyCode.ALT_RIGHT,
        Pause: KeyCode.PAUSE,
        CapsLock: KeyCode.CAPS_LOCK,
        Escape: KeyCode.ESCAPE,
        Space: KeyCode.SPACE,
        PageUp: KeyCode.PAGE_UP,
        PageDown: KeyCode.PAGE_DOWN,
        End: KeyCode.END,
        Home: KeyCode.HOME,
        ArrowLeft: KeyCode.ARROW_LEFT,
        ArrowUp: KeyCode.ARROW_UP,
        ArrowRight: KeyCode.ARROW_RIGHT,
        ArrowDown: KeyCode.ARROW_DOWN,
        Insert: KeyCode.INSERT,
        Delete: KeyCode.DELETE,
        Digit0: KeyCode.DIGIT_0,
        Digit1: KeyCode.DIGIT_1,
        Digit2: KeyCode.DIGIT_2,
        Digit3: KeyCode.DIGIT_3,
        Digit4: KeyCode.DIGIT_4,
        Digit5: KeyCode.DIGIT_5,
        Digit6: KeyCode.DIGIT_6,
        Digit7: KeyCode.DIGIT_7,
        Digit8: KeyCode.DIGIT_8,
        Digit9: KeyCode.DIGIT_9,
        KeyA: KeyCode.KEY_A,
        KeyB: KeyCode.KEY_B,
        KeyC: KeyCode.KEY_C,
        KeyD: KeyCode.KEY_D,
        KeyE: KeyCode.KEY_E,
        KeyF: KeyCode.KEY_F,
        KeyG: KeyCode.KEY_G,
        KeyH: KeyCode.KEY_H,
        KeyI: KeyCode.KEY_I,
        KeyJ: KeyCode.KEY_J,
        KeyK: KeyCode.KEY_K,
        KeyL: KeyCode.KEY_L,
        KeyM: KeyCode.KEY_M,
        KeyN: KeyCode.KEY_N,
        KeyO: KeyCode.KEY_O,
        KeyP: KeyCode.KEY_P,
        KeyQ: KeyCode.KEY_Q,
        KeyR: KeyCode.KEY_R,
        KeyS: KeyCode.KEY_S,
        KeyT: KeyCode.KEY_T,
        KeyU: KeyCode.KEY_U,
        KeyV: KeyCode.KEY_V,
        KeyW: KeyCode.KEY_W,
        KeyX: KeyCode.KEY_X,
        KeyY: KeyCode.KEY_Y,
        KeyZ: KeyCode.KEY_Z,
        Numpad0: KeyCode.NUM_0,
        Numpad1: KeyCode.NUM_1,
        Numpad2: KeyCode.NUM_2,
        Numpad3: KeyCode.NUM_3,
        Numpad4: KeyCode.NUM_4,
        Numpad5: KeyCode.NUM_5,
        Numpad6: KeyCode.NUM_6,
        Numpad7: KeyCode.NUM_7,
        Numpad8: KeyCode.NUM_8,
        Numpad9: KeyCode.NUM_9,
        NumpadMultiply: KeyCode.NUM_MULTIPLY,
        NumpadAdd: KeyCode.NUM_PLUS,
        NumpadSubtract: KeyCode.NUM_SUBTRACT,
        NumpadDecimal: KeyCode.NUM_DECIMAL,
        NumpadDivide: KeyCode.NUM_DIVIDE,
        NumpadEnter: KeyCode.NUM_ENTER,
        F1: KeyCode.F1,
        F2: KeyCode.F2,
        F3: KeyCode.F3,
        F4: KeyCode.F4,
        F5: KeyCode.F5,
        F6: KeyCode.F6,
        F7: KeyCode.F7,
        F8: KeyCode.F8,
        F9: KeyCode.F9,
        F10: KeyCode.F10,
        F11: KeyCode.F11,
        F12: KeyCode.F12,
        NumLock: KeyCode.NUM_LOCK,
        ScrollLock: KeyCode.SCROLL_LOCK,
        Semicolon: KeyCode.SEMICOLON,
        Equal: KeyCode.EQUAL,
        Comma: KeyCode.COMMA,
        Minus: KeyCode.DASH,
        Period: KeyCode.PERIOD,
        Slash: KeyCode.SLASH,
        Backquote: KeyCode.BACK_QUOTE,
        BracketLeft: KeyCode.BRACKET_LEFT,
        Backslash: KeyCode.BACKSLASH,
        BracketRight: KeyCode.BRACKET_RIGHT,
        Quote: KeyCode.QUOTE
      };

      function getKeyCode(code) {
        return code2KeyCode[code] || KeyCode.NONE;
      }
      var KeyboardInputSource = function () {
        function KeyboardInputSource() {
          this._eventTarget = new EventTarget();
          this._registerEvent();
        }
        var _proto = KeyboardInputSource.prototype;
        _proto.dispatchKeyboardDownEvent = function dispatchKeyboardDownEvent(nativeKeyboardEvent) {
          this._handleKeyboardDown(nativeKeyboardEvent);
        };
        _proto.dispatchKeyboardUpEvent = function dispatchKeyboardUpEvent(nativeKeyboardEvent) {
          this._handleKeyboardUp(nativeKeyboardEvent);
        };
        _proto.on = function on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        _proto._registerEvent = function _registerEvent() {
          var canvas = document.getElementById('GameCanvas');
          canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('keydown', this._handleKeyboardDown.bind(this));
          canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('keyup', this._handleKeyboardUp.bind(this));
        };
        _proto._getInputEvent = function _getInputEvent(event, eventType) {
          var keyCode = getKeyCode(event.code);
          var eventKeyboard = new EventKeyboard(keyCode, eventType);
          return eventKeyboard;
        };
        _proto._handleKeyboardDown = function _handleKeyboardDown(event) {
          event.stopPropagation();
          event.preventDefault();
          if (!event.repeat) {
            var keyDownInputEvent = this._getInputEvent(event, InputEventType.KEY_DOWN);
            this._eventTarget.emit(InputEventType.KEY_DOWN, keyDownInputEvent);
          } else {
            var keyPressingInputEvent = this._getInputEvent(event, InputEventType.KEY_PRESSING);
            this._eventTarget.emit(InputEventType.KEY_PRESSING, keyPressingInputEvent);
          }
        };
        _proto._handleKeyboardUp = function _handleKeyboardUp(event) {
          var inputEvent = this._getInputEvent(event, InputEventType.KEY_UP);
          event.stopPropagation();
          event.preventDefault();
          this._eventTarget.emit(InputEventType.KEY_UP, inputEvent);
        };
        return KeyboardInputSource;
      }();

      var MouseInputSource = function () {
        function MouseInputSource() {
          this._canvas = void 0;
          this._eventTarget = new EventTarget();
          this._pointLocked = false;
          this._isPressed = false;
          this._preMousePos = new Vec2();
          this._handleMouseDown = void 0;
          this._handleMouseMove = void 0;
          this._handleMouseUp = void 0;
          if (systemInfo.hasFeature(Feature$1.EVENT_MOUSE)) {
            this._canvas = document.getElementById('GameCanvas');
            if (!this._canvas && !TEST && !EDITOR) {
              console.warn('failed to access canvas');
            }
            this._handleMouseDown = this._createCallback(InputEventType.MOUSE_DOWN);
            this._handleMouseMove = this._createCallback(InputEventType.MOUSE_MOVE);
            this._handleMouseUp = this._createCallback(InputEventType.MOUSE_UP);
            {
              this._registerEvent();
            }
          }
        }
        var _proto = MouseInputSource.prototype;
        _proto.dispatchMouseDownEvent = function dispatchMouseDownEvent(nativeMouseEvent) {
          this._handleMouseDown(nativeMouseEvent);
        };
        _proto.dispatchMouseMoveEvent = function dispatchMouseMoveEvent(nativeMouseEvent) {
          this._handleMouseMove(nativeMouseEvent);
        };
        _proto.dispatchMouseUpEvent = function dispatchMouseUpEvent(nativeMouseEvent) {
          this._handleMouseUp(nativeMouseEvent);
        };
        _proto.dispatchScrollEvent = function dispatchScrollEvent(nativeMouseEvent) {
          this._handleMouseWheel(nativeMouseEvent);
        };
        _proto.on = function on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        _proto._getCanvasRect = function _getCanvasRect() {
          var canvas = this._canvas;
          var box = canvas === null || canvas === void 0 ? void 0 : canvas.getBoundingClientRect();
          if (box) {
            return new Rect$1(box.x, box.y, box.width, box.height);
          }
          return new Rect$1(0, 0, 0, 0);
        };
        _proto._getLocation = function _getLocation(mouseEvent) {
          var canvasRect = this._getCanvasRect();
          var dpr = screenAdapter.devicePixelRatio;
          var x = this._pointLocked ? this._preMousePos.x / dpr + mouseEvent.movementX : mouseEvent.clientX - canvasRect.x;
          var y = this._pointLocked ? this._preMousePos.y / dpr - mouseEvent.movementY : canvasRect.y + canvasRect.height - mouseEvent.clientY;
          x *= dpr;
          y *= dpr;
          return new Vec2(x, y);
        };
        _proto._registerEvent = function _registerEvent() {
          var _this = this,
            _this$_canvas,
            _this$_canvas2,
            _this$_canvas3,
            _this$_canvas4;
          window.addEventListener('mousedown', function () {
            _this._isPressed = true;
          });
          (_this$_canvas = this._canvas) === null || _this$_canvas === void 0 ? void 0 : _this$_canvas.addEventListener('mousedown', this._handleMouseDown);
          (_this$_canvas2 = this._canvas) === null || _this$_canvas2 === void 0 ? void 0 : _this$_canvas2.addEventListener('mousemove', this._handleMouseMove);
          window.addEventListener('mouseup', this._handleMouseUp);
          (_this$_canvas3 = this._canvas) === null || _this$_canvas3 === void 0 ? void 0 : _this$_canvas3.addEventListener('mouseup', this._handleMouseUp);
          (_this$_canvas4 = this._canvas) === null || _this$_canvas4 === void 0 ? void 0 : _this$_canvas4.addEventListener('wheel', this._handleMouseWheel.bind(this));
          this._registerPointerLockEvent();
        };
        _proto._registerPointerLockEvent = function _registerPointerLockEvent() {
          var _this2 = this;
          var lockChangeAlert = function lockChangeAlert() {
            var canvas = _this2._canvas;
            if (document.pointerLockElement === canvas || document.mozPointerLockElement === canvas) {
              _this2._pointLocked = true;
            } else {
              _this2._pointLocked = false;
            }
          };
          if ('onpointerlockchange' in document) {
            document.addEventListener('pointerlockchange', lockChangeAlert, false);
          } else if ('onmozpointerlockchange' in document) {
            document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
          }
        };
        _proto._createCallback = function _createCallback(eventType) {
          var _this3 = this;
          return function (mouseEvent) {
            var _this3$_canvas;
            var location = _this3._getLocation(mouseEvent);
            var button = mouseEvent.button,
              buttons = mouseEvent.buttons;
            var targetButton = button;
            switch (eventType) {
              case InputEventType.MOUSE_DOWN:
                (_this3$_canvas = _this3._canvas) === null || _this3$_canvas === void 0 ? void 0 : _this3$_canvas.focus();
                _this3._isPressed = true;
                break;
              case InputEventType.MOUSE_UP:
                _this3._isPressed = false;
                break;
              case InputEventType.MOUSE_MOVE:
                if (1 & buttons) {
                  targetButton = EventMouse.BUTTON_LEFT;
                } else if (2 & buttons) {
                  targetButton = EventMouse.BUTTON_RIGHT;
                } else if (4 & buttons) {
                  targetButton = EventMouse.BUTTON_MIDDLE;
                } else {
                  targetButton = EventMouse.BUTTON_MISSING;
                }
                break;
            }
            var eventMouse = new EventMouse(eventType, false, _this3._preMousePos);
            eventMouse.setLocation(location.x, location.y);
            eventMouse.setButton(targetButton);
            eventMouse.movementX = mouseEvent.movementX;
            eventMouse.movementY = mouseEvent.movementY;
            _this3._preMousePos.set(location.x, location.y);
            mouseEvent.stopPropagation();
            if (mouseEvent.target === _this3._canvas) {
              mouseEvent.preventDefault();
            }
            _this3._eventTarget.emit(eventType, eventMouse);
          };
        };
        _proto._handleMouseWheel = function _handleMouseWheel(mouseEvent) {
          var eventType = InputEventType.MOUSE_WHEEL;
          var location = this._getLocation(mouseEvent);
          var button = mouseEvent.button;
          var eventMouse = new EventMouse(eventType, false, this._preMousePos);
          eventMouse.setLocation(location.x, location.y);
          eventMouse.setButton(button);
          eventMouse.movementX = mouseEvent.movementX;
          eventMouse.movementY = mouseEvent.movementY;
          var wheelSensitivityFactor = 5;
          eventMouse.setScrollData(mouseEvent.deltaX * wheelSensitivityFactor, -mouseEvent.deltaY * wheelSensitivityFactor);
          this._preMousePos.set(location.x, location.y);
          mouseEvent.stopPropagation();
          if (mouseEvent.target === this._canvas) {
            mouseEvent.preventDefault();
          }
          this._eventTarget.emit(eventType, eventMouse);
        };
        return MouseInputSource;
      }();

      var tempVec2$1 = new Vec2();
      var TouchManager = function () {
        function TouchManager() {
          this._touchMap = void 0;
          this._maxTouches = 8;
          this._touchMap = new Map();
        }
        var _proto = TouchManager.prototype;
        _proto._createTouch = function _createTouch(touchID, x, y) {
          if (this._touchMap.has(touchID)) {
            log('Cannot create the same touch object.');
            return undefined;
          }
          var checkResult = this._checkTouchMapSizeMoreThanMax(touchID);
          if (checkResult) {
            log('The touches is more than MAX_TOUCHES.');
            return undefined;
          }
          var touch = new Touch(x, y, touchID);
          this._touchMap.set(touchID, touch);
          this._updateTouch(touch, x, y);
          return touch;
        };
        _proto.releaseTouch = function releaseTouch(touchID) {
          if (!this._touchMap.has(touchID)) {
            return;
          }
          this._touchMap["delete"](touchID);
        };
        _proto.getTouch = function getTouch(touchID) {
          return this._touchMap.get(touchID);
        };
        _proto.getOrCreateTouch = function getOrCreateTouch(touchID, x, y) {
          var touch = this.getTouch(touchID);
          if (!touch) {
            touch = this._createTouch(touchID, x, y);
          } else {
            this._updateTouch(touch, x, y);
          }
          return touch;
        };
        _proto.getAllTouches = function getAllTouches() {
          var touches = [];
          this._touchMap.forEach(function (touch) {
            if (touch) {
              touches.push(touch);
            }
          });
          return touches;
        };
        _proto.getTouchCount = function getTouchCount() {
          return touchManager._touchMap.size;
        };
        _proto._updateTouch = function _updateTouch(touch, x, y) {
          touch.getLocation(tempVec2$1);
          touch.setPrevPoint(tempVec2$1);
          touch.setPoint(x, y);
        };
        _proto._checkTouchMapSizeMoreThanMax = function _checkTouchMapSizeMoreThanMax(touchID) {
          var _this = this;
          if (this._touchMap.has(touchID)) {
            return false;
          }
          var maxSize = macro.ENABLE_MULTI_TOUCH ? this._maxTouches : 1;
          if (this._touchMap.size < maxSize) {
            return false;
          }
          var now = performance.now();
          this._touchMap.forEach(function (touch) {
            if (now - touch.lastModified > macro.TOUCH_TIMEOUT) {
              log("The touches is more than MAX_TOUCHES, release touch id " + touch.getID() + ".");
              _this.releaseTouch(touch.getID());
            }
          });
          return maxSize >= this._touchMap.size;
        };
        return TouchManager;
      }();
      var touchManager = new TouchManager();

      var TouchInputSource = function () {
        function TouchInputSource() {
          this._canvas = void 0;
          this._eventTarget = new EventTarget();
          if (systemInfo.hasFeature(Feature$1.INPUT_TOUCH)) {
            this._canvas = document.getElementById('GameCanvas');
            if (!this._canvas && !TEST && !EDITOR) {
              warn('failed to access canvas');
            }
            {
              this._registerEvent();
            }
          }
        }
        var _proto = TouchInputSource.prototype;
        _proto._registerEvent = function _registerEvent() {
          var _this$_canvas, _this$_canvas2, _this$_canvas3, _this$_canvas4;
          (_this$_canvas = this._canvas) === null || _this$_canvas === void 0 ? void 0 : _this$_canvas.addEventListener('touchstart', this._createCallback(InputEventType.TOUCH_START));
          (_this$_canvas2 = this._canvas) === null || _this$_canvas2 === void 0 ? void 0 : _this$_canvas2.addEventListener('touchmove', this._createCallback(InputEventType.TOUCH_MOVE));
          (_this$_canvas3 = this._canvas) === null || _this$_canvas3 === void 0 ? void 0 : _this$_canvas3.addEventListener('touchend', this._createCallback(InputEventType.TOUCH_END));
          (_this$_canvas4 = this._canvas) === null || _this$_canvas4 === void 0 ? void 0 : _this$_canvas4.addEventListener('touchcancel', this._createCallback(InputEventType.TOUCH_CANCEL));
        };
        _proto._createCallback = function _createCallback(eventType) {
          var _this = this;
          return function (event) {
            var canvasRect = _this._getCanvasRect();
            var handleTouches = [];
            var length = event.changedTouches.length;
            for (var i = 0; i < length; ++i) {
              var changedTouch = event.changedTouches[i];
              var touchID = changedTouch.identifier;
              if (touchID === null) {
                continue;
              }
              var location = _this._getLocation(changedTouch, canvasRect);
              var touch = touchManager.getOrCreateTouch(touchID, location.x, location.y);
              if (!touch) {
                continue;
              }
              if (eventType === InputEventType.TOUCH_END || eventType === InputEventType.TOUCH_CANCEL) {
                touchManager.releaseTouch(touchID);
              }
              handleTouches.push(touch);
            }
            event.stopPropagation();
            if (event.target === _this._canvas) {
              event.preventDefault();
            }
            if (eventType === InputEventType.TOUCH_START) {
              var _this$_canvas5;
              (_this$_canvas5 = _this._canvas) === null || _this$_canvas5 === void 0 ? void 0 : _this$_canvas5.focus();
            }
            if (handleTouches.length > 0) {
              var eventTouch = new EventTouch(handleTouches, false, eventType, macro.ENABLE_MULTI_TOUCH ? touchManager.getAllTouches() : handleTouches);
              _this._eventTarget.emit(eventType, eventTouch);
            }
          };
        };
        _proto._getCanvasRect = function _getCanvasRect() {
          var canvas = this._canvas;
          var box = canvas === null || canvas === void 0 ? void 0 : canvas.getBoundingClientRect();
          if (box) {
            return new Rect$1(box.x, box.y, box.width, box.height);
          }
          return new Rect$1(0, 0, 0, 0);
        };
        _proto._getLocation = function _getLocation(touch, canvasRect) {
          if (globalThis.__globalXR && globalThis.__globalXR.ar && globalThis.__globalXR.ar.isWebXR()) {
            return new Vec2(touch.clientX, touch.clientY);
          }
          var x = touch.clientX - canvasRect.x;
          var y = canvasRect.y + canvasRect.height - touch.clientY;
          if (screenAdapter.isFrameRotated) {
            var tmp = x;
            x = canvasRect.height - y;
            y = tmp;
          }
          var dpr = screenAdapter.devicePixelRatio;
          x *= dpr;
          y *= dpr;
          return new Vec2(x, y);
        };
        _proto.on = function on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        return TouchInputSource;
      }();

      var _pointerEventTypeMap;
      var EventDispatcherPriority;
      (function (EventDispatcherPriority) {
        EventDispatcherPriority[EventDispatcherPriority["GLOBAL"] = 0] = "GLOBAL";
        EventDispatcherPriority[EventDispatcherPriority["UI"] = 1] = "UI";
      })(EventDispatcherPriority || (EventDispatcherPriority = {}));
      var InputEventDispatcher = function () {
        function InputEventDispatcher(inputEventTarget) {
          this.priority = EventDispatcherPriority.GLOBAL;
          this._inputEventTarget = void 0;
          this._inputEventTarget = inputEventTarget;
        }
        var _proto = InputEventDispatcher.prototype;
        _proto.dispatchEvent = function dispatchEvent(event) {
          this._inputEventTarget.emit(event.type, event);
          return true;
        };
        return InputEventDispatcher;
      }();
      var pointerEventTypeMap = (_pointerEventTypeMap = {}, _pointerEventTypeMap[InputEventType.MOUSE_DOWN] = InputEventType.TOUCH_START, _pointerEventTypeMap[InputEventType.MOUSE_MOVE] = InputEventType.TOUCH_MOVE, _pointerEventTypeMap[InputEventType.MOUSE_UP] = InputEventType.TOUCH_END, _pointerEventTypeMap);
      var Input = exports('eO', function () {
        function Input() {
          this._dispatchImmediately = !NATIVE;
          this._eventTarget = new EventTarget();
          this._touchInput = new TouchInputSource();
          this._mouseInput = new MouseInputSource();
          this._keyboardInput = new KeyboardInputSource();
          this._accelerometerInput = new AccelerometerInputSource();
          this._handleInput = new HandleInputDevice();
          this._hmdInput = new HMDInputDevice();
          this._handheldInput = new HandheldInputDevice();
          this._eventTouchList = [];
          this._eventMouseList = [];
          this._eventKeyboardList = [];
          this._eventAccelerationList = [];
          this._eventGamepadList = [];
          this._eventHandleList = [];
          this._eventHMDList = [];
          this._eventHandheldList = [];
          this._needSimulateTouchMoveEvent = false;
          this._inputEventDispatcher = void 0;
          this._eventDispatcherList = [];
          this._registerEvent();
          this._inputEventDispatcher = new InputEventDispatcher(this._eventTarget);
          this._registerEventDispatcher(this._inputEventDispatcher);
          GamepadInputDevice._init();
        }
        var _proto2 = Input.prototype;
        _proto2._dispatchMouseDownEvent = function _dispatchMouseDownEvent(nativeMouseEvent) {
          var _this$_mouseInput$dis, _this$_mouseInput;
          (_this$_mouseInput$dis = (_this$_mouseInput = this._mouseInput).dispatchMouseDownEvent) === null || _this$_mouseInput$dis === void 0 ? void 0 : _this$_mouseInput$dis.call(_this$_mouseInput, nativeMouseEvent);
        };
        _proto2._dispatchMouseMoveEvent = function _dispatchMouseMoveEvent(nativeMouseEvent) {
          var _this$_mouseInput$dis2, _this$_mouseInput2;
          (_this$_mouseInput$dis2 = (_this$_mouseInput2 = this._mouseInput).dispatchMouseMoveEvent) === null || _this$_mouseInput$dis2 === void 0 ? void 0 : _this$_mouseInput$dis2.call(_this$_mouseInput2, nativeMouseEvent);
        };
        _proto2._dispatchMouseUpEvent = function _dispatchMouseUpEvent(nativeMouseEvent) {
          var _this$_mouseInput$dis3, _this$_mouseInput3;
          (_this$_mouseInput$dis3 = (_this$_mouseInput3 = this._mouseInput).dispatchMouseUpEvent) === null || _this$_mouseInput$dis3 === void 0 ? void 0 : _this$_mouseInput$dis3.call(_this$_mouseInput3, nativeMouseEvent);
        };
        _proto2._dispatchMouseScrollEvent = function _dispatchMouseScrollEvent(nativeMouseEvent) {
          var _this$_mouseInput$dis4, _this$_mouseInput4;
          (_this$_mouseInput$dis4 = (_this$_mouseInput4 = this._mouseInput).dispatchScrollEvent) === null || _this$_mouseInput$dis4 === void 0 ? void 0 : _this$_mouseInput$dis4.call(_this$_mouseInput4, nativeMouseEvent);
        };
        _proto2._dispatchKeyboardDownEvent = function _dispatchKeyboardDownEvent(nativeKeyboardEvent) {
          var _this$_keyboardInput$, _this$_keyboardInput;
          (_this$_keyboardInput$ = (_this$_keyboardInput = this._keyboardInput).dispatchKeyboardDownEvent) === null || _this$_keyboardInput$ === void 0 ? void 0 : _this$_keyboardInput$.call(_this$_keyboardInput, nativeKeyboardEvent);
        };
        _proto2._dispatchKeyboardUpEvent = function _dispatchKeyboardUpEvent(nativeKeyboardEvent) {
          var _this$_keyboardInput$2, _this$_keyboardInput2;
          (_this$_keyboardInput$2 = (_this$_keyboardInput2 = this._keyboardInput).dispatchKeyboardUpEvent) === null || _this$_keyboardInput$2 === void 0 ? void 0 : _this$_keyboardInput$2.call(_this$_keyboardInput2, nativeKeyboardEvent);
        };
        _proto2.on = function on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
          return callback;
        };
        _proto2.once = function once(eventType, callback, target) {
          this._eventTarget.once(eventType, callback, target);
          return callback;
        };
        _proto2.off = function off(eventType, callback, target) {
          this._eventTarget.off(eventType, callback, target);
        };
        _proto2.getTouch = function getTouch(touchID) {
          return touchManager.getTouch(touchID);
        };
        _proto2.getAllTouches = function getAllTouches() {
          return touchManager.getAllTouches();
        };
        _proto2.getTouchCount = function getTouchCount() {
          return touchManager.getTouchCount();
        };
        _proto2.setAccelerometerEnabled = function setAccelerometerEnabled(isEnable) {
          if (isEnable) {
            this._accelerometerInput.start();
          } else {
            this._accelerometerInput.stop();
          }
        };
        _proto2.setAccelerometerInterval = function setAccelerometerInterval(intervalInMileSeconds) {
          this._accelerometerInput.setInterval(intervalInMileSeconds);
        };
        _proto2._simulateEventTouch = function _simulateEventTouch(eventMouse) {
          var eventType = pointerEventTypeMap[eventMouse.type];
          var touchID = 0;
          var touch = touchManager.getOrCreateTouch(touchID, eventMouse.getLocationX(), eventMouse.getLocationY());
          if (!touch) {
            return;
          }
          var changedTouches = [touch];
          var eventTouch = new EventTouch(changedTouches, false, eventType, eventType === InputEventType.TOUCH_END ? [] : changedTouches);
          eventTouch.windowId = eventMouse.windowId;
          if (eventType === InputEventType.TOUCH_END) {
            touchManager.releaseTouch(touchID);
          }
          this._dispatchOrPushEventTouch(eventTouch, this._eventTouchList);
        };
        _proto2._registerEventDispatcher = function _registerEventDispatcher(eventDispatcher) {
          this._eventDispatcherList.push(eventDispatcher);
          this._eventDispatcherList.sort(function (a, b) {
            return b.priority - a.priority;
          });
        };
        _proto2._emitEvent = function _emitEvent(event) {
          var length = this._eventDispatcherList.length;
          for (var i = 0; i < length; ++i) {
            var dispatcher = this._eventDispatcherList[i];
            try {
              if (!dispatcher.dispatchEvent(event)) {
                break;
              }
            } catch (e) {
              this._clearEvents();
              throw e;
            }
          }
        };
        _proto2._registerEvent = function _registerEvent() {
          var _this = this;
          if (sys.hasFeature(sys.Feature.INPUT_TOUCH)) {
            var eventTouchList = this._eventTouchList;
            this._touchInput.on(InputEventType.TOUCH_START, function (event) {
              _this._dispatchOrPushEventTouch(event, eventTouchList);
            });
            this._touchInput.on(InputEventType.TOUCH_MOVE, function (event) {
              _this._dispatchOrPushEventTouch(event, eventTouchList);
            });
            this._touchInput.on(InputEventType.TOUCH_END, function (event) {
              _this._dispatchOrPushEventTouch(event, eventTouchList);
            });
            this._touchInput.on(InputEventType.TOUCH_CANCEL, function (event) {
              _this._dispatchOrPushEventTouch(event, eventTouchList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_MOUSE)) {
            var eventMouseList = this._eventMouseList;
            this._mouseInput.on(InputEventType.MOUSE_DOWN, function (event) {
              _this._needSimulateTouchMoveEvent = true;
              _this._simulateEventTouch(event);
              _this._dispatchOrPushEvent(event, eventMouseList);
            });
            this._mouseInput.on(InputEventType.MOUSE_MOVE, function (event) {
              if (_this._needSimulateTouchMoveEvent) {
                _this._simulateEventTouch(event);
              }
              _this._dispatchOrPushEvent(event, eventMouseList);
            });
            this._mouseInput.on(InputEventType.MOUSE_UP, function (event) {
              _this._needSimulateTouchMoveEvent = false;
              _this._simulateEventTouch(event);
              _this._dispatchOrPushEvent(event, eventMouseList);
            });
            this._mouseInput.on(InputEventType.MOUSE_WHEEL, function (event) {
              _this._dispatchOrPushEvent(event, eventMouseList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_KEYBOARD)) {
            var eventKeyboardList = this._eventKeyboardList;
            this._keyboardInput.on(InputEventType.KEY_DOWN, function (event) {
              _this._dispatchOrPushEvent(event, eventKeyboardList);
            });
            this._keyboardInput.on(InputEventType.KEY_PRESSING, function (event) {
              _this._dispatchOrPushEvent(event, eventKeyboardList);
            });
            this._keyboardInput.on(InputEventType.KEY_UP, function (event) {
              _this._dispatchOrPushEvent(event, eventKeyboardList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_ACCELEROMETER)) {
            var eventAccelerationList = this._eventAccelerationList;
            this._accelerometerInput.on(InputEventType.DEVICEMOTION, function (event) {
              _this._dispatchOrPushEvent(event, eventAccelerationList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_GAMEPAD)) {
            var eventGamepadList = this._eventGamepadList;
            GamepadInputDevice._on(InputEventType.GAMEPAD_CHANGE, function (event) {
              _this._dispatchOrPushEvent(event, eventGamepadList);
            });
            GamepadInputDevice._on(InputEventType.GAMEPAD_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventGamepadList);
            });
            GamepadInputDevice._on(InputEventType.HANDLE_POSE_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventGamepadList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_HANDLE)) {
            var eventHandleList = this._eventHandleList;
            this._handleInput._on(InputEventType.HANDLE_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventHandleList);
            });
            this._handleInput._on(InputEventType.HANDLE_POSE_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventHandleList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_HMD)) {
            var eventHMDList = this._eventHMDList;
            this._hmdInput._on(InputEventType.HMD_POSE_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventHMDList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_HANDHELD)) {
            var eventHandheldList = this._eventHandheldList;
            this._handheldInput._on(InputEventType.HANDHELD_POSE_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventHandheldList);
            });
          }
        };
        _proto2._clearEvents = function _clearEvents() {
          this._eventMouseList.length = 0;
          this._eventTouchList.length = 0;
          this._eventKeyboardList.length = 0;
          this._eventAccelerationList.length = 0;
          this._eventGamepadList.length = 0;
          this._eventHandleList.length = 0;
          this._eventHMDList.length = 0;
        };
        _proto2._dispatchOrPushEvent = function _dispatchOrPushEvent(event, eventList) {
          if (this._dispatchImmediately) {
            this._emitEvent(event);
          } else {
            eventList.push(event);
          }
        };
        _proto2._dispatchOrPushEventTouch = function _dispatchOrPushEventTouch(eventTouch, touchEventList) {
          if (this._dispatchImmediately) {
            var touches = eventTouch.getTouches();
            var touchesLength = touches.length;
            for (var i = 0; i < touchesLength; ++i) {
              eventTouch.touch = touches[i];
              eventTouch.propagationStopped = eventTouch.propagationImmediateStopped = false;
              this._emitEvent(eventTouch);
            }
          } else {
            touchEventList.push(eventTouch);
          }
        };
        _proto2._frameDispatchEvents = function _frameDispatchEvents() {
          var eventHMDList = this._eventHMDList;
          for (var i = 0, length = eventHMDList.length; i < length; ++i) {
            var eventHMD = eventHMDList[i];
            this._emitEvent(eventHMD);
          }
          var eventHandheldList = this._eventHandheldList;
          for (var _i = 0, _length = eventHandheldList.length; _i < _length; ++_i) {
            var eventHandheld = eventHandheldList[_i];
            this._emitEvent(eventHandheld);
          }
          var eventMouseList = this._eventMouseList;
          for (var _i2 = 0, _length2 = eventMouseList.length; _i2 < _length2; ++_i2) {
            var eventMouse = eventMouseList[_i2];
            this._emitEvent(eventMouse);
          }
          var eventTouchList = this._eventTouchList;
          for (var _i3 = 0, _length3 = eventTouchList.length; _i3 < _length3; ++_i3) {
            var eventTouch = eventTouchList[_i3];
            var touches = eventTouch.getTouches();
            var touchesLength = touches.length;
            for (var j = 0; j < touchesLength; ++j) {
              eventTouch.touch = touches[j];
              eventTouch.propagationStopped = eventTouch.propagationImmediateStopped = false;
              this._emitEvent(eventTouch);
            }
          }
          var eventKeyboardList = this._eventKeyboardList;
          for (var _i4 = 0, _length4 = eventKeyboardList.length; _i4 < _length4; ++_i4) {
            var eventKeyboard = eventKeyboardList[_i4];
            this._emitEvent(eventKeyboard);
          }
          var eventAccelerationList = this._eventAccelerationList;
          for (var _i5 = 0, _length5 = eventAccelerationList.length; _i5 < _length5; ++_i5) {
            var eventAcceleration = eventAccelerationList[_i5];
            this._emitEvent(eventAcceleration);
          }
          var eventGamepadList = this._eventGamepadList;
          for (var _i6 = 0, _length6 = eventGamepadList.length; _i6 < _length6; ++_i6) {
            var eventGamepad = eventGamepadList[_i6];
            this._emitEvent(eventGamepad);
          }
          var eventHandleList = this._eventHandleList;
          for (var _i7 = 0, _length7 = eventHandleList.length; _i7 < _length7; ++_i7) {
            var eventHandle = eventHandleList[_i7];
            this._emitEvent(eventHandle);
          }
          this._clearEvents();
        };
        return Input;
      }());
      Input.EventType = InputEventType;
      var input$1 = exports('eN', new Input());

      var SystemEvent = exports('eQ', function (_EventTarget) {
        _inheritsLoose(SystemEvent, _EventTarget);
        function SystemEvent() {
          var _this;
          _this = _EventTarget.call(this) || this;
          input$1.on(InputEventType.MOUSE_DOWN, function (e) {
            _this.emit(SystemEventType.MOUSE_DOWN, e);
          });
          input$1.on(InputEventType.MOUSE_MOVE, function (e) {
            _this.emit(SystemEventType.MOUSE_MOVE, e);
          });
          input$1.on(InputEventType.MOUSE_UP, function (e) {
            _this.emit(SystemEventType.MOUSE_UP, e);
          });
          input$1.on(InputEventType.MOUSE_WHEEL, function (e) {
            _this.emit(SystemEventType.MOUSE_WHEEL, e);
          });
          input$1.on(InputEventType.TOUCH_START, function (e) {
            _this.emit(SystemEventType.TOUCH_START, e.touch, e);
          });
          input$1.on(InputEventType.TOUCH_MOVE, function (e) {
            _this.emit(SystemEventType.TOUCH_MOVE, e.touch, e);
          });
          input$1.on(InputEventType.TOUCH_END, function (e) {
            _this.emit(SystemEventType.TOUCH_END, e.touch, e);
          });
          input$1.on(InputEventType.TOUCH_CANCEL, function (e) {
            _this.emit(SystemEventType.TOUCH_CANCEL, e.touch, e);
          });
          input$1.on(InputEventType.KEY_DOWN, function (e) {
            _this.emit(SystemEventType.KEY_DOWN, e);
          });
          input$1.on(InputEventType.KEY_PRESSING, function (e) {
            _this.emit(SystemEventType.KEY_DOWN, e);
          });
          input$1.on(InputEventType.KEY_UP, function (e) {
            _this.emit(SystemEventType.KEY_UP, e);
          });
          input$1.on(InputEventType.DEVICEMOTION, function (e) {
            _this.emit(SystemEventType.DEVICEMOTION, e);
          });
          return _this;
        }
        var _proto = SystemEvent.prototype;
        _proto.setAccelerometerEnabled = function setAccelerometerEnabled(isEnabled) {
          input$1.setAccelerometerEnabled(isEnabled);
        };
        _proto.setAccelerometerInterval = function setAccelerometerInterval(interval) {
          input$1.setAccelerometerInterval(interval);
        };
        _proto.on = function on(type, callback, target, once) {
          _EventTarget.prototype.on.call(this, type, callback, target, once);
          return callback;
        };
        _proto.off = function off(type, callback, target) {
          _EventTarget.prototype.off.call(this, type, callback, target);
        };
        return SystemEvent;
      }(EventTarget));
      SystemEvent.EventType = SystemEventType;
      legacyCC.SystemEvent = SystemEvent;
      var systemEvent = exports('eP', new SystemEvent());
      legacyCC.systemEvent = systemEvent;

      replaceProperty(SystemEventType, 'Node.EventType', [{
        name: 'POSITION_PART',
        newName: 'TRANSFORM_CHANGED'
      }, {
        name: 'ROTATION_PART',
        newName: 'TRANSFORM_CHANGED'
      }, {
        name: 'SCALE_PART',
        newName: 'TRANSFORM_CHANGED'
      }]);
      replaceProperty(Event, 'Event', [{
        name: 'ACCELERATION',
        newName: 'DEVICEMOTION',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      markAsWarning(Event, 'Event', [{
        name: 'TOUCH',
        suggest: 'please use SystemEvent.EventType.TOUCH_START, SystemEvent.EventType.TOUCH_MOVE, SystemEvent.EventType.TOUCH_END and SystemEvent.EventType.TOUCH_CANCEL instead'
      }, {
        name: 'MOUSE',
        suggest: 'please use SystemEvent.EventType.MOUSE_DOWN, SystemEvent.EventType.MOUSE_MOVE, SystemEvent.EventType.MOUSE_UP, SystemEvent.EventType.MOUSE_WHEEL, Node.EventType.MOUSE_ENTER and Node.EventType.MOUSE_LEAVE instead'
      }, {
        name: 'KEYBOARD',
        suggest: 'please use SystemEvent.EventType.KEY_DOWN and SystemEvent.EventType.KEY_UP instead'
      }]);
      replaceProperty(EventMouse, 'EventMouse', ['DOWN', 'UP', 'MOVE'].map(function (item) {
        return {
          name: item,
          newName: "MOUSE_" + item,
          target: SystemEvent.EventType,
          targetName: 'SystemEvent.EventType'
        };
      }));
      replaceProperty(EventMouse, 'EventMouse', [{
        name: 'SCROLL',
        newName: 'MOUSE_WHEEL',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      markAsWarning(EventMouse.prototype, 'EventMouse.prototype', [{
        name: 'eventType',
        suggest: 'please use EventMouse.prototype.type instead'
      }]);
      replaceProperty(EventTouch, 'EventTouch', [{
        name: 'BEGAN',
        newName: 'TOUCH_START',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      replaceProperty(EventTouch, 'EventTouch', [{
        name: 'MOVED',
        newName: 'TOUCH_MOVE',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      replaceProperty(EventTouch, 'EventTouch', [{
        name: 'ENDED',
        newName: 'TOUCH_END',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      replaceProperty(EventTouch, 'EventTouch', [{
        name: 'CANCELLED',
        newName: 'TOUCH_CANCEL',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      markAsWarning(EventTouch.prototype, 'EventTouch.prototype', [{
        name: 'getEventCode',
        suggest: 'please use EventTouch.prototype.type instead'
      }]);
      replaceProperty(EventTouch.prototype, 'EventTouch.prototype', [{
        name: 'getUILocationInView',
        newName: 'getLocationInView',
        target: EventTouch,
        targetName: 'EventTouch'
      }]);
      markAsWarning(macro.KEY, 'macro.KEY', ['back', 'menu', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '*', '+', '-', '/', ';', '=', ',', '.', '[', ']', 'dpadLeft', 'dpadRight', 'dpadUp', 'dpadDown', 'dpadCenter'].map(function (item) {
        return {
          name: item
        };
      }));
      markAsWarning(macro.KEY, 'macro.KEY', [{
        name: 'shift',
        suggest: 'please use KeyCode.SHIFT_LEFT instead'
      }]);
      markAsWarning(macro.KEY, 'macro.KEY', [{
        name: 'ctrl',
        suggest: 'please use KeyCode.CTRL_LEFT instead'
      }]);
      markAsWarning(macro.KEY, 'macro.KEY', [{
        name: 'alt',
        suggest: 'please use KeyCode.ALT_LEFT instead'
      }]);
      markAsWarning(macro, 'macro', [{
        name: 'KEY',
        suggest: 'please use KeyCode instead'
      }]);

      var CameraFOVAxis;
      (function (CameraFOVAxis) {
        CameraFOVAxis[CameraFOVAxis["VERTICAL"] = 0] = "VERTICAL";
        CameraFOVAxis[CameraFOVAxis["HORIZONTAL"] = 1] = "HORIZONTAL";
      })(CameraFOVAxis || (CameraFOVAxis = {}));
      var CameraProjection;
      (function (CameraProjection) {
        CameraProjection[CameraProjection["ORTHO"] = 0] = "ORTHO";
        CameraProjection[CameraProjection["PERSPECTIVE"] = 1] = "PERSPECTIVE";
      })(CameraProjection || (CameraProjection = {}));
      var CameraAperture;
      (function (CameraAperture) {
        CameraAperture[CameraAperture["F1_8"] = 0] = "F1_8";
        CameraAperture[CameraAperture["F2_0"] = 1] = "F2_0";
        CameraAperture[CameraAperture["F2_2"] = 2] = "F2_2";
        CameraAperture[CameraAperture["F2_5"] = 3] = "F2_5";
        CameraAperture[CameraAperture["F2_8"] = 4] = "F2_8";
        CameraAperture[CameraAperture["F3_2"] = 5] = "F3_2";
        CameraAperture[CameraAperture["F3_5"] = 6] = "F3_5";
        CameraAperture[CameraAperture["F4_0"] = 7] = "F4_0";
        CameraAperture[CameraAperture["F4_5"] = 8] = "F4_5";
        CameraAperture[CameraAperture["F5_0"] = 9] = "F5_0";
        CameraAperture[CameraAperture["F5_6"] = 10] = "F5_6";
        CameraAperture[CameraAperture["F6_3"] = 11] = "F6_3";
        CameraAperture[CameraAperture["F7_1"] = 12] = "F7_1";
        CameraAperture[CameraAperture["F8_0"] = 13] = "F8_0";
        CameraAperture[CameraAperture["F9_0"] = 14] = "F9_0";
        CameraAperture[CameraAperture["F10_0"] = 15] = "F10_0";
        CameraAperture[CameraAperture["F11_0"] = 16] = "F11_0";
        CameraAperture[CameraAperture["F13_0"] = 17] = "F13_0";
        CameraAperture[CameraAperture["F14_0"] = 18] = "F14_0";
        CameraAperture[CameraAperture["F16_0"] = 19] = "F16_0";
        CameraAperture[CameraAperture["F18_0"] = 20] = "F18_0";
        CameraAperture[CameraAperture["F20_0"] = 21] = "F20_0";
        CameraAperture[CameraAperture["F22_0"] = 22] = "F22_0";
      })(CameraAperture || (CameraAperture = {}));
      var CameraISO;
      (function (CameraISO) {
        CameraISO[CameraISO["ISO100"] = 0] = "ISO100";
        CameraISO[CameraISO["ISO200"] = 1] = "ISO200";
        CameraISO[CameraISO["ISO400"] = 2] = "ISO400";
        CameraISO[CameraISO["ISO800"] = 3] = "ISO800";
      })(CameraISO || (CameraISO = {}));
      var CameraShutter;
      (function (CameraShutter) {
        CameraShutter[CameraShutter["D1"] = 0] = "D1";
        CameraShutter[CameraShutter["D2"] = 1] = "D2";
        CameraShutter[CameraShutter["D4"] = 2] = "D4";
        CameraShutter[CameraShutter["D8"] = 3] = "D8";
        CameraShutter[CameraShutter["D15"] = 4] = "D15";
        CameraShutter[CameraShutter["D30"] = 5] = "D30";
        CameraShutter[CameraShutter["D60"] = 6] = "D60";
        CameraShutter[CameraShutter["D125"] = 7] = "D125";
        CameraShutter[CameraShutter["D250"] = 8] = "D250";
        CameraShutter[CameraShutter["D500"] = 9] = "D500";
        CameraShutter[CameraShutter["D1000"] = 10] = "D1000";
        CameraShutter[CameraShutter["D2000"] = 11] = "D2000";
        CameraShutter[CameraShutter["D4000"] = 12] = "D4000";
      })(CameraShutter || (CameraShutter = {}));
      var CameraType;
      (function (CameraType) {
        CameraType[CameraType["DEFAULT"] = -1] = "DEFAULT";
        CameraType[CameraType["LEFT_EYE"] = 0] = "LEFT_EYE";
        CameraType[CameraType["RIGHT_EYE"] = 1] = "RIGHT_EYE";
        CameraType[CameraType["MAIN"] = 2] = "MAIN";
      })(CameraType || (CameraType = {}));
      var TrackingType;
      (function (TrackingType) {
        TrackingType[TrackingType["NO_TRACKING"] = 0] = "NO_TRACKING";
        TrackingType[TrackingType["POSITION_AND_ROTATION"] = 1] = "POSITION_AND_ROTATION";
        TrackingType[TrackingType["POSITION"] = 2] = "POSITION";
        TrackingType[TrackingType["ROTATION"] = 3] = "ROTATION";
      })(TrackingType || (TrackingType = {}));
      var CameraUsage;
      (function (CameraUsage) {
        CameraUsage[CameraUsage["EDITOR"] = 0] = "EDITOR";
        CameraUsage[CameraUsage["GAME_VIEW"] = 1] = "GAME_VIEW";
        CameraUsage[CameraUsage["SCENE_VIEW"] = 2] = "SCENE_VIEW";
        CameraUsage[CameraUsage["PREVIEW"] = 3] = "PREVIEW";
        CameraUsage[CameraUsage["GAME"] = 100] = "GAME";
      })(CameraUsage || (CameraUsage = {}));
      var FSTOPS = [1.8, 2.0, 2.2, 2.5, 2.8, 3.2, 3.5, 4.0, 4.5, 5.0, 5.6, 6.3, 7.1, 8.0, 9.0, 10.0, 11.0, 13.0, 14.0, 16.0, 18.0, 20.0, 22.0];
      var SHUTTERS = [1.0, 1.0 / 2.0, 1.0 / 4.0, 1.0 / 8.0, 1.0 / 15.0, 1.0 / 30.0, 1.0 / 60.0, 1.0 / 125.0, 1.0 / 250.0, 1.0 / 500.0, 1.0 / 1000.0, 1.0 / 2000.0, 1.0 / 4000.0];
      var ISOS = [100.0, 200.0, 400.0, 800.0];
      var v_a = new Vec3();
      var v_b = new Vec3();
      var _tempMat1 = new Mat4();
      var SKYBOX_FLAG = ClearFlagBit.STENCIL << 1;
      var correctionMatrices = [];
      var Camera$1 = function () {
        function Camera(device) {
          this.isWindowSize = true;
          this.screenScale = void 0;
          this.postProcess = null;
          this.usePostProcess = false;
          this.pipeline = '';
          this._device = void 0;
          this._scene = null;
          this._node = null;
          this._name = null;
          this._enabled = false;
          this._proj = -1;
          this._aspect = void 0;
          this._orthoHeight = 10.0;
          this._fovAxis = CameraFOVAxis.VERTICAL;
          this._fov = toRadian(45);
          this._nearClip = 1.0;
          this._farClip = 1000.0;
          this._clearColor = new Color(0.2, 0.2, 0.2, 1);
          this._viewport = new Rect$1(0, 0, 1, 1);
          this._orientedViewport = new Rect$1(0, 0, 1, 1);
          this._curTransform = SurfaceTransform.IDENTITY;
          this._isProjDirty = true;
          this._matView = new Mat4();
          this._matProj = new Mat4();
          this._matProjInv = new Mat4();
          this._matViewProj = new Mat4();
          this._matViewProjInv = new Mat4();
          this._frustum = new Frustum();
          this._forward = new Vec3();
          this._position = new Vec3();
          this._priority = 0;
          this._aperture = CameraAperture.F16_0;
          this._apertureValue = void 0;
          this._shutter = CameraShutter.D125;
          this._shutterValue = 0.0;
          this._iso = CameraISO.ISO100;
          this._isoValue = 0.0;
          this._window = null;
          this._width = 1;
          this._height = 1;
          this._clearFlag = ClearFlagBit.NONE;
          this._clearDepth = 1.0;
          this._visibility = CAMERA_DEFAULT_MASK;
          this._exposure = 0;
          this._clearStencil = 0;
          this._geometryRenderer = null;
          this._windowId = 0;
          this._cameraType = CameraType.DEFAULT;
          this._trackingType = TrackingType.NO_TRACKING;
          this._usage = CameraUsage.GAME;
          this._device = device;
          this._apertureValue = FSTOPS[this._aperture];
          this._shutterValue = SHUTTERS[this._shutter];
          this._isoValue = ISOS[this._iso];
          this._aspect = this.screenScale = 1;
          this._frustum.accurate = true;
          if (!correctionMatrices.length) {
            var ySign = device.capabilities.clipSpaceSignY;
            correctionMatrices[SurfaceTransform.IDENTITY] = new Mat4(1, 0, 0, 0, 0, ySign);
            correctionMatrices[SurfaceTransform.ROTATE_90] = new Mat4(0, 1, 0, 0, -ySign, 0);
            correctionMatrices[SurfaceTransform.ROTATE_180] = new Mat4(-1, 0, 0, 0, 0, -ySign);
            correctionMatrices[SurfaceTransform.ROTATE_270] = new Mat4(0, -1, 0, 0, ySign, 0);
          }
        }
        var _proto = Camera.prototype;
        _proto._updateAspect = function _updateAspect(oriented) {
          if (oriented === void 0) {
            oriented = true;
          }
          this._aspect = this.window.width * this._viewport.width / (this.window.height * this._viewport.height);
          if (oriented) {
            var swapchain = this.window.swapchain;
            var orientation = swapchain && swapchain.surfaceTransform || SurfaceTransform.IDENTITY;
            if (orientation % 2) this._aspect = 1 / this._aspect;
          }
          this._isProjDirty = true;
        };
        _proto.initialize = function initialize(info) {
          if (info.usage !== undefined) {
            this._usage = info.usage;
          } else {
            this.setDefaultUsage();
          }
          if (info.trackingType !== undefined) {
            this._trackingType = info.trackingType;
          }
          if (info.cameraType !== undefined) {
            this._cameraType = info.cameraType;
          }
          this.node = info.node;
          this._width = 1;
          this._height = 1;
          this.clearFlag = ClearFlagBit.NONE;
          this.clearDepth = 1.0;
          this.visibility = CAMERA_DEFAULT_MASK;
          this._name = info.name;
          this._proj = info.projection;
          this._priority = info.priority || 0;
          this._aspect = this.screenScale = 1;
          this.updateExposure();
          this.changeTargetWindow(info.window);
        };
        _proto.destroy = function destroy() {
          var _this$_geometryRender;
          this._node = null;
          this.detachFromScene();
          if (this._window) {
            this._window.detachCamera(this);
            this.window = null;
          }
          this._name = null;
          (_this$_geometryRender = this._geometryRenderer) === null || _this$_geometryRender === void 0 ? void 0 : _this$_geometryRender.destroy();
        };
        _proto.attachToScene = function attachToScene(scene) {
          this._enabled = true;
          this._scene = scene;
        };
        _proto.detachFromScene = function detachFromScene() {
          this._enabled = false;
          this._scene = null;
        };
        _proto.resize = function resize(width, height) {
          if (!this._window) return;
          this._width = width;
          this._height = height;
          this._aspect = width * this._viewport.width / (height * this._viewport.height);
          this._isProjDirty = true;
        };
        _proto.setFixedSize = function setFixedSize(width, height) {
          this._width = width;
          this._height = height;
          this._updateAspect();
          this.isWindowSize = false;
        };
        _proto.syncCameraEditor = function syncCameraEditor(camera) {
        };
        _proto.update = function update(forceUpdate) {
          var _this$window;
          if (forceUpdate === void 0) {
            forceUpdate = false;
          }
          if (!this._node) return;
          var viewProjDirty = false;
          var xr = globalThis.__globalXR;
          if (xr && xr.isWebXR && xr.webXRWindowMap && xr.updateViewport) {
            var x = xr.webXRMatProjs ? 1 / xr.webXRMatProjs.length : 1;
            var wndXREye = xr.webXRWindowMap.get(this._window);
            this.setViewportInOrientedSpace(new Rect$1(x * wndXREye, 0, x, 1));
          }
          if (this._node.hasChangedFlags || forceUpdate) {
            Mat4.invert(this._matView, this._node.worldMatrix);
            this._forward.x = -this._matView.m02;
            this._forward.y = -this._matView.m06;
            this._forward.z = -this._matView.m10;
            Mat4.multiply(this._matView, new Mat4().scale(this._node.worldScale), this._matView);
            this._node.getWorldPosition(this._position);
            viewProjDirty = true;
          }
          var swapchain = (_this$window = this.window) === null || _this$window === void 0 ? void 0 : _this$window.swapchain;
          var orientation = swapchain && swapchain.surfaceTransform || SurfaceTransform.IDENTITY;
          if (this._isProjDirty || this._curTransform !== orientation) {
            this._curTransform = orientation;
            var projectionSignY = this._device.capabilities.clipSpaceSignY;
            if (this._proj === CameraProjection.PERSPECTIVE) {
              if (xr && xr.isWebXR && xr.webXRWindowMap && xr.webXRMatProjs) {
                var _wndXREye = xr.webXRWindowMap.get(this._window);
                this._matProj.set(xr.webXRMatProjs[_wndXREye]);
              } else {
                Mat4.perspective(this._matProj, this._fov, this._aspect, this._nearClip, this._farClip, this._fovAxis === CameraFOVAxis.VERTICAL, this._device.capabilities.clipSpaceMinZ, projectionSignY, orientation);
              }
            } else {
              var _x = this._orthoHeight * this._aspect;
              var y = this._orthoHeight;
              Mat4.ortho(this._matProj, -_x, _x, -y, y, this._nearClip, this._farClip, this._device.capabilities.clipSpaceMinZ, projectionSignY, orientation);
            }
            Mat4.invert(this._matProjInv, this._matProj);
            viewProjDirty = true;
            this._isProjDirty = false;
          }
          if (viewProjDirty) {
            Mat4.multiply(this._matViewProj, this._matProj, this._matView);
            Mat4.invert(this._matViewProjInv, this._matViewProj);
            this._frustum.update(this._matViewProj, this._matViewProjInv);
          }
        };
        _proto.setViewportInOrientedSpace = function setViewportInOrientedSpace(val) {
          var _this$window2;
          var x = val.x,
            width = val.width,
            height = val.height;
          var y = this._device.capabilities.screenSpaceSignY < 0 ? 1 - val.y - height : val.y;
          var swapchain = (_this$window2 = this.window) === null || _this$window2 === void 0 ? void 0 : _this$window2.swapchain;
          var orientation = swapchain && swapchain.surfaceTransform || SurfaceTransform.IDENTITY;
          switch (orientation) {
            case SurfaceTransform.ROTATE_90:
              this._viewport.x = 1 - y - height;
              this._viewport.y = x;
              this._viewport.width = height;
              this._viewport.height = width;
              break;
            case SurfaceTransform.ROTATE_180:
              this._viewport.x = 1 - x - width;
              this._viewport.y = 1 - y - height;
              this._viewport.width = width;
              this._viewport.height = height;
              break;
            case SurfaceTransform.ROTATE_270:
              this._viewport.x = y;
              this._viewport.y = 1 - x - width;
              this._viewport.width = height;
              this._viewport.height = width;
              break;
            case SurfaceTransform.IDENTITY:
              this._viewport.x = x;
              this._viewport.y = y;
              this._viewport.width = width;
              this._viewport.height = height;
              break;
          }
          this._orientedViewport.x = x;
          this._orientedViewport.y = y;
          this._orientedViewport.width = width;
          this._orientedViewport.height = height;
          this.resize(this.width, this.height);
        };
        _proto.initGeometryRenderer = function initGeometryRenderer() {
          if (!this._geometryRenderer) {
            var _this$_geometryRender2;
            this._geometryRenderer = legacyCC.internal.GeometryRenderer ? new legacyCC.internal.GeometryRenderer() : null;
            (_this$_geometryRender2 = this._geometryRenderer) === null || _this$_geometryRender2 === void 0 ? void 0 : _this$_geometryRender2.activate(this._device);
          }
        };
        _proto.changeTargetWindow = function changeTargetWindow(window) {
          if (window === void 0) {
            window = null;
          }
          if (this._window) {
            this._window.detachCamera(this);
          }
          var win = window || legacyCC.director.root.mainWindow;
          if (win) {
            win.attachCamera(this);
            this.window = win;
            var swapchain = win.swapchain;
            var orientation = swapchain && swapchain.surfaceTransform || SurfaceTransform.IDENTITY;
            if (orientation % 2) this.resize(win.height, win.width);else this.resize(win.width, win.height);
          }
        };
        _proto.detachCamera = function detachCamera() {
          if (this._window) {
            this._window.detachCamera(this);
          }
        };
        _proto.screenPointToRay = function screenPointToRay(out, x, y) {
          if (!this._node) return null;
          var width = this.width;
          var height = this.height;
          var cx = this._orientedViewport.x * width;
          var cy = this._orientedViewport.y * height;
          var cw = this._orientedViewport.width * width;
          var ch = this._orientedViewport.height * height;
          var isProj = this._proj === CameraProjection.PERSPECTIVE;
          var ySign = this._device.capabilities.clipSpaceSignY;
          var preTransform = preTransforms[this._curTransform];
          Vec3.set(v_a, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, isProj ? 1 : -1);
          var ox = v_a.x,
            oy = v_a.y;
          v_a.x = ox * preTransform[0] + oy * preTransform[2] * ySign;
          v_a.y = ox * preTransform[1] + oy * preTransform[3] * ySign;
          Vec3.transformMat4(isProj ? v_a : out.o, v_a, this._matViewProjInv);
          if (isProj) {
            this._node.getWorldPosition(v_b);
            Ray.fromPoints(out, v_b, v_a);
          } else {
            Vec3.transformQuat(out.d, Vec3.FORWARD, this._node.worldRotation);
          }
          return out;
        };
        _proto.screenToWorld = function screenToWorld(out, screenPos) {
          var width = this.width;
          var height = this.height;
          var cx = this._orientedViewport.x * width;
          var cy = this._orientedViewport.y * height;
          var cw = this._orientedViewport.width * width;
          var ch = this._orientedViewport.height * height;
          var ySign = this._device.capabilities.clipSpaceSignY;
          var preTransform = preTransforms[this._curTransform];
          if (this._proj === CameraProjection.PERSPECTIVE) {
            Vec3.set(out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, 1.0);
            var x = out.x,
              y = out.y;
            out.x = x * preTransform[0] + y * preTransform[2] * ySign;
            out.y = x * preTransform[1] + y * preTransform[3] * ySign;
            Vec3.transformMat4(out, out, this._matViewProjInv);
            if (this._node) {
              this._node.getWorldPosition(v_a);
            }
            Vec3.lerp(out, v_a, out, lerp(this._nearClip / this._farClip, 1, screenPos.z));
          } else {
            Vec3.set(out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, screenPos.z * 2 - 1);
            var _x2 = out.x,
              _y = out.y;
            out.x = _x2 * preTransform[0] + _y * preTransform[2] * ySign;
            out.y = _x2 * preTransform[1] + _y * preTransform[3] * ySign;
            Vec3.transformMat4(out, out, this._matViewProjInv);
          }
          return out;
        };
        _proto.worldToScreen = function worldToScreen(out, worldPos) {
          var ySign = this._device.capabilities.clipSpaceSignY;
          var preTransform = preTransforms[this._curTransform];
          Vec3.transformMat4(out, worldPos, this._matViewProj);
          var x = out.x,
            y = out.y;
          out.x = x * preTransform[0] + y * preTransform[2] * ySign;
          out.y = x * preTransform[1] + y * preTransform[3] * ySign;
          var width = this.width;
          var height = this.height;
          var cx = this._orientedViewport.x * width;
          var cy = this._orientedViewport.y * height;
          var cw = this._orientedViewport.width * width;
          var ch = this._orientedViewport.height * height;
          out.x = cx + (out.x + 1) * 0.5 * cw;
          out.y = cy + (out.y + 1) * 0.5 * ch;
          out.z = out.z * 0.5 + 0.5;
          return out;
        };
        _proto.worldMatrixToScreen = function worldMatrixToScreen(out, worldMatrix, width, height) {
          Mat4.multiply(out, this._matViewProj, worldMatrix);
          Mat4.multiply(out, correctionMatrices[this._curTransform], out);
          var halfWidth = width / 2;
          var halfHeight = height / 2;
          Mat4.identity(_tempMat1);
          Mat4.transform(_tempMat1, _tempMat1, Vec3.set(v_a, halfWidth, halfHeight, 0));
          Mat4.scale(_tempMat1, _tempMat1, Vec3.set(v_a, halfWidth, halfHeight, 1));
          Mat4.multiply(out, _tempMat1, out);
          return out;
        };
        _proto.calculateObliqueMat = function calculateObliqueMat(viewSpacePlane) {
          var clipFar = new Vec4(Math.sign(viewSpacePlane.x), Math.sign(viewSpacePlane.y), 1.0, 1.0);
          var viewFar = clipFar.transformMat4(this._matProjInv);
          var m4 = new Vec4(this._matProj.m03, this._matProj.m07, this._matProj.m11, this._matProj.m15);
          var scale = 2.0 / Vec4.dot(viewSpacePlane, viewFar);
          var newViewSpaceNearPlane = viewSpacePlane.multiplyScalar(scale);
          var m3 = newViewSpaceNearPlane.subtract(m4);
          this._matProj.m02 = m3.x;
          this._matProj.m06 = m3.y;
          this._matProj.m10 = m3.z;
          this._matProj.m14 = m3.w;
        };
        _proto.getClipSpaceMinz = function getClipSpaceMinz() {
          return this._device.capabilities.clipSpaceMinZ;
        };
        _proto.setExposure = function setExposure(ev100) {
          this._exposure = 0.833333 / Math.pow(2.0, ev100);
        };
        _proto.updateExposure = function updateExposure() {
          var ev100 = Math.log2(this._apertureValue * this._apertureValue / this._shutterValue * 100.0 / this._isoValue);
          this.setExposure(ev100);
        };
        _proto.setDefaultUsage = function setDefaultUsage() {
          {
            this._usage = CameraUsage.GAME;
          }
        };
        _createClass(Camera, [{
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "scene",
          get: function get() {
            return this._scene;
          }
        }, {
          key: "node",
          get: function get() {
            return this._node;
          },
          set: function set(val) {
            this._node = val;
          }
        }, {
          key: "systemWindowId",
          get: function get() {
            return this._windowId;
          }
        }, {
          key: "window",
          get: function get() {
            return this._window;
          },
          set: function set(val) {
            this._window = val;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(vis) {
            this._visibility = vis;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(val) {
            this._priority = val;
          }
        }, {
          key: "width",
          get: function get() {
            return this._width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          }
        }, {
          key: "position",
          get: function get() {
            return this._position;
          },
          set: function set(val) {
            this._position = val;
          }
        }, {
          key: "forward",
          get: function get() {
            return this._forward;
          },
          set: function set(val) {
            this._forward = val;
          }
        }, {
          key: "aperture",
          get: function get() {
            return this._aperture;
          },
          set: function set(val) {
            this._aperture = val;
            this._apertureValue = FSTOPS[this._aperture];
            this.updateExposure();
          }
        }, {
          key: "apertureValue",
          get: function get() {
            return this._apertureValue;
          }
        }, {
          key: "shutter",
          get: function get() {
            return this._shutter;
          },
          set: function set(val) {
            this._shutter = val;
            this._shutterValue = SHUTTERS[this._shutter];
            this.updateExposure();
          }
        }, {
          key: "shutterValue",
          get: function get() {
            return this._shutterValue;
          }
        }, {
          key: "iso",
          get: function get() {
            return this._iso;
          },
          set: function set(val) {
            this._iso = val;
            this._isoValue = ISOS[this._iso];
            this.updateExposure();
          }
        }, {
          key: "isoValue",
          get: function get() {
            return this._isoValue;
          }
        }, {
          key: "exposure",
          get: function get() {
            return this._exposure;
          }
        }, {
          key: "clearFlag",
          get: function get() {
            return this._clearFlag;
          },
          set: function set(flag) {
            this._clearFlag = flag;
          }
        }, {
          key: "clearColor",
          get: function get() {
            return this._clearColor;
          },
          set: function set(val) {
            this._clearColor.x = val.x;
            this._clearColor.y = val.y;
            this._clearColor.z = val.z;
            this._clearColor.w = val.w;
          }
        }, {
          key: "clearDepth",
          get: function get() {
            return this._clearDepth;
          },
          set: function set(depth) {
            this._clearDepth = depth;
          }
        }, {
          key: "clearStencil",
          get: function get() {
            return this._clearStencil;
          },
          set: function set(stencil) {
            this._clearStencil = stencil;
          }
        }, {
          key: "projectionType",
          get: function get() {
            return this._proj;
          },
          set: function set(val) {
            this._proj = val;
            this._isProjDirty = true;
          }
        }, {
          key: "aspect",
          get: function get() {
            return this._aspect;
          }
        }, {
          key: "orthoHeight",
          get: function get() {
            return this._orthoHeight;
          },
          set: function set(val) {
            this._orthoHeight = val;
            this._isProjDirty = true;
          }
        }, {
          key: "fovAxis",
          get: function get() {
            return this._fovAxis;
          },
          set: function set(axis) {
            this._fovAxis = axis;
            this._isProjDirty = true;
          }
        }, {
          key: "fov",
          get: function get() {
            return this._fov;
          },
          set: function set(fov) {
            this._fov = fov;
            this._isProjDirty = true;
          }
        }, {
          key: "nearClip",
          get: function get() {
            return this._nearClip;
          },
          set: function set(nearClip) {
            this._nearClip = nearClip;
            this._isProjDirty = true;
          }
        }, {
          key: "farClip",
          get: function get() {
            return this._farClip;
          },
          set: function set(farClip) {
            this._farClip = farClip;
            this._isProjDirty = true;
          }
        }, {
          key: "viewport",
          get: function get() {
            return this._viewport;
          },
          set: function set(val) {
            warnID(8302);
            this.setViewportInOrientedSpace(val);
          }
        }, {
          key: "frustum",
          get: function get() {
            return this._frustum;
          },
          set: function set(val) {
            this._frustum = val;
          }
        }, {
          key: "matView",
          get: function get() {
            return this._matView;
          }
        }, {
          key: "matProj",
          get: function get() {
            return this._matProj;
          }
        }, {
          key: "matProjInv",
          get: function get() {
            return this._matProjInv;
          }
        }, {
          key: "matViewProj",
          get: function get() {
            return this._matViewProj;
          }
        }, {
          key: "matViewProjInv",
          get: function get() {
            return this._matViewProjInv;
          }
        }, {
          key: "surfaceTransform",
          get: function get() {
            return this._curTransform;
          }
        }, {
          key: "geometryRenderer",
          get: function get() {
            return this._geometryRenderer;
          }
        }, {
          key: "cameraType",
          get: function get() {
            return this._cameraType;
          },
          set: function set(type) {
            this._cameraType = type;
          }
        }, {
          key: "trackingType",
          get: function get() {
            return this._trackingType;
          },
          set: function set(type) {
            this._trackingType = type;
          }
        }, {
          key: "cameraUsage",
          get: function get() {
            return this._usage;
          },
          set: function set(usage) {
            this._usage = usage;
          }
        }], [{
          key: "standardExposureValue",
          get: function get() {
            return 1.0 / 38400.0;
          }
        }, {
          key: "standardLightMeterScale",
          get: function get() {
            return 10000.0;
          }
        }]);
        return Camera;
      }();

      var _tempVec3$4 = new Vec3();
      var _sphere = Sphere.create(0, 0, 0, 1);
      var _rangedDirLightBoundingBox$3 = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5);
      var _tmpBoundingBox$3 = new AABB();
      var roPool = new Pool(function () {
        return {
          model: null,
          depth: 0
        };
      }, 128);
      function getRenderObject(model, camera) {
        var depth = 0;
        if (model.node) {
          Vec3.subtract(_tempVec3$4, model.worldBounds ? model.worldBounds.center : model.node.worldPosition, camera.position);
          depth = Vec3.dot(_tempVec3$4, camera.forward);
        }
        var ro = roPool.alloc();
        ro.model = model;
        ro.depth = depth;
        return ro;
      }
      function validPunctualLightsCulling$1(pipeline, camera) {
        var sceneData = pipeline.pipelineSceneData;
        var validPunctualLights = sceneData.validPunctualLights;
        validPunctualLights.length = 0;
        var _ref = camera.scene,
          spotLights = _ref.spotLights;
        for (var i = 0; i < spotLights.length; i++) {
          var light = spotLights[i];
          if (light.baked && !camera.node.scene.globals.disableLightmap) {
            continue;
          }
          Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(light);
          }
        }
        var _ref2 = camera.scene,
          sphereLights = _ref2.sphereLights;
        for (var _i = 0; _i < sphereLights.length; _i++) {
          var _light = sphereLights[_i];
          if (_light.baked && !camera.node.scene.globals.disableLightmap) {
            continue;
          }
          Sphere.set(_sphere, _light.position.x, _light.position.y, _light.position.z, _light.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(_light);
          }
        }
        var _ref3 = camera.scene,
          pointLights = _ref3.pointLights;
        for (var _i2 = 0; _i2 < pointLights.length; _i2++) {
          var _light2 = pointLights[_i2];
          if (_light2.baked) {
            continue;
          }
          Sphere.set(_sphere, _light2.position.x, _light2.position.y, _light2.position.z, _light2.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(_light2);
          }
        }
        var _ref4 = camera.scene,
          rangedDirLights = _ref4.rangedDirLights;
        for (var _i3 = 0; _i3 < rangedDirLights.length; _i3++) {
          var _light3 = rangedDirLights[_i3];
          AABB.transform(_tmpBoundingBox$3, _rangedDirLightBoundingBox$3, _light3.node.getWorldMatrix());
          if (intersect.aabbFrustum(_tmpBoundingBox$3, camera.frustum)) {
            validPunctualLights.push(_light3);
          }
        }
        sceneData.validPunctualLights = validPunctualLights;
      }
      function shadowCulling(camera, sceneData, layer) {
        var scene = camera.scene;
        var mainLight = scene.mainLight;
        var csmLayers = sceneData.csmLayers;
        var csmLayerObjects = csmLayers.layerObjects;
        var dirLightFrustum = layer.validFrustum;
        var dirShadowObjects = layer.shadowObjects;
        dirShadowObjects.length = 0;
        var visibility = camera.visibility;
        for (var i = csmLayerObjects.length - 1; i >= 0; i--) {
          var obj = csmLayerObjects.array[i];
          if (!obj) {
            csmLayerObjects.fastRemove(i);
            continue;
          }
          var model = obj.model;
          if (!model || !model.enabled || !model.node) {
            csmLayerObjects.fastRemove(i);
            continue;
          }
          if ((visibility & model.node.layer) !== model.node.layer && !(visibility & model.visFlags)) {
            csmLayerObjects.fastRemove(i);
            continue;
          }
          if (!model.worldBounds || !model.castShadow) {
            csmLayerObjects.fastRemove(i);
            continue;
          }
          var accurate = intersect.aabbFrustum(model.worldBounds, dirLightFrustum);
          if (!accurate) {
            continue;
          }
          dirShadowObjects.push(obj);
          if (layer.level < mainLight.csmLevel) {
            if (mainLight.csmOptimizationMode === CSMOptimizationMode.RemoveDuplicates && intersect.aabbFrustumCompletelyInside(model.worldBounds, dirLightFrustum)) {
              csmLayerObjects.fastRemove(i);
            }
          }
        }
      }
      function sceneCulling(pipeline, camera) {
        var scene = camera.scene;
        var mainLight = scene.mainLight;
        var sceneData = pipeline.pipelineSceneData;
        var shadows = sceneData.shadows;
        var skybox = sceneData.skybox;
        var csmLayers = sceneData.csmLayers;
        var renderObjects = sceneData.renderObjects;
        roPool.freeArray(renderObjects);
        renderObjects.length = 0;
        var castShadowObjects = csmLayers.castShadowObjects;
        castShadowObjects.length = 0;
        var csmLayerObjects = csmLayers.layerObjects;
        csmLayerObjects.clear();
        if (shadows.enabled) {
          pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor);
          if (shadows.type === ShadowType.ShadowMap) {
            if (mainLight && mainLight.node) {
              csmLayers.update(sceneData, camera);
            }
          }
        }
        if (camera.clearFlag & SKYBOX_FLAG) {
          if (skybox.enabled && skybox.model) {
            renderObjects.push(getRenderObject(skybox.model, camera));
          } else if (camera.cameraUsage !== CameraUsage.EDITOR && camera.cameraUsage !== CameraUsage.SCENE_VIEW) {
            legacyCC.warnID(15100, camera.name);
          }
        }
        var models = scene.models;
        var visibility = camera.visibility;
        function enqueueRenderObject(model) {
          if (model.enabled) {
            if (scene.isCulledByLod(camera, model)) {
              return;
            }
            if (model.castShadow) {
              castShadowObjects.push(getRenderObject(model, camera));
              csmLayerObjects.push(getRenderObject(model, camera));
            }
            if (model.node && (visibility & model.node.layer) === model.node.layer || visibility & model.visFlags) {
              if (model.worldBounds && !intersect.aabbFrustum(model.worldBounds, camera.frustum)) {
                return;
              }
              renderObjects.push(getRenderObject(model, camera));
            }
          }
        }
        for (var i = 0; i < models.length; i++) {
          enqueueRenderObject(models[i]);
        }
      }

      var _dec$3m, _class$3h;
      var _colorAttachment = new ColorAttachment();
      _colorAttachment.format = Format.RGBA8;
      var _depthStencilAttachment = new DepthStencilAttachment();
      _depthStencilAttachment.format = Format.DEPTH_STENCIL;
      var passInfo = new RenderPassInfo([_colorAttachment], _depthStencilAttachment);
      var _windowInfo = {
        width: 1,
        height: 1,
        renderPassInfo: passInfo
      };
      var RenderTexture = exports('em', (_dec$3m = ccclass$M('cc.RenderTexture'), _dec$3m(_class$3h = function (_TextureBase) {
        _inheritsLoose(RenderTexture, _TextureBase);
        function RenderTexture() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _TextureBase.call.apply(_TextureBase, [this].concat(args)) || this;
          _this._window = null;
          return _this;
        }
        var _proto = RenderTexture.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name || '';
          this._width = info.width;
          this._height = info.height;
          this._initWindow(info);
        };
        _proto.reset = function reset(info) {
          this.initialize(info);
        };
        _proto.destroy = function destroy() {
          if (this._window) {
            var root = legacyCC.director.root;
            root === null || root === void 0 ? void 0 : root.destroyWindow(this._window);
            this._window = null;
          }
          return _TextureBase.prototype.destroy.call(this);
        };
        _proto.resize = function resize(width, height) {
          this._width = Math.floor(clamp$1(width, 1, 2048));
          this._height = Math.floor(clamp$1(height, 1, 2048));
          if (this._window) {
            this._window.resize(this._width, this._height);
          }
          this.emit('resize', this._window);
        };
        _proto._serialize = function _serialize(ctxForExporting) {
          return {};
        };
        _proto._deserialize = function _deserialize(serializedData, handle) {
          var data = serializedData;
          this._width = data.w;
          this._height = data.h;
          this._name = data.n;
          _TextureBase.prototype._deserialize.call(this, data.base, handle);
        };
        _proto.getGFXTexture = function getGFXTexture() {
          return this._window && this._window.framebuffer.colorTextures[0];
        };
        _proto.onLoaded = function onLoaded() {
          this._initWindow();
        };
        _proto._initWindow = function _initWindow(info) {
          var root = legacyCC.director.root;
          _windowInfo.title = this._name;
          _windowInfo.width = this._width;
          _windowInfo.height = this._height;
          _windowInfo.renderPassInfo = info && info.passInfo ? info.passInfo : passInfo;
          _windowInfo.externalResLow = info && info.externalResLow ? info.externalResLow : 0;
          _windowInfo.externalResHigh = info && info.externalResHigh ? info.externalResHigh : 0;
          _windowInfo.externalFlag = info && info.externalFlag ? info.externalFlag : TextureFlagBit.NONE;
          _colorAttachment.barrier = deviceManager.gfxDevice.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.FRAGMENT_SHADER_READ_TEXTURE, AccessFlagBit.FRAGMENT_SHADER_READ_TEXTURE));
          if (this._window) {
            this._window.destroy();
            this._window.initialize(deviceManager.gfxDevice, _windowInfo);
          } else {
            this._window = root.createWindow(_windowInfo);
          }
        };
        _proto.initDefault = function initDefault(uuid) {
          _TextureBase.prototype.initDefault.call(this, uuid);
          this._width = this._height = 1;
          this._initWindow();
        };
        _proto.validate = function validate() {
          return this.width >= 1 && this.width <= 2048 && this.height >= 1 && this.height <= 2048;
        };
        _proto.readPixels = function readPixels(x, y, width, height, buffer) {
          if (x === void 0) {
            x = 0;
          }
          if (y === void 0) {
            y = 0;
          }
          width = width || this.width;
          height = height || this.height;
          var gfxTexture = this.getGFXTexture();
          if (!gfxTexture) {
            errorID(7606);
            return null;
          }
          var needSize = 4 * width * height;
          if (buffer === undefined) {
            buffer = new Uint8Array(needSize);
          } else if (buffer.length < needSize) {
            errorID(7607, needSize);
            return null;
          }
          var gfxDevice = this._getGFXDevice();
          var bufferViews = [];
          var regions = [];
          var region0 = new BufferTextureCopy();
          region0.texOffset.x = x;
          region0.texOffset.y = y;
          region0.texExtent.width = width;
          region0.texExtent.height = height;
          regions.push(region0);
          bufferViews.push(buffer);
          gfxDevice === null || gfxDevice === void 0 ? void 0 : gfxDevice.copyTextureToBuffers(gfxTexture, bufferViews, regions);
          return buffer;
        };
        _createClass(RenderTexture, [{
          key: "window",
          get: function get() {
            return this._window;
          }
        }]);
        return RenderTexture;
      }(TextureBase)) || _class$3h));
      legacyCC.RenderTexture = RenderTexture;

      var ProbeClearFlag;
      (function (ProbeClearFlag) {
        ProbeClearFlag[ProbeClearFlag["SKYBOX"] = SKYBOX_FLAG | ClearFlagBit.DEPTH_STENCIL] = "SKYBOX";
        ProbeClearFlag[ProbeClearFlag["SOLID_COLOR"] = ClearFlagBit.ALL] = "SOLID_COLOR";
      })(ProbeClearFlag || (ProbeClearFlag = {}));
      var ProbeType;
      (function (ProbeType) {
        ProbeType[ProbeType["CUBE"] = 0] = "CUBE";
        ProbeType[ProbeType["PLANAR"] = 1] = "PLANAR";
      })(ProbeType || (ProbeType = {}));
      var cameraDir = [new Vec3(0, -90, 0), new Vec3(0, 90, 0), new Vec3(90, 0, 0), new Vec3(-90, 0, 0), new Vec3(0, 0, 0), new Vec3(0, 180, 0)];
      var ReflectionProbe$1 = function () {
        function ReflectionProbe(id) {
          this.bakedCubeTextures = [];
          this.realtimePlanarTexture = null;
          this._resolution = 256;
          this._clearFlag = ProbeClearFlag.SKYBOX;
          this._backgroundColor = new Color$1(0, 0, 0, 255);
          this._visibility = CAMERA_DEFAULT_MASK;
          this._probeType = ProbeType.CUBE;
          this._cubemap = null;
          this._size = new Vec3(1, 1, 1);
          this._camera = null;
          this._probeId = 0;
          this._needRefresh = false;
          this._needRender = false;
          this._node = null;
          this._cameraNode = null;
          this._boundingBox = null;
          this._cameraWorldPos = new Vec3();
          this._cameraWorldRotation = new Quat();
          this._forward = new Vec3();
          this._up = new Vec3();
          this._previewSphere = null;
          this._previewPlane = null;
          this._probeId = id;
        }
        var _proto = ReflectionProbe.prototype;
        _proto.initialize = function initialize(node, cameraNode) {
          this._node = node;
          this._cameraNode = cameraNode;
          var pos = this.node.getWorldPosition();
          this._boundingBox = AABB.create(pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z);
          this._createCamera(cameraNode);
        };
        _proto.initBakedTextures = function initBakedTextures() {
          if (this.bakedCubeTextures.length === 0) {
            for (var i = 0; i < 6; i++) {
              var renderTexture = this._createTargetTexture(this._resolution, this._resolution);
              this.bakedCubeTextures.push(renderTexture);
            }
          }
        };
        _proto.captureCubemap = function captureCubemap() {
          this.initBakedTextures();
          this._resetCameraParams();
          this._needRender = true;
        };
        _proto.renderPlanarReflection = function renderPlanarReflection(sourceCamera) {
          if (!sourceCamera) return;
          if (!this.realtimePlanarTexture) {
            var canvasSize = legacyCC.view.getDesignResolutionSize();
            this.realtimePlanarTexture = this._createTargetTexture(canvasSize.width, canvasSize.height);
            legacyCC.internal.reflectionProbeManager.updatePlanarMap(this, this.realtimePlanarTexture.getGFXTexture());
          }
          this._syncCameraParams(sourceCamera);
          this._transformReflectionCamera(sourceCamera);
          this._needRender = true;
        };
        _proto.switchProbeType = function switchProbeType(type, sourceCamera) {
          if (type === ProbeType.CUBE) {
            this._needRender = false;
          } else if (sourceCamera !== null) {
            this.renderPlanarReflection(sourceCamera);
          }
        };
        _proto.getProbeId = function getProbeId() {
          return this._probeId;
        };
        _proto.updateProbeId = function updateProbeId(id) {
          this._probeId = id;
        };
        _proto.renderArea = function renderArea() {
          if (this._probeType === ProbeType.PLANAR) {
            return new Vec2(this.realtimePlanarTexture.width, this.realtimePlanarTexture.height);
          } else {
            return new Vec2(this.resolution, this.resolution);
          }
        };
        _proto.isFinishedRendering = function isFinishedRendering() {
          return true;
        };
        _proto.validate = function validate() {
          return this.cubemap !== null;
        };
        _proto.destroy = function destroy() {
          if (this._camera) {
            this._camera.destroy();
            this._camera = null;
          }
          for (var i = 0; i < this.bakedCubeTextures.length; i++) {
            this.bakedCubeTextures[i].destroy();
          }
          this.bakedCubeTextures = [];
          if (this.realtimePlanarTexture) {
            this.realtimePlanarTexture.destroy();
            this.realtimePlanarTexture = null;
          }
        };
        _proto.enable = function enable() {};
        _proto.disable = function disable() {};
        _proto.updateCameraDir = function updateCameraDir(faceIdx) {
          this.cameraNode.setRotationFromEuler(cameraDir[faceIdx]);
          this.camera.update(true);
        };
        _proto.updateBoundingBox = function updateBoundingBox() {
          if (this.node) {
            var pos = this.node.getWorldPosition();
            AABB.set(this._boundingBox, pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z);
          }
        };
        _proto.hasFrameBuffer = function hasFrameBuffer(framebuffer) {
          if (this.probeType === ProbeType.PLANAR) {
            var _this$realtimePlanarT;
            if (!this.realtimePlanarTexture) return false;
            if (((_this$realtimePlanarT = this.realtimePlanarTexture.window) === null || _this$realtimePlanarT === void 0 ? void 0 : _this$realtimePlanarT.framebuffer) === framebuffer) {
              return true;
            }
          } else {
            if (this.bakedCubeTextures.length === 0) return false;
            for (var i = 0; i < this.bakedCubeTextures.length; i++) {
              var _rt$window;
              var rt = this.bakedCubeTextures[i];
              if (((_rt$window = rt.window) === null || _rt$window === void 0 ? void 0 : _rt$window.framebuffer) === framebuffer) {
                return true;
              }
            }
          }
          return false;
        };
        _proto.isRGBE = function isRGBE() {
          return true;
        };
        _proto._syncCameraParams = function _syncCameraParams(camera) {
          this.camera.projectionType = camera.projectionType;
          this.camera.orthoHeight = camera.orthoHeight;
          this.camera.nearClip = camera.nearClip;
          this.camera.farClip = camera.farClip;
          this.camera.fov = camera.fov;
          this.camera.clearFlag = camera.clearFlag;
          this.camera.clearColor = camera.clearColor;
          this.camera.priority = camera.priority - 1;
          this.camera.resize(camera.width, camera.height);
        };
        _proto._createCamera = function _createCamera(cameraNode) {
          var root = legacyCC.director.root;
          if (!this._camera) {
            this._camera = root.createCamera();
            if (!this._camera) return null;
            this._camera.initialize({
              name: cameraNode.name,
              node: cameraNode,
              projection: CameraProjection.PERSPECTIVE,
              window: root && root.tempWindow,
              priority: 0,
              cameraType: CameraType.DEFAULT,
              trackingType: TrackingType.NO_TRACKING
            });
          }
          this._camera.setViewportInOrientedSpace(new Rect$1(0, 0, 1, 1));
          this._camera.fovAxis = CameraFOVAxis.VERTICAL;
          this._camera.fov = toRadian(90);
          this._camera.orthoHeight = 10;
          this._camera.nearClip = 1;
          this._camera.farClip = 1000;
          this._camera.clearColor = this._backgroundColor;
          this._camera.clearDepth = 1.0;
          this._camera.clearStencil = 0.0;
          this._camera.clearFlag = this._clearFlag;
          this._camera.visibility = this._visibility;
          this._camera.aperture = CameraAperture.F16_0;
          this._camera.shutter = CameraShutter.D125;
          this._camera.iso = CameraISO.ISO100;
          return this._camera;
        };
        _proto._resetCameraParams = function _resetCameraParams() {
          this.camera.projectionType = CameraProjection.PERSPECTIVE;
          this.camera.orthoHeight = 10;
          this.camera.nearClip = 1;
          this.camera.farClip = 1000;
          this.camera.fov = toRadian(90);
          this.camera.priority = 0;
          this.camera.resize(this.resolution, this.resolution);
          this.camera.visibility = this._visibility;
          this.camera.clearFlag = this._clearFlag;
          this.camera.clearColor = this._backgroundColor;
          this.cameraNode.worldPosition = this.node.worldPosition;
          this.cameraNode.worldRotation = this.node.worldRotation;
          this.camera.update(true);
        };
        _proto._createTargetTexture = function _createTargetTexture(width, height) {
          var rt = new RenderTexture();
          rt.reset({
            width: width,
            height: height
          });
          return rt;
        };
        _proto._transformReflectionCamera = function _transformReflectionCamera(sourceCamera) {
          var offset = Vec3.dot(this.node.worldPosition, this.node.up);
          this._reflect(this._cameraWorldPos, sourceCamera.node.worldPosition, this.node.up, offset);
          this.cameraNode.worldPosition = this._cameraWorldPos;
          Vec3.transformQuat(this._forward, Vec3.FORWARD, sourceCamera.node.worldRotation);
          this._reflect(this._forward, this._forward, this.node.up, 0);
          this._forward.normalize();
          this._forward.negative();
          Vec3.transformQuat(this._up, Vec3.UP, sourceCamera.node.worldRotation);
          this._reflect(this._up, this._up, this.node.up, 0);
          this._up.normalize();
          Quat.fromViewUp(this._cameraWorldRotation, this._forward, this._up);
          this.cameraNode.worldRotation = this._cameraWorldRotation;
          this.camera.update(true);
          var viewSpaceProbe = new Vec4(this.node.up.x, this.node.up.y, this.node.up.z, -Vec3.dot(this.node.up, this.node.worldPosition));
          viewSpaceProbe.transformMat4(this.camera.matView.clone().invert().transpose());
          this.camera.calculateObliqueMat(viewSpaceProbe);
        };
        _proto._reflect = function _reflect(out, point, normal, offset) {
          var n = Vec3.clone(normal);
          n.normalize();
          var dist = Vec3.dot(n, point) - offset;
          n.multiplyScalar(2.0 * dist);
          Vec3.subtract(out, point, n);
          return out;
        };
        _createClass(ReflectionProbe, [{
          key: "probeType",
          get: function get() {
            return this._probeType;
          },
          set: function set(value) {
            this._probeType = value;
          }
        }, {
          key: "resolution",
          get: function get() {
            return this._resolution;
          },
          set: function set(value) {
            if (value !== this._resolution) {
              this.bakedCubeTextures.forEach(function (rt, idx) {
                rt.resize(value, value);
              });
            }
            this._resolution = value;
          }
        }, {
          key: "clearFlag",
          get: function get() {
            return this._clearFlag;
          },
          set: function set(value) {
            this._clearFlag = value;
            this.camera.clearFlag = this._clearFlag;
          }
        }, {
          key: "backgroundColor",
          get: function get() {
            return this._backgroundColor;
          },
          set: function set(val) {
            this._backgroundColor = val;
            this.camera.clearColor = this._backgroundColor;
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(val) {
            this._visibility = val;
            this._camera.visibility = this._visibility;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(value) {
            this._size.set(value);
            var pos = this.node.getWorldPosition();
            AABB.set(this._boundingBox, pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z);
          }
        }, {
          key: "cubemap",
          get: function get() {
            return this._cubemap;
          },
          set: function set(val) {
            this._cubemap = val;
          }
        }, {
          key: "node",
          get: function get() {
            return this._node;
          }
        }, {
          key: "camera",
          get: function get() {
            return this._camera;
          }
        }, {
          key: "needRefresh",
          get: function get() {
            return this._needRefresh;
          },
          set: function set(value) {
            this._needRefresh = value;
          }
        }, {
          key: "needRender",
          get: function get() {
            return this._needRender;
          },
          set: function set(value) {
            this._needRender = value;
          }
        }, {
          key: "boundingBox",
          get: function get() {
            return this._boundingBox;
          }
        }, {
          key: "cameraNode",
          get: function get() {
            return this._cameraNode;
          },
          set: function set(node) {
            this._cameraNode = node;
          }
        }, {
          key: "previewSphere",
          get: function get() {
            return this._previewSphere;
          },
          set: function set(val) {
            this._previewSphere = val;
          }
        }, {
          key: "previewPlane",
          get: function get() {
            return this._previewPlane;
          },
          set: function set(val) {
            this._previewPlane = val;
          }
        }]);
        return ReflectionProbe;
      }();

      function ColorTemperatureToRGB(rgb, kelvin) {
        if (kelvin < 1000.0) {
          kelvin = 1000.0;
        } else if (kelvin > 15000.0) {
          kelvin = 15000.0;
        }
        var kSqr = kelvin * kelvin;
        var u = (0.860117757 + 1.54118254e-4 * kelvin + 1.28641212e-7 * kSqr) / (1.0 + 8.42420235e-4 * kelvin + 7.08145163e-7 * kSqr);
        var v = (0.317398726 + 4.22806245e-5 * kelvin + 4.20481691e-8 * kSqr) / (1.0 - 2.89741816e-5 * kelvin + 1.61456053e-7 * kSqr);
        var d = 2.0 * u - 8.0 * v + 4.0;
        var x = 3.0 * u / d;
        var y = 2.0 * v / d;
        var z = 1.0 - x - y;
        var X = 1.0 / y * x;
        var Z = 1.0 / y * z;
        rgb.x = 3.2404542 * X + -1.5371385 + -0.4985314 * Z;
        rgb.y = -0.9692660 * X + 1.8760108 + 0.0415560 * Z;
        rgb.z = 0.0556434 * X + -0.2040259 + 1.0572252 * Z;
      }
      var LightType;
      (function (LightType) {
        LightType[LightType["DIRECTIONAL"] = 0] = "DIRECTIONAL";
        LightType[LightType["SPHERE"] = 1] = "SPHERE";
        LightType[LightType["SPOT"] = 2] = "SPOT";
        LightType[LightType["POINT"] = 3] = "POINT";
        LightType[LightType["RANGED_DIRECTIONAL"] = 4] = "RANGED_DIRECTIONAL";
        LightType[LightType["UNKNOWN"] = 5] = "UNKNOWN";
      })(LightType || (LightType = {}));
      var nt2lm = function nt2lm(size) {
        return 4 * Math.PI * Math.PI * size * size;
      };
      var Light$1 = function () {
        function Light() {
          this._baked = false;
          this._color = new Vec3(1, 1, 1);
          this._colorTemp = 6550.0;
          this._colorTempRGB = new Vec3(1, 1, 1);
          this._finalColor = new Vec3(1, 1, 1);
          this._scene = null;
          this._node = null;
          this._name = null;
          this._useColorTemperature = false;
          this._type = LightType.UNKNOWN;
          this._visibility = CAMERA_DEFAULT_MASK;
        }
        var _proto = Light.prototype;
        _proto.initialize = function initialize() {
          this.color = new Vec3(1, 1, 1);
          this.colorTemperature = 6550.0;
        };
        _proto.attachToScene = function attachToScene(scene) {
          this._scene = scene;
        };
        _proto.detachFromScene = function detachFromScene() {
          this._scene = null;
        };
        _proto.destroy = function destroy() {
          this._name = null;
          this._node = null;
        };
        _proto.update = function update() {};
        _createClass(Light, [{
          key: "baked",
          get: function get() {
            return this._baked;
          },
          set: function set(val) {
            this._baked = val;
          }
        }, {
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(color) {
            this._color.set(color);
            if (this._useColorTemperature) {
              Vec3.multiply(this._finalColor, this._color, this._colorTempRGB);
            }
          }
        }, {
          key: "useColorTemperature",
          get: function get() {
            return this._useColorTemperature;
          },
          set: function set(enable) {
            this._useColorTemperature = enable;
            if (enable) {
              Vec3.multiply(this._finalColor, this._color, this._colorTempRGB);
            }
          }
        }, {
          key: "colorTemperature",
          get: function get() {
            return this._colorTemp;
          },
          set: function set(val) {
            this._colorTemp = val;
            ColorTemperatureToRGB(this._colorTempRGB, this._colorTemp);
            if (this._useColorTemperature) {
              Vec3.multiply(this._finalColor, this._color, this._colorTempRGB);
            }
          }
        }, {
          key: "colorTemperatureRGB",
          get: function get() {
            return this._colorTempRGB;
          }
        }, {
          key: "finalColor",
          get: function get() {
            return this._finalColor;
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(vis) {
            this._visibility = vis;
          }
        }, {
          key: "node",
          get: function get() {
            return this._node;
          },
          set: function set(n) {
            this._node = n;
            if (this._node) {
              this._node.hasChangedFlags |= TransformBit.ROTATION;
            }
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "name",
          get: function get() {
            return this._name;
          },
          set: function set(n) {
            this._name = n;
          }
        }, {
          key: "scene",
          get: function get() {
            return this._scene;
          }
        }]);
        return Light;
      }();

      var UpdateFrequency;
      (function (UpdateFrequency) {
        UpdateFrequency[UpdateFrequency["PER_INSTANCE"] = 0] = "PER_INSTANCE";
        UpdateFrequency[UpdateFrequency["PER_BATCH"] = 1] = "PER_BATCH";
        UpdateFrequency[UpdateFrequency["PER_PHASE"] = 2] = "PER_PHASE";
        UpdateFrequency[UpdateFrequency["PER_PASS"] = 3] = "PER_PASS";
        UpdateFrequency[UpdateFrequency["COUNT"] = 4] = "COUNT";
      })(UpdateFrequency || (UpdateFrequency = {}));
      var ParameterType;
      (function (ParameterType) {
        ParameterType[ParameterType["CONSTANTS"] = 0] = "CONSTANTS";
        ParameterType[ParameterType["CBV"] = 1] = "CBV";
        ParameterType[ParameterType["UAV"] = 2] = "UAV";
        ParameterType[ParameterType["SRV"] = 3] = "SRV";
        ParameterType[ParameterType["TABLE"] = 4] = "TABLE";
        ParameterType[ParameterType["SSV"] = 5] = "SSV";
      })(ParameterType || (ParameterType = {}));
      var ResourceResidency;
      (function (ResourceResidency) {
        ResourceResidency[ResourceResidency["MANAGED"] = 0] = "MANAGED";
        ResourceResidency[ResourceResidency["MEMORYLESS"] = 1] = "MEMORYLESS";
        ResourceResidency[ResourceResidency["PERSISTENT"] = 2] = "PERSISTENT";
        ResourceResidency[ResourceResidency["EXTERNAL"] = 3] = "EXTERNAL";
        ResourceResidency[ResourceResidency["BACKBUFFER"] = 4] = "BACKBUFFER";
      })(ResourceResidency || (ResourceResidency = {}));
      var QueueHint;
      (function (QueueHint) {
        QueueHint[QueueHint["NONE"] = 0] = "NONE";
        QueueHint[QueueHint["OPAQUE"] = 1] = "OPAQUE";
        QueueHint[QueueHint["MASK"] = 2] = "MASK";
        QueueHint[QueueHint["BLEND"] = 3] = "BLEND";
        QueueHint[QueueHint["RENDER_OPAQUE"] = 1] = "RENDER_OPAQUE";
        QueueHint[QueueHint["RENDER_CUTOUT"] = 2] = "RENDER_CUTOUT";
        QueueHint[QueueHint["RENDER_TRANSPARENT"] = 3] = "RENDER_TRANSPARENT";
      })(QueueHint || (QueueHint = {}));
      var ResourceDimension;
      (function (ResourceDimension) {
        ResourceDimension[ResourceDimension["BUFFER"] = 0] = "BUFFER";
        ResourceDimension[ResourceDimension["TEXTURE1D"] = 1] = "TEXTURE1D";
        ResourceDimension[ResourceDimension["TEXTURE2D"] = 2] = "TEXTURE2D";
        ResourceDimension[ResourceDimension["TEXTURE3D"] = 3] = "TEXTURE3D";
      })(ResourceDimension || (ResourceDimension = {}));
      var ResourceFlags;
      (function (ResourceFlags) {
        ResourceFlags[ResourceFlags["NONE"] = 0] = "NONE";
        ResourceFlags[ResourceFlags["UNIFORM"] = 1] = "UNIFORM";
        ResourceFlags[ResourceFlags["INDIRECT"] = 2] = "INDIRECT";
        ResourceFlags[ResourceFlags["STORAGE"] = 4] = "STORAGE";
        ResourceFlags[ResourceFlags["SAMPLED"] = 8] = "SAMPLED";
        ResourceFlags[ResourceFlags["COLOR_ATTACHMENT"] = 16] = "COLOR_ATTACHMENT";
        ResourceFlags[ResourceFlags["DEPTH_STENCIL_ATTACHMENT"] = 32] = "DEPTH_STENCIL_ATTACHMENT";
        ResourceFlags[ResourceFlags["INPUT_ATTACHMENT"] = 64] = "INPUT_ATTACHMENT";
        ResourceFlags[ResourceFlags["SHADING_RATE"] = 128] = "SHADING_RATE";
        ResourceFlags[ResourceFlags["TRANSFER_SRC"] = 256] = "TRANSFER_SRC";
        ResourceFlags[ResourceFlags["TRANSFER_DST"] = 512] = "TRANSFER_DST";
      })(ResourceFlags || (ResourceFlags = {}));
      var TaskType;
      (function (TaskType) {
        TaskType[TaskType["SYNC"] = 0] = "SYNC";
        TaskType[TaskType["ASYNC"] = 1] = "ASYNC";
      })(TaskType || (TaskType = {}));
      var SceneFlags;
      (function (SceneFlags) {
        SceneFlags[SceneFlags["NONE"] = 0] = "NONE";
        SceneFlags[SceneFlags["OPAQUE"] = 1] = "OPAQUE";
        SceneFlags[SceneFlags["MASK"] = 2] = "MASK";
        SceneFlags[SceneFlags["BLEND"] = 4] = "BLEND";
        SceneFlags[SceneFlags["OPAQUE_OBJECT"] = 1] = "OPAQUE_OBJECT";
        SceneFlags[SceneFlags["CUTOUT_OBJECT"] = 2] = "CUTOUT_OBJECT";
        SceneFlags[SceneFlags["TRANSPARENT_OBJECT"] = 4] = "TRANSPARENT_OBJECT";
        SceneFlags[SceneFlags["SHADOW_CASTER"] = 8] = "SHADOW_CASTER";
        SceneFlags[SceneFlags["UI"] = 16] = "UI";
        SceneFlags[SceneFlags["DEFAULT_LIGHTING"] = 32] = "DEFAULT_LIGHTING";
        SceneFlags[SceneFlags["VOLUMETRIC_LIGHTING"] = 64] = "VOLUMETRIC_LIGHTING";
        SceneFlags[SceneFlags["CLUSTERED_LIGHTING"] = 128] = "CLUSTERED_LIGHTING";
        SceneFlags[SceneFlags["PLANAR_SHADOW"] = 256] = "PLANAR_SHADOW";
        SceneFlags[SceneFlags["GEOMETRY"] = 512] = "GEOMETRY";
        SceneFlags[SceneFlags["PROFILER"] = 1024] = "PROFILER";
        SceneFlags[SceneFlags["DRAW_INSTANCING"] = 2048] = "DRAW_INSTANCING";
        SceneFlags[SceneFlags["DRAW_NON_INSTANCING"] = 4096] = "DRAW_NON_INSTANCING";
        SceneFlags[SceneFlags["REFLECTION_PROBE"] = 8192] = "REFLECTION_PROBE";
        SceneFlags[SceneFlags["GPU_DRIVEN"] = 16384] = "GPU_DRIVEN";
        SceneFlags[SceneFlags["NON_BUILTIN"] = 32768] = "NON_BUILTIN";
        SceneFlags[SceneFlags["ALL"] = 4294967295] = "ALL";
      })(SceneFlags || (SceneFlags = {}));
      var LightingMode;
      (function (LightingMode) {
        LightingMode[LightingMode["NONE"] = 0] = "NONE";
        LightingMode[LightingMode["DEFAULT"] = 1] = "DEFAULT";
        LightingMode[LightingMode["CLUSTERED"] = 2] = "CLUSTERED";
      })(LightingMode || (LightingMode = {}));
      var AttachmentType;
      (function (AttachmentType) {
        AttachmentType[AttachmentType["RENDER_TARGET"] = 0] = "RENDER_TARGET";
        AttachmentType[AttachmentType["DEPTH_STENCIL"] = 1] = "DEPTH_STENCIL";
        AttachmentType[AttachmentType["SHADING_RATE"] = 2] = "SHADING_RATE";
      })(AttachmentType || (AttachmentType = {}));
      var AccessType;
      (function (AccessType) {
        AccessType[AccessType["READ"] = 0] = "READ";
        AccessType[AccessType["READ_WRITE"] = 1] = "READ_WRITE";
        AccessType[AccessType["WRITE"] = 2] = "WRITE";
      })(AccessType || (AccessType = {}));
      var ClearValueType;
      (function (ClearValueType) {
        ClearValueType[ClearValueType["NONE"] = 0] = "NONE";
        ClearValueType[ClearValueType["FLOAT_TYPE"] = 1] = "FLOAT_TYPE";
        ClearValueType[ClearValueType["INT_TYPE"] = 2] = "INT_TYPE";
      })(ClearValueType || (ClearValueType = {}));
      var LightInfo = function () {
        function LightInfo(light, level, culledByLight, probe) {
          if (light === void 0) {
            light = null;
          }
          if (level === void 0) {
            level = 0;
          }
          if (culledByLight === void 0) {
            culledByLight = false;
          }
          if (probe === void 0) {
            probe = null;
          }
          this.light = void 0;
          this.probe = void 0;
          this.level = void 0;
          this.culledByLight = void 0;
          this.light = light;
          this.probe = probe;
          this.level = level;
          this.culledByLight = culledByLight;
        }
        var _proto = LightInfo.prototype;
        _proto.reset = function reset(light, level, culledByLight, probe) {
          if (light === void 0) {
            light = null;
          }
          if (level === void 0) {
            level = 0;
          }
          if (culledByLight === void 0) {
            culledByLight = false;
          }
          if (probe === void 0) {
            probe = null;
          }
          this.light = light;
          this.probe = probe;
          this.level = level;
          this.culledByLight = culledByLight;
        };
        return LightInfo;
      }();
      var DescriptorTypeOrder;
      (function (DescriptorTypeOrder) {
        DescriptorTypeOrder[DescriptorTypeOrder["UNIFORM_BUFFER"] = 0] = "UNIFORM_BUFFER";
        DescriptorTypeOrder[DescriptorTypeOrder["DYNAMIC_UNIFORM_BUFFER"] = 1] = "DYNAMIC_UNIFORM_BUFFER";
        DescriptorTypeOrder[DescriptorTypeOrder["SAMPLER_TEXTURE"] = 2] = "SAMPLER_TEXTURE";
        DescriptorTypeOrder[DescriptorTypeOrder["SAMPLER"] = 3] = "SAMPLER";
        DescriptorTypeOrder[DescriptorTypeOrder["TEXTURE"] = 4] = "TEXTURE";
        DescriptorTypeOrder[DescriptorTypeOrder["STORAGE_BUFFER"] = 5] = "STORAGE_BUFFER";
        DescriptorTypeOrder[DescriptorTypeOrder["DYNAMIC_STORAGE_BUFFER"] = 6] = "DYNAMIC_STORAGE_BUFFER";
        DescriptorTypeOrder[DescriptorTypeOrder["STORAGE_IMAGE"] = 7] = "STORAGE_IMAGE";
        DescriptorTypeOrder[DescriptorTypeOrder["INPUT_ATTACHMENT"] = 8] = "INPUT_ATTACHMENT";
      })(DescriptorTypeOrder || (DescriptorTypeOrder = {}));
      var ResolveFlags;
      (function (ResolveFlags) {
        ResolveFlags[ResolveFlags["NONE"] = 0] = "NONE";
        ResolveFlags[ResolveFlags["COLOR"] = 1] = "COLOR";
        ResolveFlags[ResolveFlags["DEPTH"] = 2] = "DEPTH";
        ResolveFlags[ResolveFlags["STENCIL"] = 4] = "STENCIL";
      })(ResolveFlags || (ResolveFlags = {}));
      var UploadPair = function () {
        function UploadPair(source, target, mipLevels, numSlices, targetMostDetailedMip, targetFirstSlice, targetPlaneSlice) {
          if (source === void 0) {
            source = new Uint8Array(0);
          }
          if (target === void 0) {
            target = '';
          }
          if (mipLevels === void 0) {
            mipLevels = 0xFFFFFFFF;
          }
          if (numSlices === void 0) {
            numSlices = 0xFFFFFFFF;
          }
          if (targetMostDetailedMip === void 0) {
            targetMostDetailedMip = 0;
          }
          if (targetFirstSlice === void 0) {
            targetFirstSlice = 0;
          }
          if (targetPlaneSlice === void 0) {
            targetPlaneSlice = 0;
          }
          this.source = void 0;
          this.target = void 0;
          this.mipLevels = void 0;
          this.numSlices = void 0;
          this.targetMostDetailedMip = void 0;
          this.targetFirstSlice = void 0;
          this.targetPlaneSlice = void 0;
          this.source = source;
          this.target = target;
          this.mipLevels = mipLevels;
          this.numSlices = numSlices;
          this.targetMostDetailedMip = targetMostDetailedMip;
          this.targetFirstSlice = targetFirstSlice;
          this.targetPlaneSlice = targetPlaneSlice;
        }
        var _proto7 = UploadPair.prototype;
        _proto7.reset = function reset(target, mipLevels, numSlices, targetMostDetailedMip, targetFirstSlice, targetPlaneSlice) {
          if (target === void 0) {
            target = '';
          }
          if (mipLevels === void 0) {
            mipLevels = 0xFFFFFFFF;
          }
          if (numSlices === void 0) {
            numSlices = 0xFFFFFFFF;
          }
          if (targetMostDetailedMip === void 0) {
            targetMostDetailedMip = 0;
          }
          if (targetFirstSlice === void 0) {
            targetFirstSlice = 0;
          }
          if (targetPlaneSlice === void 0) {
            targetPlaneSlice = 0;
          }
          this.target = target;
          this.mipLevels = mipLevels;
          this.numSlices = numSlices;
          this.targetMostDetailedMip = targetMostDetailedMip;
          this.targetFirstSlice = targetFirstSlice;
          this.targetPlaneSlice = targetPlaneSlice;
        };
        return UploadPair;
      }();

      removeProperty(TextureBase.prototype, 'TextureBase.prototype', [{
        name: 'hasPremultipliedAlpha'
      }, {
        name: 'setPremultiplyAlpha'
      }, {
        name: 'setFlipY'
      }]);
      replaceProperty(RenderTexture.prototype, 'RenderTexture.prototype', [{
        name: 'getGFXWindow',
        customFunction: function customFunction() {
          return this.window;
        }
      }]);

      var _typeMap2;
      var _typeMap = (_typeMap2 = {}, _typeMap2[FormatType.UNORM] = 'Uint', _typeMap2[FormatType.SNORM] = 'Int', _typeMap2[FormatType.UINT] = 'Uint', _typeMap2[FormatType.INT] = 'Int', _typeMap2[FormatType.UFLOAT] = 'Float', _typeMap2[FormatType.FLOAT] = 'Float', _typeMap2["default"] = 'Uint', _typeMap2);
      function _getDataViewType(info) {
        var type = _typeMap[info.type] || _typeMap["default"];
        var bytes = info.size / info.count * 8;
        return "" + type + bytes;
      }
      function writeBuffer(target, data, format, offset, stride) {
        if (format === void 0) {
          format = Format.R32F;
        }
        if (offset === void 0) {
          offset = 0;
        }
        if (stride === void 0) {
          stride = 0;
        }
        var info = FormatInfos[format];
        if (!stride) {
          stride = info.size;
        }
        var writer = "set" + _getDataViewType(info);
        var componentBytesLength = info.size / info.count;
        var nSeg = Math.floor(data.length / info.count);
        var isLittleEndian = sys.isLittleEndian;
        for (var iSeg = 0; iSeg < nSeg; ++iSeg) {
          var x = offset + stride * iSeg;
          for (var iComponent = 0; iComponent < info.count; ++iComponent) {
            var y = x + componentBytesLength * iComponent;
            target[writer](y, data[info.count * iSeg + iComponent], isLittleEndian);
          }
        }
      }
      function readBuffer(target, format, offset, length, stride, out) {
        if (format === void 0) {
          format = Format.R32F;
        }
        if (offset === void 0) {
          offset = 0;
        }
        if (length === void 0) {
          length = target.byteLength - offset;
        }
        if (stride === void 0) {
          stride = 0;
        }
        if (out === void 0) {
          out = [];
        }
        var info = FormatInfos[format];
        if (!stride) {
          stride = info.size;
        }
        var reader = "get" + _getDataViewType(info);
        var componentBytesLength = info.size / info.count;
        var nSeg = Math.floor(length / stride);
        var isLittleEndian = sys.isLittleEndian;
        for (var iSeg = 0; iSeg < nSeg; ++iSeg) {
          var x = offset + stride * iSeg;
          for (var iComponent = 0; iComponent < info.count; ++iComponent) {
            var y = x + componentBytesLength * iComponent;
            out[info.count * iSeg + iComponent] = target[reader](y, isLittleEndian);
          }
        }
        return out;
      }
      function mapBuffer(target, callback, format, offset, length, stride, out) {
        if (format === void 0) {
          format = Format.R32F;
        }
        if (offset === void 0) {
          offset = 0;
        }
        if (length === void 0) {
          length = target.byteLength - offset;
        }
        if (stride === void 0) {
          stride = 0;
        }
        if (!out) {
          out = new DataView(target.buffer.slice(target.byteOffset, target.byteOffset + target.byteLength));
        }
        var info = FormatInfos[format];
        if (!stride) {
          stride = info.size;
        }
        var writer = "set" + _getDataViewType(info);
        var reader = "get" + _getDataViewType(info);
        var componentBytesLength = info.size / info.count;
        var nSeg = Math.floor(length / stride);
        var isLittleEndian = sys.isLittleEndian;
        for (var iSeg = 0; iSeg < nSeg; ++iSeg) {
          var x = offset + stride * iSeg;
          for (var iComponent = 0; iComponent < info.count; ++iComponent) {
            var y = x + componentBytesLength * iComponent;
            var _cur = target[reader](y, isLittleEndian);
            out[writer](y, callback(_cur, iComponent, target), isLittleEndian);
          }
        }
        return out;
      }

      var RenderingSubMesh = exports('ed', function () {
        function RenderingSubMesh(vertexBuffers, attributes, primitiveMode, indexBuffer, indirectBuffer, isOwnerOfIndexBuffer) {
          if (indexBuffer === void 0) {
            indexBuffer = null;
          }
          if (indirectBuffer === void 0) {
            indirectBuffer = null;
          }
          if (isOwnerOfIndexBuffer === void 0) {
            isOwnerOfIndexBuffer = true;
          }
          this.mesh = void 0;
          this.subMeshIdx = void 0;
          this._flatBuffers = [];
          this._jointMappedBuffers = void 0;
          this._jointMappedBufferIndices = void 0;
          this._vertexIdChannel = void 0;
          this._geometricInfo = void 0;
          this._vertexBuffers = void 0;
          this._attributes = void 0;
          this._indexBuffer = null;
          this._indirectBuffer = null;
          this._primitiveMode = void 0;
          this._iaInfo = void 0;
          this._isOwnerOfIndexBuffer = true;
          this._drawInfo = null;
          this._attributes = attributes;
          this._vertexBuffers = vertexBuffers;
          this._indexBuffer = indexBuffer;
          this._indirectBuffer = indirectBuffer;
          this._primitiveMode = primitiveMode;
          this._iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer, indirectBuffer);
          this._isOwnerOfIndexBuffer = isOwnerOfIndexBuffer;
        }
        var _proto = RenderingSubMesh.prototype;
        _proto.invalidateGeometricInfo = function invalidateGeometricInfo() {
          this._geometricInfo = undefined;
        };
        _proto.genFlatBuffers = function genFlatBuffers() {
          if (this._flatBuffers.length || !this.mesh || this.subMeshIdx === undefined) {
            return;
          }
          var mesh = this.mesh;
          var idxCount = 0;
          var prim = mesh.struct.primitives[this.subMeshIdx];
          if (prim.indexView) {
            idxCount = prim.indexView.count;
          }
          for (var i = 0; i < prim.vertexBundelIndices.length; i++) {
            var bundleIdx = prim.vertexBundelIndices[i];
            var vertexBundle = mesh.struct.vertexBundles[bundleIdx];
            var vbCount = prim.indexView ? prim.indexView.count : vertexBundle.view.count;
            var vbStride = vertexBundle.view.stride;
            var vbSize = vbStride * vbCount;
            var view = new Uint8Array(mesh.data.buffer, vertexBundle.view.offset, vertexBundle.view.length);
            var sharedView = new Uint8Array(prim.indexView ? vbSize : vertexBundle.view.length);
            if (!prim.indexView) {
              sharedView.set(mesh.data.subarray(vertexBundle.view.offset, vertexBundle.view.offset + vertexBundle.view.length));
              this._flatBuffers.push({
                stride: vbStride,
                count: vbCount,
                buffer: sharedView
              });
              continue;
            }
            var ibView = mesh.readIndices(this.subMeshIdx);
            for (var n = 0; n < idxCount; ++n) {
              var idx = ibView[n];
              var offset = n * vbStride;
              var srcOffset = idx * vbStride;
              for (var m = 0; m < vbStride; ++m) {
                sharedView[offset + m] = view[srcOffset + m];
              }
            }
            this._flatBuffers.push({
              stride: vbStride,
              count: vbCount,
              buffer: sharedView
            });
          }
        };
        _proto.destroy = function destroy() {
          for (var i = 0; i < this.vertexBuffers.length; i++) {
            this.vertexBuffers[i].destroy();
          }
          this.vertexBuffers.length = 0;
          if (this._indexBuffer) {
            if (this._isOwnerOfIndexBuffer) {
              this._indexBuffer.destroy();
            }
            this._indexBuffer = null;
          }
          if (this._jointMappedBuffers && this._jointMappedBufferIndices) {
            for (var _i = 0; _i < this._jointMappedBufferIndices.length; _i++) {
              this._jointMappedBuffers[this._jointMappedBufferIndices[_i]].destroy();
            }
            this._jointMappedBuffers = undefined;
            this._jointMappedBufferIndices = undefined;
          }
          if (this._indirectBuffer) {
            this._indirectBuffer.destroy();
            this._indirectBuffer = null;
          }
        };
        _proto.enableVertexIdChannel = function enableVertexIdChannel(device) {
          if (this._vertexIdChannel) {
            return;
          }
          var streamIndex = this.vertexBuffers.length;
          var attributeIndex = this.attributes.length;
          var vertexIdBuffer = this._allocVertexIdBuffer(device);
          this._vertexBuffers.push(vertexIdBuffer);
          this._attributes.push(new Attribute('a_vertexId', Format.R32F, false, streamIndex));
          this._iaInfo.attributes = this._attributes;
          this._iaInfo.vertexBuffers = this._vertexBuffers;
          this._vertexIdChannel = {
            stream: streamIndex,
            index: attributeIndex
          };
        };
        _proto._allocVertexIdBuffer = function _allocVertexIdBuffer(device) {
          var vertexCount = this.vertexBuffers.length === 0 || this.vertexBuffers[0].stride === 0 ? 0 : this.vertexBuffers[0].size / this.vertexBuffers[0].stride;
          var vertexIds = new Float32Array(vertexCount);
          for (var iVertex = 0; iVertex < vertexCount; ++iVertex) {
            vertexIds[iVertex] = iVertex + 0.5;
          }
          var vertexIdBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, vertexIds.byteLength, vertexIds.BYTES_PER_ELEMENT));
          vertexIdBuffer.update(vertexIds);
          return vertexIdBuffer;
        };
        _createClass(RenderingSubMesh, [{
          key: "attributes",
          get: function get() {
            return this._attributes;
          }
        }, {
          key: "vertexBuffers",
          get: function get() {
            return this._vertexBuffers;
          }
        }, {
          key: "indexBuffer",
          get: function get() {
            return this._indexBuffer;
          }
        }, {
          key: "indirectBuffer",
          get: function get() {
            return this._indirectBuffer;
          }
        }, {
          key: "primitiveMode",
          get: function get() {
            return this._primitiveMode;
          }
        }, {
          key: "geometricInfo",
          get: function get() {
            if (this._geometricInfo) {
              return this._geometricInfo;
            }
            if (this.mesh === undefined) {
              return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
            }
            if (this.subMeshIdx === undefined) {
              return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
            }
            var mesh = this.mesh;
            var index = this.subMeshIdx;
            var pAttri = this.attributes.find(function (element) {
              return element.name === AttributeName.ATTR_POSITION;
            });
            if (!pAttri) {
              return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
            }
            var positions;
            switch (pAttri.format) {
              case Format.RG32F:
              case Format.RGB32F:
                {
                  positions = mesh.readAttribute(index, AttributeName.ATTR_POSITION);
                  if (!positions) {
                    return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
                  }
                  break;
                }
              case Format.RGBA32F:
                {
                  var data = mesh.readAttribute(index, AttributeName.ATTR_POSITION);
                  if (!data) {
                    return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
                  }
                  var count = data.length / 4;
                  positions = new Float32Array(count * 3);
                  for (var i = 0; i < count; ++i) {
                    var dstPtr = i * 3;
                    var srcPtr = i * 4;
                    positions[dstPtr] = data[srcPtr];
                    positions[dstPtr + 1] = data[srcPtr + 1];
                    positions[dstPtr + 2] = data[srcPtr + 2];
                  }
                  break;
                }
              case Format.RG16F:
              case Format.RGB16F:
                {
                  var _data = mesh.readAttribute(index, AttributeName.ATTR_POSITION);
                  if (!_data) {
                    return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
                  }
                  positions = new Float32Array(_data.length);
                  for (var _i2 = 0; _i2 < _data.length; ++_i2) {
                    positions[_i2] = halfToFloat(_data[_i2]);
                  }
                  break;
                }
              case Format.RGBA16F:
                {
                  var _data2 = mesh.readAttribute(index, AttributeName.ATTR_POSITION);
                  if (!_data2) {
                    return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
                  }
                  var _count = _data2.length / 4;
                  positions = new Float32Array(_count * 3);
                  for (var _i3 = 0; _i3 < _count; ++_i3) {
                    var _dstPtr = _i3 * 3;
                    var _srcPtr = _i3 * 4;
                    positions[_dstPtr] = halfToFloat(_data2[_srcPtr]);
                    positions[_dstPtr + 1] = halfToFloat(_data2[_srcPtr + 1]);
                    positions[_dstPtr + 2] = halfToFloat(_data2[_srcPtr + 2]);
                  }
                  break;
                }
              default:
                return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
            }
            var indices = mesh.readIndices(index) || undefined;
            var max = new Vec3();
            var min = new Vec3();
            var conut = FormatInfos[pAttri.format].count;
            if (conut === 2) {
              max.set(positions[0], positions[1], 0);
              min.set(positions[0], positions[1], 0);
            } else {
              max.set(positions[0], positions[1], positions[2]);
              min.set(positions[0], positions[1], positions[2]);
            }
            for (var _i4 = 0; _i4 < positions.length; _i4 += conut) {
              if (conut === 2) {
                max.x = positions[_i4] > max.x ? positions[_i4] : max.x;
                max.y = positions[_i4 + 1] > max.y ? positions[_i4 + 1] : max.y;
                min.x = positions[_i4] < min.x ? positions[_i4] : min.x;
                min.y = positions[_i4 + 1] < min.y ? positions[_i4 + 1] : min.y;
              } else {
                max.x = positions[_i4] > max.x ? positions[_i4] : max.x;
                max.y = positions[_i4 + 1] > max.y ? positions[_i4 + 1] : max.y;
                max.z = positions[_i4 + 2] > max.z ? positions[_i4 + 2] : max.z;
                min.x = positions[_i4] < min.x ? positions[_i4] : min.x;
                min.y = positions[_i4 + 1] < min.y ? positions[_i4 + 1] : min.y;
                min.z = positions[_i4 + 2] < min.z ? positions[_i4 + 2] : min.z;
              }
            }
            this._geometricInfo = {
              positions: positions,
              indices: indices,
              boundingBox: {
                max: max,
                min: min
              }
            };
            return this._geometricInfo;
          }
        }, {
          key: "drawInfo",
          get: function get() {
            return this._drawInfo;
          },
          set: function set(info) {
            this._drawInfo = info;
          }
        }, {
          key: "flatBuffers",
          get: function get() {
            return this._flatBuffers;
          }
        }, {
          key: "jointMappedBuffers",
          get: function get() {
            var _this = this;
            if (this._jointMappedBuffers) {
              return this._jointMappedBuffers;
            }
            var buffers = this._jointMappedBuffers = [];
            var indices = this._jointMappedBufferIndices = [];
            if (!this.mesh || this.subMeshIdx === undefined) {
              return this._jointMappedBuffers = this.vertexBuffers;
            }
            var struct = this.mesh.struct;
            var prim = struct.primitives[this.subMeshIdx];
            if (!struct.jointMaps || prim.jointMapIndex === undefined || !struct.jointMaps[prim.jointMapIndex]) {
              return this._jointMappedBuffers = this.vertexBuffers;
            }
            var jointFormat;
            var jointOffset;
            var _ref = legacyCC.director.root,
              device = _ref.device;
            var _loop = function _loop() {
              var bundle = struct.vertexBundles[prim.vertexBundelIndices[i]];
              jointOffset = 0;
              jointFormat = Format.UNKNOWN;
              for (var j = 0; j < bundle.attributes.length; j++) {
                var attr = bundle.attributes[j];
                if (attr.name === AttributeName.ATTR_JOINTS) {
                  jointFormat = attr.format;
                  break;
                }
                jointOffset += FormatInfos[attr.format].size;
              }
              if (jointFormat) {
                var data = new Uint8Array(_this.mesh.data.buffer, bundle.view.offset, bundle.view.length);
                var dataView = new DataView(data.slice().buffer);
                var idxMap = struct.jointMaps[prim.jointMapIndex];
                mapBuffer(dataView, function (cur) {
                  return idxMap.indexOf(cur);
                }, jointFormat, jointOffset, bundle.view.length, bundle.view.stride, dataView);
                var buffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, bundle.view.length, bundle.view.stride));
                buffer.update(dataView.buffer);
                buffers.push(buffer);
                indices.push(i);
              } else {
                buffers.push(_this.vertexBuffers[prim.vertexBundelIndices[i]]);
              }
            };
            for (var i = 0; i < prim.vertexBundelIndices.length; i++) {
              _loop();
            }
            if (this._vertexIdChannel) {
              buffers.push(this._allocVertexIdBuffer(device));
            }
            return buffers;
          }
        }, {
          key: "iaInfo",
          get: function get() {
            return this._iaInfo;
          }
        }]);
        return RenderingSubMesh;
      }());
      RenderingSubMesh.EMPTY_GEOMETRIC_INFO = {
        positions: new Float32Array(),
        indices: new Uint8Array(),
        boundingBox: {
          min: Vec3.ZERO,
          max: Vec3.ZERO
        }
      };

      var RenderingDebugViewType = {
        NONE: 0,
        SINGLE: 1,
        COMPOSITE_AND_MISC: 2
      };
      var DebugViewSingleType = {
        NONE: 0,
        VERTEX_COLOR: 1,
        VERTEX_NORMAL: 2,
        VERTEX_TANGENT: 3,
        WORLD_POS: 4,
        VERTEX_MIRROR: 5,
        FACE_SIDE: 6,
        UV0: 7,
        UV1: 8,
        UV_LIGHTMAP: 9,
        PROJ_DEPTH: 10,
        LINEAR_DEPTH: 11,
        FRAGMENT_NORMAL: 12,
        FRAGMENT_TANGENT: 13,
        FRAGMENT_BINORMAL: 14,
        BASE_COLOR: 15,
        DIFFUSE_COLOR: 16,
        SPECULAR_COLOR: 17,
        TRANSPARENCY: 18,
        METALLIC: 19,
        ROUGHNESS: 20,
        SPECULAR_INTENSITY: 21,
        IOR: 22,
        DIRECT_DIFFUSE: 23,
        DIRECT_SPECULAR: 24,
        DIRECT_ALL: 25,
        ENV_DIFFUSE: 26,
        ENV_SPECULAR: 27,
        ENV_ALL: 28,
        EMISSIVE: 29,
        LIGHT_MAP: 30,
        SHADOW: 31,
        AO: 32,
        FRESNEL: 33,
        DIRECT_TRANSMIT_DIFFUSE: 34,
        DIRECT_TRANSMIT_SPECULAR: 35,
        ENV_TRANSMIT_DIFFUSE: 36,
        ENV_TRANSMIT_SPECULAR: 37,
        TRANSMIT_ALL: 38,
        DIRECT_TRT: 39,
        ENV_TRT: 40,
        TRT_ALL: 41,
        FOG: 42
      };
      var DebugViewCompositeType = {
        DIRECT_DIFFUSE: 0,
        DIRECT_SPECULAR: 1,
        ENV_DIFFUSE: 2,
        ENV_SPECULAR: 3,
        EMISSIVE: 4,
        LIGHT_MAP: 5,
        SHADOW: 6,
        AO: 7,
        NORMAL_MAP: 8,
        FOG: 9,
        TONE_MAPPING: 10,
        GAMMA_CORRECTION: 11,
        FRESNEL: 12,
        TRANSMIT_DIFFUSE: 13,
        TRANSMIT_SPECULAR: 14,
        TRT: 15,
        TT: 16,
        MAX_BIT_COUNT: 17
      };
      var DebugView = exports('dw', function () {
        function DebugView() {
          this._singleMode = DebugViewSingleType.NONE;
          this._compositeModeValue = 0;
          this._lightingWithAlbedo = true;
          this._csmLayerColoration = false;
          this._activate();
        }
        var _proto = DebugView.prototype;
        _proto.isCompositeModeEnabled = function isCompositeModeEnabled(val) {
          var mode = this._compositeModeValue & 1 << val;
          return mode !== 0;
        };
        _proto.enableCompositeMode = function enableCompositeMode(val, enable) {
          this._enableCompositeMode(val, enable);
          this._updatePipeline();
        };
        _proto.enableAllCompositeMode = function enableAllCompositeMode(enable) {
          this._enableAllCompositeMode(enable);
          this._updatePipeline();
        };
        _proto.isEnabled = function isEnabled() {
          return this._getType() !== RenderingDebugViewType.NONE;
        };
        _proto.reset = function reset() {
          this._activate();
          this._updatePipeline();
        };
        _proto._activate = function _activate() {
          this._singleMode = DebugViewSingleType.NONE;
          this._enableAllCompositeMode(true);
          this._lightingWithAlbedo = true;
          this._csmLayerColoration = false;
        };
        _proto._updatePipeline = function _updatePipeline() {
          var root = legacyCC.director.root;
          var pipeline = root.pipeline;
          var useDebugView = this._getType();
          if (pipeline.macros.CC_USE_DEBUG_VIEW !== useDebugView) {
            pipeline.macros.CC_USE_DEBUG_VIEW = useDebugView;
            root.onGlobalPipelineStateChanged();
          }
        };
        _proto._enableCompositeMode = function _enableCompositeMode(val, enable) {
          if (enable) {
            this._compositeModeValue |= 1 << val;
          } else {
            this._compositeModeValue &= ~(1 << val);
          }
        };
        _proto._enableAllCompositeMode = function _enableAllCompositeMode(enable) {
          for (var i = 0; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) {
            if (enable) {
              this._compositeModeValue |= 1 << i;
            } else {
              this._compositeModeValue &= ~(1 << i);
            }
          }
        };
        _proto._getType = function _getType() {
          if (this._singleMode !== DebugViewSingleType.NONE) {
            return RenderingDebugViewType.SINGLE;
          } else if (this._lightingWithAlbedo !== true || this._csmLayerColoration !== false) {
            return RenderingDebugViewType.COMPOSITE_AND_MISC;
          } else {
            for (var i = 0; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) {
              if (!this.isCompositeModeEnabled(i)) {
                return RenderingDebugViewType.COMPOSITE_AND_MISC;
              }
            }
          }
          return RenderingDebugViewType.NONE;
        };
        _createClass(DebugView, [{
          key: "singleMode",
          get: function get() {
            return this._singleMode;
          },
          set: function set(val) {
            this._singleMode = val;
            this._updatePipeline();
          }
        }, {
          key: "lightingWithAlbedo",
          get: function get() {
            return this._lightingWithAlbedo;
          },
          set: function set(val) {
            this._lightingWithAlbedo = val;
            this._updatePipeline();
          }
        }, {
          key: "csmLayerColoration",
          get: function get() {
            return this._csmLayerColoration;
          },
          set: function set(val) {
            this._csmLayerColoration = val;
            this._updatePipeline();
          }
        }, {
          key: "debugViewType",
          get: function get() {
            return this._getType();
          }
        }]);
        return DebugView;
      }());

      var _rangedDirLightBoundingBox$2 = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5);
      var _tmpBoundingBox$2 = new AABB();
      var AntiAliasing$1;
      (function (AntiAliasing) {
        AntiAliasing[AntiAliasing["NONE"] = 0] = "NONE";
        AntiAliasing[AntiAliasing["FXAA"] = 1] = "FXAA";
        AntiAliasing[AntiAliasing["FXAAHQ"] = 2] = "FXAAHQ";
      })(AntiAliasing$1 || (AntiAliasing$1 = {}));
      function getRTFormatBeforeToneMapping(ppl) {
        var useFloatOutput = ppl.getMacroBool('CC_USE_FLOAT_OUTPUT');
        return ppl.pipelineSceneData.isHDR && useFloatOutput && supportsRGBA16HalfFloatTexture(ppl.device) ? Format.RGBA16F : Format.RGBA8;
      }
      function validPunctualLightsCulling(pipeline, camera) {
        var sceneData = pipeline.pipelineSceneData;
        var validPunctualLights = sceneData.validPunctualLights;
        validPunctualLights.length = 0;
        var _sphere = Sphere.create(0, 0, 0, 1);
        var _ref = camera.scene,
          spotLights = _ref.spotLights;
        for (var i = 0; i < spotLights.length; i++) {
          var light = spotLights[i];
          if (light.baked && !camera.node.scene.globals.disableLightmap) {
            continue;
          }
          Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(light);
          }
        }
        var _ref2 = camera.scene,
          sphereLights = _ref2.sphereLights;
        for (var _i = 0; _i < sphereLights.length; _i++) {
          var _light = sphereLights[_i];
          if (_light.baked && !camera.node.scene.globals.disableLightmap) {
            continue;
          }
          Sphere.set(_sphere, _light.position.x, _light.position.y, _light.position.z, _light.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(_light);
          }
        }
        var _ref3 = camera.scene,
          pointLights = _ref3.pointLights;
        for (var _i2 = 0; _i2 < pointLights.length; _i2++) {
          var _light2 = pointLights[_i2];
          if (_light2.baked) {
            continue;
          }
          Sphere.set(_sphere, _light2.position.x, _light2.position.y, _light2.position.z, _light2.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(_light2);
          }
        }
        var _ref4 = camera.scene,
          rangedDirLights = _ref4.rangedDirLights;
        for (var _i3 = 0; _i3 < rangedDirLights.length; _i3++) {
          var _light3 = rangedDirLights[_i3];
          AABB.transform(_tmpBoundingBox$2, _rangedDirLightBoundingBox$2, _light3.node.getWorldMatrix());
          if (intersect.aabbFrustum(_tmpBoundingBox$2, camera.frustum)) {
            validPunctualLights.push(_light3);
          }
        }
        sceneData.validPunctualLights = validPunctualLights;
      }
      var _cameras = [];
      function getCameraUniqueID(camera) {
        if (!_cameras.includes(camera)) {
          _cameras.push(camera);
        }
        return _cameras.indexOf(camera);
      }
      function getLoadOpOfClearFlag(clearFlag, attachment) {
        var loadOp = LoadOp.CLEAR;
        if (!(clearFlag & ClearFlagBit.COLOR) && attachment === AttachmentType.RENDER_TARGET) {
          if (clearFlag & SKYBOX_FLAG) {
            loadOp = LoadOp.CLEAR;
          } else {
            loadOp = LoadOp.LOAD;
          }
        }
        if ((clearFlag & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL && attachment === AttachmentType.DEPTH_STENCIL) {
          if (!(clearFlag & ClearFlagBit.DEPTH)) loadOp = LoadOp.LOAD;
          if (!(clearFlag & ClearFlagBit.STENCIL)) loadOp = LoadOp.LOAD;
        }
        return loadOp;
      }
      function getRenderArea(camera, width, height, light, level, out) {
        if (light === void 0) {
          light = null;
        }
        if (level === void 0) {
          level = 0;
        }
        if (out === void 0) {
          out = undefined;
        }
        out = out || new Rect();
        var vp = camera ? camera.viewport : new Rect(0, 0, 1, 1);
        var w = width;
        var h = height;
        out.x = vp.x * w;
        out.y = vp.y * h;
        out.width = vp.width * w;
        out.height = vp.height * h;
        if (light) {
          switch (light.type) {
            case LightType.DIRECTIONAL:
              {
                var mainLight = light;
                if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) {
                  out.x = 0;
                  out.y = 0;
                  out.width = w;
                  out.height = h;
                } else {
                  var screenSpaceSignY = legacyCC.director.root.device.capabilities.screenSpaceSignY;
                  out.x = level % 2 * 0.5 * w;
                  if (screenSpaceSignY > 0) {
                    out.y = (1 - Math.floor(level / 2)) * 0.5 * h;
                  } else {
                    out.y = Math.floor(level / 2) * 0.5 * h;
                  }
                  out.width = 0.5 * w;
                  out.height = 0.5 * h;
                }
                break;
              }
            case LightType.SPOT:
              {
                out.x = 0;
                out.y = 0;
                out.width = w;
                out.height = h;
                break;
              }
          }
        }
        return out;
      }
      var PostInfo = function () {
        var _proto3 = PostInfo.prototype;
        _proto3._init = function _init() {
          this.postMaterial = new Material();
          this.postMaterial.name = 'builtin-post-process-material';
          this.postMaterial.initialize({
            effectName: 'pipeline/post-process',
            defines: {
              ANTIALIAS_TYPE: this.antiAliasing
            }
          });
          for (var i = 0; i < this.postMaterial.passes.length; ++i) {
            this.postMaterial.passes[i].tryCompile();
          }
        };
        function PostInfo(antiAliasing) {
          if (antiAliasing === void 0) {
            antiAliasing = AntiAliasing$1.NONE;
          }
          this.antiAliasing = AntiAliasing$1.NONE;
          this.antiAliasing = antiAliasing;
          this._init();
        }
        return PostInfo;
      }();
      var ShadowInfo = function () {
        function ShadowInfo() {
          this.shadowEnabled = false;
          this.mainLightShadowNames = new Array();
          this.spotLightShadowNames = new Array();
          this.validLights = [];
        }
        var _proto4 = ShadowInfo.prototype;
        _proto4.reset = function reset() {
          this.shadowEnabled = false;
          this.mainLightShadowNames.length = 0;
          this.spotLightShadowNames.length = 0;
          this.validLights.length = 0;
        };
        return ShadowInfo;
      }();
      new ShadowInfo();
      var GBufferInfo = function GBufferInfo() {
        this.color = void 0;
        this.normal = void 0;
        this.emissive = void 0;
        this.ds = void 0;
      };
      var LightingInfo = function () {
        var _proto5 = LightingInfo.prototype;
        _proto5._init = function _init() {
          this.deferredLightingMaterial = new Material();
          this.deferredLightingMaterial.name = 'builtin-deferred-material';
          this.deferredLightingMaterial.initialize({
            effectName: 'pipeline/deferred-lighting',
            defines: {
              CC_ENABLE_CLUSTERED_LIGHT_CULLING: this.enableCluster,
              CC_RECEIVE_SHADOW: 1
            }
          });
          for (var i = 0; i < this.deferredLightingMaterial.passes.length; ++i) {
            this.deferredLightingMaterial.passes[i].tryCompile();
          }
        };
        function LightingInfo(clusterEn) {
          this.enableCluster = void 0;
          this.enableCluster = clusterEn ? 1 : 0;
          this._init();
        }
        return LightingInfo;
      }();
      function getDescBinding(descId, descData) {
        var layoutData = descData;
        for (var _iterator5 = _createForOfIteratorHelperLoose(layoutData.descriptorSetLayoutData.descriptorBlocks), _step5; !(_step5 = _iterator5()).done;) {
          var block = _step5.value;
          for (var i = 0; i !== block.descriptors.length; ++i) {
            if (descId === block.descriptors[i].descriptorID) {
              return block.offset + i;
            }
          }
        }
        return -1;
      }
      function getDescBindingFromName(bindingName) {
        var pipeline = legacyCC.director.root.pipeline;
        var layoutGraph = pipeline.layoutGraph;
        var vertIds = layoutGraph.vertices();
        var descId = layoutGraph.attributeIndex.get(bindingName);
        var currDesData;
        for (var _iterator6 = _createForOfIteratorHelperLoose(vertIds), _step6; !(_step6 = _iterator6()).done;) {
          var i = _step6.value;
          var layout = layoutGraph.getLayout(i);
          for (var _iterator7 = _createForOfIteratorHelperLoose(layout.descriptorSets), _step7; !(_step7 = _iterator7()).done;) {
            var _step7$value = _step7.value;
              _step7$value[0];
              var descData = _step7$value[1];
            var layoutData = descData.descriptorSetLayoutData;
            var blocks = layoutData.descriptorBlocks;
            for (var _iterator8 = _createForOfIteratorHelperLoose(blocks), _step8; !(_step8 = _iterator8()).done;) {
              var b = _step8.value;
              for (var _iterator9 = _createForOfIteratorHelperLoose(b.descriptors), _step9; !(_step9 = _iterator9()).done;) {
                var ds = _step9.value;
                if (ds.descriptorID === descId) {
                  currDesData = descData;
                  return getDescBinding(descId, currDesData);
                }
              }
            }
          }
        }
        return -1;
      }
      var layouts = new Map();
      function getDescriptorSetDataFromLayout(layoutName) {
        var descLayout = layouts.get(layoutName);
        if (descLayout) {
          return descLayout;
        }
        var webPip = legacyCC.director.root.pipeline;
        var stageId = webPip.layoutGraph.locateChild(webPip.layoutGraph.nullVertex(), layoutName);
        assert(stageId !== 0xFFFFFFFF);
        var layout = webPip.layoutGraph.getLayout(stageId);
        var layoutData = layout.descriptorSets.get(UpdateFrequency.PER_PASS);
        layouts.set(layoutName, layoutData);
        return layoutData;
      }
      var _varianceArray = [0.0484, 0.187, 0.567, 1.99, 7.41];
      var _strengthParameterArray = [0.100, 0.118, 0.113, 0.358, 0.078];
      var _vec3Temp = new Vec3();
      var _vec3Temp2 = new Vec3();
      var _vec4Temp = new Vec4();
      var _vec4Temp2 = new Vec4();
      var COPY_INPUT_DS_PASS_INDEX = 0;
      var SSSS_BLUR_X_PASS_INDEX = 1;
      var SSSS_BLUR_Y_PASS_INDEX = 2;
      var EXPONENT = 2.0;
      var I_SAMPLES_COUNT = 25;
      (function () {
        var _proto6 = SSSSBlurData.prototype;
        _proto6._gaussian = function _gaussian(out, variance, r) {
          var xx = r / (0.001 + this._v3SSSSFallOff.x);
          out.x = Math.exp(-(xx * xx) / (2.0 * variance)) / (2.0 * 3.14 * variance);
          var yy = r / (0.001 + this._v3SSSSFallOff.y);
          out.y = Math.exp(-(yy * yy) / (2.0 * variance)) / (2.0 * 3.14 * variance);
          var zz = r / (0.001 + this._v3SSSSFallOff.z);
          out.z = Math.exp(-(zz * zz) / (2.0 * variance)) / (2.0 * 3.14 * variance);
        };
        _proto6._profile = function _profile(out, val) {
          for (var i = 0; i < 5; i++) {
            this._gaussian(_vec3Temp2, _varianceArray[i], val);
            _vec3Temp2.multiplyScalar(_strengthParameterArray[i]);
            out.add(_vec3Temp2);
          }
        };
        _proto6._updateSampleCount = function _updateSampleCount() {
          var strength = this._v3SSSSStrength;
          var nSamples = I_SAMPLES_COUNT;
          var range = 3.0 ;
          var step = 2.0 * range / (nSamples - 1);
          for (var i = 0; i < nSamples; i++) {
            var o = -range + i * step;
            var sign = o < 0.0 ? -1.0 : 1.0;
            this._kernel[i].w = range * sign * Math.abs(Math.pow(o, EXPONENT)) / Math.pow(range, EXPONENT);
          }
          for (var _i5 = 0; _i5 < nSamples; _i5++) {
            var w0 = _i5 > 0 ? Math.abs(this._kernel[_i5].w - this._kernel[_i5 - 1].w) : 0.0;
            var w1 = _i5 < nSamples - 1 ? Math.abs(this._kernel[_i5].w - this._kernel[_i5 + 1].w) : 0.0;
            var area = (w0 + w1) / 2.0;
            _vec3Temp.set(0);
            this._profile(_vec3Temp, this._kernel[_i5].w);
            _vec3Temp.multiplyScalar(area);
            this._kernel[_i5].x = _vec3Temp.x;
            this._kernel[_i5].y = _vec3Temp.y;
            this._kernel[_i5].z = _vec3Temp.z;
          }
          var remainder = nSamples % 2;
          _vec4Temp.set(this._kernel[(nSamples - remainder) / 2]);
          for (var _i6 = (nSamples - remainder) / 2; _i6 > 0; _i6--) {
            _vec4Temp2.set(this._kernel[_i6 - 1]);
            this._kernel[_i6].set(_vec4Temp2);
          }
          this._kernel[0].set(_vec4Temp);
          _vec3Temp.set(0.0);
          for (var _i7 = 0; _i7 < nSamples; _i7++) {
            _vec3Temp.add3f(this._kernel[_i7].x, this._kernel[_i7].y, this._kernel[_i7].z);
          }
          for (var _i8 = 0; _i8 < nSamples; _i8++) {
            this._kernel[_i8].x /= _vec3Temp.x;
            this._kernel[_i8].y /= _vec3Temp.y;
            this._kernel[_i8].z /= _vec3Temp.z;
          }
          this._kernel[0].x = (1.0 - strength.x) * 1.0 + strength.x * this._kernel[0].x;
          this._kernel[0].y = (1.0 - strength.y) * 1.0 + strength.y * this._kernel[0].y;
          this._kernel[0].z = (1.0 - strength.z) * 1.0 + strength.z * this._kernel[0].z;
          for (var _i9 = 1; _i9 < nSamples; _i9++) {
            this._kernel[_i9].x *= strength.x;
            this._kernel[_i9].y *= strength.y;
            this._kernel[_i9].z *= strength.z;
          }
        };
        _proto6._updateBlurPass = function _updateBlurPass() {
          if (!this.ssssBlurMaterial) return;
          var copyInputDSPass = this.ssssBlurMaterial.passes[COPY_INPUT_DS_PASS_INDEX];
          copyInputDSPass.beginChangeStatesSilently();
          copyInputDSPass.tryCompile();
          copyInputDSPass.endChangeStatesSilently();
          var ssssBlurXPass = this.ssssBlurMaterial.passes[SSSS_BLUR_X_PASS_INDEX];
          ssssBlurXPass.beginChangeStatesSilently();
          ssssBlurXPass.tryCompile();
          ssssBlurXPass.endChangeStatesSilently();
          var ssssBlurYPass = this.ssssBlurMaterial.passes[SSSS_BLUR_Y_PASS_INDEX];
          ssssBlurYPass.beginChangeStatesSilently();
          ssssBlurYPass.tryCompile();
          ssssBlurYPass.endChangeStatesSilently();
        };
        _proto6._init = function _init() {
          if (this.ssssBlurMaterial) return;
          this.ssssBlurMaterial = new Material();
          this.ssssBlurMaterial._uuid = 'builtin-ssssBlur-material';
          this.ssssBlurMaterial.initialize({
            effectName: 'pipeline/ssss-blur'
          });
          for (var i = 0; i < this.ssssBlurMaterial.passes.length; ++i) {
            this.ssssBlurMaterial.passes[i].tryCompile();
          }
          this._updateBlurPass();
          for (var _i10 = 0; _i10 < I_SAMPLES_COUNT; _i10++) {
            this._kernel[_i10] = new Vec4();
          }
          this._updateSampleCount();
        };
        function SSSSBlurData() {
          this.ssssFov = 45.0 / 57.3;
          this.ssssWidth = 0.01;
          this.boundingBox = 0.4;
          this.ssssScale = 3.0;
          this._v3SSSSStrength = new Vec3(0.48, 0.41, 0.28);
          this._v3SSSSFallOff = new Vec3(1.0, 0.37, 0.3);
          this._kernel = [];
          this._init();
        }
        _createClass(SSSSBlurData, [{
          key: "ssssStrength",
          get: function get() {
            return this._v3SSSSStrength;
          },
          set: function set(val) {
            this._v3SSSSStrength = val;
            this._updateSampleCount();
          }
        }, {
          key: "ssssFallOff",
          get: function get() {
            return this._v3SSSSFallOff;
          },
          set: function set(val) {
            this._v3SSSSFallOff = val;
            this._updateSampleCount();
          }
        }, {
          key: "kernel",
          get: function get() {
            return this._kernel;
          }
        }]);
        return SSSSBlurData;
      })();
      (function () {
        var _proto8 = HBAOParams.prototype;
        _proto8._init = function _init() {
          if (this.hbaoMaterial) return;
          this.hbaoMaterial = new Material();
          this.hbaoMaterial.name = 'builtin-hbao-material';
          this.hbaoMaterial.initialize({
            effectName: 'pipeline/post-process/hbao'
          });
          for (var i = 0; i < this.hbaoMaterial.passes.length; ++i) {
            this.hbaoMaterial.passes[i].tryCompile();
          }
          var width = 4;
          var height = 4;
          var pixelFormat = Texture2D.PixelFormat.RGBA8888;
          var arrayBuffer = new Uint8Array(width * height * 4);
          for (var _i11 = 0; _i11 < this._randomDirAndJitter.length; _i11++) {
            arrayBuffer[_i11] = this._randomDirAndJitter[_i11];
          }
          var image = new ImageAsset({
            width: width,
            height: height,
            _data: arrayBuffer,
            _compressed: false,
            format: pixelFormat
          });
          this.randomTexture = new Texture2D();
          this.randomTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
          this.randomTexture.setMipFilter(Texture2D.Filter.NONE);
          this.randomTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT);
          this.randomTexture.image = image;
          this.hbaoMaterial.setProperty('RandomTex', this.randomTexture, 0);
        };
        _proto8.update = function update() {
          var HALF_KERNEL_RADIUS = 4;
          var INV_LN2 = 1.44269504;
          var SQRT_LN2 = 0.8325546;
          var gR = this._radiusScale * this._sceneScale;
          var gR2 = gR * gR;
          var gNegInvR2 = -1.0 / gR2;
          var gMaxRadiusPixels = 0.1 * Math.min(this._depthTexFullResolution.x, this._depthTexFullResolution.y);
          this._radiusParam.set(gR, gR2, gNegInvR2, gMaxRadiusPixels);
          var vec2 = new Vec2(this._depthTexResolution.y / this._depthTexResolution.x, 1.0);
          var gFocalLen = new Vec2(vec2.x / Math.tan(this._cameraFov * 0.5), vec2.y / Math.tan(this._cameraFov * 0.5));
          var gTanAngleBias = Math.tan(toRadian(this._angleBiasDegree));
          var gStrength = this._aoStrength;
          this._miscParam.set(gFocalLen.x, gFocalLen.y, gTanAngleBias, gStrength);
          var gUVToViewA = new Vec2(2.0 / gFocalLen.x, -2.0 / gFocalLen.y);
          var gUVToViewB = new Vec2(-1.0 / gFocalLen.x, 1.0 / gFocalLen.y);
          this._uvDepthToEyePosParams.set(gUVToViewA.x, gUVToViewA.y, gUVToViewB.x, gUVToViewB.y);
          var BlurSigma = (HALF_KERNEL_RADIUS + 1.0) * 0.5;
          var gBlurFallOff = INV_LN2 / (2.0 * BlurSigma * BlurSigma);
          var gBlurDepthThreshold = 2.0 * SQRT_LN2 * (this._sceneScale / this._blurSharpness);
          this._blurParam.set(gBlurFallOff, gBlurDepthThreshold, this._blurSharpness / 8.0, this._aoSaturation);
        };
        function HBAOParams() {
          this._uvDepthToEyePosParams = new Vec4();
          this._radiusParam = new Vec4();
          this._miscParam = new Vec4();
          this._blurParam = new Vec4();
          this._depthTexFullResolution = new Vec2(1024);
          this._depthTexResolution = new Vec2(1024);
          this._sceneScale = 1.0;
          this._cameraFov = toRadian(45.0);
          this._radiusScale = 1.0;
          this._angleBiasDegree = 10.0;
          this._aoStrength = 1.0;
          this._blurSharpness = 8;
          this._aoSaturation = 1.0;
          this._randomDirAndJitter = [238, 91, 87, 255, 251, 44, 119, 255, 247, 64, 250, 255, 232, 5, 225, 255, 253, 177, 140, 255, 250, 51, 84, 255, 243, 76, 97, 255, 252, 36, 232, 255, 235, 100, 24, 255, 252, 36, 158, 255, 254, 20, 142, 255, 245, 135, 124, 255, 251, 43, 121, 255, 253, 31, 145, 255, 235, 98, 160, 255, 240, 146, 198, 255];
          this._init();
          this.update();
        }
        _createClass(HBAOParams, [{
          key: "uvDepthToEyePosParams",
          get: function get() {
            return this._uvDepthToEyePosParams;
          }
        }, {
          key: "radiusParam",
          get: function get() {
            return this._radiusParam;
          }
        }, {
          key: "miscParam",
          get: function get() {
            return this._miscParam;
          }
        }, {
          key: "blurParam",
          get: function get() {
            return this._blurParam;
          }
        }, {
          key: "depthTexFullResolution",
          set: function set(val) {
            this._depthTexFullResolution.set(val);
          }
        }, {
          key: "depthTexResolution",
          set: function set(val) {
            this._depthTexResolution.set(val);
          }
        }, {
          key: "sceneScale",
          set: function set(val) {
            this._sceneScale = val;
          }
        }, {
          key: "cameraFov",
          set: function set(val) {
            this._cameraFov = val;
          }
        }, {
          key: "radiusScale",
          set: function set(val) {
            this._radiusScale = val;
          }
        }, {
          key: "angleBiasDegree",
          set: function set(val) {
            this._angleBiasDegree = val;
          }
        }, {
          key: "aoStrength",
          set: function set(val) {
            this._aoStrength = val;
          }
        }, {
          key: "blurSharpness",
          set: function set(val) {
            this._blurSharpness = val;
          }
        }, {
          key: "aoSaturation",
          set: function set(val) {
            this._aoSaturation = val;
          }
        }]);
        return HBAOParams;
      })();
      new Vec2();
      var MAX_LIGHTS_PER_CLUSTER = 200;
      var CLUSTERS_X = 16;
      var CLUSTERS_Y = 8;
      var CLUSTERS_Z = 24;
      var CLUSTER_COUNT = CLUSTERS_X * CLUSTERS_Y * CLUSTERS_Z;
      var ClusterLightData = function () {
        var _proto9 = ClusterLightData.prototype;
        _proto9._initMaterial = function _initMaterial(id, effect) {
          var mat = new Material();
          mat.name = id;
          mat.initialize({
            effectName: effect
          });
          for (var i = 0; i < mat.passes.length; ++i) {
            mat.passes[i].tryCompile();
          }
          return mat;
        };
        _proto9._init = function _init() {
          this.clusterBuildCS = this._initMaterial('builtin-cluster-build-cs-material', 'pipeline/cluster-build');
          this.clusterLightCullingCS = this._initMaterial('builtin-cluster-culling-cs-material', 'pipeline/cluster-culling');
          this.dispatchX = CLUSTERS_X / this.clusters_x_threads;
          this.dispatchY = CLUSTERS_Y / this.clusters_y_threads;
          this.dispatchZ = CLUSTERS_Z / this.clusters_z_threads;
        };
        function ClusterLightData() {
          this.clusters_x_threads = 16;
          this.clusters_y_threads = 8;
          this.clusters_z_threads = 1;
          this.dispatchX = 1;
          this.dispatchY = 1;
          this.dispatchZ = 1;
          this._init();
        }
        return ClusterLightData;
      }();
      var _clusterLightData = null;
      function buildLightClusterBuildPass(camera, clusterData, ppl) {
        var cameraID = getCameraUniqueID(camera);
        var clusterBufferName = "clusterBuffer" + cameraID;
        var clusterBufferSize = CLUSTER_COUNT * 2 * 4 * 4;
        if (!ppl.containsResource(clusterBufferName)) {
          ppl.addStorageBuffer(clusterBufferName, Format.UNKNOWN, clusterBufferSize, ResourceResidency.MANAGED);
        }
        ppl.updateStorageBuffer(clusterBufferName, clusterBufferSize);
        var clusterPass = ppl.addComputePass('cluster-build-cs');
        clusterPass.addStorageBuffer(clusterBufferName, AccessType.WRITE, 'b_clustersBuffer');
        clusterPass.addQueue().addDispatch(clusterData.dispatchX, clusterData.dispatchY, clusterData.dispatchZ, clusterData.clusterBuildCS, 0);
        var width = camera.width * ppl.pipelineSceneData.shadingScale;
        var height = camera.height * ppl.pipelineSceneData.shadingScale;
        if ('setCurrConstant' in clusterPass) {
          clusterPass.addConstant('CCConst', 'cluster-build-cs');
        }
        clusterPass.setVec4('cc_nearFar', new Vec4(camera.nearClip, camera.farClip, camera.getClipSpaceMinz(), 0));
        clusterPass.setVec4('cc_viewPort', new Vec4(0, 0, width, height));
        clusterPass.setVec4('cc_workGroup', new Vec4(CLUSTERS_X, CLUSTERS_Y, CLUSTERS_Z, 0));
        clusterPass.setMat4('cc_matView', camera.matView);
        clusterPass.setMat4('cc_matProjInv', camera.matProjInv);
      }
      function buildLightClusterCullingPass(camera, clusterData, ppl) {
        var cameraID = getCameraUniqueID(camera);
        var clusterBufferName = "clusterBuffer" + cameraID;
        var clusterLightBufferName = "clusterLightBuffer" + cameraID;
        var clusterGlobalIndexBufferName = "globalIndexBuffer" + cameraID;
        var clusterLightIndicesBufferName = "clusterLightIndicesBuffer" + cameraID;
        var clusterLightGridBufferName = "clusterLightGridBuffer" + cameraID;
        var lightIndexBufferSize = MAX_LIGHTS_PER_CLUSTER * CLUSTER_COUNT * 4;
        var lightGridBufferSize = CLUSTER_COUNT * 4 * 4;
        if (!ppl.containsResource(clusterLightIndicesBufferName)) {
          ppl.addStorageBuffer(clusterLightIndicesBufferName, Format.UNKNOWN, lightIndexBufferSize, ResourceResidency.MANAGED);
        }
        if (!ppl.containsResource(clusterLightGridBufferName)) {
          ppl.addStorageBuffer(clusterLightGridBufferName, Format.UNKNOWN, lightGridBufferSize, ResourceResidency.MANAGED);
        }
        var clusterPass = ppl.addComputePass('cluster-culling-cs');
        clusterPass.addStorageBuffer(clusterLightBufferName, AccessType.READ, 'b_ccLightsBuffer');
        clusterPass.addStorageBuffer(clusterBufferName, AccessType.READ, 'b_clustersBuffer');
        clusterPass.addStorageBuffer(clusterLightIndicesBufferName, AccessType.WRITE, 'b_clusterLightIndicesBuffer');
        clusterPass.addStorageBuffer(clusterLightGridBufferName, AccessType.WRITE, 'b_clusterLightGridBuffer');
        clusterPass.addStorageBuffer(clusterGlobalIndexBufferName, AccessType.WRITE, 'b_globalIndexBuffer');
        clusterPass.addQueue().addDispatch(clusterData.dispatchX, clusterData.dispatchY, clusterData.dispatchZ, clusterData.clusterLightCullingCS, 0);
        var width = camera.width * ppl.pipelineSceneData.shadingScale;
        var height = camera.height * ppl.pipelineSceneData.shadingScale;
        if ('setCurrConstant' in clusterPass) {
          clusterPass.addConstant('CCConst', 'cluster-build-cs');
        }
        clusterPass.setVec4('cc_nearFar', new Vec4(camera.nearClip, camera.farClip, camera.getClipSpaceMinz(), 0));
        clusterPass.setVec4('cc_viewPort', new Vec4(width, height, width, height));
        clusterPass.setVec4('cc_workGroup', new Vec4(CLUSTERS_X, CLUSTERS_Y, CLUSTERS_Z, 0));
        clusterPass.setMat4('cc_matView', camera.matView);
        clusterPass.setMat4('cc_matProjInv', camera.matProjInv);
      }
      function buildLightBuffer(size, floatPerLight, camera, pipeline) {
        var buffer = new ArrayBuffer(size);
        var view = new Float32Array(buffer);
        var data = pipeline.pipelineSceneData;
        var lightMeterScale = 10000.0;
        var exposure = camera.exposure;
        var index = 0;
        for (var _iterator18 = _createForOfIteratorHelperLoose(data.validPunctualLights), _step18; !(_step18 = _iterator18()).done;) {
          var light = _step18.value;
          var offset = index * floatPerLight;
          var positionOffset = offset + 0;
          var colorOffset = offset + 4;
          var sizeRangeAngleOffset = offset + 8;
          var directionOffset = offset + 12;
          var boundSizeOffset = offset + 16;
          var luminanceHDR = 0;
          var luminanceLDR = 0;
          var position = void 0;
          if (light.type === LightType.POINT) {
            var point = light;
            position = point.position;
            luminanceLDR = point.luminanceLDR;
            luminanceHDR = point.luminanceHDR;
            view[sizeRangeAngleOffset] = 0;
            view[sizeRangeAngleOffset + 1] = point.range;
            view[sizeRangeAngleOffset + 2] = 0;
            view[sizeRangeAngleOffset + 3] = 0;
          } else if (light.type === LightType.SPHERE) {
            var sphere = light;
            position = sphere.position;
            luminanceLDR = sphere.luminanceLDR;
            luminanceHDR = sphere.luminanceHDR;
            view[sizeRangeAngleOffset] = sphere.size;
            view[sizeRangeAngleOffset + 1] = sphere.range;
            view[sizeRangeAngleOffset + 2] = 0;
            view[sizeRangeAngleOffset + 3] = 0;
          } else if (light.type === LightType.SPOT) {
            var spot = light;
            position = spot.position;
            luminanceLDR = spot.luminanceLDR;
            luminanceHDR = spot.luminanceHDR;
            view[sizeRangeAngleOffset] = spot.size;
            view[sizeRangeAngleOffset + 1] = spot.range;
            view[sizeRangeAngleOffset + 2] = spot.spotAngle;
            view[sizeRangeAngleOffset + 3] = 0;
            var dir = spot.direction;
            view[directionOffset] = dir.x;
            view[directionOffset + 1] = dir.y;
            view[directionOffset + 2] = dir.z;
            view[directionOffset + 3] = 0;
          } else if (light.type === LightType.RANGED_DIRECTIONAL) {
            var directional = light;
            position = directional.position;
            luminanceLDR = directional.illuminanceLDR;
            luminanceHDR = directional.illuminanceHDR;
            var right = directional.right;
            view[sizeRangeAngleOffset] = right.x;
            view[sizeRangeAngleOffset + 1] = right.y;
            view[sizeRangeAngleOffset + 2] = right.z;
            view[sizeRangeAngleOffset + 3] = 0;
            var _dir = directional.direction;
            view[directionOffset] = _dir.x;
            view[directionOffset + 1] = _dir.y;
            view[directionOffset + 2] = _dir.z;
            view[directionOffset + 3] = 0;
            var scale = directional.scale;
            view[boundSizeOffset] = scale.x * 0.5;
            view[boundSizeOffset + 1] = scale.y * 0.5;
            view[boundSizeOffset + 2] = scale.z * 0.5;
            view[boundSizeOffset + 3] = 0;
          }
          view[positionOffset] = position.x;
          view[positionOffset + 1] = position.y;
          view[positionOffset + 2] = position.z;
          view[positionOffset + 3] = light.type;
          var color = light.color;
          if (light.useColorTemperature) {
            var tempRGB = light.colorTemperatureRGB;
            view[colorOffset] = color.x * tempRGB.x;
            view[colorOffset + 1] = color.y * tempRGB.y;
            view[colorOffset + 2] = color.z * tempRGB.z;
          } else {
            view[colorOffset] = color.x;
            view[colorOffset + 1] = color.y;
            view[colorOffset + 2] = color.z;
          }
          view[colorOffset + 3] = data.isHDR ? luminanceHDR * exposure * lightMeterScale : luminanceLDR;
          index++;
        }
        view[3 * 4 + 3] = data.validPunctualLights.length;
        return buffer;
      }
      function buildClusterLightData(camera, pipeline) {
        validPunctualLightsCulling(pipeline, camera);
        var data = pipeline.pipelineSceneData;
        var validLightCountForBuffer = nextPow2(Math.max(data.validPunctualLights.length, 1));
        var lightBufferFloatNum = 20;
        var clusterLightBufferSize = validLightCountForBuffer * 4 * lightBufferFloatNum;
        var cameraID = getCameraUniqueID(camera);
        var clusterLightBufferName = "clusterLightBuffer" + cameraID;
        var clusterGlobalIndexBufferName = "globalIndexBuffer" + cameraID;
        var ppl = pipeline;
        if (!ppl.containsResource(clusterGlobalIndexBufferName)) {
          ppl.addStorageBuffer(clusterGlobalIndexBufferName, Format.UNKNOWN, 4, ResourceResidency.PERSISTENT);
        }
        if (!ppl.containsResource(clusterLightBufferName)) {
          ppl.addStorageBuffer(clusterLightBufferName, Format.UNKNOWN, clusterLightBufferSize, ResourceResidency.PERSISTENT);
        }
        ppl.updateStorageBuffer(clusterLightBufferName, clusterLightBufferSize);
        var buffer = buildLightBuffer(clusterLightBufferSize, lightBufferFloatNum, camera, pipeline);
        var globalIndexBuffer = new ArrayBuffer(4);
        var globalIndexBufferView = new Uint32Array(globalIndexBuffer);
        globalIndexBufferView[0] = 0;
        var uploadPair1 = new UploadPair(new Uint8Array(buffer), clusterLightBufferName);
        var uploadPair2 = new UploadPair(new Uint8Array(globalIndexBuffer), clusterGlobalIndexBufferName);
        ppl.addUploadPass([uploadPair1, uploadPair2]);
      }
      function buildClusterPasses(camera, pipeline) {
        buildClusterLightData(camera, pipeline);
        var ppl = pipeline;
        if (!_clusterLightData) _clusterLightData = new ClusterLightData();
        buildLightClusterBuildPass(camera, _clusterLightData, ppl);
        buildLightClusterCullingPass(camera, _clusterLightData, ppl);
      }

      var _samplerLinearInfo = new SamplerInfo(Filter$1.LINEAR, Filter$1.LINEAR, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP);
      var _samplerPointInfo = new SamplerInfo(Filter$1.POINT, Filter$1.POINT, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP);
      var GlobalDSManager = function () {
        function GlobalDSManager(device) {
          this._device = void 0;
          this._descriptorSetMap = new Map();
          this._globalDescriptorSet = void 0;
          this._descriptorSetLayout = void 0;
          this._linearSampler = void 0;
          this._pointSampler = void 0;
          this._device = device;
          this._linearSampler = this._device.getSampler(_samplerLinearInfo);
          this._pointSampler = this._device.getSampler(_samplerPointInfo);
          var layoutInfo = new DescriptorSetLayoutInfo(globalDescriptorSetLayout.bindings);
          this._descriptorSetLayout = this._device.createDescriptorSetLayout(layoutInfo);
          this._globalDescriptorSet = this._device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout));
        }
        var _proto = GlobalDSManager.prototype;
        _proto.regenLayout = function regenLayout() {
          var layoutInfo = new DescriptorSetLayoutInfo(globalDescriptorSetLayout.bindings);
          this._descriptorSetLayout = this._device.createDescriptorSetLayout(layoutInfo);
          this._globalDescriptorSet = this._device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout));
        };
        _proto.bindBuffer = function bindBuffer(binding, buffer) {
          this._globalDescriptorSet.bindBuffer(binding, buffer);
          var it = this._descriptorSetMap.values();
          var res = it.next();
          while (!res.done) {
            var descriptorSet = res.value;
            descriptorSet.bindBuffer(binding, buffer);
            res = it.next();
          }
        };
        _proto.bindSampler = function bindSampler(binding, sampler) {
          this._globalDescriptorSet.bindSampler(binding, sampler);
          var it = this._descriptorSetMap.values();
          var res = it.next();
          while (!res.done) {
            var descriptorSet = res.value;
            descriptorSet.bindSampler(binding, sampler);
            res = it.next();
          }
        };
        _proto.bindTexture = function bindTexture(binding, texture) {
          this._globalDescriptorSet.bindTexture(binding, texture);
          var it = this._descriptorSetMap.values();
          var res = it.next();
          while (!res.done) {
            var descriptorSet = res.value;
            descriptorSet.bindTexture(binding, texture);
            res = it.next();
          }
        };
        _proto.update = function update() {
          this._globalDescriptorSet.update();
          var it = this._descriptorSetMap.values();
          var res = it.next();
          while (!res.done) {
            var descriptorSet = res.value;
            descriptorSet.update();
            res = it.next();
          }
        };
        _proto.getOrCreateDescriptorSet = function getOrCreateDescriptorSet(light) {
          var device = this._device;
          if (!this._descriptorSetMap.has(light)) {
            var globalDescriptorSet = isEnableEffect() ? getDescriptorSetDataFromLayout('default').descriptorSet : this._globalDescriptorSet;
            var descriptorSet = device.createDescriptorSet(new DescriptorSetInfo(isEnableEffect() ? getDescriptorSetDataFromLayout('default').descriptorSetLayout : this._descriptorSetLayout));
            this._descriptorSetMap.set(light, descriptorSet);
            for (var i = PipelineGlobalBindings.UBO_GLOBAL; i < PipelineGlobalBindings.COUNT; i++) {
              descriptorSet.bindBuffer(i, globalDescriptorSet.getBuffer(i));
              descriptorSet.bindSampler(i, globalDescriptorSet.getSampler(i));
              descriptorSet.bindTexture(i, globalDescriptorSet.getTexture(i));
            }
            var shadowUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOShadow.SIZE, UBOShadow.SIZE));
            var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
            descriptorSet.bindBuffer(binding, shadowUBO);
            descriptorSet.update();
          }
          return this._descriptorSetMap.get(light);
        };
        _proto.destroy = function destroy() {
          this._descriptorSetLayout.destroy();
        };
        _createClass(GlobalDSManager, [{
          key: "descriptorSetMap",
          get: function get() {
            return this._descriptorSetMap;
          }
        }, {
          key: "linearSampler",
          get: function get() {
            return this._linearSampler;
          }
        }, {
          key: "pointSampler",
          get: function get() {
            return this._pointSampler;
          }
        }, {
          key: "descriptorSetLayout",
          get: function get() {
            return this._descriptorSetLayout;
          }
        }, {
          key: "globalDescriptorSet",
          get: function get() {
            return this._globalDescriptorSet;
          },
          set: function set(val) {
            this._globalDescriptorSet = val;
          }
        }]);
        return GlobalDSManager;
      }();

      var _matShadowView$2 = new Mat4();
      var _matShadowProj$1 = new Mat4();
      var _matShadowViewProj$2 = new Mat4();
      var _vec4ShadowInfo = new Vec4();
      var _lightDir = new Vec4(0.0, 0.0, 1.0, 0.0);
      var _tempVec3$3 = new Vec3();
      var PipelineUBO = function () {
        function PipelineUBO() {
          this._globalUBO = new Float32Array(UBOGlobal.COUNT);
          this._cameraUBO = new Float32Array(UBOCamera.COUNT);
          this._shadowUBO = new Float32Array(UBOShadow.COUNT);
          this._csmUBO = new Float32Array(UBOCSM.COUNT);
        }
        PipelineUBO.updateGlobalUBOView = function updateGlobalUBOView(window, bufferView) {
          var director = legacyCC.director;
          var root = director.root;
          var fv = bufferView;
          var shadingWidth = Math.floor(window.width);
          var shadingHeight = Math.floor(window.height);
          fv[UBOGlobal.TIME_OFFSET] = root.cumulativeTime;
          fv[UBOGlobal.TIME_OFFSET + 1] = root.frameTime;
          fv[UBOGlobal.TIME_OFFSET + 2] = director.getTotalFrames();
          fv[UBOGlobal.TIME_OFFSET + 3] = root.cumulativeTime - Math.floor(root.frameTime);
          fv[UBOGlobal.SCREEN_SIZE_OFFSET] = shadingWidth;
          fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = shadingHeight;
          fv[UBOGlobal.SCREEN_SIZE_OFFSET + 2] = 1.0 / shadingWidth;
          fv[UBOGlobal.SCREEN_SIZE_OFFSET + 3] = 1.0 / shadingHeight;
          fv[UBOGlobal.NATIVE_SIZE_OFFSET] = shadingWidth;
          fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1] = shadingHeight;
          fv[UBOGlobal.NATIVE_SIZE_OFFSET + 2] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET];
          fv[UBOGlobal.NATIVE_SIZE_OFFSET + 3] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1];
          if (legacyCC.internal.reflectionProbeManager) {
            fv[UBOGlobal.PROBE_INFO_OFFSET] = legacyCC.internal.reflectionProbeManager.getMaxProbeId() + 1;
          }
          var debugView = root.debugView;
          for (var i = 0; i <= 3; i++) {
            fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + i] = 0.0;
          }
          if (debugView.isEnabled()) {
            fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET] = debugView.singleMode;
            for (var _i = DebugViewCompositeType.DIRECT_DIFFUSE; _i < DebugViewCompositeType.MAX_BIT_COUNT; _i++) {
              var offset = _i >> 3;
              var bit = _i % 8;
              fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 1 + offset] += (debugView.isCompositeModeEnabled(_i) ? 1.0 : 0.0) * Math.pow(10.0, bit);
            }
            fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 3] += (debugView.lightingWithAlbedo ? 1.0 : 0.0) * Math.pow(10.0, 6.0);
            fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 3] += (debugView.csmLayerColoration ? 1.0 : 0.0) * Math.pow(10.0, 7.0);
          }
        };
        PipelineUBO.updateCameraUBOView = function updateCameraUBOView(pipeline, bufferView, camera) {
          var _skybox$envmap;
          var scene = camera.scene ? camera.scene : legacyCC.director.getScene().renderScene;
          var mainLight = scene.mainLight;
          var sceneData = pipeline.pipelineSceneData;
          var ambient = sceneData.ambient;
          var skybox = sceneData.skybox;
          var fog = sceneData.fog;
          var shadowInfo = sceneData.shadows;
          var cv = bufferView;
          var exposure = camera.exposure;
          var isHDR = sceneData.isHDR;
          cv[UBOCamera.SCREEN_SCALE_OFFSET] = sceneData.shadingScale;
          cv[UBOCamera.SCREEN_SCALE_OFFSET + 1] = sceneData.shadingScale;
          cv[UBOCamera.SCREEN_SCALE_OFFSET + 2] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET];
          cv[UBOCamera.SCREEN_SCALE_OFFSET + 3] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET + 1];
          cv[UBOCamera.EXPOSURE_OFFSET] = exposure;
          cv[UBOCamera.EXPOSURE_OFFSET + 1] = 1.0 / exposure;
          cv[UBOCamera.EXPOSURE_OFFSET + 2] = isHDR ? 1.0 : 0.0;
          cv[UBOCamera.EXPOSURE_OFFSET + 3] = 1.0 / Camera$1.standardExposureValue;
          if (mainLight) {
            var shadowEnable = mainLight.shadowEnabled && shadowInfo.type === ShadowType.ShadowMap ? 1.0 : 0.0;
            var mainLightDir = mainLight.direction;
            _lightDir.set(mainLightDir.x, mainLightDir.y, mainLightDir.z, shadowEnable);
            Vec4.toArray(cv, _lightDir, UBOCamera.MAIN_LIT_DIR_OFFSET);
            Vec3.toArray(cv, mainLight.color, UBOCamera.MAIN_LIT_COLOR_OFFSET);
            if (mainLight.useColorTemperature) {
              var _colorTempRGB = mainLight.colorTemperatureRGB;
              cv[UBOCamera.MAIN_LIT_COLOR_OFFSET] *= _colorTempRGB.x;
              cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 1] *= _colorTempRGB.y;
              cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 2] *= _colorTempRGB.z;
            }
            if (isHDR) {
              cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * exposure;
            } else {
              cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance;
            }
          } else {
            _lightDir.set(0, 0, 1, 0);
            Vec4.toArray(cv, _lightDir, UBOCamera.MAIN_LIT_DIR_OFFSET);
            Vec4.toArray(cv, Vec4.ZERO, UBOCamera.MAIN_LIT_COLOR_OFFSET);
          }
          var skyColor = ambient.skyColor;
          if (isHDR) {
            skyColor.w = ambient.skyIllum * exposure;
          } else {
            skyColor.w = ambient.skyIllum;
          }
          cv[UBOCamera.AMBIENT_SKY_OFFSET + 0] = skyColor.x;
          cv[UBOCamera.AMBIENT_SKY_OFFSET + 1] = skyColor.y;
          cv[UBOCamera.AMBIENT_SKY_OFFSET + 2] = skyColor.z;
          cv[UBOCamera.AMBIENT_SKY_OFFSET + 3] = skyColor.w;
          cv[UBOCamera.AMBIENT_GROUND_OFFSET + 0] = ambient.groundAlbedo.x;
          cv[UBOCamera.AMBIENT_GROUND_OFFSET + 1] = ambient.groundAlbedo.y;
          cv[UBOCamera.AMBIENT_GROUND_OFFSET + 2] = ambient.groundAlbedo.z;
          cv[UBOCamera.AMBIENT_GROUND_OFFSET + 3] = skybox.envmap ? (_skybox$envmap = skybox.envmap) === null || _skybox$envmap === void 0 ? void 0 : _skybox$envmap.mipmapLevel : 1.0;
          Mat4.toArray(cv, camera.matView, UBOCamera.MAT_VIEW_OFFSET);
          Mat4.toArray(cv, camera.node.worldMatrix, UBOCamera.MAT_VIEW_INV_OFFSET);
          Vec3.toArray(cv, camera.position, UBOCamera.CAMERA_POS_OFFSET);
          Mat4.toArray(cv, camera.matProj, UBOCamera.MAT_PROJ_OFFSET);
          Mat4.toArray(cv, camera.matProjInv, UBOCamera.MAT_PROJ_INV_OFFSET);
          Mat4.toArray(cv, camera.matViewProj, UBOCamera.MAT_VIEW_PROJ_OFFSET);
          Mat4.toArray(cv, camera.matViewProjInv, UBOCamera.MAT_VIEW_PROJ_INV_OFFSET);
          cv[UBOCamera.CAMERA_POS_OFFSET + 3] = this.getCombineSignY();
          cv[UBOCamera.SURFACE_TRANSFORM_OFFSET] = camera.surfaceTransform;
          cv[UBOCamera.SURFACE_TRANSFORM_OFFSET + 1] = camera.cameraUsage;
          cv[UBOCamera.SURFACE_TRANSFORM_OFFSET + 2] = Math.cos(toRadian(sceneData.skybox.getRotationAngle()));
          cv[UBOCamera.SURFACE_TRANSFORM_OFFSET + 3] = Math.sin(toRadian(sceneData.skybox.getRotationAngle()));
          var colorTempRGB = fog.colorArray;
          cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET] = colorTempRGB.x;
          cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 1] = colorTempRGB.y;
          cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 2] = colorTempRGB.z;
          cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 3] = colorTempRGB.z;
          cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET] = fog.fogStart;
          cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 1] = fog.fogEnd;
          cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 2] = fog.fogDensity;
          cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET] = fog.fogTop;
          cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 1] = fog.fogRange;
          cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 2] = fog.fogAtten;
          cv[UBOCamera.NEAR_FAR_OFFSET] = camera.nearClip;
          cv[UBOCamera.NEAR_FAR_OFFSET + 1] = camera.farClip;
          cv[UBOCamera.NEAR_FAR_OFFSET + 2] = camera.getClipSpaceMinz();
          cv[UBOCamera.VIEW_PORT_OFFSET] = sceneData.shadingScale * camera.window.width * camera.viewport.x;
          cv[UBOCamera.VIEW_PORT_OFFSET + 1] = sceneData.shadingScale * camera.window.height * camera.viewport.y;
          cv[UBOCamera.VIEW_PORT_OFFSET + 2] = sceneData.shadingScale * camera.window.width * camera.viewport.z;
          cv[UBOCamera.VIEW_PORT_OFFSET + 3] = sceneData.shadingScale * camera.window.height * camera.viewport.w;
        };
        PipelineUBO.getPCFRadius = function getPCFRadius(shadowInfo, mainLight) {
          var shadowMapSize = shadowInfo.size.x;
          switch (mainLight.shadowPcf) {
            case PCFType.HARD:
              return 0.0;
            case PCFType.SOFT:
              return 1.0 / (shadowMapSize * 0.5);
            case PCFType.SOFT_2X:
              return 2.0 / (shadowMapSize * 0.5);
            case PCFType.SOFT_4X:
              return 3.0 / (shadowMapSize * 0.5);
          }
          return 0.0;
        };
        PipelineUBO.updatePlanarNormalAndDistance = function updatePlanarNormalAndDistance(shadowInfo, shadowUBO) {
          Vec3.normalize(_tempVec3$3, shadowInfo.normal);
          shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 0] = _tempVec3$3.x;
          shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 1] = _tempVec3$3.y;
          shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 2] = _tempVec3$3.z;
          shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 3] = -shadowInfo.distance;
        };
        PipelineUBO.updateShadowUBOView = function updateShadowUBOView(pipeline, shadowBufferView, csmBufferView, camera) {
          var device = pipeline.device;
          var mainLight = camera.scene.mainLight;
          var sceneData = pipeline.pipelineSceneData;
          var shadowInfo = sceneData.shadows;
          var csmLayers = sceneData.csmLayers;
          var sv = shadowBufferView;
          var cv = csmBufferView;
          var csmSupported = sceneData.csmSupported;
          var packing = supportsR32FloatTexture(device) ? 0.0 : 1.0;
          if (mainLight && shadowInfo.enabled) {
            if (shadowInfo.type === ShadowType.ShadowMap) {
              if (mainLight.shadowEnabled) {
                if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !csmSupported) {
                  var matShadowView = csmLayers.specialLayer.matShadowView;
                  var matShadowProj = csmLayers.specialLayer.matShadowProj;
                  var matShadowViewProj = csmLayers.specialLayer.matShadowViewProj;
                  var near = 0.1;
                  var far = 0;
                  var levelCount = 0;
                  if (mainLight.shadowFixedArea) {
                    near = mainLight.shadowNear;
                    far = mainLight.shadowFar;
                    levelCount = 0;
                  } else {
                    far = csmLayers.specialLayer.shadowCameraFar;
                    levelCount = 1;
                  }
                  Mat4.toArray(sv, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                  sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10;
                  sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14;
                  sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11;
                  sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15;
                  sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00;
                  sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05;
                  sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00;
                  sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05;
                  Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET);
                  _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET);
                  _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, levelCount);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                } else {
                  var layerThreshold = this.getPCFRadius(shadowInfo, mainLight);
                  for (var i = 0; i < mainLight.csmLevel; i++) {
                    var layer = csmLayers.layers[i];
                    var _matShadowView2 = layer.matShadowView;
                    _vec4ShadowInfo.set(_matShadowView2.m00, _matShadowView2.m04, _matShadowView2.m08, layerThreshold);
                    Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_0_OFFSET + 4 * i);
                    _vec4ShadowInfo.set(_matShadowView2.m01, _matShadowView2.m05, _matShadowView2.m09, layer.splitCameraNear);
                    Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_1_OFFSET + 4 * i);
                    _vec4ShadowInfo.set(_matShadowView2.m02, _matShadowView2.m06, _matShadowView2.m10, layer.splitCameraFar);
                    Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_2_OFFSET + 4 * i);
                    var csmAtlas = layer.csmAtlas;
                    Vec4.toArray(cv, csmAtlas, UBOCSM.CSM_ATLAS_OFFSET + 4 * i);
                    var _matShadowViewProj2 = layer.matShadowViewProj;
                    Mat4.toArray(cv, _matShadowViewProj2, UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i);
                    var _matShadowProj2 = layer.matShadowProj;
                    cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = _matShadowProj2.m10;
                    cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = _matShadowProj2.m14;
                    cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = _matShadowProj2.m11;
                    cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = _matShadowProj2.m15;
                    cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = _matShadowProj2.m00;
                    cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = _matShadowProj2.m05;
                    cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / _matShadowProj2.m00;
                    cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / _matShadowProj2.m05;
                  }
                  _vec4ShadowInfo.set(mainLight.csmTransitionRange, 0, 0, 0);
                  Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_SPLITS_INFO_OFFSET);
                  _vec4ShadowInfo.set(0.1, mainLight.shadowDistance, 0, 1.0 - mainLight.shadowSaturation);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET);
                  _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, mainLight.csmLevel);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                }
                _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias);
                Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET);
              }
            } else {
              PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, sv);
              _vec4ShadowInfo.set(0, 0, 0, shadowInfo.planeBias);
              Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET);
            }
            Color$1.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
          }
        };
        PipelineUBO.updateShadowUBOLightView = function updateShadowUBOLightView(pipeline, shadowBufferView, light, level) {
          var device = pipeline.device;
          var sceneData = pipeline.pipelineSceneData;
          var shadowInfo = sceneData.shadows;
          var csmLayers = sceneData.csmLayers;
          var sv = shadowBufferView;
          var packing = supportsR32FloatTexture(device) ? 0.0 : 1.0;
          var cap = pipeline.device.capabilities;
          var csmSupported = sceneData.csmSupported;
          switch (light.type) {
            case LightType.DIRECTIONAL:
              {
                var mainLight = light;
                if (shadowInfo.enabled && mainLight && mainLight.shadowEnabled) {
                  if (shadowInfo.type === ShadowType.ShadowMap) {
                    var near = 0.1;
                    var far = 0;
                    var matShadowView;
                    var matShadowProj;
                    var matShadowViewProj;
                    var levelCount = 0;
                    if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !csmSupported) {
                      matShadowView = csmLayers.specialLayer.matShadowView;
                      matShadowProj = csmLayers.specialLayer.matShadowProj;
                      matShadowViewProj = csmLayers.specialLayer.matShadowViewProj;
                      if (mainLight.shadowFixedArea) {
                        near = mainLight.shadowNear;
                        far = mainLight.shadowFar;
                        levelCount = 0;
                      } else {
                        near = 0.1;
                        far = csmLayers.specialLayer.shadowCameraFar;
                        levelCount = 1;
                      }
                      _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, 0);
                      Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                    } else {
                      var layer = csmLayers.layers[level];
                      matShadowView = layer.matShadowView;
                      matShadowProj = layer.matShadowProj;
                      matShadowViewProj = layer.matShadowViewProj;
                      near = layer.splitCameraNear;
                      far = layer.splitCameraFar;
                      levelCount = mainLight.csmLevel;
                    }
                    Mat4.toArray(sv, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                    sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10;
                    sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14;
                    sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11;
                    sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15;
                    sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00;
                    sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05;
                    sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00;
                    sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05;
                    Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET);
                    _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation);
                    Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET);
                    _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, levelCount);
                    Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                    _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias);
                    Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET);
                  }
                }
                break;
              }
            case LightType.SPOT:
              {
                var spotLight = light;
                if (shadowInfo.enabled && spotLight && spotLight.shadowEnabled) {
                  Mat4.invert(_matShadowView$2, light.node.getWorldMatrix());
                  Mat4.toArray(sv, _matShadowView$2, UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                  Mat4.perspective(_matShadowProj$1, spotLight.angle, 1.0, 0.001, spotLight.range, true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0);
                  Mat4.multiply(_matShadowViewProj$2, _matShadowProj$1, _matShadowView$2);
                  Mat4.toArray(sv, _matShadowViewProj$2, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET);
                  _vec4ShadowInfo.set(0.01, light.range, 0.0, 0.0);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET);
                  _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, spotLight.shadowPcf, spotLight.shadowBias);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET);
                  _vec4ShadowInfo.set(LightType.SPOT, packing, spotLight.shadowNormalBias, 0.0);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                }
                break;
              }
          }
          Color$1.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
        };
        PipelineUBO.getCombineSignY = function getCombineSignY() {
          return PipelineUBO._combineSignY;
        };
        var _proto = PipelineUBO.prototype;
        _proto._initCombineSignY = function _initCombineSignY() {
          var device = this._device;
          PipelineUBO._combineSignY = device.capabilities.screenSpaceSignY * 0.5 + 0.5 << 1 | device.capabilities.clipSpaceSignY * 0.5 + 0.5;
        };
        _proto.activate = function activate(device, pipeline) {
          this._device = device;
          this._pipeline = pipeline;
          var ds = this._pipeline.descriptorSet;
          if (isEnableEffect()) {
            return;
          }
          this._initCombineSignY();
          var globalUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOGlobal.SIZE, UBOGlobal.SIZE));
          ds.bindBuffer(UBOGlobal.BINDING, globalUBO);
          var cameraUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOCamera.SIZE, UBOCamera.SIZE));
          ds.bindBuffer(UBOCamera.BINDING, cameraUBO);
          var shadowUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOShadow.SIZE, UBOShadow.SIZE));
          var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
          ds.bindBuffer(binding, shadowUBO);
          var csmUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOCSM.SIZE, UBOCSM.SIZE));
          var csmBinding = isEnableEffect() ? getDescBindingFromName('CCCSM') : UBOCSM.BINDING;
          ds.bindBuffer(csmBinding, csmUBO);
        };
        _proto.updateGlobalUBO = function updateGlobalUBO(window) {
          var globalDSManager = this._pipeline.globalDSManager;
          var ds = this._pipeline.descriptorSet;
          var cmdBuffer = this._pipeline.commandBuffers;
          ds.update();
          PipelineUBO.updateGlobalUBOView(window, this._globalUBO);
          cmdBuffer[0].updateBuffer(ds.getBuffer(UBOGlobal.BINDING), this._globalUBO);
          globalDSManager.bindBuffer(UBOGlobal.BINDING, ds.getBuffer(UBOGlobal.BINDING));
          globalDSManager.update();
        };
        _proto.updateCameraUBO = function updateCameraUBO(camera) {
          var globalDSManager = this._pipeline.globalDSManager;
          var ds = this._pipeline.descriptorSet;
          var cmdBuffer = this._pipeline.commandBuffers;
          PipelineUBO.updateCameraUBOView(this._pipeline, this._cameraUBO, camera);
          cmdBuffer[0].updateBuffer(ds.getBuffer(UBOCamera.BINDING), this._cameraUBO);
          globalDSManager.bindBuffer(UBOCamera.BINDING, ds.getBuffer(UBOCamera.BINDING));
          globalDSManager.update();
        };
        _proto.updateShadowUBO = function updateShadowUBO(camera) {
          var sceneData = this._pipeline.pipelineSceneData;
          var shadowInfo = sceneData.shadows;
          if (!shadowInfo.enabled) return;
          var ds = this._pipeline.descriptorSet;
          var cmdBuffer = this._pipeline.commandBuffers;
          var shadowFrameBufferMap = sceneData.shadowFrameBufferMap;
          var mainLight = camera.scene.mainLight;
          if (mainLight && shadowFrameBufferMap.has(mainLight)) {
            ds.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight).colorTextures[0]);
          }
          PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, this._csmUBO, camera);
          ds.update();
          var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
          cmdBuffer[0].updateBuffer(ds.getBuffer(binding), this._shadowUBO);
          var csmBinding = isEnableEffect() ? getDescBindingFromName('CCCSM') : UBOCSM.BINDING;
          cmdBuffer[0].updateBuffer(ds.getBuffer(csmBinding), this._csmUBO);
        };
        _proto.updateShadowUBOLight = function updateShadowUBOLight(globalDS, light, level) {
          if (level === void 0) {
            level = 0;
          }
          PipelineUBO.updateShadowUBOLightView(this._pipeline, this._shadowUBO, light, level);
          globalDS.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          globalDS.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          globalDS.update();
          var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
          this._pipeline.commandBuffers[0].updateBuffer(globalDS.getBuffer(binding), this._shadowUBO);
        };
        _proto.updateShadowUBORange = function updateShadowUBORange(offset, data) {
          if (data instanceof Mat4) {
            Mat4.toArray(this._shadowUBO, data, offset);
          } else if (data instanceof Color$1) {
            Color$1.toArray(this._shadowUBO, data, offset);
          }
        };
        _proto.destroy = function destroy() {};
        return PipelineUBO;
      }();
      PipelineUBO._combineSignY = 0;

      var _dec$3l, _class$3g, _class2$2Y, _initializer$2J, _initializer2$2c, _initializer3$1C;
      var RenderStage = exports('dd', (_dec$3l = ccclass$M('RenderStage'), _dec$3l(_class$3g = (_class2$2Y = function () {
        function RenderStage() {
          this._name = _initializer$2J && _initializer$2J();
          this._priority = _initializer2$2c && _initializer2$2c();
          this._enabled = true;
          this._tag = _initializer3$1C && _initializer3$1C();
          this._pipeline = void 0;
          this._flow = void 0;
        }
        var _proto = RenderStage.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name;
          this._priority = info.priority;
          if (info.tag) {
            this._tag = info.tag;
          }
          return true;
        };
        _proto.activate = function activate(pipeline, flow) {
          this._pipeline = pipeline;
          this._flow = flow;
        };
        _createClass(RenderStage, [{
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          }
        }, {
          key: "tag",
          get: function get() {
            return this._tag;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }]);
        return RenderStage;
      }(), (_initializer$2J = applyDecoratedInitializer(_class2$2Y.prototype, "_name", [serializable$p], function () {
        return '';
      }), _initializer2$2c = applyDecoratedInitializer(_class2$2Y.prototype, "_priority", [serializable$p], function () {
        return 0;
      }), _initializer3$1C = applyDecoratedInitializer(_class2$2Y.prototype, "_tag", [serializable$p], function () {
        return 0;
      })), _class2$2Y)) || _class$3g));
      legacyCC.RenderStage = RenderStage;

      var _dec$3k, _dec2$2t, _class$3f, _class2$2X, _initializer$2I, _initializer2$2b, _initializer3$1B, _initializer4$1m;
      var RenderFlow = exports('dc', (_dec$3k = ccclass$M('RenderFlow'), _dec2$2t = type$d([RenderStage]), _dec$3k(_class$3f = (_class2$2X = function () {
        function RenderFlow() {
          this._name = _initializer$2I && _initializer$2I();
          this._priority = _initializer2$2b && _initializer2$2b();
          this._tag = _initializer3$1B && _initializer3$1B();
          this._stages = _initializer4$1m && _initializer4$1m();
          this._pipeline = void 0;
        }
        var _proto = RenderFlow.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name;
          this._priority = info.priority;
          this._stages = info.stages;
          if (info.tag) {
            this._tag = info.tag;
          }
          return true;
        };
        _proto.activate = function activate(pipeline) {
          this._pipeline = pipeline;
          this._stages.sort(function (a, b) {
            return a.priority - b.priority;
          });
          for (var i = 0, len = this._stages.length; i < len; i++) {
            this._stages[i].activate(pipeline, this);
          }
        };
        _proto.render = function render(camera) {
          for (var i = 0, len = this._stages.length; i < len; i++) {
            if (this._stages[i].enabled) this._stages[i].render(camera);
          }
        };
        _proto.destroy = function destroy() {
          for (var i = 0, len = this._stages.length; i < len; i++) {
            this._stages[i].destroy();
          }
          this._stages.length = 0;
        };
        _createClass(RenderFlow, [{
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          }
        }, {
          key: "tag",
          get: function get() {
            return this._tag;
          }
        }, {
          key: "stages",
          get: function get() {
            return this._stages;
          }
        }, {
          key: "pipeline",
          get: function get() {
            return this._pipeline;
          }
        }]);
        return RenderFlow;
      }(), (_initializer$2I = applyDecoratedInitializer(_class2$2X.prototype, "_name", [serializable$p], function () {
        return '';
      }), _initializer2$2b = applyDecoratedInitializer(_class2$2X.prototype, "_priority", [serializable$p], function () {
        return 0;
      }), _initializer3$1B = applyDecoratedInitializer(_class2$2X.prototype, "_tag", [serializable$p], function () {
        return 0;
      }), _initializer4$1m = applyDecoratedInitializer(_class2$2X.prototype, "_stages", [_dec2$2t, serializable$p], function () {
        return [];
      })), _class2$2X)) || _class$3f));
      legacyCC.RenderFlow = RenderFlow;

      var PipelineEventType; exports('dv', PipelineEventType);
      (function (PipelineEventType) {
        PipelineEventType["RENDER_FRAME_BEGIN"] = "render-frame-begin";
        PipelineEventType["RENDER_FRAME_END"] = "render-frame-end";
        PipelineEventType["RENDER_CAMERA_BEGIN"] = "render-camera-begin";
        PipelineEventType["RENDER_CAMERA_END"] = "render-camera-end";
        PipelineEventType["ATTACHMENT_SCALE_CAHNGED"] = "attachment-scale-changed";
      })(PipelineEventType || (exports('dv', PipelineEventType = {})));
      var PipelineEventProcessor = exports('du', function (_EventTarget) {
        _inheritsLoose(PipelineEventProcessor, _EventTarget);
        function PipelineEventProcessor() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EventTarget.call.apply(_EventTarget, [this].concat(args)) || this;
          _this.eventTargetOn = _EventTarget.prototype.on;
          _this.eventTargetOnce = _EventTarget.prototype.once;
          return _this;
        }
        var _proto = PipelineEventProcessor.prototype;
        _proto.on = function on(type, callback, target, once) {
          return this.eventTargetOn(type, callback, target, once);
        };
        _proto.once = function once(type, callback, target) {
          return this.eventTargetOnce(type, callback, target);
        };
        return PipelineEventProcessor;
      }(EventTarget));

      var _dec$3j, _dec2$2s, _class4$v, _class5$v, _initializer$2H, _initializer2$2a;
      var MAX_BLOOM_FILTER_PASS_NUM = 6;
      var tmpRect = new Rect();
      var tmpViewport = new Viewport();
      var BloomRenderData = function BloomRenderData() {
        this.renderPass = null;
        this.sampler = null;
        this.prefiterTex = null;
        this.downsampleTexs = [];
        this.upsampleTexs = [];
        this.combineTex = null;
        this.prefilterFramebuffer = null;
        this.downsampleFramebuffers = [];
        this.upsampleFramebuffers = [];
        this.combineFramebuffer = null;
      };
      var PipelineRenderData = function PipelineRenderData() {
        this.outputFrameBuffer = null;
        this.outputRenderTargets = [];
        this.outputDepth = null;
        this.sampler = null;
        this.bloom = null;
      };
      var PipelineInputAssemblerData = function PipelineInputAssemblerData() {
        this.quadIB = null;
        this.quadVB = null;
        this.quadIA = null;
      };
      function hashFrameBuffer(fbo) {
        var hash = 666;
        for (var _iterator = _createForOfIteratorHelperLoose(fbo.colorTextures), _step; !(_step = _iterator()).done;) {
          var color = _step.value;
          var _info = color === null || color === void 0 ? void 0 : color.info;
          var _hashStr = _info.type + "_" + _info.usage + "_" + _info.format + "_" + _info.width + "_" + _info.height + "_" + _info.flags + "_\n            " + _info.layerCount + "_" + _info.levelCount + "_" + _info.samples + "_" + _info.depth + "_" + _info.externalRes;
          hash = murmurhash2_32_gc(_hashStr, hash);
        }
        if (fbo.depthStencilTexture) {
          var info = fbo.depthStencilTexture.info;
          var hashStr = info.type + "_" + info.usage + "_" + info.format + "_" + info.width + "_" + info.height + "_" + info.flags + "_\n            " + info.layerCount + "_" + info.levelCount + "_" + info.samples + "_" + info.depth + "_" + info.externalRes;
          hash = murmurhash2_32_gc(hashStr, hash);
        }
        return hash;
      }
      var RenderPipeline = exports('db', (_dec$3j = ccclass$M('cc.RenderPipeline'), _dec2$2s = type$d([RenderFlow]), _dec$3j(_class4$v = (_class5$v = function (_Asset) {
        _inheritsLoose(RenderPipeline, _Asset);
        function RenderPipeline() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this._tag = _initializer$2H && _initializer$2H();
          _this._flows = _initializer2$2a && _initializer2$2a();
          _this._quadIB = null;
          _this._quadVBOnscreen = null;
          _this._quadVBOffscreen = null;
          _this._quadIAOnscreen = null;
          _this._quadIAOffscreen = null;
          _this._eventProcessor = new PipelineEventProcessor();
          _this._device = void 0;
          _this._globalDSManager = void 0;
          _this._descriptorSet = void 0;
          _this._commandBuffers = [];
          _this._pipelineUBO = new PipelineUBO();
          _this._macros = {};
          _this._constantMacros = '';
          _this._profiler = null;
          _this._geometryRenderer = null;
          _this._pipelineRenderData = null;
          _this._renderPasses = new Map();
          _this._width = 0;
          _this._height = 0;
          _this._lastUsedRenderArea = new Rect();
          _this._clusterEnabled = false;
          _this._bloomEnabled = false;
          return _this;
        }
        var _proto = RenderPipeline.prototype;
        _proto.getPipelineRenderData = function getPipelineRenderData() {
          return this._pipelineRenderData;
        };
        _proto.initialize = function initialize(info) {
          this._flows = info.flows;
          if (info.tag) {
            this._tag = info.tag;
          }
          return true;
        };
        _proto.createRenderPass = function createRenderPass(clearFlags, colorFmt, depthFmt) {
          var device = this._device;
          var colorAttachment = new ColorAttachment();
          var depthStencilAttachment = new DepthStencilAttachment();
          colorAttachment.format = colorFmt;
          depthStencilAttachment.format = depthFmt;
          depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
          depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;
          if (!(clearFlags & ClearFlagBit.COLOR)) {
            if (clearFlags & SKYBOX_FLAG) {
              colorAttachment.loadOp = LoadOp.CLEAR;
            } else {
              colorAttachment.loadOp = LoadOp.LOAD;
              colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.COLOR_ATTACHMENT_WRITE, AccessFlagBit.COLOR_ATTACHMENT_WRITE));
            }
          }
          if ((clearFlags & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL) {
            if (!(clearFlags & ClearFlagBit.DEPTH)) depthStencilAttachment.depthLoadOp = LoadOp.LOAD;
            if (!(clearFlags & ClearFlagBit.STENCIL)) depthStencilAttachment.stencilLoadOp = LoadOp.LOAD;
          }
          depthStencilAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE, AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE));
          var renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment);
          return device.createRenderPass(renderPassInfo);
        };
        _proto.getRenderPass = function getRenderPass(clearFlags, fbo) {
          var fbHash = hashFrameBuffer(fbo);
          var hash = murmurhash2_32_gc(fbHash + "_" + clearFlags, 666);
          var renderPass = this._renderPasses.get(hash);
          if (renderPass) {
            return renderPass;
          }
          renderPass = this.createRenderPass(clearFlags, fbo.colorTextures[0].format, fbo.depthStencilTexture.format);
          this._renderPasses.set(hash, renderPass);
          return renderPass;
        };
        _proto.newFramebufferByRatio = function newFramebufferByRatio(dyingFramebuffer) {
          var sceneData = this.pipelineSceneData;
          var width = this._width * sceneData.shadingScale;
          var height = this._height * sceneData.shadingScale;
          var colorTexArr = dyingFramebuffer.colorTextures;
          for (var i = 0; i < colorTexArr.length; i++) {
            colorTexArr[i].resize(width, height);
          }
          if (dyingFramebuffer.depthStencilTexture) {
            dyingFramebuffer.depthStencilTexture.resize(width, height);
          }
          var newFramebuffer = this._device.createFramebuffer(new FramebufferInfo(dyingFramebuffer.renderPass, colorTexArr, dyingFramebuffer.depthStencilTexture));
          dyingFramebuffer.destroy();
          return newFramebuffer;
        };
        _proto.generateRenderArea = function generateRenderArea(camera, out) {
          var vp = camera.viewport;
          var w = camera.window.width;
          var h = camera.window.height;
          out.x = vp.x * w;
          out.y = vp.y * h;
          out.width = vp.width * w;
          out.height = vp.height * h;
        };
        _proto.generateViewport = function generateViewport(camera, out) {
          this.generateRenderArea(camera, tmpRect);
          if (!out) out = tmpViewport;
          var shadingScale = this.pipelineSceneData.shadingScale;
          out.left = tmpRect.x * shadingScale;
          out.top = tmpRect.y * shadingScale;
          out.width = tmpRect.width * shadingScale;
          out.height = tmpRect.height * shadingScale;
          return out;
        };
        _proto.generateScissor = function generateScissor(camera, out) {
          if (!out) out = tmpRect;
          this.generateRenderArea(camera, out);
          var shadingScale = this.pipelineSceneData.shadingScale;
          out.x *= shadingScale;
          out.y *= shadingScale;
          out.width *= shadingScale;
          out.height *= shadingScale;
          return out;
        };
        _proto.getMacroString = function getMacroString(name) {
          var str = this._macros[name];
          if (str === undefined) {
            return '';
          }
          return str;
        };
        _proto.getMacroInt = function getMacroInt(name) {
          var value = this._macros[name];
          if (value === undefined) {
            return 0;
          }
          return value;
        };
        _proto.getMacroBool = function getMacroBool(name) {
          var value = this._macros[name];
          if (value === undefined) {
            return false;
          }
          return value;
        };
        _proto.setMacroString = function setMacroString(name, value) {
          this._macros[name] = value;
        };
        _proto.setMacroInt = function setMacroInt(name, value) {
          this._macros[name] = value;
        };
        _proto.setMacroBool = function setMacroBool(name, value) {
          this._macros[name] = value;
        };
        _proto.activate = function activate(swapchain) {
          this._device = deviceManager.gfxDevice;
          this._generateConstantMacros();
          this._globalDSManager = new GlobalDSManager(this._device);
          this._descriptorSet = this._globalDSManager.globalDescriptorSet;
          this._pipelineUBO.activate(this._device, this);
          this._macros.CC_USE_HDR = this._pipelineSceneData.isHDR;
          this._macros.CC_USE_DEBUG_VIEW = 0;
          this._generateConstantMacros();
          this._pipelineSceneData.activate(this._device);
          for (var i = 0; i < this._flows.length; i++) {
            this._flows[i].activate(this);
          }
          return true;
        };
        _proto._ensureEnoughSize = function _ensureEnoughSize(cameras) {};
        _proto.render = function render(cameras) {
          if (cameras.length === 0) {
            return;
          }
          this.updateGeometryRenderer(cameras);
          this._commandBuffers[0].begin();
          this.emit(PipelineEventType.RENDER_FRAME_BEGIN, cameras);
          this._ensureEnoughSize(cameras);
          decideProfilerCamera(cameras);
          for (var i = 0; i < cameras.length; i++) {
            var camera = cameras[i];
            if (camera.scene) {
              this.emit(PipelineEventType.RENDER_CAMERA_BEGIN, camera);
              validPunctualLightsCulling$1(this, camera);
              sceneCulling(this, camera);
              this._pipelineUBO.updateGlobalUBO(camera.window);
              this._pipelineUBO.updateCameraUBO(camera);
              for (var j = 0; j < this._flows.length; j++) {
                this._flows[j].render(camera);
              }
              this.emit(PipelineEventType.RENDER_CAMERA_END, camera);
            }
          }
          this.emit(PipelineEventType.RENDER_FRAME_END, cameras);
          this._commandBuffers[0].end();
          this._device.queue.submit(this._commandBuffers);
        };
        _proto._destroyQuadInputAssembler = function _destroyQuadInputAssembler() {
          if (this._quadIB) {
            this._quadIB.destroy();
            this._quadIB = null;
          }
          if (this._quadVBOnscreen) {
            this._quadVBOnscreen.destroy();
            this._quadVBOnscreen = null;
          }
          if (this._quadVBOffscreen) {
            this._quadVBOffscreen.destroy();
            this._quadVBOffscreen = null;
          }
          if (this._quadIAOnscreen) {
            this._quadIAOnscreen.destroy();
            this._quadIAOnscreen = null;
          }
          if (this._quadIAOffscreen) {
            this._quadIAOffscreen.destroy();
            this._quadIAOffscreen = null;
          }
        };
        _proto._destroyBloomData = function _destroyBloomData() {
          var _bloom$renderPass;
          var bloom = this._pipelineRenderData.bloom;
          if (bloom === null) return;
          if (bloom.prefiterTex) bloom.prefiterTex.destroy();
          if (bloom.prefilterFramebuffer) bloom.prefilterFramebuffer.destroy();
          for (var i = 0; i < bloom.downsampleTexs.length; ++i) {
            bloom.downsampleTexs[i].destroy();
            bloom.downsampleFramebuffers[i].destroy();
          }
          bloom.downsampleTexs.length = 0;
          bloom.downsampleFramebuffers.length = 0;
          for (var _i = 0; _i < bloom.upsampleTexs.length; ++_i) {
            bloom.upsampleTexs[_i].destroy();
            bloom.upsampleFramebuffers[_i].destroy();
          }
          bloom.upsampleTexs.length = 0;
          bloom.upsampleFramebuffers.length = 0;
          if (bloom.combineTex) bloom.combineTex.destroy();
          if (bloom.combineFramebuffer) bloom.combineFramebuffer.destroy();
          (_bloom$renderPass = bloom.renderPass) === null || _bloom$renderPass === void 0 ? void 0 : _bloom$renderPass.destroy();
          this._pipelineRenderData.bloom = null;
        };
        _proto._genQuadVertexData = function _genQuadVertexData(surfaceTransform, renderArea) {
          var vbData = new Float32Array(4 * 4);
          var minX = renderArea.x / this._width;
          var maxX = (renderArea.x + renderArea.width) / this._width;
          var minY = renderArea.y / this._height;
          var maxY = (renderArea.y + renderArea.height) / this._height;
          if (this.device.capabilities.screenSpaceSignY > 0) {
            var temp = maxY;
            maxY = minY;
            minY = temp;
          }
          var n = 0;
          switch (surfaceTransform) {
            case SurfaceTransform.IDENTITY:
              n = 0;
              vbData[n++] = -1.0;
              vbData[n++] = -1.0;
              vbData[n++] = minX;
              vbData[n++] = maxY;
              vbData[n++] = 1.0;
              vbData[n++] = -1.0;
              vbData[n++] = maxX;
              vbData[n++] = maxY;
              vbData[n++] = -1.0;
              vbData[n++] = 1.0;
              vbData[n++] = minX;
              vbData[n++] = minY;
              vbData[n++] = 1.0;
              vbData[n++] = 1.0;
              vbData[n++] = maxX;
              vbData[n++] = minY;
              break;
            case SurfaceTransform.ROTATE_90:
              n = 0;
              vbData[n++] = -1.0;
              vbData[n++] = -1.0;
              vbData[n++] = maxX;
              vbData[n++] = maxY;
              vbData[n++] = 1.0;
              vbData[n++] = -1.0;
              vbData[n++] = maxX;
              vbData[n++] = minY;
              vbData[n++] = -1.0;
              vbData[n++] = 1.0;
              vbData[n++] = minX;
              vbData[n++] = maxY;
              vbData[n++] = 1.0;
              vbData[n++] = 1.0;
              vbData[n++] = minX;
              vbData[n++] = minY;
              break;
            case SurfaceTransform.ROTATE_180:
              n = 0;
              vbData[n++] = -1.0;
              vbData[n++] = -1.0;
              vbData[n++] = minX;
              vbData[n++] = minY;
              vbData[n++] = 1.0;
              vbData[n++] = -1.0;
              vbData[n++] = maxX;
              vbData[n++] = minY;
              vbData[n++] = -1.0;
              vbData[n++] = 1.0;
              vbData[n++] = minX;
              vbData[n++] = maxY;
              vbData[n++] = 1.0;
              vbData[n++] = 1.0;
              vbData[n++] = maxX;
              vbData[n++] = maxY;
              break;
            case SurfaceTransform.ROTATE_270:
              n = 0;
              vbData[n++] = -1.0;
              vbData[n++] = -1.0;
              vbData[n++] = minX;
              vbData[n++] = minY;
              vbData[n++] = 1.0;
              vbData[n++] = -1.0;
              vbData[n++] = minX;
              vbData[n++] = maxY;
              vbData[n++] = -1.0;
              vbData[n++] = 1.0;
              vbData[n++] = maxX;
              vbData[n++] = minY;
              vbData[n++] = 1.0;
              vbData[n++] = 1.0;
              vbData[n++] = maxX;
              vbData[n++] = maxY;
              break;
          }
          return vbData;
        };
        _proto._createQuadInputAssembler = function _createQuadInputAssembler() {
          var inputAssemblerData = new PipelineInputAssemblerData();
          var vbStride = Float32Array.BYTES_PER_ELEMENT * 4;
          var vbSize = vbStride * 4;
          var quadVB = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE | MemoryUsageBit.HOST, vbSize, vbStride));
          if (!quadVB) {
            return inputAssemblerData;
          }
          var ibStride = Uint8Array.BYTES_PER_ELEMENT;
          var ibSize = ibStride * 6;
          var quadIB = this._device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibSize, ibStride));
          if (!quadIB) {
            return inputAssemblerData;
          }
          var indices = new Uint8Array(6);
          indices[0] = 0;
          indices[1] = 1;
          indices[2] = 2;
          indices[3] = 1;
          indices[4] = 3;
          indices[5] = 2;
          quadIB.update(indices);
          var attributes = new Array(2);
          attributes[0] = new Attribute('a_position', Format.RG32F);
          attributes[1] = new Attribute('a_texCoord', Format.RG32F);
          var quadIA = this._device.createInputAssembler(new InputAssemblerInfo(attributes, [quadVB], quadIB));
          inputAssemblerData.quadIB = quadIB;
          inputAssemblerData.quadVB = quadVB;
          inputAssemblerData.quadIA = quadIA;
          return inputAssemblerData;
        };
        _proto.updateQuadVertexData = function updateQuadVertexData(renderArea, window) {
          var cachedArea = this._lastUsedRenderArea;
          if (cachedArea.x === renderArea.x && cachedArea.y === renderArea.y && cachedArea.width === renderArea.width && cachedArea.height === renderArea.height) {
            return;
          }
          var offData = this._genQuadVertexData(SurfaceTransform.IDENTITY, renderArea);
          this._quadVBOffscreen.update(offData);
          var onData = this._genQuadVertexData(window.swapchain && window.swapchain.surfaceTransform || SurfaceTransform.IDENTITY, renderArea);
          this._quadVBOnscreen.update(onData);
          cachedArea.copy(renderArea);
        };
        _proto.destroy = function destroy() {
          var _this$_globalDSManage, _this$_pipelineSceneD;
          for (var i = 0; i < this._flows.length; i++) {
            this._flows[i].destroy();
          }
          this._flows.length = 0;
          if (this._descriptorSet) {
            this._descriptorSet.destroy();
          }
          (_this$_globalDSManage = this._globalDSManager) === null || _this$_globalDSManage === void 0 ? void 0 : _this$_globalDSManage.destroy();
          for (var _i2 = 0; _i2 < this._commandBuffers.length; _i2++) {
            this._commandBuffers[_i2].destroy();
          }
          this._commandBuffers.length = 0;
          this._pipelineUBO.destroy();
          (_this$_pipelineSceneD = this._pipelineSceneData) === null || _this$_pipelineSceneD === void 0 ? void 0 : _this$_pipelineSceneD.destroy();
          return _Asset.prototype.destroy.call(this);
        };
        _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {};
        _proto._generateConstantMacros = function _generateConstantMacros() {
          var str = '';
          str += "#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE " + (this.device.getFormatFeatures(Format.RGBA32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) ? 1 : 0) + "\n";
          str += "#define CC_ENABLE_CLUSTERED_LIGHT_CULLING " + (this._clusterEnabled ? 1 : 0) + "\n";
          str += "#define CC_DEVICE_MAX_VERTEX_UNIFORM_VECTORS " + this.device.capabilities.maxVertexUniformVectors + "\n";
          str += "#define CC_DEVICE_MAX_FRAGMENT_UNIFORM_VECTORS " + this.device.capabilities.maxFragmentUniformVectors + "\n";
          str += "#define CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT " + (this.device.hasFeature(Feature.INPUT_ATTACHMENT_BENEFIT) ? 1 : 0) + "\n";
          str += "#define CC_PLATFORM_ANDROID_AND_WEBGL " + (systemInfo.os === OS.ANDROID && systemInfo.isBrowser ? 1 : 0) + "\n";
          str += "#define CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES " + (macro.ENABLE_WEBGL_HIGHP_STRUCT_VALUES ? 1 : 0) + "\n";
          var jointUniformCapacity = UBOSkinning.JOINT_UNIFORM_CAPACITY;
          str += "#define CC_JOINT_UNIFORM_CAPACITY " + jointUniformCapacity + "\n";
          this._constantMacros = str;
        };
        _proto.updateGeometryRenderer = function updateGeometryRenderer(cameras) {
          if (this._geometryRenderer) {
            return;
          }
          for (var i = 0; i < cameras.length; i++) {
            var camera = cameras[i];
            if (camera && camera.window && camera.window.swapchain) {
              camera.initGeometryRenderer();
              this._geometryRenderer = camera.geometryRenderer;
              return;
            }
          }
        };
        _proto.generateBloomRenderData = function generateBloomRenderData() {
          if (this._pipelineRenderData.bloom != null) return;
          var bloom = this._pipelineRenderData.bloom = new BloomRenderData();
          var device = this.device;
          var colorAttachment = new ColorAttachment();
          colorAttachment.format = Format.RGBA8;
          colorAttachment.loadOp = LoadOp.CLEAR;
          colorAttachment.storeOp = StoreOp.STORE;
          colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.NONE, AccessFlagBit.COLOR_ATTACHMENT_WRITE));
          bloom.renderPass = device.createRenderPass(new RenderPassInfo([colorAttachment]));
          var curWidth = this._width;
          var curHeight = this._height;
          bloom.prefiterTex = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA8, curWidth >> 1, curHeight >> 1));
          bloom.prefilterFramebuffer = device.createFramebuffer(new FramebufferInfo(bloom.renderPass, [bloom.prefiterTex]));
          curWidth >>= 1;
          curHeight >>= 1;
          for (var i = 0; i < MAX_BLOOM_FILTER_PASS_NUM; ++i) {
            bloom.downsampleTexs.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA8, curWidth >> 1, curHeight >> 1)));
            bloom.downsampleFramebuffers[i] = device.createFramebuffer(new FramebufferInfo(bloom.renderPass, [bloom.downsampleTexs[i]]));
            bloom.upsampleTexs.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA8, curWidth, curHeight)));
            bloom.upsampleFramebuffers[i] = device.createFramebuffer(new FramebufferInfo(bloom.renderPass, [bloom.upsampleTexs[i]]));
            curWidth >>= 1;
            curHeight >>= 1;
          }
          bloom.combineTex = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA8, this._width, this._height));
          bloom.combineFramebuffer = device.createFramebuffer(new FramebufferInfo(bloom.renderPass, [bloom.combineTex]));
          bloom.sampler = this.globalDSManager.linearSampler;
        };
        _proto.on = function on(type, callback, target, once) {
          return this._eventProcessor.on(type, callback, target, once);
        };
        _proto.once = function once(type, callback, target) {
          return this._eventProcessor.once(type, callback, target);
        };
        _proto.off = function off(type, callback, target) {
          this._eventProcessor.off(type, callback, target);
        };
        _proto.emit = function emit(type, arg0, arg1, arg2, arg3, arg4) {
          this._eventProcessor.emit(type, arg0, arg1, arg2, arg3, arg4);
        };
        _proto.targetOff = function targetOff(typeOrTarget) {
          this._eventProcessor.targetOff(typeOrTarget);
        };
        _proto.removeAll = function removeAll(typeOrTarget) {
          this._eventProcessor.removeAll(typeOrTarget);
        };
        _proto.hasEventListener = function hasEventListener(type, callback, target) {
          return this._eventProcessor.hasEventListener(type, callback, target);
        };
        _createClass(RenderPipeline, [{
          key: "tag",
          get: function get() {
            return this._tag;
          }
        }, {
          key: "flows",
          get: function get() {
            return this._flows;
          }
        }, {
          key: "quadIAOnscreen",
          get: function get() {
            return this._quadIAOnscreen;
          }
        }, {
          key: "quadIAOffscreen",
          get: function get() {
            return this._quadIAOffscreen;
          }
        }, {
          key: "constantMacros",
          get: function get() {
            return this._constantMacros;
          }
        }, {
          key: "macros",
          get: function get() {
            return this._macros;
          }
        }, {
          key: "device",
          get: function get() {
            return this._device;
          }
        }, {
          key: "globalDSManager",
          get: function get() {
            return this._globalDSManager;
          }
        }, {
          key: "descriptorSetLayout",
          get: function get() {
            return this._globalDSManager.descriptorSetLayout;
          }
        }, {
          key: "descriptorSet",
          get: function get() {
            return this._descriptorSet;
          }
        }, {
          key: "commandBuffers",
          get: function get() {
            return this._commandBuffers;
          }
        }, {
          key: "pipelineUBO",
          get: function get() {
            return this._pipelineUBO;
          }
        }, {
          key: "pipelineSceneData",
          get: function get() {
            return this._pipelineSceneData;
          }
        }, {
          key: "profiler",
          get: function get() {
            return this._profiler;
          },
          set: function set(value) {
            this._profiler = value;
          }
        }, {
          key: "geometryRenderer",
          get: function get() {
            return this._geometryRenderer;
          }
        }, {
          key: "clusterEnabled",
          get: function get() {
            return this._clusterEnabled;
          },
          set: function set(value) {
            this._clusterEnabled = value;
          }
        }, {
          key: "bloomEnabled",
          get: function get() {
            return this._bloomEnabled;
          },
          set: function set(value) {
            this._bloomEnabled = value;
          }
        }, {
          key: "shadingScale",
          get: function get() {
            return this._pipelineSceneData.shadingScale;
          },
          set: function set(val) {
            if (this._pipelineSceneData.shadingScale !== val) {
              this._pipelineSceneData.shadingScale = val;
              this.emit(PipelineEventType.ATTACHMENT_SCALE_CAHNGED, val);
            }
          }
        }]);
        return RenderPipeline;
      }(Asset), (_initializer$2H = applyDecoratedInitializer(_class5$v.prototype, "_tag", [serializable$p], function () {
        return 0;
      }), _initializer2$2a = applyDecoratedInitializer(_class5$v.prototype, "_flows", [_dec2$2s, serializable$p], function () {
        return [];
      })), _class5$v)) || _class4$v));
      legacyCC.RenderPipeline = RenderPipeline;

      var CommonStagePriority;
      (function (CommonStagePriority) {
        CommonStagePriority[CommonStagePriority["BLOOM"] = 18] = "BLOOM";
        CommonStagePriority[CommonStagePriority["POST_PROCESS"] = 19] = "POST_PROCESS";
        CommonStagePriority[CommonStagePriority["UI"] = 20] = "UI";
      })(CommonStagePriority || (CommonStagePriority = {}));
      var ForwardStagePriority;
      (function (ForwardStagePriority) {
        ForwardStagePriority[ForwardStagePriority["AR"] = 5] = "AR";
        ForwardStagePriority[ForwardStagePriority["FORWARD"] = 10] = "FORWARD";
      })(ForwardStagePriority || (ForwardStagePriority = {}));
      var ForwardFlowPriority;
      (function (ForwardFlowPriority) {
        ForwardFlowPriority[ForwardFlowPriority["SHADOW"] = 0] = "SHADOW";
        ForwardFlowPriority[ForwardFlowPriority["FORWARD"] = 1] = "FORWARD";
        ForwardFlowPriority[ForwardFlowPriority["UI"] = 10] = "UI";
      })(ForwardFlowPriority || (ForwardFlowPriority = {}));
      var DeferredStagePriority;
      (function (DeferredStagePriority) {
        DeferredStagePriority[DeferredStagePriority["GBUFFER"] = 10] = "GBUFFER";
        DeferredStagePriority[DeferredStagePriority["LIGHTING"] = 15] = "LIGHTING";
        DeferredStagePriority[DeferredStagePriority["TRANSPARENT"] = 18] = "TRANSPARENT";
      })(DeferredStagePriority || (DeferredStagePriority = {}));
      var DeferredFlowPriority;
      (function (DeferredFlowPriority) {
        DeferredFlowPriority[DeferredFlowPriority["SHADOW"] = 0] = "SHADOW";
        DeferredFlowPriority[DeferredFlowPriority["MAIN"] = 1] = "MAIN";
        DeferredFlowPriority[DeferredFlowPriority["UI"] = 10] = "UI";
      })(DeferredFlowPriority || (DeferredFlowPriority = {}));

      var _dec$3i, _dec2$2r, _dec3$1J, _dec4$1c, _class$3e, _class2$2W, _initializer$2G, _initializer2$29, _initializer3$1A, _initializer4$1l, _initializer5$13, _initializer6$T, _dec5$13, _dec6$P, _class4$u, _class5$u, _initializer7$H, _initializer8$D, _dec7$E, _dec8$s, _class7$8, _class8$9, _initializer9$y, _initializer10$v, _dec9$n, _dec10$f, _dec11$a, _class10$4, _class11$5, _initializer11$t, _initializer12$q, _initializer13$n, _initializer14$j, _initializer15$f, _dec12$9, _dec13$7, _dec14$6, _dec15$5, _dec16$4, _dec17$4, _class13$4, _class14$3, _initializer16$f, _initializer17$c, _initializer18$c, _initializer19$b, _initializer20$9, _initializer21$9, _dec18$4, _dec19$4, _dec20$4, _dec21$4, _dec22$4, _dec23$4, _dec24$4, _dec25$4, _class16, _class17$1, _initializer22$8, _initializer23$6, _initializer24$6, _initializer25$5, _initializer26$5, _initializer27$4, _initializer28$4, _initializer29$4, _dec26$4, _dec27$4, _dec28$4, _class19, _class20$2, _initializer30$4, _initializer31$4, _initializer32$3, _dec29$4, _dec30$3, _dec31$3, _class22, _class23$1, _initializer33$3, _initializer34$3, _initializer35$3;
      ccenum(TextureType);
      ccenum(TextureUsageBit);
      ccenum(StoreOp);
      ccenum(LoadOp);
      ccenum(AccessFlagBit);
      ccenum(Format);
      var RenderFlowTag;
      (function (RenderFlowTag) {
        RenderFlowTag[RenderFlowTag["SCENE"] = 0] = "SCENE";
        RenderFlowTag[RenderFlowTag["POSTPROCESS"] = 1] = "POSTPROCESS";
        RenderFlowTag[RenderFlowTag["UI"] = 2] = "UI";
      })(RenderFlowTag || (RenderFlowTag = {}));
      ccenum(RenderFlowTag);
      (_dec$3i = ccclass$M('RenderTextureDesc'), _dec2$2r = type$d(TextureType), _dec3$1J = type$d(TextureUsageBit), _dec4$1c = type$d(Format), _dec$3i(_class$3e = (_class2$2W = function RenderTextureDesc() {
        this.name = _initializer$2G && _initializer$2G();
        this.type = _initializer2$29 && _initializer2$29();
        this.usage = _initializer3$1A && _initializer3$1A();
        this.format = _initializer4$1l && _initializer4$1l();
        this.width = _initializer5$13 && _initializer5$13();
        this.height = _initializer6$T && _initializer6$T();
      }, (_initializer$2G = applyDecoratedInitializer(_class2$2W.prototype, "name", [serializable$p], function () {
        return '';
      }), _initializer2$29 = applyDecoratedInitializer(_class2$2W.prototype, "type", [_dec2$2r], function () {
        return TextureType.TEX2D;
      }), _initializer3$1A = applyDecoratedInitializer(_class2$2W.prototype, "usage", [_dec3$1J], function () {
        return TextureUsageBit.COLOR_ATTACHMENT;
      }), _initializer4$1l = applyDecoratedInitializer(_class2$2W.prototype, "format", [_dec4$1c], function () {
        return Format.UNKNOWN;
      }), _initializer5$13 = applyDecoratedInitializer(_class2$2W.prototype, "width", [serializable$p], function () {
        return -1;
      }), _initializer6$T = applyDecoratedInitializer(_class2$2W.prototype, "height", [serializable$p], function () {
        return -1;
      })), _class2$2W)) || _class$3e);
      var RenderTextureConfig = (_dec5$13 = ccclass$M('RenderTextureConfig'), _dec6$P = type$d(RenderTexture), _dec5$13(_class4$u = (_class5$u = function RenderTextureConfig() {
        this.name = _initializer7$H && _initializer7$H();
        this.texture = _initializer8$D && _initializer8$D();
      }, (_initializer7$H = applyDecoratedInitializer(_class5$u.prototype, "name", [serializable$p], function () {
        return '';
      }), _initializer8$D = applyDecoratedInitializer(_class5$u.prototype, "texture", [_dec6$P], function () {
        return null;
      })), _class5$u)) || _class4$u);
      (_dec7$E = ccclass$M('MaterialConfig'), _dec8$s = type$d(Material), _dec7$E(_class7$8 = (_class8$9 = function MaterialConfig() {
        this.name = _initializer9$y && _initializer9$y();
        this.material = _initializer10$v && _initializer10$v();
      }, (_initializer9$y = applyDecoratedInitializer(_class8$9.prototype, "name", [serializable$p], function () {
        return '';
      }), _initializer10$v = applyDecoratedInitializer(_class8$9.prototype, "material", [_dec8$s], function () {
        return null;
      })), _class8$9)) || _class7$8);
      (_dec9$n = ccclass$M('FrameBufferDesc'), _dec10$f = type$d([CCString]), _dec11$a = type$d(RenderTexture), _dec9$n(_class10$4 = (_class11$5 = function FrameBufferDesc() {
        this.name = _initializer11$t && _initializer11$t();
        this.renderPass = _initializer12$q && _initializer12$q();
        this.colorTextures = _initializer13$n && _initializer13$n();
        this.depthStencilTexture = _initializer14$j && _initializer14$j();
        this.texture = _initializer15$f && _initializer15$f();
      }, (_initializer11$t = applyDecoratedInitializer(_class11$5.prototype, "name", [serializable$p], function () {
        return '';
      }), _initializer12$q = applyDecoratedInitializer(_class11$5.prototype, "renderPass", [serializable$p], function () {
        return 0;
      }), _initializer13$n = applyDecoratedInitializer(_class11$5.prototype, "colorTextures", [_dec10$f], function () {
        return [];
      }), _initializer14$j = applyDecoratedInitializer(_class11$5.prototype, "depthStencilTexture", [serializable$p], function () {
        return '';
      }), _initializer15$f = applyDecoratedInitializer(_class11$5.prototype, "texture", [_dec11$a], function () {
        return null;
      })), _class11$5)) || _class10$4);
      var ColorDesc = (_dec12$9 = ccclass$M('ColorDesc'), _dec13$7 = type$d(Format), _dec14$6 = type$d(LoadOp), _dec15$5 = type$d(StoreOp), _dec16$4 = type$d(AccessFlagBit), _dec17$4 = type$d(AccessFlagBit), _dec12$9(_class13$4 = (_class14$3 = function ColorDesc() {
        this.format = _initializer16$f && _initializer16$f();
        this.loadOp = _initializer17$c && _initializer17$c();
        this.storeOp = _initializer18$c && _initializer18$c();
        this.sampleCount = _initializer19$b && _initializer19$b();
        this.beginAccesses = _initializer20$9 && _initializer20$9();
        this.endAccesses = _initializer21$9 && _initializer21$9();
      }, (_initializer16$f = applyDecoratedInitializer(_class14$3.prototype, "format", [_dec13$7], function () {
        return Format.UNKNOWN;
      }), _initializer17$c = applyDecoratedInitializer(_class14$3.prototype, "loadOp", [_dec14$6], function () {
        return LoadOp.CLEAR;
      }), _initializer18$c = applyDecoratedInitializer(_class14$3.prototype, "storeOp", [_dec15$5], function () {
        return StoreOp.STORE;
      }), _initializer19$b = applyDecoratedInitializer(_class14$3.prototype, "sampleCount", [serializable$p], function () {
        return 1;
      }), _initializer20$9 = applyDecoratedInitializer(_class14$3.prototype, "beginAccesses", [_dec16$4], function () {
        return AccessFlagBit.NONE;
      }), _initializer21$9 = applyDecoratedInitializer(_class14$3.prototype, "endAccesses", [_dec17$4], function () {
        return AccessFlagBit.COLOR_ATTACHMENT_WRITE;
      })), _class14$3)) || _class13$4);
      var DepthStencilDesc = (_dec18$4 = ccclass$M('DepthStencilDesc'), _dec19$4 = type$d(Format), _dec20$4 = type$d(LoadOp), _dec21$4 = type$d(StoreOp), _dec22$4 = type$d(LoadOp), _dec23$4 = type$d(StoreOp), _dec24$4 = type$d(AccessFlagBit), _dec25$4 = type$d(AccessFlagBit), _dec18$4(_class16 = (_class17$1 = function DepthStencilDesc() {
        this.format = _initializer22$8 && _initializer22$8();
        this.depthLoadOp = _initializer23$6 && _initializer23$6();
        this.depthStoreOp = _initializer24$6 && _initializer24$6();
        this.stencilLoadOp = _initializer25$5 && _initializer25$5();
        this.stencilStoreOp = _initializer26$5 && _initializer26$5();
        this.sampleCount = _initializer27$4 && _initializer27$4();
        this.beginAccesses = _initializer28$4 && _initializer28$4();
        this.endAccesses = _initializer29$4 && _initializer29$4();
      }, (_initializer22$8 = applyDecoratedInitializer(_class17$1.prototype, "format", [_dec19$4], function () {
        return Format.UNKNOWN;
      }), _initializer23$6 = applyDecoratedInitializer(_class17$1.prototype, "depthLoadOp", [_dec20$4], function () {
        return LoadOp.CLEAR;
      }), _initializer24$6 = applyDecoratedInitializer(_class17$1.prototype, "depthStoreOp", [_dec21$4], function () {
        return StoreOp.STORE;
      }), _initializer25$5 = applyDecoratedInitializer(_class17$1.prototype, "stencilLoadOp", [_dec22$4], function () {
        return LoadOp.CLEAR;
      }), _initializer26$5 = applyDecoratedInitializer(_class17$1.prototype, "stencilStoreOp", [_dec23$4], function () {
        return StoreOp.STORE;
      }), _initializer27$4 = applyDecoratedInitializer(_class17$1.prototype, "sampleCount", [serializable$p], function () {
        return 1;
      }), _initializer28$4 = applyDecoratedInitializer(_class17$1.prototype, "beginAccesses", [_dec24$4], function () {
        return AccessFlagBit.NONE;
      }), _initializer29$4 = applyDecoratedInitializer(_class17$1.prototype, "endAccesses", [_dec25$4], function () {
        return AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE;
      })), _class17$1)) || _class16);
      (_dec26$4 = ccclass$M('RenderPassDesc'), _dec27$4 = type$d([ColorDesc]), _dec28$4 = type$d(DepthStencilDesc), _dec26$4(_class19 = (_class20$2 = function RenderPassDesc() {
        this.index = _initializer30$4 && _initializer30$4();
        this.colorAttachments = _initializer31$4 && _initializer31$4();
        this.depthStencilAttachment = _initializer32$3 && _initializer32$3();
      }, (_initializer30$4 = applyDecoratedInitializer(_class20$2.prototype, "index", [serializable$p], function () {
        return -1;
      }), _initializer31$4 = applyDecoratedInitializer(_class20$2.prototype, "colorAttachments", [_dec27$4], function () {
        return [];
      }), _initializer32$3 = applyDecoratedInitializer(_class20$2.prototype, "depthStencilAttachment", [_dec28$4], function () {
        return new DepthStencilDesc();
      })), _class20$2)) || _class19);
      var RenderQueueSortMode;
      (function (RenderQueueSortMode) {
        RenderQueueSortMode[RenderQueueSortMode["FRONT_TO_BACK"] = 0] = "FRONT_TO_BACK";
        RenderQueueSortMode[RenderQueueSortMode["BACK_TO_FRONT"] = 1] = "BACK_TO_FRONT";
      })(RenderQueueSortMode || (RenderQueueSortMode = {}));
      ccenum(RenderQueueSortMode);
      var RenderQueueDesc = (_dec29$4 = ccclass$M('RenderQueueDesc'), _dec30$3 = type$d(RenderQueueSortMode), _dec31$3 = type$d([CCString]), _dec29$4(_class22 = (_class23$1 = function RenderQueueDesc() {
        this.isTransparent = _initializer33$3 && _initializer33$3();
        this.sortMode = _initializer34$3 && _initializer34$3();
        this.stages = _initializer35$3 && _initializer35$3();
      }, (_initializer33$3 = applyDecoratedInitializer(_class23$1.prototype, "isTransparent", [serializable$p], function () {
        return false;
      }), _initializer34$3 = applyDecoratedInitializer(_class23$1.prototype, "sortMode", [_dec30$3], function () {
        return RenderQueueSortMode.FRONT_TO_BACK;
      }), _initializer35$3 = applyDecoratedInitializer(_class23$1.prototype, "stages", [_dec31$3], function () {
        return [];
      })), _class23$1)) || _class22);

      function opaqueCompareFn(a, b) {
        return a.hash - b.hash || a.depth - b.depth || a.shaderId - b.shaderId;
      }
      function transparentCompareFn(a, b) {
        return a.priority - b.priority || a.hash - b.hash || b.depth - a.depth || a.shaderId - b.shaderId;
      }
      var RenderQueue$1 = function () {
        function RenderQueue(desc) {
          this.queue = void 0;
          this._passDesc = void 0;
          this._passPool = void 0;
          this._passDesc = desc;
          this._passPool = new RecyclePool(function () {
            return {
              priority: 0,
              hash: 0,
              depth: 0,
              shaderId: 0,
              subModel: null,
              passIdx: 0
            };
          }, 64);
          this.queue = new CachedArray(64, this._passDesc.sortFunc);
        }
        var _proto = RenderQueue.prototype;
        _proto.clear = function clear() {
          this.queue.clear();
          this._passPool.reset();
        };
        _proto.insertRenderPass = function insertRenderPass(renderObj, subModelIdx, passIdx) {
          var subModel = renderObj.model.subModels[subModelIdx];
          var pass = subModel.passes[passIdx];
          var shader = subModel.shaders[passIdx];
          var isTransparent = pass.blendState.targets[0].blend;
          if (isTransparent !== this._passDesc.isTransparent || !(pass.phase & this._passDesc.phases)) {
            return false;
          }
          var hash = 0 << 30 | pass.priority << 16 | subModel.priority << 8 | passIdx;
          var rp = this._passPool.add();
          rp.priority = renderObj.model.priority;
          rp.hash = hash;
          rp.depth = renderObj.depth || 0;
          rp.shaderId = shader.typedID;
          rp.subModel = subModel;
          rp.passIdx = passIdx;
          this.queue.push(rp);
          return true;
        };
        _proto.sort = function sort() {
          this.queue.sort();
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
          for (var i = 0; i < this.queue.length; ++i) {
            var _this$queue$array$i = this.queue.array[i],
              subModel = _this$queue$array$i.subModel,
              passIdx = _this$queue$array$i.passIdx;
            var inputAssembler = subModel.inputAssembler;
            var pass = subModel.passes[passIdx];
            var shader = subModel.shaders[passIdx];
            var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
            cmdBuff.bindInputAssembler(inputAssembler);
            cmdBuff.draw(inputAssembler);
          }
        };
        return RenderQueue;
      }();
      function convertRenderQueue(desc) {
        var phase = 0;
        for (var j = 0; j < desc.stages.length; j++) {
          phase |= getPhaseID(desc.stages[j]);
        }
        var sortFunc = opaqueCompareFn;
        switch (desc.sortMode) {
          case RenderQueueSortMode.BACK_TO_FRONT:
            sortFunc = transparentCompareFn;
            break;
          case RenderQueueSortMode.FRONT_TO_BACK:
            sortFunc = opaqueCompareFn;
            break;
        }
        return new RenderQueue$1({
          isTransparent: desc.isTransparent,
          phases: phase,
          sortFunc: sortFunc
        });
      }
      function renderQueueClearFunc(rq) {
        rq.clear();
      }
      function renderQueueSortFunc(rq) {
        rq.sort();
      }

      var RenderInstancedQueue = function () {
        function RenderInstancedQueue() {
          this.queue = new Set();
          this._renderQueue = [];
        }
        var _proto = RenderInstancedQueue.prototype;
        _proto.clear = function clear() {
          var it = this.queue.values();
          var res = it.next();
          while (!res.done) {
            res.value.clear();
            res = it.next();
          }
          this._renderQueue.length = 0;
          this.queue.clear();
        };
        _proto.sort = function sort() {
          var it = this.queue.values();
          var res = it.next();
          while (!res.done) {
            if (!res.value.pass.blendState.targets[0].blend) {
              this._renderQueue.push(res.value);
            }
            res = it.next();
          }
          it = this.queue.values();
          res = it.next();
          while (!res.done) {
            if (res.value.pass.blendState.targets[0].blend) {
              this._renderQueue.push(res.value);
            }
            res = it.next();
          }
        };
        _proto.uploadBuffers = function uploadBuffers(cmdBuff) {
          var it = this.queue.values();
          var res = it.next();
          while (!res.done) {
            if (res.value.hasPendingModels) res.value.uploadBuffers(cmdBuff);
            res = it.next();
          }
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, dynamicOffsets) {
          if (descriptorSet === void 0) {
            descriptorSet = null;
          }
          var it = this._renderQueue.length === 0 ? this.queue.values() : this._renderQueue[Symbol.iterator]();
          var res = it.next();
          while (!res.done) {
            var _res$value = res.value,
              instances = _res$value.instances,
              pass = _res$value.pass,
              hasPendingModels = _res$value.hasPendingModels;
            if (hasPendingModels) {
              cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
              var lastPSO = null;
              for (var b = 0; b < instances.length; ++b) {
                var instance = instances[b];
                if (!instance.count) {
                  continue;
                }
                var shader = instance.shader;
                var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, instance.ia);
                if (lastPSO !== pso) {
                  cmdBuff.bindPipelineState(pso);
                  lastPSO = pso;
                }
                if (descriptorSet) cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, descriptorSet);
                if (dynamicOffsets) {
                  cmdBuff.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, dynamicOffsets);
                } else {
                  cmdBuff.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, res.value.dynamicOffsets);
                }
                cmdBuff.bindInputAssembler(instance.ia);
                cmdBuff.draw(instance.ia);
              }
            }
            res = it.next();
          }
        };
        return RenderInstancedQueue;
      }();

      var _dec$3h, _dec2$2q, _class$3d, _class2$2V, _initializer$2F, _class3$T;
      var colors$6 = [new Color(0, 0, 0, 0), new Color(0, 0, 0, 0), new Color(0, 0, 0, 0)];
      var GbufferStage = exports('dl', (_dec$3h = ccclass$M('GbufferStage'), _dec2$2q = type$d([RenderQueueDesc]), _dec$3h(_class$3d = (_class2$2V = (_class3$T = function (_RenderStage) {
        _inheritsLoose(GbufferStage, _RenderStage);
        function GbufferStage() {
          var _this;
          _this = _RenderStage.call(this) || this;
          _this.renderQueues = _initializer$2F && _initializer$2F();
          _this._renderQueues = [];
          _this._renderArea = new Rect();
          _this._instancedQueue = void 0;
          _this._phaseID = getPhaseID('default');
          _this._instancedQueue = new RenderInstancedQueue();
          return _this;
        }
        var _proto = GbufferStage.prototype;
        _proto.initialize = function initialize(info) {
          _RenderStage.prototype.initialize.call(this, info);
          if (info.renderQueues) {
            this.renderQueues = info.renderQueues;
          }
          return true;
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          for (var i = 0; i < this.renderQueues.length; i++) {
            this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]);
          }
        };
        _proto.destroy = function destroy() {};
        _proto.render = function render(camera) {
          this._instancedQueue.clear();
          var pipeline = this._pipeline;
          var device = pipeline.device;
          this._renderQueues.forEach(renderQueueClearFunc);
          pipeline.generateRenderArea(camera, this._renderArea);
          pipeline.updateQuadVertexData(this._renderArea, camera.window);
          var renderObjects = pipeline.pipelineSceneData.renderObjects;
          var m = 0;
          var p = 0;
          var k = 0;
          for (var i = 0; i < renderObjects.length; ++i) {
            var ro = renderObjects[i];
            var subModels = ro.model.subModels;
            for (m = 0; m < subModels.length; ++m) {
              var subModel = subModels[m];
              var passes = subModel.passes;
              for (p = 0; p < passes.length; ++p) {
                var pass = passes[p];
                if (pass.phase !== this._phaseID) continue;
                var batchingScheme = pass.batchingScheme;
                if (batchingScheme === BatchingSchemes.INSTANCING) {
                  var instancedBuffer = pass.getInstancedBuffer();
                  instancedBuffer.merge(subModel, p);
                  this._instancedQueue.queue.add(instancedBuffer);
                } else {
                  for (k = 0; k < this._renderQueues.length; k++) {
                    this._renderQueues[k].insertRenderPass(ro, m, p);
                  }
                }
              }
            }
          }
          this._renderQueues.forEach(renderQueueSortFunc);
          var cmdBuff = pipeline.commandBuffers[0];
          this._instancedQueue.uploadBuffers(cmdBuff);
          if (camera.clearFlag & ClearFlagBit.COLOR) {
            if (pipeline.pipelineSceneData.isHDR) {
              SRGBToLinear(colors$6[0], camera.clearColor);
            } else {
              colors$6[0].x = camera.clearColor.x;
              colors$6[0].y = camera.clearColor.y;
              colors$6[0].z = camera.clearColor.z;
            }
          }
          colors$6[0].w = camera.clearColor.w;
          var deferredData = pipeline.getPipelineRenderData();
          var framebuffer = deferredData.gbufferFrameBuffer;
          var renderPass = framebuffer.renderPass;
          cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors$6, camera.clearDepth, camera.clearStencil);
          cmdBuff.setScissor(pipeline.generateScissor(camera));
          cmdBuff.setViewport(pipeline.generateViewport(camera));
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          for (var _i = 0; _i < this.renderQueues.length; _i++) {
            this._renderQueues[_i].recordCommandBuffer(device, renderPass, cmdBuff);
          }
          this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          cmdBuff.endRenderPass();
        };
        return GbufferStage;
      }(RenderStage), _class3$T.initInfo = {
        name: 'GbufferStage',
        priority: DeferredStagePriority.GBUFFER,
        tag: 0,
        renderQueues: [{
          isTransparent: false,
          sortMode: RenderQueueSortMode.FRONT_TO_BACK,
          stages: ['default']
        }, {
          isTransparent: true,
          sortMode: RenderQueueSortMode.BACK_TO_FRONT,
          stages: ['default']
        }]
      }, _class3$T), (_initializer$2F = applyDecoratedInitializer(_class2$2V.prototype, "renderQueues", [_dec2$2q, serializable$p], function () {
        return [];
      })), _class2$2V)) || _class$3d));

      var _ab = new AABB();
      var _phaseID$4 = getPhaseID('planar-shadow');
      function getPlanarShadowPassIndex(subModel) {
        var passes = subModel.passes;
        var r = legacyCC.rendering;
        if (isEnableEffect()) _phaseID$4 = r.getPhaseID(r.getPassID('default'), 'planar-shadow');
        for (var k = 0; k < passes.length; k++) {
          if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseID$4 || isEnableEffect() && passes[k].phaseID === _phaseID$4) {
            return k;
          }
        }
        return -1;
      }
      var PlanarShadowQueue = function () {
        function PlanarShadowQueue(pipeline) {
          this._subModelArray = [];
          this._shaderArray = [];
          this._passArray = [];
          this._castModels = [];
          this._instancedQueue = new RenderInstancedQueue();
          this._pipeline = void 0;
          this._pipeline = pipeline;
        }
        var _proto = PlanarShadowQueue.prototype;
        _proto.clear = function clear() {
          this._subModelArray.length = 0;
          this._shaderArray.length = 0;
          this._passArray.length = 0;
          this._instancedQueue.clear();
          this._castModels.length = 0;
        };
        _proto.gatherShadowPasses = function gatherShadowPasses(camera, cmdBuff) {
          this.clear();
          var pipelineSceneData = this._pipeline.pipelineSceneData;
          var shadows = pipelineSceneData.shadows;
          if (!shadows.enabled || shadows.type !== ShadowType.Planar || shadows.normal.length() < 0.000001) {
            return;
          }
          var scene = camera.scene;
          var frustum = camera.frustum;
          var shadowVisible = (camera.visibility & Layers.BitMask.DEFAULT) !== 0;
          if (!scene.mainLight || !shadowVisible) {
            return;
          }
          var models = scene.models;
          var visibility = camera.visibility;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (scene.isCulledByLod(camera, model)) {
              continue;
            }
            if (model.enabled && model.node && model.castShadow && model.node && (visibility & model.node.layer) === model.node.layer) {
              this._castModels.push(model);
            }
          }
          for (var _i = 0; _i < this._castModels.length; _i++) {
            var _model = this._castModels[_i];
            if (_model.worldBounds) {
              AABB.transform(_ab, _model.worldBounds, shadows.matLight);
              if (!intersect.aabbFrustum(_ab, frustum)) {
                continue;
              }
            }
            var subModels = _model.subModels;
            for (var j = 0; j < subModels.length; j++) {
              var subModel = subModels[j];
              var shadowPassIdx = getPlanarShadowPassIndex(subModel);
              if (shadowPassIdx < 0) {
                this._subModelArray.push(subModel);
                var planarShader = shadows.getPlanarShader(subModel.patches);
                if (!planarShader) {
                  continue;
                }
                this._shaderArray.push(planarShader);
                this._passArray.push(shadows.material.passes[0]);
                continue;
              }
              var pass = subModel.passes[shadowPassIdx];
              var batchingScheme = pass.batchingScheme;
              if (batchingScheme === BatchingSchemes.INSTANCING) {
                var buffer = pass.getInstancedBuffer();
                buffer.merge(subModel, shadowPassIdx);
                this._instancedQueue.queue.add(buffer);
              } else {
                var shader = subModel.shaders[shadowPassIdx];
                this._subModelArray.push(subModel);
                if (shader) this._shaderArray.push(shader);
                this._passArray.push(pass);
              }
            }
          }
          this._instancedQueue.uploadBuffers(cmdBuff);
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
          var shadows = this._pipeline.pipelineSceneData.shadows;
          if (!shadows.enabled || shadows.type !== ShadowType.Planar) {
            return;
          }
          this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          for (var i = 0; i < this._subModelArray.length; ++i) {
            var subModel = this._subModelArray[i];
            var shader = this._shaderArray[i];
            var pass = this._passArray[i];
            var ia = subModel.inputAssembler;
            var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, ia);
            var descriptorSet = pass.descriptorSet;
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
            cmdBuff.bindInputAssembler(ia);
            cmdBuff.draw(ia);
          }
        };
        return PlanarShadowQueue;
      }();

      var UIPhase = function () {
        function UIPhase() {
          this._phaseID = getPhaseID('default');
          var r = legacyCC.rendering;
          if (isEnableEffect()) this._phaseID = r.getPhaseID(r.getPassID('default'), 'default');
        }
        var _proto = UIPhase.prototype;
        _proto.activate = function activate(pipeline) {
          this._pipeline = pipeline;
        };
        _proto.render = function render(camera, renderPass) {
          var pipeline = this._pipeline;
          var device = pipeline.device;
          var cmdBuff = pipeline.commandBuffers[0];
          var scene = camera.scene;
          var batches = scene.batches;
          for (var i = 0; i < batches.length; i++) {
            var batch = batches[i];
            var visible = false;
            if (camera.visibility & batch.visFlags) {
              visible = true;
            }
            if (!visible) continue;
            var count = batch.shaders.length;
            for (var j = 0; j < count; j++) {
              var pass = batch.passes[j];
              if (pass.phase !== this._phaseID) continue;
              var shader = batch.shaders[j];
              var inputAssembler = batch.inputAssembler;
              var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
              cmdBuff.bindPipelineState(pso);
              cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
              var ds = batch.descriptorSet;
              cmdBuff.bindDescriptorSet(SetIndex.LOCAL, ds);
              cmdBuff.bindInputAssembler(inputAssembler);
              cmdBuff.draw(inputAssembler);
            }
          }
        };
        return UIPhase;
      }();

      var _dec$3g, _dec2$2p, _dec3$1I, _class$3c, _class2$2U, _initializer$2E, _initializer2$28, _class3$S;
      var _v3$2 = new Vec3();
      var _rangedDirLightBoundingBox$1 = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5);
      var _tmpBoundingBox$1 = new AABB();
      var colors$5 = [new Color(0, 0, 0, 1)];
      var LightingStage = exports('dm', (_dec$3g = ccclass$M('LightingStage'), _dec2$2p = type$d(Material), _dec3$1I = type$d([RenderQueueDesc]), _dec$3g(_class$3c = (_class2$2U = (_class3$S = function (_RenderStage) {
        _inheritsLoose(LightingStage, _RenderStage);
        function LightingStage() {
          var _this;
          _this = _RenderStage.call(this) || this;
          _this._deferredLitsBufs = null;
          _this._maxDeferredLights = UBODeferredLight.LIGHTS_PER_PASS;
          _this._lightBufferData = void 0;
          _this._lightMeterScale = 10000.0;
          _this._descriptorSet = null;
          _this._descriptorSetLayout = void 0;
          _this._renderArea = new Rect();
          _this._uiPhase = void 0;
          _this._deferredMaterial = _initializer$2E && _initializer$2E();
          _this.renderQueues = _initializer2$28 && _initializer2$28();
          _this._phaseID = getPhaseID('default');
          _this._renderQueues = [];
          _this._uiPhase = new UIPhase();
          return _this;
        }
        var _proto = LightingStage.prototype;
        _proto.initialize = function initialize(info) {
          _RenderStage.prototype.initialize.call(this, info);
          return true;
        };
        _proto.gatherLights = function gatherLights(camera) {
          var pipeline = this._pipeline;
          var cmdBuff = pipeline.commandBuffers[0];
          var sphereLights = camera.scene.sphereLights;
          var spotLights = camera.scene.spotLights;
          var pointLights = camera.scene.pointLights;
          var rangedDirLights = camera.scene.rangedDirLights;
          var _sphere = Sphere.create(0, 0, 0, 1);
          var _vec4Array = new Float32Array(4);
          var exposure = camera.exposure;
          var idx = 0;
          var elementLen = Vec4.length;
          var fieldLen = elementLen * this._maxDeferredLights;
          for (var i = 0; i < sphereLights.length && idx < this._maxDeferredLights; i++, ++idx) {
            var light = sphereLights[i];
            Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);
            if (intersect.sphereFrustum(_sphere, camera.frustum)) {
              Vec3.toArray(_vec4Array, light.position);
              _vec4Array[3] = LightType.SPHERE;
              this._lightBufferData.set(_vec4Array, idx * elementLen);
              Vec3.toArray(_vec4Array, light.color);
              if (light.useColorTemperature) {
                var finalColor = light.finalColor;
                _vec4Array[0] = finalColor.x;
                _vec4Array[1] = finalColor.y;
                _vec4Array[2] = finalColor.z;
              }
              if (pipeline.pipelineSceneData.isHDR) {
                _vec4Array[3] = light.luminance * exposure * this._lightMeterScale;
              } else {
                _vec4Array[3] = light.luminance;
              }
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1);
              _vec4Array[0] = light.size;
              _vec4Array[1] = light.range;
              _vec4Array[2] = 0.0;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2);
            }
          }
          for (var _i = 0; _i < spotLights.length && idx < this._maxDeferredLights; _i++, ++idx) {
            var _light = spotLights[_i];
            Sphere.set(_sphere, _light.position.x, _light.position.y, _light.position.z, _light.range);
            if (intersect.sphereFrustum(_sphere, camera.frustum)) {
              Vec3.toArray(_vec4Array, _light.position);
              _vec4Array[3] = LightType.SPOT;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 0);
              Vec3.toArray(_vec4Array, _light.color);
              if (_light.useColorTemperature) {
                var _finalColor = _light.finalColor;
                _vec4Array[0] = _finalColor.x;
                _vec4Array[1] = _finalColor.y;
                _vec4Array[2] = _finalColor.z;
              }
              if (pipeline.pipelineSceneData.isHDR) {
                _vec4Array[3] = _light.luminance * exposure * this._lightMeterScale;
              } else {
                _vec4Array[3] = _light.luminance;
              }
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1);
              _vec4Array[0] = _light.size;
              _vec4Array[1] = _light.range;
              _vec4Array[2] = _light.spotAngle;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2);
              Vec3.toArray(_vec4Array, _light.direction);
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 3);
            }
          }
          for (var _i2 = 0; _i2 < pointLights.length && idx < this._maxDeferredLights; _i2++, ++idx) {
            var _light2 = pointLights[_i2];
            Sphere.set(_sphere, _light2.position.x, _light2.position.y, _light2.position.z, _light2.range);
            if (intersect.sphereFrustum(_sphere, camera.frustum)) {
              Vec3.toArray(_vec4Array, _light2.position);
              _vec4Array[3] = LightType.POINT;
              this._lightBufferData.set(_vec4Array, idx * elementLen);
              Vec3.toArray(_vec4Array, _light2.color);
              if (_light2.useColorTemperature) {
                var _finalColor2 = _light2.finalColor;
                _vec4Array[0] = _finalColor2.x;
                _vec4Array[1] = _finalColor2.y;
                _vec4Array[2] = _finalColor2.z;
              }
              if (pipeline.pipelineSceneData.isHDR) {
                _vec4Array[3] = _light2.luminance * exposure * this._lightMeterScale;
              } else {
                _vec4Array[3] = _light2.luminance;
              }
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1);
              _vec4Array[0] = 0.0;
              _vec4Array[1] = _light2.range;
              _vec4Array[2] = 0.0;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2);
            }
          }
          for (var _i3 = 0; _i3 < rangedDirLights.length && idx < this._maxDeferredLights; _i3++, ++idx) {
            var _light3 = rangedDirLights[_i3];
            AABB.transform(_tmpBoundingBox$1, _rangedDirLightBoundingBox$1, _light3.node.getWorldMatrix());
            if (intersect.aabbFrustum(_tmpBoundingBox$1, camera.frustum)) {
              Vec3.toArray(_vec4Array, _light3.position);
              _vec4Array[3] = LightType.RANGED_DIRECTIONAL;
              this._lightBufferData.set(_vec4Array, idx * elementLen);
              Vec3.toArray(_vec4Array, _light3.color);
              if (_light3.useColorTemperature) {
                var _finalColor3 = _light3.finalColor;
                _vec4Array[0] = _finalColor3.x;
                _vec4Array[1] = _finalColor3.y;
                _vec4Array[2] = _finalColor3.z;
              }
              if (pipeline.pipelineSceneData.isHDR) {
                _vec4Array[3] = _light3.illuminance * exposure;
              } else {
                _vec4Array[3] = _light3.illuminance;
              }
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1);
              Vec3.toArray(_vec4Array, _light3.right);
              _vec4Array[3] = 0;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2);
              Vec3.toArray(_vec4Array, _light3.direction);
              _vec4Array[3] = 0;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 3);
              var scale = _light3.scale;
              _v3$2.set(scale.x * 0.5, scale.y * 0.5, scale.z * 0.5);
              Vec3.toArray(_vec4Array, _v3$2);
              _vec4Array[3] = 0;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 4);
            }
          }
          var offset = fieldLen * 3 + 3;
          this._lightBufferData.set([idx], offset);
          cmdBuff.updateBuffer(this._deferredLitsBufs, this._lightBufferData);
        };
        _proto._createStageDescriptor = function _createStageDescriptor(pass) {
          var device = this._pipeline.device;
          var totalSize = Float32Array.BYTES_PER_ELEMENT * 4 * 4 * this._maxDeferredLights;
          totalSize = Math.ceil(totalSize / device.capabilities.uboOffsetAlignment) * device.capabilities.uboOffsetAlignment;
          this._deferredLitsBufs = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, totalSize, device.capabilities.uboOffsetAlignment));
          var deferredLitsBufView = device.createBuffer(new BufferViewInfo(this._deferredLitsBufs, 0, totalSize));
          this._lightBufferData = new Float32Array(totalSize / Float32Array.BYTES_PER_ELEMENT);
          this._descriptorSet = device.createDescriptorSet(new DescriptorSetInfo(pass.localSetLayout));
          this._descriptorSet.bindBuffer(UBOForwardLight.BINDING, deferredLitsBufView);
          var _localUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOLocal.SIZE, UBOLocal.SIZE));
          this._descriptorSet.bindBuffer(UBOLocal.BINDING, _localUBO);
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          this._uiPhase.activate(pipeline);
          for (var i = 0; i < this.renderQueues.length; i++) {
            this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]);
          }
          this._planarQueue = new PlanarShadowQueue(this._pipeline);
          if (this._deferredMaterial) {
            pipeline.pipelineSceneData.deferredLightingMaterial = this._deferredMaterial;
          }
        };
        _proto.destroy = function destroy() {
          var _this$_deferredLitsBu;
          (_this$_deferredLitsBu = this._deferredLitsBufs) === null || _this$_deferredLitsBu === void 0 ? void 0 : _this$_deferredLitsBu.destroy();
          this._deferredLitsBufs = null;
          this._descriptorSet = null;
        };
        _proto.render = function render(camera) {
          var _camera$geometryRende;
          var pipeline = this._pipeline;
          var device = pipeline.device;
          var cmdBuff = pipeline.commandBuffers[0];
          var sceneData = pipeline.pipelineSceneData;
          var renderObjects = sceneData.renderObjects;
          this._planarQueue.gatherShadowPasses(camera, cmdBuff);
          pipeline.generateRenderArea(camera, this._renderArea);
          var deferredData = pipeline.getPipelineRenderData();
          var lightingMat = sceneData.deferredLightingMaterial;
          var pass = lightingMat.passes[0];
          var shader = pass.getShaderVariant();
          for (var i = 0; i < 3; ++i) {
            pass.descriptorSet.bindTexture(i, deferredData.gbufferRenderTargets[i]);
            pass.descriptorSet.bindSampler(i, deferredData.sampler);
          }
          pass.descriptorSet.bindTexture(3, deferredData.outputDepth);
          pass.descriptorSet.bindSampler(3, deferredData.sampler);
          pass.descriptorSet.update();
          if (!this._descriptorSet) {
            this._createStageDescriptor(pass);
          }
          this.gatherLights(camera);
          if (camera.clearFlag & ClearFlagBit.COLOR) {
            colors$5[0].x = camera.clearColor.x;
            colors$5[0].y = camera.clearColor.y;
            colors$5[0].z = camera.clearColor.z;
          }
          colors$5[0].w = 0;
          var framebuffer = deferredData.outputFrameBuffer;
          var renderPass = framebuffer.renderPass;
          pipeline.pipelineUBO.updateShadowUBO(camera);
          cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors$5, camera.clearDepth, camera.clearStencil);
          cmdBuff.setScissor(pipeline.generateScissor(camera));
          cmdBuff.setViewport(pipeline.generateViewport(camera));
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          var inputAssembler = pipeline.quadIAOffscreen;
          var pso = null;
          if (pass != null && shader != null && inputAssembler != null) {
            pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
          }
          if (pso != null) {
            this._descriptorSet.update();
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, this._descriptorSet);
            cmdBuff.bindInputAssembler(inputAssembler);
            cmdBuff.draw(inputAssembler);
          }
          this._renderQueues.forEach(renderQueueClearFunc);
          var m = 0;
          var p = 0;
          var k = 0;
          for (var _i4 = 0; _i4 < renderObjects.length; ++_i4) {
            var ro = renderObjects[_i4];
            var subModels = ro.model.subModels;
            for (m = 0; m < subModels.length; ++m) {
              var subModel = subModels[m];
              var passes = subModel.passes;
              for (p = 0; p < passes.length; ++p) {
                var _pass = passes[p];
                if (_pass.phase !== this._phaseID) continue;
                for (k = 0; k < this._renderQueues.length; k++) {
                  this._renderQueues[k].insertRenderPass(ro, m, p);
                }
              }
            }
          }
          if (renderObjects.length > 0) {
            this._renderQueues.forEach(renderQueueSortFunc);
            for (var _i5 = 0; _i5 < this._renderQueues.length; _i5++) {
              this._renderQueues[_i5].recordCommandBuffer(device, renderPass, cmdBuff);
            }
            this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          }
          (_camera$geometryRende = camera.geometryRenderer) === null || _camera$geometryRende === void 0 ? void 0 : _camera$geometryRende.render(renderPass, cmdBuff, pipeline.pipelineSceneData);
          this._uiPhase.render(camera, renderPass);
          cmdBuff.endRenderPass();
        };
        return LightingStage;
      }(RenderStage), _class3$S.initInfo = {
        name: 'LightingStage',
        priority: DeferredStagePriority.LIGHTING,
        tag: 0
      }, _class3$S), (_initializer$2E = applyDecoratedInitializer(_class2$2U.prototype, "_deferredMaterial", [_dec2$2p, serializable$p], function () {
        return null;
      }), _initializer2$28 = applyDecoratedInitializer(_class2$2U.prototype, "renderQueues", [_dec3$1I, serializable$p], function () {
        return [];
      })), _class2$2U)) || _class$3c));

      var _dec$3f, _dec2$2o, _dec3$1H, _class$3b, _class2$2T, _initializer$2D, _initializer2$27, _class3$R;
      var colors$4 = [new Color(0, 0, 0, 1)];
      var PostProcessStage = exports('dp', (_dec$3f = ccclass$M('PostProcessStage'), _dec2$2o = type$d(Material), _dec3$1H = type$d([RenderQueueDesc]), _dec$3f(_class$3b = (_class2$2T = (_class3$R = function (_RenderStage) {
        _inheritsLoose(PostProcessStage, _RenderStage);
        function PostProcessStage() {
          var _this;
          _this = _RenderStage.call(this) || this;
          _this._postProcessMaterial = _initializer$2D && _initializer$2D();
          _this.renderQueues = _initializer2$27 && _initializer2$27();
          _this._renderArea = new Rect();
          _this._stageDesc = void 0;
          _this._localUBO = void 0;
          _this._uiPhase = new UIPhase();
          return _this;
        }
        var _proto = PostProcessStage.prototype;
        _proto.initialize = function initialize(info) {
          _RenderStage.prototype.initialize.call(this, info);
          return true;
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          if (this._postProcessMaterial) {
            pipeline.pipelineSceneData.postprocessMaterial = this._postProcessMaterial;
          }
          this._uiPhase.activate(pipeline);
        };
        _proto.destroy = function destroy() {};
        _proto.render = function render(camera) {
          var pipeline = this._pipeline;
          var device = pipeline.device;
          var sceneData = pipeline.pipelineSceneData;
          var cmdBuff = pipeline.commandBuffers[0];
          pipeline.pipelineUBO.updateCameraUBO(camera);
          var vp = camera.viewport;
          this._renderArea.x = vp.x * camera.window.width;
          this._renderArea.y = vp.y * camera.window.height;
          this._renderArea.width = vp.width * camera.window.width;
          this._renderArea.height = vp.height * camera.window.height;
          var renderData = pipeline.getPipelineRenderData();
          var framebuffer = camera.window.framebuffer;
          var renderPass = pipeline.getRenderPass(camera.clearFlag, framebuffer);
          if (camera.clearFlag & ClearFlagBit.COLOR) {
            colors$4[0].x = camera.clearColor.x;
            colors$4[0].y = camera.clearColor.y;
            colors$4[0].z = camera.clearColor.z;
          }
          colors$4[0].w = camera.clearColor.w;
          cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors$4, camera.clearDepth, camera.clearStencil);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          var builtinPostProcess = sceneData.postprocessMaterial;
          var pass = builtinPostProcess.passes[0];
          var shader = pass.getShaderVariant();
          if (pipeline.bloomEnabled) {
            pass.descriptorSet.bindTexture(0, renderData.bloom.combineTex);
          } else {
            pass.descriptorSet.bindTexture(0, renderData.outputRenderTargets[0]);
          }
          pass.descriptorSet.bindSampler(0, renderData.sampler);
          pass.descriptorSet.update();
          var inputAssembler = camera.window.swapchain ? pipeline.quadIAOnscreen : pipeline.quadIAOffscreen;
          var pso = null;
          if (pass != null && shader != null && inputAssembler != null) {
            pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
          }
          var renderObjects = pipeline.pipelineSceneData.renderObjects;
          if (pso != null && renderObjects.length > 0) {
            if (!this._stageDesc) {
              this._stageDesc = device.createDescriptorSet(new DescriptorSetInfo(pass.localSetLayout));
              this._localUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOLocal.SIZE, UBOLocal.SIZE));
              this._stageDesc.bindBuffer(UBOLocal.BINDING, this._localUBO);
            }
            this._stageDesc.update();
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, this._stageDesc);
            cmdBuff.bindInputAssembler(inputAssembler);
            cmdBuff.draw(inputAssembler);
          }
          this._uiPhase.render(camera, renderPass);
          renderProfiler(device, renderPass, cmdBuff, pipeline.profiler, camera);
          cmdBuff.endRenderPass();
        };
        return PostProcessStage;
      }(RenderStage), _class3$R.initInfo = {
        name: 'PostProcessStage',
        priority: CommonStagePriority.POST_PROCESS,
        tag: 0
      }, _class3$R), (_initializer$2D = applyDecoratedInitializer(_class2$2T.prototype, "_postProcessMaterial", [_dec2$2o, serializable$p], function () {
        return null;
      }), _initializer2$27 = applyDecoratedInitializer(_class2$2T.prototype, "renderQueues", [_dec3$1H, serializable$p], function () {
        return [];
      })), _class2$2T)) || _class$3b));

      var Octree = function () {
        function Octree() {
          this._enabled = false;
          this._minPos = new Vec3(0, 0, 0);
          this._maxPos = new Vec3(0, 0, 0);
          this._depth = 0;
        }
        var _proto = Octree.prototype;
        _proto.initialize = function initialize(octreeInfo) {
          this._enabled = octreeInfo.enabled;
          this._minPos = octreeInfo.minPos;
          this._maxPos = octreeInfo.maxPos;
          this._depth = octreeInfo.depth;
        };
        _createClass(Octree, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }, {
          key: "minPos",
          get: function get() {
            return this._minPos;
          },
          set: function set(val) {
            this._minPos = val;
          }
        }, {
          key: "maxPos",
          get: function get() {
            return this._maxPos;
          },
          set: function set(val) {
            this._maxPos = val;
          }
        }, {
          key: "depth",
          get: function get() {
            return this._depth;
          },
          set: function set(val) {
            this._depth = val;
          }
        }]);
        return Octree;
      }();

      var _mat4Trans = new Mat4();
      var _matShadowTrans = new Mat4();
      var _matShadowView$1 = new Mat4();
      var _matShadowProj = new Mat4();
      var _matShadowViewProj$1 = new Mat4();
      var _matShadowViewProjArbitaryPos = new Mat4();
      var _matShadowViewProjArbitaryPosInv = new Mat4();
      var _focus = new Vec3(0, 0, 0);
      var _projPos = new Vec3();
      var _texelSize = new Vec2();
      var _projSnap = new Vec3();
      var _snap = new Vec3();
      var _maxVec3 = new Vec3(10000000, 10000000, 10000000);
      var _minVec3 = new Vec3(-10000000, -10000000, -10000000);
      var _shadowPos = new Vec3();
      var _maxLayerPosz = 0.0;
      var _maxLayerFarPlane = 0.0;
      var ShadowLayerVolume = function () {
        function ShadowLayerVolume(level) {
          this._shadowObjects = [];
          this._shadowCameraFar = 0;
          this._level = void 0;
          this._matShadowView = new Mat4();
          this._matShadowProj = new Mat4();
          this._matShadowViewProj = new Mat4();
          this._validFrustum = new Frustum();
          this._splitFrustum = new Frustum();
          this._lightViewFrustum = new Frustum();
          this._castLightViewBoundingBox = new AABB();
          this._level = level;
          this._validFrustum.accurate = true;
          this._splitFrustum.accurate = true;
          this._lightViewFrustum.accurate = true;
        }
        var _proto = ShadowLayerVolume.prototype;
        _proto.copyToValidFrustum = function copyToValidFrustum(validFrustum) {
          Frustum.copy(this._validFrustum, validFrustum);
        };
        _proto.calculateValidFrustumOrtho = function calculateValidFrustumOrtho(width, height, near, far, transform) {
          Frustum.createOrtho(this._validFrustum, width, height, near, far, transform);
        };
        _proto.calculateSplitFrustum = function calculateSplitFrustum(camera, m, start, end) {
          this._splitFrustum.split(start, end, camera.aspect, camera.fov, m);
        };
        _proto.destroy = function destroy() {
          this._shadowObjects.length = 0;
        };
        _proto.createMatrix = function createMatrix(dirLight, shadowMapWidth, onlyForCulling) {
          var device = legacyCC.director.root.device;
          var invisibleOcclusionRange = dirLight.shadowInvisibleOcclusionRange;
          Frustum.copy(this._lightViewFrustum, this._splitFrustum);
          Mat4.fromRT(_matShadowTrans, dirLight.node.rotation, _focus);
          Mat4.invert(_matShadowView$1, _matShadowTrans);
          var shadowViewArbitaryPos = _matShadowView$1.clone();
          this._lightViewFrustum.transform(_matShadowView$1);
          AABB.fromPoints(this._castLightViewBoundingBox, _maxVec3, _minVec3);
          this._castLightViewBoundingBox.mergeFrustum(this._lightViewFrustum);
          var orthoSizeWidth;
          var orthoSizeHeight;
          if (dirLight.csmOptimizationMode === CSMOptimizationMode.DisableRotationFix) {
            orthoSizeWidth = this._castLightViewBoundingBox.halfExtents.x * 2.0;
            orthoSizeHeight = this._castLightViewBoundingBox.halfExtents.y * 2.0;
          } else {
            orthoSizeWidth = orthoSizeHeight = Vec3.distance(this._lightViewFrustum.vertices[0], this._lightViewFrustum.vertices[6]);
          }
          var csmLevel = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1;
          if (csmLevel > 1 && dirLight.csmOptimizationMode === CSMOptimizationMode.RemoveDuplicates) {
            if (this._level >= csmLevel - 1) {
              _maxLayerFarPlane = this._castLightViewBoundingBox.halfExtents.z;
              _maxLayerPosz = this._castLightViewBoundingBox.center.z;
            } else {
              var alignFarPlaneDist = Math.abs(this._castLightViewBoundingBox.center.z - _maxLayerPosz) + _maxLayerFarPlane;
              this._castLightViewBoundingBox.halfExtents.z = Math.max(this._castLightViewBoundingBox.center.z, alignFarPlaneDist);
            }
          }
          var r = this._castLightViewBoundingBox.halfExtents.z;
          this._shadowCameraFar = r * 2 + invisibleOcclusionRange;
          var center = this._castLightViewBoundingBox.center;
          _shadowPos.set(center.x, center.y, center.z + r + invisibleOcclusionRange);
          Vec3.transformMat4(_shadowPos, _shadowPos, _matShadowTrans);
          Mat4.fromRT(_matShadowTrans, dirLight.node.rotation, _shadowPos);
          Mat4.invert(_matShadowView$1, _matShadowTrans);
          if (!onlyForCulling) {
            var halfOrthoSizeWidth = orthoSizeWidth * 0.5;
            var halfOrthoSizeHeight = orthoSizeHeight * 0.5;
            Mat4.ortho(_matShadowProj, -halfOrthoSizeWidth, halfOrthoSizeWidth, -halfOrthoSizeHeight, halfOrthoSizeHeight, 0.1, this._shadowCameraFar, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY);
            Mat4.multiply(_matShadowViewProjArbitaryPos, _matShadowProj, shadowViewArbitaryPos);
            Vec3.transformMat4(_projPos, _shadowPos, _matShadowViewProjArbitaryPos);
            var invActualSize = 2.0 / shadowMapWidth;
            _texelSize.set(invActualSize, invActualSize);
            var modX = _projPos.x % _texelSize.x;
            var modY = _projPos.y % _texelSize.y;
            _projSnap.set(_projPos.x - modX, _projPos.y - modY, _projPos.z);
            Mat4.invert(_matShadowViewProjArbitaryPosInv, _matShadowViewProjArbitaryPos);
            Vec3.transformMat4(_snap, _projSnap, _matShadowViewProjArbitaryPosInv);
            Mat4.fromRT(_matShadowTrans, dirLight.node.rotation, _snap);
            Mat4.invert(_matShadowView$1, _matShadowTrans);
            Mat4.multiply(_matShadowViewProj$1, _matShadowProj, _matShadowView$1);
            Mat4.copy(this._matShadowView, _matShadowView$1);
            Mat4.copy(this._matShadowProj, _matShadowProj);
            Mat4.copy(this._matShadowViewProj, _matShadowViewProj$1);
          }
          Frustum.createOrtho(this._validFrustum, orthoSizeWidth, orthoSizeHeight, 0.1, this._shadowCameraFar, _matShadowTrans);
        };
        _createClass(ShadowLayerVolume, [{
          key: "level",
          get: function get() {
            return this._level;
          }
        }, {
          key: "shadowObjects",
          get: function get() {
            return this._shadowObjects;
          }
        }, {
          key: "shadowCameraFar",
          get: function get() {
            return this._shadowCameraFar;
          },
          set: function set(val) {
            this._shadowCameraFar = val;
          }
        }, {
          key: "matShadowView",
          get: function get() {
            return this._matShadowView;
          },
          set: function set(val) {
            this._matShadowView = val;
          }
        }, {
          key: "matShadowProj",
          get: function get() {
            return this._matShadowProj;
          },
          set: function set(val) {
            this._matShadowProj = val;
          }
        }, {
          key: "matShadowViewProj",
          get: function get() {
            return this._matShadowViewProj;
          },
          set: function set(val) {
            this._matShadowViewProj = val;
          }
        }, {
          key: "validFrustum",
          get: function get() {
            return this._validFrustum;
          }
        }, {
          key: "splitFrustum",
          get: function get() {
            return this._splitFrustum;
          }
        }, {
          key: "lightViewFrustum",
          get: function get() {
            return this._lightViewFrustum;
          }
        }, {
          key: "castLightViewBoundingBox",
          get: function get() {
            return this._castLightViewBoundingBox;
          }
        }]);
        return ShadowLayerVolume;
      }();
      var CSMShadowLayer = function (_ShadowLayerVolume) {
        _inheritsLoose(CSMShadowLayer, _ShadowLayerVolume);
        function CSMShadowLayer(level) {
          var _this;
          _this = _ShadowLayerVolume.call(this, level) || this;
          _this._splitCameraNear = 0;
          _this._splitCameraFar = 0;
          _this._csmAtlas = new Vec4();
          _this._calculateAtlas(level);
          return _this;
        }
        var _proto2 = CSMShadowLayer.prototype;
        _proto2.destroy = function destroy() {
          _ShadowLayerVolume.prototype.destroy.call(this);
        };
        _proto2._calculateAtlas = function _calculateAtlas(level) {
          var clipSpaceSignY = legacyCC.director.root.device.capabilities.clipSpaceSignY;
          var x = level % 2 - 0.5;
          var y = (0.5 - Math.floor(level / 2)) * clipSpaceSignY;
          this._csmAtlas.set(0.5, 0.5, x, y);
        };
        _createClass(CSMShadowLayer, [{
          key: "splitCameraNear",
          get: function get() {
            return this._splitCameraNear;
          },
          set: function set(val) {
            this._splitCameraNear = val;
          }
        }, {
          key: "splitCameraFar",
          get: function get() {
            return this._splitCameraFar;
          },
          set: function set(val) {
            this._splitCameraFar = val;
          }
        }, {
          key: "csmAtlas",
          get: function get() {
            return this._csmAtlas;
          },
          set: function set(val) {
            this._csmAtlas = val;
          }
        }]);
        return CSMShadowLayer;
      }(ShadowLayerVolume);
      var CSMLayers = function () {
        function CSMLayers() {
          this._castShadowObjects = [];
          this._layerObjects = new CachedArray(64);
          this._layers = [];
          this._levelCount = 0;
          this._specialLayer = new ShadowLayerVolume(1);
          this._shadowDistance = 0;
          for (var i = 0; i < CSMLevel.LEVEL_4; i++) {
            this._layers[i] = new CSMShadowLayer(i);
          }
        }
        var _proto3 = CSMLayers.prototype;
        _proto3.update = function update(sceneData, camera) {
          var scene = camera.scene;
          var dirLight = scene.mainLight;
          if (dirLight === null) {
            return;
          }
          var shadowInfo = sceneData.shadows;
          var levelCount = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1;
          var shadowDistance = dirLight.shadowDistance;
          if (!shadowInfo.enabled || !dirLight.shadowEnabled) {
            return;
          }
          if (dirLight.shadowFixedArea) {
            this._updateFixedArea(dirLight);
          } else {
            if (dirLight.csmNeedUpdate || this._levelCount !== levelCount || this._shadowDistance !== shadowDistance) {
              this._splitFrustumLevels(dirLight);
              this._levelCount = levelCount;
              this._shadowDistance = shadowDistance;
            }
            this._calculateCSM(camera, dirLight, shadowInfo);
          }
        };
        _proto3.destroy = function destroy() {
          this._castShadowObjects.length = 0;
          for (var i = 0; i < this._layers.length; i++) {
            this._layers[i].destroy();
          }
          this._layers.length = 0;
        };
        _proto3._updateFixedArea = function _updateFixedArea(dirLight) {
          var device = legacyCC.director.root.device;
          var x = dirLight.shadowOrthoSize;
          var y = dirLight.shadowOrthoSize;
          var near = dirLight.shadowNear;
          var far = dirLight.shadowFar;
          Mat4.fromRT(_matShadowTrans, dirLight.node.getWorldRotation(), dirLight.node.getWorldPosition());
          Mat4.invert(_matShadowView$1, _matShadowTrans);
          Mat4.ortho(_matShadowProj, -x, x, -y, y, near, far, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY);
          Mat4.multiply(_matShadowViewProj$1, _matShadowProj, _matShadowView$1);
          this._specialLayer.matShadowView = _matShadowView$1;
          this._specialLayer.matShadowProj = _matShadowProj;
          this._specialLayer.matShadowViewProj = _matShadowViewProj$1;
          this._specialLayer.calculateValidFrustumOrtho(x * 2.0, y * 2.0, near, far, _matShadowTrans);
        };
        _proto3._splitFrustumLevels = function _splitFrustumLevels(dirLight) {
          var nd = 0.1;
          var fd = dirLight.shadowDistance;
          var ratio = fd / nd;
          var level = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1;
          var lambda = dirLight.csmLayerLambda;
          this._layers[0].splitCameraNear = nd;
          for (var i = 1; i < level; i++) {
            var si = i / level;
            var preNear = lambda * (nd * Math.pow(ratio, si)) + (1 - lambda) * (nd + (fd - nd) * si);
            var nextFar = preNear * 1.005;
            this._layers[i].splitCameraNear = preNear;
            this._layers[i - 1].splitCameraFar = nextFar;
          }
          this._layers[level - 1].splitCameraFar = fd;
          dirLight.csmNeedUpdate = false;
        };
        _proto3._calculateCSM = function _calculateCSM(camera, dirLight, shadowInfo) {
          var level = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1;
          var shadowMapWidth = level > 1 ? shadowInfo.size.x * 0.5 : shadowInfo.size.x;
          if (shadowMapWidth < 0.0) {
            return;
          }
          this._getCameraWorldMatrix(_mat4Trans, camera);
          for (var i = level - 1; i >= 0; i--) {
            var csmLayer = this._layers[i];
            var near = csmLayer.splitCameraNear;
            var far = csmLayer.splitCameraFar;
            csmLayer.calculateSplitFrustum(camera, _mat4Trans, near, far);
            csmLayer.createMatrix(dirLight, shadowMapWidth, false);
          }
          if (level === CSMLevel.LEVEL_1) {
            this._specialLayer.shadowCameraFar = this._layers[0].shadowCameraFar;
            Mat4.copy(this._specialLayer.matShadowView, this._layers[0].matShadowView);
            Mat4.copy(this._specialLayer.matShadowProj, this._layers[0].matShadowProj);
            Mat4.copy(this._specialLayer.matShadowViewProj, this._layers[0].matShadowViewProj);
            this._specialLayer.copyToValidFrustum(this._layers[0].validFrustum);
          } else {
            this._specialLayer.calculateSplitFrustum(camera, _mat4Trans, 0.1, dirLight.shadowDistance);
            this._specialLayer.createMatrix(dirLight, shadowMapWidth, true);
          }
        };
        _proto3._getCameraWorldMatrix = function _getCameraWorldMatrix(out, camera) {
          if (!camera.node) {
            return;
          }
          var cameraNode = camera.node;
          var position = cameraNode.getWorldPosition();
          var rotation = cameraNode.getWorldRotation();
          Mat4.fromRT(out, rotation, position);
        };
        _createClass(CSMLayers, [{
          key: "castShadowObjects",
          get: function get() {
            return this._castShadowObjects;
          }
        }, {
          key: "layerObjects",
          get: function get() {
            return this._layerObjects;
          }
        }, {
          key: "layers",
          get: function get() {
            return this._layers;
          }
        }, {
          key: "specialLayer",
          get: function get() {
            return this._specialLayer;
          }
        }]);
        return CSMLayers;
      }();

      var Skin = function () {
        function Skin() {
          this._enabled = true;
          this._blurRadius = 0.01;
          this._sssIntensity = 3.0;
        }
        var _proto = Skin.prototype;
        _proto.initialize = function initialize(skinInfo) {
          this._enabled = skinInfo.enabled;
          this._blurRadius = skinInfo.blurRadius;
          this._sssIntensity = skinInfo.sssIntensity;
        };
        _createClass(Skin, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }, {
          key: "blurRadius",
          get: function get() {
            return this._blurRadius;
          },
          set: function set(val) {
            this._blurRadius = val;
          }
        }, {
          key: "sssIntensity",
          get: function get() {
            return this._sssIntensity;
          },
          set: function set(val) {
            this._sssIntensity = val;
          }
        }]);
        return Skin;
      }();

      var GEOMETRY_RENDERER_TECHNIQUE_COUNT = 6;
      var PipelineSceneData = exports('de', function () {
        function PipelineSceneData() {
          this.fog = new Fog();
          this.ambient = new Ambient();
          this.skybox = new Skybox();
          this.shadows = new Shadows();
          this.csmLayers = new CSMLayers();
          this.octree = new Octree();
          this.skin = new Skin();
          this.postSettings = new PostSettings();
          this.lightProbes = legacyCC.internal.LightProbes ? new legacyCC.internal.LightProbes() : null;
          this.validPunctualLights = [];
          this.renderObjects = [];
          this.shadowFrameBufferMap = new Map();
          this._geometryRendererMaterials = [];
          this._geometryRendererPasses = [];
          this._geometryRendererShaders = [];
          this._occlusionQueryVertexBuffer = null;
          this._occlusionQueryIndicesBuffer = null;
          this._occlusionQueryInputAssembler = null;
          this._occlusionQueryMaterial = null;
          this._occlusionQueryShader = null;
          this._isHDR = true;
          this._shadingScale = 1.0;
          this._csmSupported = true;
          this._standardSkinMeshRenderer = null;
          this._standardSkinModel = null;
          this._skinMaterialModel = null;
          this._shadingScale = 1.0;
        }
        var _proto = PipelineSceneData.prototype;
        _proto.activate = function activate(device) {
          this._device = device;
          this.initGeometryRendererMaterials();
          this.initOcclusionQuery();
          return true;
        };
        _proto.initGeometryRendererMaterials = function initGeometryRendererMaterials() {
          var offset = 0;
          for (var tech = 0; tech < GEOMETRY_RENDERER_TECHNIQUE_COUNT; tech++) {
            this._geometryRendererMaterials[tech] = new Material();
            this._geometryRendererMaterials[tech]._uuid = "geometry-renderer-material-" + tech;
            this._geometryRendererMaterials[tech].initialize({
              effectName: 'internal/builtin-geometry-renderer',
              technique: tech
            });
            for (var pass = 0; pass < this._geometryRendererMaterials[tech].passes.length; ++pass) {
              this._geometryRendererPasses[offset] = this._geometryRendererMaterials[tech].passes[pass];
              this._geometryRendererShaders[offset] = this._geometryRendererMaterials[tech].passes[pass].getShaderVariant();
              offset++;
            }
          }
        };
        _proto.initOcclusionQuery = function initOcclusionQuery() {
          if (!this._occlusionQueryInputAssembler) {
            this._occlusionQueryInputAssembler = this._createOcclusionQueryIA();
          }
          if (!this._occlusionQueryMaterial) {
            var mat = new Material();
            mat._uuid = 'default-occlusion-query-material';
            mat.initialize({
              effectName: 'internal/builtin-occlusion-query'
            });
            this._occlusionQueryMaterial = mat;
            if (mat.passes.length > 0) {
              this._occlusionQueryShader = mat.passes[0].getShaderVariant();
            }
          }
        };
        _proto.getOcclusionQueryPass = function getOcclusionQueryPass() {
          if (this._occlusionQueryMaterial && this._occlusionQueryMaterial.passes.length > 0) {
            return this._occlusionQueryMaterial.passes[0];
          }
          return null;
        };
        _proto.updatePipelineSceneData = function updatePipelineSceneData() {};
        _proto.destroy = function destroy() {
          var _this$_occlusionQuery, _this$_occlusionQuery2, _this$_occlusionQuery3;
          this.shadows.destroy();
          this.csmLayers.destroy();
          this.validPunctualLights.length = 0;
          (_this$_occlusionQuery = this._occlusionQueryInputAssembler) === null || _this$_occlusionQuery === void 0 ? void 0 : _this$_occlusionQuery.destroy();
          this._occlusionQueryInputAssembler = null;
          (_this$_occlusionQuery2 = this._occlusionQueryVertexBuffer) === null || _this$_occlusionQuery2 === void 0 ? void 0 : _this$_occlusionQuery2.destroy();
          this._occlusionQueryVertexBuffer = null;
          (_this$_occlusionQuery3 = this._occlusionQueryIndicesBuffer) === null || _this$_occlusionQuery3 === void 0 ? void 0 : _this$_occlusionQuery3.destroy();
          this._occlusionQueryIndicesBuffer = null;
          this._standardSkinMeshRenderer = null;
          this._standardSkinModel = null;
          this._skinMaterialModel = null;
        };
        _proto._createOcclusionQueryIA = function _createOcclusionQueryIA() {
          var device = this._device;
          var vertices = new Float32Array([-1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1]);
          var vbStride = Float32Array.BYTES_PER_ELEMENT * 3;
          var vbSize = vbStride * 8;
          this._occlusionQueryVertexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, vbSize, vbStride));
          this._occlusionQueryVertexBuffer.update(vertices);
          var indices = new Uint16Array([0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6, 1, 3, 7, 1, 7, 5, 0, 4, 6, 0, 6, 2, 0, 1, 5, 0, 5, 4, 2, 6, 7, 2, 7, 3]);
          var ibStride = Uint16Array.BYTES_PER_ELEMENT;
          var ibSize = ibStride * 36;
          this._occlusionQueryIndicesBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibSize, ibStride));
          this._occlusionQueryIndicesBuffer.update(indices);
          var attributes = [new Attribute('a_position', Format.RGB32F)];
          var info = new InputAssemblerInfo(attributes, [this._occlusionQueryVertexBuffer], this._occlusionQueryIndicesBuffer);
          var inputAssembler = device.createInputAssembler(info);
          return inputAssembler;
        };
        _createClass(PipelineSceneData, [{
          key: "isHDR",
          get: function get() {
            return this._isHDR;
          },
          set: function set(val) {
            this._isHDR = val;
          }
        }, {
          key: "shadingScale",
          get: function get() {
            return this._shadingScale;
          },
          set: function set(val) {
            this._shadingScale = val;
          }
        }, {
          key: "csmSupported",
          get: function get() {
            return this._csmSupported;
          },
          set: function set(val) {
            this._csmSupported = val;
          }
        }, {
          key: "standardSkinModel",
          get: function get() {
            return this._standardSkinModel;
          },
          set: function set(val) {
            this._standardSkinModel = val;
          }
        }, {
          key: "standardSkinMeshRenderer",
          get: function get() {
            return this._standardSkinMeshRenderer;
          },
          set: function set(val) {
            if (this._standardSkinMeshRenderer && this._standardSkinMeshRenderer !== val) {
              this._standardSkinMeshRenderer.clearGlobalStandardSkinObjectFlag();
            }
            this._standardSkinMeshRenderer = val;
            this.standardSkinModel = val ? val.model : null;
          }
        }, {
          key: "skinMaterialModel",
          get: function get() {
            return this._skinMaterialModel;
          },
          set: function set(val) {
            this._skinMaterialModel = val;
          }
        }, {
          key: "geometryRendererPasses",
          get: function get() {
            return this._geometryRendererPasses;
          }
        }, {
          key: "geometryRendererShaders",
          get: function get() {
            return this._geometryRendererShaders;
          }
        }]);
        return PipelineSceneData;
      }());

      var AntiAliasing;
      (function (AntiAliasing) {
        AntiAliasing[AntiAliasing["NONE"] = 0] = "NONE";
        AntiAliasing[AntiAliasing["FXAA"] = 1] = "FXAA";
      })(AntiAliasing || (AntiAliasing = {}));
      var BLOOM_PREFILTERPASS_INDEX = 0;
      var BLOOM_DOWNSAMPLEPASS_INDEX = 1;
      var BLOOM_UPSAMPLEPASS_INDEX = BLOOM_DOWNSAMPLEPASS_INDEX + MAX_BLOOM_FILTER_PASS_NUM;
      var BLOOM_COMBINEPASS_INDEX = BLOOM_UPSAMPLEPASS_INDEX + MAX_BLOOM_FILTER_PASS_NUM;
      var DeferredPipelineSceneData = function (_PipelineSceneData) {
        _inheritsLoose(DeferredPipelineSceneData, _PipelineSceneData);
        function DeferredPipelineSceneData() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineSceneData.call.apply(_PipelineSceneData, [this].concat(args)) || this;
          _this._antiAliasing = AntiAliasing.NONE;
          return _this;
        }
        var _proto = DeferredPipelineSceneData.prototype;
        _proto.updatePipelineSceneData = function updatePipelineSceneData() {
          this.updatePipelinePassInfo();
        };
        _proto.updateBloomPass = function updateBloomPass() {
          if (!this._bloomMaterial) return;
          var prefilterPass = this._bloomMaterial.passes[BLOOM_PREFILTERPASS_INDEX];
          prefilterPass.beginChangeStatesSilently();
          prefilterPass.tryCompile();
          prefilterPass.endChangeStatesSilently();
          for (var i = 0; i < MAX_BLOOM_FILTER_PASS_NUM; ++i) {
            var downsamplePass = this._bloomMaterial.passes[BLOOM_DOWNSAMPLEPASS_INDEX + i];
            downsamplePass.beginChangeStatesSilently();
            downsamplePass.tryCompile();
            downsamplePass.endChangeStatesSilently();
            var upsamplePass = this._bloomMaterial.passes[BLOOM_UPSAMPLEPASS_INDEX + i];
            upsamplePass.beginChangeStatesSilently();
            upsamplePass.tryCompile();
            upsamplePass.endChangeStatesSilently();
          }
          var combinePass = this._bloomMaterial.passes[BLOOM_COMBINEPASS_INDEX];
          combinePass.beginChangeStatesSilently();
          combinePass.tryCompile();
          combinePass.endChangeStatesSilently();
        };
        _proto.updatePostProcessPass = function updatePostProcessPass() {
          if (!this.postprocessMaterial) return;
          var passPost = this.postprocessMaterial.passes[0];
          passPost.beginChangeStatesSilently();
          passPost.tryCompile();
          passPost.endChangeStatesSilently();
        };
        _proto.initPipelinePassInfo = function initPipelinePassInfo() {
          var deferredMat = new Material();
          deferredMat._uuid = 'builtin-deferred-material';
          deferredMat.initialize({
            effectName: 'pipeline/deferred-lighting'
          });
          for (var i = 0; i < deferredMat.passes.length; ++i) {
            deferredMat.passes[i].tryCompile();
          }
          this._deferredLightingMaterial = deferredMat;
          var bloomMat = new Material();
          bloomMat._uuid = 'builtin-bloom-material';
          bloomMat.initialize({
            effectName: 'pipeline/bloom'
          });
          for (var _i = 0; _i < bloomMat.passes.length; ++_i) {
            bloomMat.passes[_i].tryCompile();
          }
          this._bloomMaterial = bloomMat;
          var postMat = new Material();
          postMat._uuid = 'builtin-post-process-material';
          postMat.initialize({
            effectName: 'pipeline/post-process',
            defines: {
              ANTIALIAS_TYPE: this._antiAliasing
            }
          });
          for (var _i2 = 0; _i2 < postMat.passes.length; ++_i2) {
            postMat.passes[_i2].tryCompile();
          }
          this._postprocessMaterial = postMat;
          this.updatePipelinePassInfo();
        };
        _proto.updatePipelinePassInfo = function updatePipelinePassInfo() {
          this.updateBloomPass();
          this.updatePostProcessPass();
          this.updateDeferredPassInfo();
        };
        _proto.activate = function activate(device) {
          _PipelineSceneData.prototype.activate.call(this, device);
          this.initPipelinePassInfo();
          return true;
        };
        _proto.updateDeferredPassInfo = function updateDeferredPassInfo() {
          this.updateDeferredLightPass();
        };
        _proto.updateDeferredLightPass = function updateDeferredLightPass() {
          if (!this._deferredLightingMaterial) return;
          legacyCC.director.root.pipeline.macros.CC_RECEIVE_SHADOW = 1;
          var passLit = this._deferredLightingMaterial.passes[0];
          passLit.beginChangeStatesSilently();
          passLit.tryCompile();
          passLit.endChangeStatesSilently();
        };
        _createClass(DeferredPipelineSceneData, [{
          key: "antiAliasing",
          get: function get() {
            return this._antiAliasing;
          },
          set: function set(value) {
            this._antiAliasing = value;
            if (this._postprocessMaterial) {
              var defines = this._postprocessMaterial.passes[0].defines;
              Object.assign(defines, {
                ANTIALIAS_TYPE: value
              });
              var renderMat = new Material();
              renderMat.initialize({
                effectAsset: this._postprocessMaterial.effectAsset,
                defines: defines
              });
              for (var i = 0; i < renderMat.passes.length; ++i) {
                renderMat.passes[i].tryCompile();
              }
              this._postprocessMaterial = renderMat;
            }
          }
        }, {
          key: "bloomMaterial",
          get: function get() {
            return this._bloomMaterial;
          },
          set: function set(mat) {
            if (this._bloomMaterial === mat || !mat) return;
            this._bloomMaterial = mat;
            this.updatePipelinePassInfo();
          }
        }, {
          key: "postprocessMaterial",
          get: function get() {
            return this._postprocessMaterial;
          },
          set: function set(mat) {
            if (this._postprocessMaterial === mat || !mat) return;
            this._postprocessMaterial = mat;
            this.updatePipelinePassInfo();
          }
        }, {
          key: "deferredLightingMaterial",
          get: function get() {
            return this._deferredLightingMaterial;
          },
          set: function set(mat) {
            if (this._deferredLightingMaterial === mat || !mat) return;
            this._deferredLightingMaterial = mat;
            this.updatePipelinePassInfo();
          }
        }]);
        return DeferredPipelineSceneData;
      }(PipelineSceneData);

      var _class$3a, _dec$3e, _dec2$2n, _class2$2S, _class3$Q, _initializer$2C, _class4$t;
      var colors$3 = [new Color(0, 0, 0, 1)];
      var UBOBloom = function UBOBloom() {};
      _class$3a = UBOBloom;
      UBOBloom.TEXTURE_SIZE_OFFSET = 0;
      UBOBloom.COUNT = _class$3a.TEXTURE_SIZE_OFFSET + 4;
      UBOBloom.SIZE = _class$3a.COUNT * 4;
      var BloomStage = exports('dn', (_dec$3e = ccclass$M('BloomStage'), _dec2$2n = type$d(Material), _dec$3e(_class2$2S = (_class3$Q = (_class4$t = function (_RenderStage) {
        _inheritsLoose(BloomStage, _RenderStage);
        function BloomStage() {
          var _this;
          _this = _RenderStage.call(this) || this;
          _this.threshold = 1.0;
          _this.intensity = 0.8;
          _this.iterations = 2;
          _this._bloomMaterial = _initializer$2C && _initializer$2C();
          _this._renderArea = new Rect();
          _this._bloomUBO = [];
          return _this;
        }
        var _proto = BloomStage.prototype;
        _proto.initialize = function initialize(info) {
          _RenderStage.prototype.initialize.call(this, info);
          return true;
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          if (this._bloomMaterial) {
            pipeline.pipelineSceneData.bloomMaterial = this._bloomMaterial;
          }
        };
        _proto.destroy = function destroy() {};
        _proto.render = function render(camera) {
          var _camera$window;
          var pipeline = this._pipeline;
          pipeline.generateBloomRenderData();
          if (!((_camera$window = camera.window) !== null && _camera$window !== void 0 && _camera$window.swapchain) && !pipeline.macros.CC_PIPELINE_TYPE) {
            return;
          }
          if (!pipeline.bloomEnabled || pipeline.pipelineSceneData.renderObjects.length === 0) return;
          if (this._bloomUBO.length === 0) {
            var passNumber = MAX_BLOOM_FILTER_PASS_NUM * 2 + 2;
            for (var i = 0; i < passNumber; ++i) {
              this._bloomUBO[i] = pipeline.device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOBloom.SIZE, UBOBloom.SIZE));
            }
          }
          if (camera.clearFlag & ClearFlagBit.COLOR) {
            colors$3[0].x = camera.clearColor.x;
            colors$3[0].y = camera.clearColor.y;
            colors$3[0].z = camera.clearColor.z;
          }
          colors$3[0].w = camera.clearColor.w;
          this._prefilterPass(camera, pipeline);
          this._downsamplePass(camera, pipeline);
          this._upsamplePass(camera, pipeline);
          this._combinePass(camera, pipeline);
        };
        _proto._prefilterPass = function _prefilterPass(camera, pipeline) {
          pipeline.generateRenderArea(camera, this._renderArea);
          this._renderArea.width >>= 1;
          this._renderArea.height >>= 1;
          var cmdBuff = pipeline.commandBuffers[0];
          var sceneData = pipeline.pipelineSceneData;
          var builtinBloomProcess = sceneData.bloomMaterial;
          var pass = builtinBloomProcess.passes[BLOOM_PREFILTERPASS_INDEX];
          var renderData = pipeline.getPipelineRenderData();
          var bloomData = renderData.bloom;
          var textureSize = new Float32Array(UBOBloom.COUNT);
          textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 2] = this.threshold;
          cmdBuff.updateBuffer(this._bloomUBO[0], textureSize);
          cmdBuff.beginRenderPass(bloomData.renderPass, bloomData.prefilterFramebuffer, this._renderArea, colors$3, 0, 0);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          pass.descriptorSet.bindBuffer(0, this._bloomUBO[0]);
          pass.descriptorSet.bindTexture(1, renderData.outputRenderTargets[0]);
          pass.descriptorSet.bindSampler(1, bloomData.sampler);
          pass.descriptorSet.update();
          cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
          var inputAssembler = camera.window.swapchain ? pipeline.quadIAOffscreen : pipeline.quadIAOnscreen;
          var pso = null;
          var shader = pass.getShaderVariant();
          if (pass != null && shader != null && inputAssembler != null) {
            pso = PipelineStateManager.getOrCreatePipelineState(pipeline.device, pass, shader, bloomData.renderPass, inputAssembler);
          }
          if (pso != null) {
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindInputAssembler(inputAssembler);
            cmdBuff.draw(inputAssembler);
          }
          cmdBuff.endRenderPass();
        };
        _proto._downsamplePass = function _downsamplePass(camera, pipeline) {
          pipeline.generateRenderArea(camera, this._renderArea);
          this._renderArea.width >>= 1;
          this._renderArea.height >>= 1;
          var cmdBuff = pipeline.commandBuffers[0];
          var sceneData = pipeline.pipelineSceneData;
          var builtinBloomProcess = sceneData.bloomMaterial;
          var bloomData = pipeline.getPipelineRenderData().bloom;
          var textureSize = new Float32Array(UBOBloom.COUNT);
          for (var i = 0; i < this.iterations; ++i) {
            textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 0] = this._renderArea.width;
            textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 1] = this._renderArea.height;
            cmdBuff.updateBuffer(this._bloomUBO[i + 1], textureSize);
            this._renderArea.width >>= 1;
            this._renderArea.height >>= 1;
            cmdBuff.beginRenderPass(bloomData.renderPass, bloomData.downsampleFramebuffers[i], this._renderArea, colors$3, 0, 0);
            var pass = builtinBloomProcess.passes[BLOOM_DOWNSAMPLEPASS_INDEX + i];
            var shader = pass.getShaderVariant();
            pass.descriptorSet.bindBuffer(0, this._bloomUBO[i + 1]);
            if (i === 0) {
              pass.descriptorSet.bindTexture(1, bloomData.prefiterTex);
            } else {
              pass.descriptorSet.bindTexture(1, bloomData.downsampleTexs[i - 1]);
            }
            pass.descriptorSet.bindSampler(1, bloomData.sampler);
            pass.descriptorSet.update();
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
            var inputAssembler = camera.window.swapchain ? pipeline.quadIAOffscreen : pipeline.quadIAOnscreen;
            var pso = null;
            if (pass != null && shader != null && inputAssembler != null) {
              pso = PipelineStateManager.getOrCreatePipelineState(pipeline.device, pass, shader, bloomData.renderPass, inputAssembler);
            }
            if (pso != null) {
              cmdBuff.bindPipelineState(pso);
              cmdBuff.bindInputAssembler(inputAssembler);
              cmdBuff.draw(inputAssembler);
            }
            cmdBuff.endRenderPass();
          }
        };
        _proto._upsamplePass = function _upsamplePass(camera, pipeline) {
          var bloomData = pipeline.getPipelineRenderData().bloom;
          pipeline.generateRenderArea(camera, this._renderArea);
          this._renderArea.width >>= this.iterations + 1;
          this._renderArea.height >>= this.iterations + 1;
          var cmdBuff = pipeline.commandBuffers[0];
          var sceneData = pipeline.pipelineSceneData;
          var builtinBloomProcess = sceneData.bloomMaterial;
          var textureSize = new Float32Array(UBOBloom.COUNT);
          for (var i = 0; i < this.iterations; ++i) {
            var index = i + MAX_BLOOM_FILTER_PASS_NUM + 1;
            textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 0] = this._renderArea.width;
            textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 1] = this._renderArea.height;
            cmdBuff.updateBuffer(this._bloomUBO[index], textureSize);
            this._renderArea.width <<= 1;
            this._renderArea.height <<= 1;
            cmdBuff.beginRenderPass(bloomData.renderPass, bloomData.upsampleFramebuffers[this.iterations - 1 - i], this._renderArea, colors$3, 0, 0);
            var pass = builtinBloomProcess.passes[BLOOM_UPSAMPLEPASS_INDEX + i];
            var shader = pass.getShaderVariant();
            pass.descriptorSet.bindBuffer(0, this._bloomUBO[index]);
            if (i === 0) {
              pass.descriptorSet.bindTexture(1, bloomData.downsampleTexs[this.iterations - 1]);
            } else {
              pass.descriptorSet.bindTexture(1, bloomData.upsampleTexs[this.iterations - i]);
            }
            pass.descriptorSet.bindSampler(1, bloomData.sampler);
            pass.descriptorSet.update();
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
            var inputAssembler = camera.window.swapchain ? pipeline.quadIAOffscreen : pipeline.quadIAOnscreen;
            var pso = null;
            if (pass != null && shader != null && inputAssembler != null) {
              pso = PipelineStateManager.getOrCreatePipelineState(pipeline.device, pass, shader, bloomData.renderPass, inputAssembler);
            }
            if (pso != null) {
              cmdBuff.bindPipelineState(pso);
              cmdBuff.bindInputAssembler(inputAssembler);
              cmdBuff.draw(inputAssembler);
            }
            cmdBuff.endRenderPass();
          }
        };
        _proto._combinePass = function _combinePass(camera, pipeline) {
          pipeline.generateRenderArea(camera, this._renderArea);
          var cmdBuff = pipeline.commandBuffers[0];
          var sceneData = pipeline.pipelineSceneData;
          var builtinBloomProcess = sceneData.bloomMaterial;
          var deferredData = pipeline.getPipelineRenderData();
          var bloomData = deferredData.bloom;
          var uboIndex = MAX_BLOOM_FILTER_PASS_NUM * 2 + 1;
          var textureSize = new Float32Array(UBOBloom.COUNT);
          textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 3] = this.intensity;
          cmdBuff.updateBuffer(this._bloomUBO[uboIndex], textureSize);
          cmdBuff.beginRenderPass(bloomData.renderPass, bloomData.combineFramebuffer, this._renderArea, colors$3, 0, 0);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          var pass = builtinBloomProcess.passes[BLOOM_COMBINEPASS_INDEX];
          pass.descriptorSet.bindBuffer(0, this._bloomUBO[uboIndex]);
          pass.descriptorSet.bindTexture(1, deferredData.outputRenderTargets[0]);
          pass.descriptorSet.bindTexture(2, bloomData.upsampleTexs[0]);
          pass.descriptorSet.bindSampler(1, bloomData.sampler);
          pass.descriptorSet.bindSampler(2, bloomData.sampler);
          pass.descriptorSet.update();
          cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
          var inputAssembler = camera.window.swapchain ? pipeline.quadIAOffscreen : pipeline.quadIAOnscreen;
          var pso = null;
          var shader = pass.getShaderVariant();
          if (pass != null && shader != null && inputAssembler != null) {
            pso = PipelineStateManager.getOrCreatePipelineState(pipeline.device, pass, shader, bloomData.renderPass, inputAssembler);
          }
          if (pso != null) {
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindInputAssembler(inputAssembler);
            cmdBuff.draw(inputAssembler);
          }
          cmdBuff.endRenderPass();
        };
        return BloomStage;
      }(RenderStage), _class4$t.initInfo = {
        name: 'BloomStage',
        priority: CommonStagePriority.BLOOM,
        tag: 0
      }, _class4$t), (_initializer$2C = applyDecoratedInitializer(_class3$Q.prototype, "_bloomMaterial", [_dec2$2n, serializable$p], function () {
        return null;
      })), _class3$Q)) || _class2$2S));

      var _dec$3d, _class$39, _class2$2R;
      var MainFlow = exports('dk', (_dec$3d = ccclass$M('MainFlow'), _dec$3d(_class$39 = (_class2$2R = function (_RenderFlow) {
        _inheritsLoose(MainFlow, _RenderFlow);
        function MainFlow() {
          return _RenderFlow.apply(this, arguments) || this;
        }
        var _proto = MainFlow.prototype;
        _proto.initialize = function initialize(info) {
          _RenderFlow.prototype.initialize.call(this, info);
          if (this._stages.length === 0) {
            var gbufferStage = new GbufferStage();
            gbufferStage.initialize(GbufferStage.initInfo);
            this._stages.push(gbufferStage);
            var lightingStage = new LightingStage();
            lightingStage.initialize(LightingStage.initInfo);
            this._stages.push(lightingStage);
            var bloomStage = new BloomStage();
            bloomStage.initialize(BloomStage.initInfo);
            this._stages.push(bloomStage);
            var postProcessStage = new PostProcessStage();
            postProcessStage.initialize(PostProcessStage.initInfo);
            this._stages.push(postProcessStage);
          }
          return true;
        };
        _proto.activate = function activate(pipeline) {
          _RenderFlow.prototype.activate.call(this, pipeline);
        };
        _proto.render = function render(camera) {
          _RenderFlow.prototype.render.call(this, camera);
        };
        _proto.destroy = function destroy() {
          _RenderFlow.prototype.destroy.call(this);
        };
        return MainFlow;
      }(RenderFlow), _class2$2R.initInfo = {
        name: PIPELINE_FLOW_MAIN,
        priority: DeferredFlowPriority.MAIN,
        stages: []
      }, _class2$2R)) || _class$39));

      var _phaseID$3 = getPhaseID('shadow-caster');
      function getShadowPassIndex(subModel) {
        var passes = subModel.passes;
        var r = legacyCC.rendering;
        if (isEnableEffect()) _phaseID$3 = r.getPhaseID(r.getPassID('default'), 'shadow-caster');
        for (var k = 0; k < passes.length; k++) {
          if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseID$3 || isEnableEffect() && passes[k].phaseID === _phaseID$3) {
            return k;
          }
        }
        return -1;
      }
      var RenderShadowMapBatchedQueue = function () {
        function RenderShadowMapBatchedQueue(pipeline) {
          this._pipeline = void 0;
          this._subModelsArray = [];
          this._passArray = [];
          this._shaderArray = [];
          this._instancedQueue = void 0;
          this._pipeline = pipeline;
          this._instancedQueue = new RenderInstancedQueue();
        }
        var _proto = RenderShadowMapBatchedQueue.prototype;
        _proto.gatherLightPasses = function gatherLightPasses(camera, light, cmdBuff, level) {
          if (level === void 0) {
            level = 0;
          }
          this.clear();
          var sceneData = this._pipeline.pipelineSceneData;
          var shadowInfo = sceneData.shadows;
          if (light && shadowInfo.enabled && shadowInfo.type === ShadowType.ShadowMap) {
            switch (light.type) {
              case LightType.DIRECTIONAL:
                var dirLight = light;
                if (dirLight.shadowEnabled) {
                  var csmLayers = sceneData.csmLayers;
                  var layer;
                  if (dirLight.shadowFixedArea) {
                    layer = csmLayers.specialLayer;
                  } else {
                    layer = csmLayers.layers[level];
                  }
                  shadowCulling(camera, sceneData, layer);
                  var dirShadowObjects = layer.shadowObjects;
                  for (var i = 0; i < dirShadowObjects.length; i++) {
                    var ro = dirShadowObjects[i];
                    var model = ro.model;
                    this.add(model, level);
                  }
                }
                break;
              case LightType.SPOT:
                var spotLight = light;
                if (spotLight.shadowEnabled) {
                  var visibility = spotLight.visibility;
                  var castShadowObjects = sceneData.csmLayers.castShadowObjects;
                  for (var _i = 0; _i < castShadowObjects.length; _i++) {
                    var _ro = castShadowObjects[_i];
                    var _model = _ro.model;
                    if (_model.worldBounds) {
                      if ((visibility & _model.node.layer) !== _model.node.layer || !intersect.aabbFrustum(_model.worldBounds, spotLight.frustum)) {
                        continue;
                      }
                    }
                    this.add(_model, level);
                  }
                }
                break;
            }
            this._instancedQueue.uploadBuffers(cmdBuff);
          }
        };
        _proto.clear = function clear() {
          this._subModelsArray.length = 0;
          this._shaderArray.length = 0;
          this._passArray.length = 0;
          this._instancedQueue.clear();
        };
        _proto.add = function add(model, level) {
          var subModels = model.subModels;
          for (var j = 0; j < subModels.length; j++) {
            var subModel = subModels[j];
            var shadowPassIdx = getShadowPassIndex(subModel);
            if (shadowPassIdx < 0) {
              continue;
            }
            var pass = subModel.passes[shadowPassIdx];
            var batchingScheme = pass.batchingScheme;
            if (batchingScheme === BatchingSchemes.INSTANCING) {
              var buffer = pass.getInstancedBuffer(level);
              buffer.merge(subModel, shadowPassIdx);
              this._instancedQueue.queue.add(buffer);
            } else {
              var shader = subModel.shaders[shadowPassIdx];
              this._subModelsArray.push(subModel);
              if (shader) this._shaderArray.push(shader);
              this._passArray.push(pass);
            }
          }
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
          this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          for (var i = 0; i < this._subModelsArray.length; ++i) {
            var subModel = this._subModelsArray[i];
            var shader = this._shaderArray[i];
            var pass = this._passArray[i];
            var ia = subModel.inputAssembler;
            var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, ia);
            var descriptorSet = pass.descriptorSet;
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
            cmdBuff.bindInputAssembler(ia);
            cmdBuff.draw(ia);
          }
        };
        return RenderShadowMapBatchedQueue;
      }();

      var _dec$3c, _class$38, _class2$2Q;
      var colors$2 = [new Color(1, 1, 1, 1)];
      var ShadowStage = exports('dr', (_dec$3c = ccclass$M('ShadowStage'), _dec$3c(_class$38 = (_class2$2Q = function (_RenderStage) {
        _inheritsLoose(ShadowStage, _RenderStage);
        function ShadowStage() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderStage.call.apply(_RenderStage, [this].concat(args)) || this;
          _this._additiveShadowQueue = void 0;
          _this._shadowFrameBuffer = null;
          _this._renderArea = new Rect();
          _this._light = null;
          _this._globalDS = null;
          _this._level = 0;
          _this._isShadowMapCleared = false;
          return _this;
        }
        var _proto = ShadowStage.prototype;
        _proto.setUsage = function setUsage(globalDS, light, shadowFrameBuffer, level) {
          if (level === void 0) {
            level = 0;
          }
          this._globalDS = globalDS;
          this._light = light;
          this._shadowFrameBuffer = shadowFrameBuffer;
          this._level = level;
        };
        _proto.destroy = function destroy() {
          var _this$_additiveShadow;
          this._shadowFrameBuffer = null;
          this._globalDS = null;
          this._light = null;
          (_this$_additiveShadow = this._additiveShadowQueue) === null || _this$_additiveShadow === void 0 ? void 0 : _this$_additiveShadow.clear();
        };
        _proto.clearFramebuffer = function clearFramebuffer(camera) {
          if (!this._light || !this._shadowFrameBuffer || this._isShadowMapCleared) {
            return;
          }
          colors$2[0].w = camera.clearColor.w;
          var pipeline = this._pipeline;
          var pipelineSceneData = pipeline.pipelineSceneData;
          var shadingScale = pipelineSceneData.shadingScale;
          var shadowInfo = pipelineSceneData.shadows;
          var vp = camera.viewport;
          var shadowMapSize = shadowInfo.size;
          this._renderArea.x = vp.x * shadowMapSize.x;
          this._renderArea.y = vp.y * shadowMapSize.y;
          this._renderArea.width = vp.width * shadowMapSize.x * shadingScale;
          this._renderArea.height = vp.height * shadowMapSize.y * shadingScale;
          var cmdBuff = pipeline.commandBuffers[0];
          var renderPass = this._shadowFrameBuffer.renderPass;
          cmdBuff.beginRenderPass(renderPass, this._shadowFrameBuffer, this._renderArea, colors$2, camera.clearDepth, camera.clearStencil);
          cmdBuff.endRenderPass();
          this._isShadowMapCleared = true;
        };
        _proto.render = function render(camera) {
          var pipeline = this._pipeline;
          var pipelineSceneData = pipeline.pipelineSceneData;
          var shadowInfo = pipelineSceneData.shadows;
          var descriptorSet = this._globalDS;
          var cmdBuff = pipeline.commandBuffers[0];
          var level = this._level;
          var device = pipeline.device;
          if (!this._light || !this._shadowFrameBuffer) {
            return;
          }
          this._pipeline.pipelineUBO.updateShadowUBOLight(descriptorSet, this._light, level);
          this._additiveShadowQueue.gatherLightPasses(camera, this._light, cmdBuff, level);
          var shadowMapSize = shadowInfo.size;
          switch (this._light.type) {
            case LightType.DIRECTIONAL:
              {
                var mainLight = this._light;
                if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !pipelineSceneData.csmSupported) {
                  this._renderArea.x = 0;
                  this._renderArea.y = 0;
                  this._renderArea.width = shadowMapSize.x;
                  this._renderArea.height = shadowMapSize.y;
                } else {
                  var screenSpaceSignY = device.capabilities.screenSpaceSignY;
                  this._renderArea.x = level % 2 * 0.5 * shadowMapSize.x;
                  if (screenSpaceSignY > 0.0) {
                    this._renderArea.y = (1 - Math.floor(level / 2)) * 0.5 * shadowMapSize.y;
                  } else {
                    this._renderArea.y = Math.floor(level / 2) * 0.5 * shadowMapSize.y;
                  }
                  this._renderArea.width = 0.5 * shadowMapSize.x;
                  this._renderArea.height = 0.5 * shadowMapSize.y;
                }
                break;
              }
            case LightType.SPOT:
              {
                this._renderArea.x = 0;
                this._renderArea.y = 0;
                this._renderArea.width = shadowMapSize.x;
                this._renderArea.height = shadowMapSize.y;
                break;
              }
          }
          var renderPass = this._shadowFrameBuffer.renderPass;
          cmdBuff.beginRenderPass(renderPass, this._shadowFrameBuffer, this._renderArea, colors$2, camera.clearDepth, camera.clearStencil);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, descriptorSet);
          this._additiveShadowQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          cmdBuff.endRenderPass();
          this._isShadowMapCleared = false;
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          this._additiveShadowQueue = new RenderShadowMapBatchedQueue(pipeline);
          this._isShadowMapCleared = false;
        };
        return ShadowStage;
      }(RenderStage), _class2$2Q.initInfo = {
        name: 'ShadowStage',
        priority: ForwardStagePriority.FORWARD,
        tag: 0
      }, _class2$2Q)) || _class$38));

      var _dec$3b, _class$37, _class2$2P;
      var _validLights = [];
      var ShadowFlow = exports('dq', (_dec$3b = ccclass$M('ShadowFlow'), _dec$3b(_class$37 = (_class2$2P = function (_RenderFlow) {
        _inheritsLoose(ShadowFlow, _RenderFlow);
        function ShadowFlow() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderFlow.call.apply(_RenderFlow, [this].concat(args)) || this;
          _this._shadowRenderPass = null;
          return _this;
        }
        var _proto = ShadowFlow.prototype;
        _proto.initialize = function initialize(info) {
          _RenderFlow.prototype.initialize.call(this, info);
          if (this._stages.length === 0) {
            var shadowMapStage = new ShadowStage();
            shadowMapStage.initialize(ShadowStage.initInfo);
            this._stages.push(shadowMapStage);
          }
          return true;
        };
        _proto.activate = function activate(pipeline) {
          _RenderFlow.prototype.activate.call(this, pipeline);
          var isRGBE = supportsR32FloatTexture(pipeline.device) ? 0 : 1;
          pipeline.macros.CC_SHADOWMAP_FORMAT = isRGBE;
          var isLinear = pipeline.device.gfxAPI === API.WEBGL ? 1 : 0;
          pipeline.macros.CC_SHADOWMAP_USE_LINEAR_DEPTH = isLinear;
          pipeline.pipelineSceneData.csmSupported = pipeline.device.capabilities.maxFragmentUniformVectors >= (UBOGlobal.COUNT + UBOCamera.COUNT + UBOShadow.COUNT + UBOCSM.COUNT) / 4;
          pipeline.macros.CC_SUPPORT_CASCADED_SHADOW_MAP = pipeline.pipelineSceneData.csmSupported;
          pipeline.macros.CC_SHADOW_TYPE = 0;
          pipeline.macros.CC_DIR_SHADOW_PCF_TYPE = PCFType.HARD;
          pipeline.macros.CC_DIR_LIGHT_SHADOW_TYPE = 0;
          pipeline.macros.CC_CASCADED_LAYERS_TRANSITION = 0;
          pipeline.onGlobalPipelineStateChanged();
        };
        _proto.render = function render(camera) {
          var pipeline = this._pipeline;
          var shadowInfo = pipeline.pipelineSceneData.shadows;
          var csmLayers = pipeline.pipelineSceneData.csmLayers;
          var shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap;
          var castShadowObjects = csmLayers.castShadowObjects;
          var validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights;
          if (!shadowInfo.enabled || shadowInfo.type !== ShadowType.ShadowMap) {
            return;
          }
          var n = 0;
          var m = 0;
          for (; n < shadowInfo.maxReceived && m < validPunctualLights.length;) {
            var light = validPunctualLights[m];
            if (light.type === LightType.SPOT) {
              var spotLight = light;
              if (spotLight.shadowEnabled) {
                _validLights.push(light);
                n++;
              }
            }
            m++;
          }
          if (castShadowObjects.length === 0) {
            this.clearShadowMap(_validLights, camera);
            return;
          }
          if (shadowInfo.shadowMapDirty) {
            this.resizeShadowMap();
          }
          var _ref = camera.scene,
            mainLight = _ref.mainLight;
          if (mainLight && mainLight.shadowEnabled) {
            var globalDS = pipeline.descriptorSet;
            if (!shadowFrameBufferMap.has(mainLight)) {
              this._initShadowFrameBuffer(pipeline, mainLight, camera.window.swapchain);
            }
            var shadowFrameBuffer = shadowFrameBufferMap.get(mainLight);
            if (mainLight.shadowFixedArea) {
              this._renderStage(camera, mainLight, shadowFrameBuffer, globalDS);
            } else {
              var csmLevel = pipeline.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1;
              for (var i = 0; i < csmLevel; i++) {
                this._renderStage(camera, mainLight, shadowFrameBuffer, globalDS, i);
              }
            }
          }
          for (var l = 0; l < _validLights.length; l++) {
            var _light = _validLights[l];
            var ds = pipeline.globalDSManager.getOrCreateDescriptorSet(_light);
            if (!shadowFrameBufferMap.has(_light)) {
              this._initShadowFrameBuffer(pipeline, _light, camera.window.swapchain);
            }
            var _shadowFrameBuffer = shadowFrameBufferMap.get(_light);
            this._renderStage(camera, _light, _shadowFrameBuffer, ds);
          }
          _validLights.length = 0;
        };
        _proto.destroy = function destroy() {
          _RenderFlow.prototype.destroy.call(this);
          if (this._pipeline) {
            var shadowFrameBufferMap = this._pipeline.pipelineSceneData.shadowFrameBufferMap;
            var shadowFrameBuffers = Array.from(shadowFrameBufferMap.values());
            for (var i = 0; i < shadowFrameBuffers.length; i++) {
              var frameBuffer = shadowFrameBuffers[i];
              if (!frameBuffer) {
                continue;
              }
              var renderTargets = frameBuffer.colorTextures;
              for (var j = 0; j < renderTargets.length; j++) {
                var renderTarget = renderTargets[j];
                if (renderTarget) {
                  renderTarget.destroy();
                }
              }
              renderTargets.length = 0;
              var depth = frameBuffer.depthStencilTexture;
              if (depth) {
                depth.destroy();
              }
              frameBuffer.destroy();
            }
            shadowFrameBufferMap.clear();
          }
          if (this._shadowRenderPass) {
            this._shadowRenderPass.destroy();
          }
        };
        _proto._initShadowFrameBuffer = function _initShadowFrameBuffer(pipeline, light, swapchain) {
          var device = pipeline.device;
          var shadows = pipeline.pipelineSceneData.shadows;
          var shadowMapSize = shadows.size;
          var shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap;
          var format = supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8;
          if (!this._shadowRenderPass) {
            var colorAttachment = new ColorAttachment();
            colorAttachment.format = format;
            colorAttachment.loadOp = LoadOp.CLEAR;
            colorAttachment.storeOp = StoreOp.STORE;
            colorAttachment.sampleCount = 1;
            var depthStencilAttachment = new DepthStencilAttachment();
            depthStencilAttachment.format = Format.DEPTH_STENCIL;
            depthStencilAttachment.depthLoadOp = LoadOp.CLEAR;
            depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;
            depthStencilAttachment.stencilLoadOp = LoadOp.CLEAR;
            depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
            depthStencilAttachment.sampleCount = 1;
            var renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment);
            this._shadowRenderPass = device.createRenderPass(renderPassInfo);
          }
          var shadowRenderTargets = [];
          shadowRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, format, shadowMapSize.x, shadowMapSize.y)));
          var depth = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.DEPTH_STENCIL_ATTACHMENT, Format.DEPTH_STENCIL, shadowMapSize.x, shadowMapSize.y));
          var shadowFrameBuffer = device.createFramebuffer(new FramebufferInfo(this._shadowRenderPass, shadowRenderTargets, depth));
          shadowFrameBufferMap.set(light, shadowFrameBuffer);
        };
        _proto._renderStage = function _renderStage(camera, light, shadowFrameBuffer, globalDS, level) {
          if (level === void 0) {
            level = 0;
          }
          for (var i = 0; i < this._stages.length; i++) {
            var shadowStage = this._stages[i];
            shadowStage.setUsage(globalDS, light, shadowFrameBuffer, level);
            shadowStage.render(camera);
          }
        };
        _proto.clearShadowMap = function clearShadowMap(validLights, camera) {
          var pipeline = this._pipeline;
          var scene = pipeline.pipelineSceneData;
          var _ref2 = camera.scene,
            mainLight = _ref2.mainLight;
          if (mainLight) {
            var globalDS = this._pipeline.descriptorSet;
            if (!scene.shadowFrameBufferMap.has(mainLight)) {
              this._initShadowFrameBuffer(this._pipeline, mainLight, camera.window.swapchain);
            }
            var shadowFrameBuffer = scene.shadowFrameBufferMap.get(mainLight);
            for (var i = 0; i < this._stages.length; i++) {
              var shadowStage = this._stages[i];
              shadowStage.setUsage(globalDS, mainLight, shadowFrameBuffer);
              shadowStage.clearFramebuffer(camera);
            }
          }
          for (var l = 0; l < validLights.length; l++) {
            var light = validLights[l];
            var ds = pipeline.globalDSManager.getOrCreateDescriptorSet(light);
            if (!scene.shadowFrameBufferMap.has(light)) {
              this._initShadowFrameBuffer(this._pipeline, light, camera.window.swapchain);
            }
            var _shadowFrameBuffer2 = scene.shadowFrameBufferMap.get(light);
            for (var _i = 0; _i < this._stages.length; _i++) {
              var _shadowStage = this._stages[_i];
              _shadowStage.setUsage(ds, light, _shadowFrameBuffer2);
              _shadowStage.clearFramebuffer(camera);
            }
          }
        };
        _proto.resizeShadowMap = function resizeShadowMap() {
          var shadows = this._pipeline.pipelineSceneData.shadows;
          var shadowMapSize = shadows.size;
          var pipeline = this._pipeline;
          var device = pipeline.device;
          var shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap;
          var format = supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8;
          for (var _iterator = _createForOfIteratorHelperLoose(shadowFrameBufferMap.keys()), _step; !(_step = _iterator()).done;) {
            var key = _step.value;
            var frameBuffer = shadowFrameBufferMap.get(key);
            if (!frameBuffer) {
              continue;
            }
            var renderTargets = [];
            renderTargets.push(pipeline.device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, format, shadowMapSize.x, shadowMapSize.y)));
            var depth = frameBuffer.depthStencilTexture;
            if (depth) {
              depth.resize(shadowMapSize.x, shadowMapSize.y);
            }
            var shadowRenderPass = frameBuffer.renderPass;
            frameBuffer.destroy();
            var newFrameBuffer = device.createFramebuffer(new FramebufferInfo(shadowRenderPass, renderTargets, depth));
            shadowFrameBufferMap.set(key, newFrameBuffer);
          }
          shadows.shadowMapDirty = false;
        };
        return ShadowFlow;
      }(RenderFlow), _class2$2P.initInfo = {
        name: PIPELINE_FLOW_SHADOW,
        priority: ForwardFlowPriority.SHADOW,
        tag: RenderFlowTag.SCENE,
        stages: []
      }, _class2$2P)) || _class$37));

      var _dec$3a, _dec2$2m, _class2$2O, _class3$P, _initializer$2B;
      var PIPELINE_TYPE$1 = 1;
      var DeferredRenderData = function (_PipelineRenderData) {
        _inheritsLoose(DeferredRenderData, _PipelineRenderData);
        function DeferredRenderData() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineRenderData.call.apply(_PipelineRenderData, [this].concat(args)) || this;
          _this.gbufferFrameBuffer = null;
          _this.gbufferRenderTargets = [];
          return _this;
        }
        return DeferredRenderData;
      }(PipelineRenderData);
      var DeferredPipeline = exports('dj', (_dec$3a = ccclass$M('DeferredPipeline'), _dec2$2m = type$d([RenderTextureConfig]), _dec$3a(_class2$2O = (_class3$P = function (_RenderPipeline) {
        _inheritsLoose(DeferredPipeline, _RenderPipeline);
        function DeferredPipeline() {
          var _this2;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this2 = _RenderPipeline.call.apply(_RenderPipeline, [this].concat(args)) || this;
          _this2._gbufferRenderPass = null;
          _this2._lightingRenderPass = null;
          _this2.renderTextures = _initializer$2B && _initializer$2B();
          return _this2;
        }
        var _proto = DeferredPipeline.prototype;
        _proto.initialize = function initialize(info) {
          _RenderPipeline.prototype.initialize.call(this, info);
          if (this._flows.length === 0) {
            var shadowFlow = new ShadowFlow();
            shadowFlow.initialize(ShadowFlow.initInfo);
            this._flows.push(shadowFlow);
            var mainFlow = new MainFlow();
            mainFlow.initialize(MainFlow.initInfo);
            this._flows.push(mainFlow);
          }
          return true;
        };
        _proto.activate = function activate(swapchain) {
          this._macros = {
            CC_PIPELINE_TYPE: PIPELINE_TYPE$1
          };
          this._pipelineSceneData = new DeferredPipelineSceneData();
          if (!_RenderPipeline.prototype.activate.call(this, swapchain)) {
            return false;
          }
          if (!this._activeRenderer(swapchain)) {
            errorID(2402);
            return false;
          }
          return true;
        };
        _proto.destroy = function destroy() {
          this._destroyUBOs();
          this._destroyQuadInputAssembler();
          this._destroyDeferredData();
          var rpIter = this._renderPasses.values();
          var rpRes = rpIter.next();
          while (!rpRes.done) {
            rpRes.value.destroy();
            rpRes = rpIter.next();
          }
          this._commandBuffers.length = 0;
          return _RenderPipeline.prototype.destroy.call(this);
        };
        _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {
          this.pipelineSceneData.updatePipelineSceneData();
        };
        _proto.getPipelineRenderData = function getPipelineRenderData() {
          if (!this._pipelineRenderData) {
            this._generateDeferredRenderData();
          }
          return this._pipelineRenderData;
        };
        _proto._activeRenderer = function _activeRenderer(swapchain) {
          var device = this.device;
          this._commandBuffers.push(device.commandBuffer);
          var sampler = this.globalDSManager.pointSampler;
          this._descriptorSet.bindSampler(UNIFORM_SHADOWMAP_BINDING, sampler);
          this._descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          this._descriptorSet.bindSampler(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, sampler);
          this._descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          this._descriptorSet.update();
          var inputAssemblerDataOffscreen = new PipelineInputAssemblerData();
          inputAssemblerDataOffscreen = this._createQuadInputAssembler();
          if (!inputAssemblerDataOffscreen.quadIB || !inputAssemblerDataOffscreen.quadVB || !inputAssemblerDataOffscreen.quadIA) {
            return false;
          }
          this._quadIB = inputAssemblerDataOffscreen.quadIB;
          this._quadVBOffscreen = inputAssemblerDataOffscreen.quadVB;
          this._quadIAOffscreen = inputAssemblerDataOffscreen.quadIA;
          var inputAssemblerDataOnscreen = this._createQuadInputAssembler();
          if (!inputAssemblerDataOnscreen.quadIB || !inputAssemblerDataOnscreen.quadVB || !inputAssemblerDataOnscreen.quadIA) {
            return false;
          }
          this._quadVBOnscreen = inputAssemblerDataOnscreen.quadVB;
          this._quadIAOnscreen = inputAssemblerDataOnscreen.quadIA;
          if (!this._gbufferRenderPass) {
            var colorAttachment0 = new ColorAttachment();
            colorAttachment0.format = Format.RGBA16F;
            colorAttachment0.loadOp = LoadOp.CLEAR;
            colorAttachment0.storeOp = StoreOp.STORE;
            var colorAttachment1 = new ColorAttachment();
            colorAttachment1.format = Format.RGBA16F;
            colorAttachment1.loadOp = LoadOp.CLEAR;
            colorAttachment1.storeOp = StoreOp.STORE;
            var colorAttachment2 = new ColorAttachment();
            colorAttachment2.format = Format.RGBA16F;
            colorAttachment2.loadOp = LoadOp.CLEAR;
            colorAttachment2.storeOp = StoreOp.STORE;
            var depthStencilAttachment = new DepthStencilAttachment();
            depthStencilAttachment.format = Format.DEPTH_STENCIL;
            depthStencilAttachment.depthLoadOp = LoadOp.CLEAR;
            depthStencilAttachment.depthStoreOp = StoreOp.STORE;
            depthStencilAttachment.stencilLoadOp = LoadOp.CLEAR;
            depthStencilAttachment.stencilStoreOp = StoreOp.STORE;
            var renderPassInfo = new RenderPassInfo([colorAttachment0, colorAttachment1, colorAttachment2], depthStencilAttachment);
            this._gbufferRenderPass = device.createRenderPass(renderPassInfo);
          }
          if (!this._lightingRenderPass) {
            var colorAttachment = new ColorAttachment();
            colorAttachment.format = Format.RGBA8;
            colorAttachment.loadOp = LoadOp.CLEAR;
            colorAttachment.storeOp = StoreOp.STORE;
            colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.NONE, AccessFlagBit.COLOR_ATTACHMENT_WRITE));
            var _depthStencilAttachment = new DepthStencilAttachment();
            _depthStencilAttachment.format = Format.DEPTH_STENCIL;
            _depthStencilAttachment.depthLoadOp = LoadOp.LOAD;
            _depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;
            _depthStencilAttachment.stencilLoadOp = LoadOp.LOAD;
            _depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
            colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE, AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE));
            var _renderPassInfo = new RenderPassInfo([colorAttachment], _depthStencilAttachment);
            this._lightingRenderPass = device.createRenderPass(_renderPassInfo);
          }
          this._width = swapchain.width;
          this._height = swapchain.height;
          this._generateDeferredRenderData();
          return true;
        };
        _proto._destroyUBOs = function _destroyUBOs() {
          if (this._descriptorSet) {
            this._descriptorSet.getBuffer(UBOGlobal.BINDING).destroy();
            this._descriptorSet.getBuffer(UBOShadow.BINDING).destroy();
            this._descriptorSet.getBuffer(UBOCamera.BINDING).destroy();
            this._descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy();
            this._descriptorSet.getTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING).destroy();
          }
        };
        _proto._destroyDeferredData = function _destroyDeferredData() {
          var deferredData = this._pipelineRenderData;
          if (deferredData) {
            if (deferredData.gbufferFrameBuffer) deferredData.gbufferFrameBuffer.destroy();
            if (deferredData.outputFrameBuffer) deferredData.outputFrameBuffer.destroy();
            if (deferredData.outputDepth) deferredData.outputDepth.destroy();
            for (var i = 0; i < deferredData.gbufferRenderTargets.length; i++) {
              deferredData.gbufferRenderTargets[i].destroy();
            }
            deferredData.gbufferRenderTargets.length = 0;
            for (var _i = 0; _i < deferredData.outputRenderTargets.length; _i++) {
              deferredData.outputRenderTargets[_i].destroy();
            }
            deferredData.outputRenderTargets.length = 0;
            this._destroyBloomData();
          }
          this._pipelineRenderData = null;
        };
        _proto._ensureEnoughSize = function _ensureEnoughSize(cameras) {
          var newWidth = this._width;
          var newHeight = this._height;
          for (var i = 0; i < cameras.length; ++i) {
            var window = cameras[i].window;
            newWidth = Math.max(window.width, newWidth);
            newHeight = Math.max(window.height, newHeight);
          }
          if (newWidth !== this._width || newHeight !== this._height) {
            this._width = newWidth;
            this._height = newHeight;
            this._destroyDeferredData();
            this._generateDeferredRenderData();
          }
        };
        _proto._generateDeferredRenderData = function _generateDeferredRenderData() {
          var _this3 = this;
          var device = this.device;
          var data = this._pipelineRenderData = new DeferredRenderData();
          var sceneData = this.pipelineSceneData;
          for (var i = 0; i < 3; ++i) {
            data.gbufferRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA16F, this._width * sceneData.shadingScale, this._height * sceneData.shadingScale)));
          }
          data.outputDepth = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.DEPTH_STENCIL_ATTACHMENT | TextureUsageBit.SAMPLED, Format.DEPTH_STENCIL, this._width * sceneData.shadingScale, this._height * sceneData.shadingScale));
          data.gbufferFrameBuffer = device.createFramebuffer(new FramebufferInfo(this._gbufferRenderPass, data.gbufferRenderTargets, data.outputDepth));
          data.outputRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA16F, this._width * sceneData.shadingScale, this._height * sceneData.shadingScale)));
          data.outputFrameBuffer = device.createFramebuffer(new FramebufferInfo(this._lightingRenderPass, data.outputRenderTargets, null));
          data.sampler = this.globalDSManager.pointSampler;
          this.on(PipelineEventType.ATTACHMENT_SCALE_CAHNGED, function (val) {
            data.sampler = val < 1 ? _this3.globalDSManager.pointSampler : _this3.globalDSManager.linearSampler;
            data.gbufferFrameBuffer = _this3.newFramebufferByRatio(data.gbufferFrameBuffer);
            data.gbufferFrameBuffer = _this3.newFramebufferByRatio(data.outputFrameBuffer);
          });
        };
        return DeferredPipeline;
      }(RenderPipeline), (_initializer$2B = applyDecoratedInitializer(_class3$P.prototype, "renderTextures", [_dec2$2m, serializable$p], function () {
        return [];
      })), _class3$P)) || _class2$2O));

      var _lightPassPool = new Pool(function () {
        return {
          subModel: null,
          passIdx: -1,
          dynamicOffsets: [],
          lights: []
        };
      }, 16);
      var _v3$1 = new Vec3();
      var _vec4Array = new Float32Array(4);
      var _dynamicOffsets = [];
      var _lightIndices = [];
      var _matShadowView = new Mat4();
      var _matShadowViewProj = new Mat4();
      var _rangedDirLightBoundingBox = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5);
      var _tmpBoundingBox = new AABB();
      function cullSphereLight(light, model) {
        return !!(model.worldBounds && !intersect.aabbWithAABB(model.worldBounds, light.aabb));
      }
      function cullSpotLight(light, model) {
        return !!(model.worldBounds && (!intersect.aabbWithAABB(model.worldBounds, light.aabb) || !intersect.aabbFrustum(model.worldBounds, light.frustum)));
      }
      function cullPointLight(light, model) {
        return !!(model.worldBounds && !intersect.aabbWithAABB(model.worldBounds, light.aabb));
      }
      function cullRangedDirLight(light, model) {
        AABB.transform(_tmpBoundingBox, _rangedDirLightBoundingBox, light.node.getWorldMatrix());
        return !!(model.worldBounds && !intersect.aabbWithAABB(model.worldBounds, _tmpBoundingBox));
      }
      var phaseName = 'forward-add';
      var _phaseID$2 = getPhaseID(phaseName);
      var _lightPassIndices = [];
      function getLightPassIndices(subModels, lightPassIndices, passLayout) {
        if (passLayout === void 0) {
          passLayout = 'default';
        }
        var r = legacyCC.rendering;
        if (isEnableEffect()) {
          _phaseID$2 = r.getPhaseID(r.getPassID(passLayout), phaseName);
        }
        lightPassIndices.length = 0;
        var hasValidLightPass = false;
        for (var j = 0; j < subModels.length; j++) {
          var passes = subModels[j].passes;
          var lightPassIndex = -1;
          for (var k = 0; k < passes.length; k++) {
            if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseID$2 || isEnableEffect() && passes[k].phaseID === _phaseID$2) {
              lightPassIndex = k;
              hasValidLightPass = true;
              break;
            }
          }
          lightPassIndices.push(lightPassIndex);
        }
        return hasValidLightPass;
      }
      var RenderAdditiveLightQueue = function () {
        function RenderAdditiveLightQueue(pipeline) {
          this._pipeline = void 0;
          this._device = void 0;
          this._lightPasses = [];
          this._instancedLightPassPool = _lightPassPool.alloc();
          this._shadowUBO = new Float32Array(UBOShadow.COUNT);
          this._lightBufferCount = 16;
          this._lightBufferStride = void 0;
          this._lightBufferElementCount = void 0;
          this._lightBuffer = void 0;
          this._firstLightBufferView = void 0;
          this._lightBufferData = void 0;
          this._instancedQueues = [];
          this._lightMeterScale = 10000.0;
          this._pipeline = pipeline;
          this._device = pipeline.device;
          var alignment = this._device.capabilities.uboOffsetAlignment;
          this._lightBufferStride = Math.ceil(UBOForwardLight.SIZE / alignment) * alignment;
          this._lightBufferElementCount = this._lightBufferStride / Float32Array.BYTES_PER_ELEMENT;
          this._lightBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, this._lightBufferStride * this._lightBufferCount, this._lightBufferStride));
          this._firstLightBufferView = this._device.createBuffer(new BufferViewInfo(this._lightBuffer, 0, UBOForwardLight.SIZE));
          this._lightBufferData = new Float32Array(this._lightBufferElementCount * this._lightBufferCount);
        }
        var _proto = RenderAdditiveLightQueue.prototype;
        _proto.clear = function clear() {
          this._instancedQueues.forEach(function (instancedQueue) {
            instancedQueue.clear();
          });
          this._instancedQueues.length = 0;
          for (var i = 0; i < this._lightPasses.length; i++) {
            var lp = this._lightPasses[i];
            lp.dynamicOffsets.length = 0;
            lp.lights.length = 0;
          }
          _lightPassPool.freeArray(this._lightPasses);
          this._lightPasses.length = 0;
          this._instancedLightPassPool.dynamicOffsets.length = 0;
          this._instancedLightPassPool.lights.length = 0;
        };
        _proto.destroy = function destroy() {
          var descriptorSetMap = this._pipeline.globalDSManager.descriptorSetMap;
          var keys = descriptorSetMap.keys;
          for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            var descriptorSet = descriptorSetMap.get(key);
            if (descriptorSet) {
              var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
              descriptorSet.getBuffer(binding).destroy();
              descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy();
              descriptorSet.getTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING).destroy();
              descriptorSet.destroy();
            }
            descriptorSetMap["delete"](key);
          }
        };
        _proto._bindForwardAddLight = function _bindForwardAddLight(validPunctualLights, passLayout) {
          if (passLayout === void 0) {
            passLayout = 'default';
          }
          var renderObjects = this._pipeline.pipelineSceneData.renderObjects;
          for (var i = 0; i < renderObjects.length; i++) {
            var ro = renderObjects[i];
            var model = ro.model;
            var subModels = model.subModels;
            if (!getLightPassIndices(subModels, _lightPassIndices, passLayout)) {
              continue;
            }
            _lightIndices.length = 0;
            this._lightCulling(model, validPunctualLights);
            if (!_lightIndices.length && validPunctualLights.length > 0) {
              continue;
            }
            for (var j = 0; j < subModels.length; j++) {
              var lightPassIdx = _lightPassIndices[j];
              if (lightPassIdx < 0) {
                continue;
              }
              var subModel = subModels[j];
              var pass = subModel.passes[lightPassIdx];
              var isTransparent = subModel.passes[0].blendState.targets[0].blend;
              if (isTransparent) {
                continue;
              }
              isEnableEffect() ? getDescBindingFromName('CCForwardLight') : UBOForwardLight.BINDING;
              subModel.descriptorSet.bindBuffer(UBOForwardLight.BINDING, this._firstLightBufferView);
              subModel.descriptorSet.update();
              this._addRenderQueue(pass, subModel, model, lightPassIdx);
            }
          }
        };
        _proto.gatherLightPasses = function gatherLightPasses(camera, cmdBuff, passLayout) {
          if (passLayout === void 0) {
            passLayout = 'default';
          }
          this.clear();
          var validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights;
          if (!validPunctualLights.length) {
            this._bindForwardAddLight(validPunctualLights, passLayout);
            return;
          }
          this._updateUBOs(camera, cmdBuff);
          this._updateLightDescriptorSet(camera, cmdBuff);
          this._bindForwardAddLight(validPunctualLights, passLayout);
          for (var l = 0; l < validPunctualLights.length; l++) {
            var light = validPunctualLights[l];
            this._instancedLightPassPool.lights.push(light);
            this._instancedLightPassPool.dynamicOffsets.push(this._lightBufferStride * l);
          }
          this._instancedQueues.forEach(function (instancedQueue) {
            instancedQueue.uploadBuffers(cmdBuff);
          });
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
          var globalDSManager = this._pipeline.globalDSManager;
          for (var j = 0; j < this._instancedQueues.length; ++j) {
            var light = this._instancedLightPassPool.lights[j];
            _dynamicOffsets[0] = this._instancedLightPassPool.dynamicOffsets[j];
            var descriptorSet = globalDSManager.getOrCreateDescriptorSet(light);
            this._instancedQueues[j].recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets);
          }
          for (var i = 0; i < this._lightPasses.length; i++) {
            var _this$_lightPasses$i = this._lightPasses[i],
              subModel = _this$_lightPasses$i.subModel,
              passIdx = _this$_lightPasses$i.passIdx,
              dynamicOffsets = _this$_lightPasses$i.dynamicOffsets,
              lights = _this$_lightPasses$i.lights;
            var pass = subModel.passes[passIdx];
            var shader = subModel.shaders[passIdx];
            var ia = subModel.inputAssembler;
            var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, ia);
            var matDS = pass.descriptorSet;
            var localDS = subModel.descriptorSet;
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, matDS);
            cmdBuff.bindInputAssembler(ia);
            for (var _j = 0; _j < dynamicOffsets.length; ++_j) {
              var _light = lights[_j];
              var _descriptorSet = globalDSManager.getOrCreateDescriptorSet(_light);
              _dynamicOffsets[0] = dynamicOffsets[_j];
              cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, _descriptorSet);
              cmdBuff.bindDescriptorSet(SetIndex.LOCAL, localDS, _dynamicOffsets);
              cmdBuff.draw(ia);
            }
          }
        };
        _proto._lightCulling = function _lightCulling(model, validPunctualLights) {
          var isCulled = false;
          for (var l = 0; l < validPunctualLights.length; l++) {
            var light = validPunctualLights[l];
            switch (light.type) {
              case LightType.SPHERE:
                isCulled = cullSphereLight(light, model);
                break;
              case LightType.SPOT:
                isCulled = cullSpotLight(light, model);
                break;
              case LightType.POINT:
                isCulled = cullPointLight(light, model);
                break;
              case LightType.RANGED_DIRECTIONAL:
                isCulled = cullRangedDirLight(light, model);
                break;
            }
            if (!isCulled) {
              _lightIndices.push(l);
            }
          }
        };
        _proto._addRenderQueue = function _addRenderQueue(pass, subModel, model, lightPassIdx) {
          var validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights;
          var batchingScheme = pass.batchingScheme;
          var lp = null;
          if (batchingScheme === BatchingSchemes.NONE) {
            lp = _lightPassPool.alloc();
            lp.subModel = subModel;
            lp.passIdx = lightPassIdx;
          }
          for (var l = 0; l < _lightIndices.length; l++) {
            var lightIdx = _lightIndices[l];
            var light = validPunctualLights[lightIdx];
            var visibility = light.visibility;
            if ((visibility & model.node.layer) === model.node.layer) {
              switch (batchingScheme) {
                case BatchingSchemes.INSTANCING:
                  {
                    var buffer = pass.getInstancedBuffer(l);
                    buffer.merge(subModel, lightPassIdx);
                    buffer.dynamicOffsets[0] = this._lightBufferStride;
                    if (!this._instancedQueues[l]) {
                      this._instancedQueues[l] = new RenderInstancedQueue();
                    }
                    this._instancedQueues[l].queue.add(buffer);
                  }
                  break;
                default:
                  lp.lights.push(light);
                  lp.dynamicOffsets.push(this._lightBufferStride * lightIdx);
              }
            }
          }
          if (batchingScheme === BatchingSchemes.NONE) {
            this._lightPasses.push(lp);
          }
        };
        _proto._updateLightDescriptorSet = function _updateLightDescriptorSet(camera, cmdBuff) {
          var device = this._pipeline.device;
          var sceneData = this._pipeline.pipelineSceneData;
          var shadowInfo = sceneData.shadows;
          var shadowFrameBufferMap = sceneData.shadowFrameBufferMap;
          var mainLight = camera.scene.mainLight;
          var packing = supportsR32FloatTexture(device) ? 0.0 : 1.0;
          var globalDSManager = this._pipeline.globalDSManager;
          var validPunctualLights = sceneData.validPunctualLights;
          var cap = this._pipeline.device.capabilities;
          for (var i = 0; i < validPunctualLights.length; i++) {
            var light = validPunctualLights[i];
            var descriptorSet = globalDSManager.getOrCreateDescriptorSet(light);
            if (!descriptorSet) {
              continue;
            }
            var matShadowProj = void 0;
            var matShadowInvProj = void 0;
            switch (light.type) {
              case LightType.SPHERE:
                {
                  if (mainLight) {
                    PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO);
                  }
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = 1.0;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.SPHERE;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
                  Color$1.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
                  break;
                }
              case LightType.SPOT:
                {
                  var spotLight = light;
                  if (mainLight) {
                    PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO);
                  }
                  Mat4.invert(_matShadowView, light.node.getWorldMatrix());
                  Mat4.perspective(_matShadowViewProj, light.angle, 1.0, 0.001, light.range, true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0);
                  matShadowProj = _matShadowViewProj.clone();
                  matShadowInvProj = _matShadowViewProj.clone().invert();
                  Mat4.multiply(_matShadowViewProj, _matShadowViewProj, _matShadowView);
                  Mat4.toArray(this._shadowUBO, _matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                  Mat4.toArray(this._shadowUBO, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET);
                  this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 0] = 0.01;
                  this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 1] = light.range;
                  this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 2] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 3] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = spotLight.shadowPcf;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = spotLight.shadowBias;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.SPOT;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = spotLight.shadowNormalBias;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15;
                  this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowInvProj.m10;
                  this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowInvProj.m14;
                  this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowInvProj.m11;
                  this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowInvProj.m15;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05;
                  Color$1.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
                  if (shadowFrameBufferMap.has(light)) {
                    var _shadowFrameBufferMap;
                    var texture = (_shadowFrameBufferMap = shadowFrameBufferMap.get(light)) === null || _shadowFrameBufferMap === void 0 ? void 0 : _shadowFrameBufferMap.colorTextures[0];
                    if (texture) {
                      descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, texture);
                    }
                  }
                  break;
                }
              case LightType.POINT:
                {
                  if (mainLight) {
                    PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO);
                  }
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = 1.0;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.POINT;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
                  Color$1.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
                  break;
                }
            }
            descriptorSet.update();
            var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
            cmdBuff.updateBuffer(descriptorSet.getBuffer(binding), this._shadowUBO);
          }
        };
        _proto._updateUBOs = function _updateUBOs(camera, cmdBuff) {
          var exposure = camera.exposure;
          var sceneData = this._pipeline.pipelineSceneData;
          var isHDR = sceneData.isHDR;
          var shadowInfo = sceneData.shadows;
          var validPunctualLights = sceneData.validPunctualLights;
          if (validPunctualLights.length > this._lightBufferCount) {
            this._firstLightBufferView.destroy();
            this._lightBufferCount = nextPow2(validPunctualLights.length);
            this._lightBuffer.resize(this._lightBufferStride * this._lightBufferCount);
            this._lightBufferData = new Float32Array(this._lightBufferElementCount * this._lightBufferCount);
            this._firstLightBufferView = deviceManager.gfxDevice.createBuffer(new BufferViewInfo(this._lightBuffer, 0, UBOForwardLight.SIZE));
          }
          for (var l = 0, offset = 0; l < validPunctualLights.length; l++, offset += this._lightBufferElementCount) {
            var light = validPunctualLights[l];
            switch (light.type) {
              case LightType.SPHERE:
                Vec3.toArray(_vec4Array, light.position);
                _vec4Array[3] = LightType.SPHERE;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET);
                _vec4Array[0] = light.size;
                _vec4Array[1] = light.range;
                _vec4Array[2] = 0.0;
                _vec4Array[3] = 0.0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET);
                Vec3.toArray(_vec4Array, light.color);
                if (light.useColorTemperature) {
                  var finalColor = light.finalColor;
                  _vec4Array[0] = finalColor.x;
                  _vec4Array[1] = finalColor.y;
                  _vec4Array[2] = finalColor.z;
                }
                if (isHDR) {
                  _vec4Array[3] = light.luminance * exposure * this._lightMeterScale;
                } else {
                  _vec4Array[3] = light.luminance;
                }
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET);
                break;
              case LightType.SPOT:
                Vec3.toArray(_vec4Array, light.position);
                _vec4Array[3] = LightType.SPOT;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET);
                _vec4Array[0] = light.size;
                _vec4Array[1] = light.range;
                _vec4Array[2] = light.spotAngle;
                _vec4Array[3] = shadowInfo.enabled && light.shadowEnabled && shadowInfo.type === ShadowType.ShadowMap ? 1 : 0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET);
                Vec3.toArray(_vec4Array, light.direction);
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_DIR_OFFSET);
                Vec3.toArray(_vec4Array, light.color);
                if (light.useColorTemperature) {
                  var _finalColor = light.finalColor;
                  _vec4Array[0] = _finalColor.x;
                  _vec4Array[1] = _finalColor.y;
                  _vec4Array[2] = _finalColor.z;
                }
                if (isHDR) {
                  _vec4Array[3] = light.luminance * exposure * this._lightMeterScale;
                } else {
                  _vec4Array[3] = light.luminance;
                }
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET);
                _vec4Array[0] = 0;
                _vec4Array[1] = 0;
                _vec4Array[2] = 0;
                _vec4Array[3] = light.angleAttenuationStrength;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET);
                break;
              case LightType.POINT:
                Vec3.toArray(_vec4Array, light.position);
                _vec4Array[3] = LightType.POINT;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET);
                _vec4Array[0] = 0.0;
                _vec4Array[1] = light.range;
                _vec4Array[2] = 0.0;
                _vec4Array[3] = 0.0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET);
                Vec3.toArray(_vec4Array, light.color);
                if (light.useColorTemperature) {
                  var _finalColor2 = light.finalColor;
                  _vec4Array[0] = _finalColor2.x;
                  _vec4Array[1] = _finalColor2.y;
                  _vec4Array[2] = _finalColor2.z;
                }
                if (isHDR) {
                  _vec4Array[3] = light.luminance * exposure * this._lightMeterScale;
                } else {
                  _vec4Array[3] = light.luminance;
                }
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET);
                break;
              case LightType.RANGED_DIRECTIONAL:
                Vec3.toArray(_vec4Array, light.position);
                _vec4Array[3] = LightType.RANGED_DIRECTIONAL;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET);
                Vec3.toArray(_vec4Array, light.right);
                _vec4Array[3] = 0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET);
                Vec3.toArray(_vec4Array, light.direction);
                _vec4Array[3] = 0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_DIR_OFFSET);
                var scale = light.scale;
                _v3$1.set(scale.x * 0.5, scale.y * 0.5, scale.z * 0.5);
                Vec3.toArray(_vec4Array, _v3$1);
                _vec4Array[3] = 0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET);
                Vec3.toArray(_vec4Array, light.color);
                if (light.useColorTemperature) {
                  var _finalColor3 = light.finalColor;
                  _vec4Array[0] = _finalColor3.x;
                  _vec4Array[1] = _finalColor3.y;
                  _vec4Array[2] = _finalColor3.z;
                }
                if (isHDR) {
                  _vec4Array[3] = light.illuminance * exposure;
                } else {
                  _vec4Array[3] = light.illuminance;
                }
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET);
                break;
            }
          }
          cmdBuff.updateBuffer(this._lightBuffer, this._lightBufferData);
        };
        return RenderAdditiveLightQueue;
      }();

      var _dec$39, _dec2$2l, _class$36, _class2$2N, _initializer$2A, _class3$O;
      var colors$1 = [new Color(0, 0, 0, 1)];
      var ForwardStage = exports('di', (_dec$39 = ccclass$M('ForwardStage'), _dec2$2l = type$d([RenderQueueDesc]), _dec$39(_class$36 = (_class2$2N = (_class3$O = function (_RenderStage) {
        _inheritsLoose(ForwardStage, _RenderStage);
        function ForwardStage() {
          var _this;
          _this = _RenderStage.call(this) || this;
          _this.renderQueues = _initializer$2A && _initializer$2A();
          _this._renderQueues = [];
          _this._renderArea = new Rect();
          _this._instancedQueue = void 0;
          _this._phaseID = getPhaseID('default');
          _this._clearFlag = 0xffffffff;
          _this.additiveInstanceQueues = [];
          _this._instancedQueue = new RenderInstancedQueue();
          _this._uiPhase = new UIPhase();
          return _this;
        }
        var _proto = ForwardStage.prototype;
        _proto.addRenderInstancedQueue = function addRenderInstancedQueue(queue) {
          if (this.additiveInstanceQueues.includes(queue)) {
            return;
          }
          this.additiveInstanceQueues.push(queue);
        };
        _proto.removeRenderInstancedQueue = function removeRenderInstancedQueue(queue) {
          var index = this.additiveInstanceQueues.indexOf(queue);
          if (index > -1) {
            this.additiveInstanceQueues.splice(index, 1);
          }
        };
        _proto.initialize = function initialize(info) {
          _RenderStage.prototype.initialize.call(this, info);
          if (info.renderQueues) {
            this.renderQueues = info.renderQueues;
          }
          return true;
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          for (var i = 0; i < this.renderQueues.length; i++) {
            this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]);
          }
          this._additiveLightQueue = new RenderAdditiveLightQueue(this._pipeline);
          this._planarQueue = new PlanarShadowQueue(this._pipeline);
          this._uiPhase.activate(pipeline);
        };
        _proto.destroy = function destroy() {};
        _proto.render = function render(camera) {
          var _camera$geometryRende;
          this._instancedQueue.clear();
          var pipeline = this._pipeline;
          var device = pipeline.device;
          this._renderQueues.forEach(renderQueueClearFunc);
          var renderObjects = pipeline.pipelineSceneData.renderObjects;
          var m = 0;
          var p = 0;
          var k = 0;
          for (var i = 0; i < renderObjects.length; ++i) {
            var ro = renderObjects[i];
            var subModels = ro.model.subModels;
            for (m = 0; m < subModels.length; ++m) {
              var subModel = subModels[m];
              var passes = subModel.passes;
              for (p = 0; p < passes.length; ++p) {
                var pass = passes[p];
                if (pass.phase !== this._phaseID) continue;
                var batchingScheme = pass.batchingScheme;
                if (batchingScheme === BatchingSchemes.INSTANCING) {
                  var instancedBuffer = pass.getInstancedBuffer();
                  instancedBuffer.merge(subModel, p);
                  this._instancedQueue.queue.add(instancedBuffer);
                } else {
                  for (k = 0; k < this._renderQueues.length; k++) {
                    this._renderQueues[k].insertRenderPass(ro, m, p);
                  }
                }
              }
            }
          }
          this._instancedQueue.sort();
          this._renderQueues.forEach(renderQueueSortFunc);
          var cmdBuff = pipeline.commandBuffers[0];
          pipeline.pipelineUBO.updateShadowUBO(camera);
          for (var _i = 0; _i < this.additiveInstanceQueues.length; _i++) {
            this.additiveInstanceQueues[_i].uploadBuffers(cmdBuff);
          }
          this._instancedQueue.uploadBuffers(cmdBuff);
          this._additiveLightQueue.gatherLightPasses(camera, cmdBuff);
          this._planarQueue.gatherShadowPasses(camera, cmdBuff);
          if (camera.clearFlag & ClearFlagBit.COLOR) {
            colors$1[0].x = camera.clearColor.x;
            colors$1[0].y = camera.clearColor.y;
            colors$1[0].z = camera.clearColor.z;
            colors$1[0].w = camera.clearColor.w;
          }
          pipeline.generateRenderArea(camera, this._renderArea);
          var framebuffer = camera.window.framebuffer;
          var renderPass = pipeline.getRenderPass(camera.clearFlag & this._clearFlag, framebuffer);
          cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors$1, camera.clearDepth, camera.clearStencil);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          this._renderQueues[0].recordCommandBuffer(device, renderPass, cmdBuff);
          for (var _i2 = 0; _i2 < this.additiveInstanceQueues.length; _i2++) {
            this.additiveInstanceQueues[_i2].recordCommandBuffer(device, renderPass, cmdBuff);
          }
          this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          this._additiveLightQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          this._renderQueues[1].recordCommandBuffer(device, renderPass, cmdBuff);
          (_camera$geometryRende = camera.geometryRenderer) === null || _camera$geometryRende === void 0 ? void 0 : _camera$geometryRende.render(renderPass, cmdBuff, pipeline.pipelineSceneData);
          this._uiPhase.render(camera, renderPass);
          renderProfiler(device, renderPass, cmdBuff, pipeline.profiler, camera);
          cmdBuff.endRenderPass();
        };
        return ForwardStage;
      }(RenderStage), _class3$O.initInfo = {
        name: 'ForwardStage',
        priority: ForwardStagePriority.FORWARD,
        tag: 0,
        renderQueues: [{
          isTransparent: false,
          sortMode: RenderQueueSortMode.FRONT_TO_BACK,
          stages: ['default']
        }, {
          isTransparent: true,
          sortMode: RenderQueueSortMode.BACK_TO_FRONT,
          stages: ['default', 'planarShadow']
        }]
      }, _class3$O), (_initializer$2A = applyDecoratedInitializer(_class2$2N.prototype, "renderQueues", [_dec2$2l, serializable$p], function () {
        return [];
      })), _class2$2N)) || _class$36));

      var _dec$38, _class$35, _class2$2M;
      var ForwardFlow = exports('dh', (_dec$38 = ccclass$M('ForwardFlow'), _dec$38(_class$35 = (_class2$2M = function (_RenderFlow) {
        _inheritsLoose(ForwardFlow, _RenderFlow);
        function ForwardFlow() {
          return _RenderFlow.apply(this, arguments) || this;
        }
        var _proto = ForwardFlow.prototype;
        _proto.initialize = function initialize(info) {
          _RenderFlow.prototype.initialize.call(this, info);
          if (this._stages.length === 0) {
            var forwardStage = new ForwardStage();
            forwardStage.initialize(ForwardStage.initInfo);
            this._stages.push(forwardStage);
          }
          return true;
        };
        _proto.activate = function activate(pipeline) {
          _RenderFlow.prototype.activate.call(this, pipeline);
        };
        _proto.render = function render(camera) {
          _RenderFlow.prototype.render.call(this, camera);
        };
        _proto.destroy = function destroy() {
          _RenderFlow.prototype.destroy.call(this);
        };
        return ForwardFlow;
      }(RenderFlow), _class2$2M.initInfo = {
        name: PIPELINE_FLOW_FORWARD,
        priority: ForwardFlowPriority.FORWARD,
        stages: []
      }, _class2$2M)) || _class$35));

      var CC_USE_RGBE_OUTPUT = 'CC_USE_RGBE_OUTPUT';
      var _phaseID$1 = getPhaseID('default');
      var _phaseReflectMapID = getPhaseID('reflect-map');
      function getPassIndex(subModel) {
        var passes = subModel.passes;
        var r = legacyCC.rendering;
        if (isEnableEffect()) _phaseID$1 = r.getPhaseID(r.getPassID('default'), 'default');
        for (var k = 0; k < passes.length; k++) {
          if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseID$1 || isEnableEffect() && passes[k].phaseID === _phaseID$1) {
            return k;
          }
        }
        return -1;
      }
      function getReflectMapPassIndex(subModel) {
        var passes = subModel.passes;
        var r = legacyCC.rendering;
        if (isEnableEffect()) _phaseReflectMapID = r.getPhaseID(r.getPassID('default'), 'reflect-map');
        for (var k = 0; k < passes.length; k++) {
          if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseReflectMapID || isEnableEffect() && passes[k].phaseID === _phaseReflectMapID) {
            return k;
          }
        }
        return -1;
      }
      var RenderReflectionProbeQueue = function () {
        function RenderReflectionProbeQueue(pipeline) {
          this._pipeline = void 0;
          this._subModelsArray = [];
          this._passArray = [];
          this._shaderArray = [];
          this._rgbeSubModelsArray = [];
          this._instancedQueue = void 0;
          this._patches = [];
          this._pipeline = pipeline;
          this._instancedQueue = new RenderInstancedQueue();
        }
        var _proto = RenderReflectionProbeQueue.prototype;
        _proto.gatherRenderObjects = function gatherRenderObjects(probe, camera, cmdBuff) {
          this.clear();
          var scene = camera.scene;
          var sceneData = this._pipeline.pipelineSceneData;
          var skybox = sceneData.skybox;
          if (skybox.enabled && skybox.model && probe.camera.clearFlag & SKYBOX_FLAG) {
            this.add(skybox.model);
          }
          var models = scene.models;
          var visibility = probe.visibility;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (!model.node || scene.isCulledByLod(camera, model)) {
              continue;
            }
            if ((visibility & model.node.layer) !== model.node.layer && !(visibility & model.visFlags)) {
              continue;
            }
            if (model.enabled && model.worldBounds && model.bakeToReflectionProbe) {
              if (probe.probeType === ProbeType.CUBE) {
                if (intersect.aabbWithAABB(model.worldBounds, probe.boundingBox)) {
                  this.add(model);
                }
              } else if (intersect.aabbFrustum(model.worldBounds, probe.camera.frustum)) {
                this.add(model);
              }
            }
          }
          this._instancedQueue.uploadBuffers(cmdBuff);
        };
        _proto.clear = function clear() {
          this._subModelsArray.length = 0;
          this._shaderArray.length = 0;
          this._passArray.length = 0;
          this._instancedQueue.clear();
          this._rgbeSubModelsArray.length = 0;
        };
        _proto.add = function add(model) {
          var subModels = model.subModels;
          for (var j = 0; j < subModels.length; j++) {
            var subModel = subModels[j];
            var isTransparent = subModel.passes[0].blendState.targets[0].blend;
            if (isTransparent) {
              continue;
            }
            var passIdx = getReflectMapPassIndex(subModel);
            var bUseReflectPass = true;
            if (passIdx < 0) {
              passIdx = getPassIndex(subModel);
              bUseReflectPass = false;
            }
            if (passIdx < 0) {
              continue;
            }
            var pass = subModel.passes[passIdx];
            var batchingScheme = pass.batchingScheme;
            if (!bUseReflectPass) {
              this._patches = [];
              this._patches = this._patches.concat(subModel.patches);
              var useRGBEPatchs = [{
                name: CC_USE_RGBE_OUTPUT,
                value: true
              }];
              this._patches = this._patches.concat(useRGBEPatchs);
              subModel.onMacroPatchesStateChanged(this._patches);
              this._rgbeSubModelsArray.push(subModel);
            }
            if (batchingScheme === BatchingSchemes.INSTANCING) {
              var buffer = pass.getInstancedBuffer();
              buffer.merge(subModel, passIdx);
              this._instancedQueue.queue.add(buffer);
            } else {
              var shader = subModel.shaders[passIdx];
              this._subModelsArray.push(subModel);
              if (shader) this._shaderArray.push(shader);
              this._passArray.push(pass);
            }
          }
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
          this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          for (var i = 0; i < this._subModelsArray.length; ++i) {
            var subModel = this._subModelsArray[i];
            var shader = this._shaderArray[i];
            var pass = this._passArray[i];
            var ia = subModel.inputAssembler;
            var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, ia);
            var descriptorSet = pass.descriptorSet;
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
            cmdBuff.bindInputAssembler(ia);
            cmdBuff.draw(ia);
          }
          this.resetRGBEMacro();
          this._instancedQueue.clear();
        };
        _proto.resetRGBEMacro = function resetRGBEMacro() {
          for (var i = 0; i < this._rgbeSubModelsArray.length; i++) {
            this._patches = [];
            var subModel = this._rgbeSubModelsArray[i];
            this._patches = this._patches.concat(subModel.patches);
            if (!this._patches) continue;
            for (var j = 0; j < this._patches.length; j++) {
              var patch = this._patches[j];
              if (patch.name === CC_USE_RGBE_OUTPUT) {
                this._patches.splice(j, 1);
                break;
              }
            }
            subModel.onMacroPatchesStateChanged(this._patches);
          }
        };
        return RenderReflectionProbeQueue;
      }();

      var _dec$37, _class$34, _class2$2L;
      var colors = [new Color(1, 1, 1, 1)];
      var ReflectionProbeStage = exports('dy', (_dec$37 = ccclass$M('ReflectionProbeStage'), _dec$37(_class$34 = (_class2$2L = function (_RenderStage) {
        _inheritsLoose(ReflectionProbeStage, _RenderStage);
        function ReflectionProbeStage() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderStage.call.apply(_RenderStage, [this].concat(args)) || this;
          _this._frameBuffer = null;
          _this._renderArea = new Rect();
          _this._probe = null;
          _this._probeRenderQueue = void 0;
          _this._rgbeColor = new Vec3();
          return _this;
        }
        var _proto = ReflectionProbeStage.prototype;
        _proto.setUsageInfo = function setUsageInfo(probe, frameBuffer) {
          this._probe = probe;
          this._frameBuffer = frameBuffer;
        };
        _proto.destroy = function destroy() {
          var _this$_probeRenderQue;
          this._frameBuffer = null;
          (_this$_probeRenderQue = this._probeRenderQueue) === null || _this$_probeRenderQue === void 0 ? void 0 : _this$_probeRenderQue.clear();
        };
        _proto.clearFramebuffer = function clearFramebuffer(camera) {
          if (!this._frameBuffer) {
            return;
          }
          colors[0].w = camera.clearColor.w;
          var pipeline = this._pipeline;
          var pipelineSceneData = pipeline.pipelineSceneData;
          var shadingScale = pipelineSceneData.shadingScale;
          var vp = camera.viewport;
          var size = this._probe.resolution;
          this._renderArea.x = vp.x * size;
          this._renderArea.y = vp.y * size;
          this._renderArea.width = vp.width * size * shadingScale;
          this._renderArea.height = vp.height * size * shadingScale;
          var cmdBuff = pipeline.commandBuffers[0];
          var renderPass = this._frameBuffer.renderPass;
          cmdBuff.beginRenderPass(renderPass, this._frameBuffer, this._renderArea, colors, camera.clearDepth, camera.clearStencil);
          cmdBuff.endRenderPass();
        };
        _proto.render = function render(camera) {
          var pipeline = this._pipeline;
          var cmdBuff = pipeline.commandBuffers[0];
          this._probeRenderQueue.gatherRenderObjects(this._probe, camera, cmdBuff);
          pipeline.pipelineUBO.updateCameraUBO(this._probe.camera);
          this._renderArea.x = 0;
          this._renderArea.y = 0;
          this._renderArea.width = this._probe.renderArea().x;
          this._renderArea.height = this._probe.renderArea().y;
          var renderPass = this._frameBuffer.renderPass;
          if (this._probe.camera.clearFlag & ClearFlagBit.COLOR) {
            this._rgbeColor.x = this._probe.camera.clearColor.x;
            this._rgbeColor.y = this._probe.camera.clearColor.y;
            this._rgbeColor.z = this._probe.camera.clearColor.z;
            var rgbe = packRGBE(this._rgbeColor);
            colors[0].x = rgbe.x;
            colors[0].y = rgbe.y;
            colors[0].z = rgbe.z;
            colors[0].w = rgbe.w;
          }
          var device = pipeline.device;
          cmdBuff.beginRenderPass(renderPass, this._frameBuffer, this._renderArea, colors, this._probe.camera.clearDepth, this._probe.camera.clearStencil);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          this._probeRenderQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          cmdBuff.endRenderPass();
          pipeline.pipelineUBO.updateCameraUBO(camera);
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          this._probeRenderQueue = new RenderReflectionProbeQueue(pipeline);
        };
        return ReflectionProbeStage;
      }(RenderStage), _class2$2L.initInfo = {
        name: 'ReflectionProbeStage',
        priority: ForwardStagePriority.FORWARD,
        tag: 0
      }, _class2$2L)) || _class$34));

      var _dec$36, _class$33, _class2$2K;
      var ReflectionProbeFlow = exports('dx', (_dec$36 = ccclass$M('ReflectionProbeFlow'), _dec$36(_class$33 = (_class2$2K = function (_RenderFlow) {
        _inheritsLoose(ReflectionProbeFlow, _RenderFlow);
        function ReflectionProbeFlow() {
          return _RenderFlow.apply(this, arguments) || this;
        }
        var _proto = ReflectionProbeFlow.prototype;
        _proto.initialize = function initialize(info) {
          _RenderFlow.prototype.initialize.call(this, info);
          if (this._stages.length === 0) {
            var probeStage = new ReflectionProbeStage();
            probeStage.initialize(ReflectionProbeStage.initInfo);
            this._stages.push(probeStage);
          }
          return true;
        };
        _proto.activate = function activate(pipeline) {
          _RenderFlow.prototype.activate.call(this, pipeline);
        };
        _proto.render = function render(camera) {
          if (!legacyCC.internal.reflectionProbeManager) {
            return;
          }
          var probes = legacyCC.internal.reflectionProbeManager.getProbes();
          for (var i = 0; i < probes.length; i++) {
            if (probes[i].needRender) {
              if (probes[i].probeType === ProbeType.PLANAR) {
                this._renderStage(camera, probes[i]);
              }
            }
          }
        };
        _proto.destroy = function destroy() {
          _RenderFlow.prototype.destroy.call(this);
        };
        _proto._renderStage = function _renderStage(camera, probe) {
          for (var i = 0; i < this._stages.length; i++) {
            var probeStage = this._stages[i];
            if (probe.probeType === ProbeType.PLANAR) {
              legacyCC.internal.reflectionProbeManager.updatePlanarMap(probe, null);
              probeStage.setUsageInfo(probe, probe.realtimePlanarTexture.window.framebuffer);
              probeStage.render(camera);
              legacyCC.internal.reflectionProbeManager.updatePlanarMap(probe, probe.realtimePlanarTexture.getGFXTexture());
            } else {
              for (var faceIdx = 0; faceIdx < 6; faceIdx++) {
                var renderTexture = probe.bakedCubeTextures[faceIdx];
                if (!renderTexture) return;
                probe.updateCameraDir(faceIdx);
                probeStage.setUsageInfo(probe, renderTexture.window.framebuffer);
                probeStage.render(camera);
              }
              probe.needRender = false;
            }
          }
        };
        return ReflectionProbeFlow;
      }(RenderFlow), _class2$2K.initInfo = {
        name: 'PIPELINE_FLOW_RELECTION_PROBE',
        priority: 0,
        tag: RenderFlowTag.SCENE,
        stages: []
      }, _class2$2K)) || _class$33));

      var _dec$35, _dec2$2k, _class$32, _class2$2J, _initializer$2z;
      var PIPELINE_TYPE = 0;
      function createDefaultPipeline() {
        var rppl = new ForwardPipeline();
        rppl.initialize({
          flows: []
        });
        return rppl;
      }
      var ForwardPipeline = exports('df', (_dec$35 = ccclass$M('ForwardPipeline'), _dec2$2k = type$d([RenderTextureConfig]), _dec$35(_class$32 = (_class2$2J = function (_RenderPipeline) {
        _inheritsLoose(ForwardPipeline, _RenderPipeline);
        function ForwardPipeline() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderPipeline.call.apply(_RenderPipeline, [this].concat(args)) || this;
          _this.renderTextures = _initializer$2z && _initializer$2z();
          _this._postRenderPass = null;
          return _this;
        }
        var _proto = ForwardPipeline.prototype;
        _proto.initialize = function initialize(info) {
          _RenderPipeline.prototype.initialize.call(this, info);
          if (this._flows.length === 0) {
            var shadowFlow = new ShadowFlow();
            shadowFlow.initialize(ShadowFlow.initInfo);
            this._flows.push(shadowFlow);
            var reflectionFlow = new ReflectionProbeFlow();
            reflectionFlow.initialize(ReflectionProbeFlow.initInfo);
            this._flows.push(reflectionFlow);
            var forwardFlow = new ForwardFlow();
            forwardFlow.initialize(ForwardFlow.initInfo);
            this._flows.push(forwardFlow);
          }
          return true;
        };
        _proto.activate = function activate(swapchain) {
          this._macros = {
            CC_PIPELINE_TYPE: PIPELINE_TYPE
          };
          this._pipelineSceneData = new PipelineSceneData();
          if (!_RenderPipeline.prototype.activate.call(this, swapchain)) {
            return false;
          }
          if (!this._activeRenderer(swapchain)) {
            errorID(2402);
            return false;
          }
          return true;
        };
        _proto._ensureEnoughSize = function _ensureEnoughSize(cameras) {
          var newWidth = this._width;
          var newHeight = this._height;
          for (var i = 0; i < cameras.length; ++i) {
            var window = cameras[i].window;
            newWidth = Math.max(window.width, newWidth);
            newHeight = Math.max(window.height, newHeight);
          }
          if (newWidth !== this._width || newHeight !== this._height) {
            this._width = newWidth;
            this._height = newHeight;
          }
        };
        _proto.destroy = function destroy() {
          this._destroyUBOs();
          this._destroyQuadInputAssembler();
          var rpIter = this._renderPasses.values();
          var rpRes = rpIter.next();
          while (!rpRes.done) {
            rpRes.value.destroy();
            rpRes = rpIter.next();
          }
          this._commandBuffers.length = 0;
          return _RenderPipeline.prototype.destroy.call(this);
        };
        _proto._activeRenderer = function _activeRenderer(swapchain) {
          var device = this.device;
          this._commandBuffers.push(device.commandBuffer);
          var shadowMapSampler = this.globalDSManager.pointSampler;
          this._descriptorSet.bindSampler(UNIFORM_SHADOWMAP_BINDING, shadowMapSampler);
          this._descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          this._descriptorSet.bindSampler(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, shadowMapSampler);
          this._descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          this._descriptorSet.update();
          return true;
        };
        _proto._destroyUBOs = function _destroyUBOs() {
          if (this._descriptorSet) {
            this._descriptorSet.getBuffer(UBOGlobal.BINDING).destroy();
            this._descriptorSet.getBuffer(UBOShadow.BINDING).destroy();
            this._descriptorSet.getBuffer(UBOCamera.BINDING).destroy();
            this._descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy();
            this._descriptorSet.getTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING).destroy();
          }
        };
        _createClass(ForwardPipeline, [{
          key: "postRenderPass",
          get: function get() {
            return this._postRenderPass;
          }
        }]);
        return ForwardPipeline;
      }(RenderPipeline), (_initializer$2z = applyDecoratedInitializer(_class2$2J.prototype, "renderTextures", [_dec2$2k, serializable$p], function () {
        return [];
      })), _class2$2J)) || _class$32));

      var _dsInfo$1 = new DescriptorSetInfo(null);
      var MAX_PASS_COUNT = 8;
      var SubModel = function () {
        function SubModel() {
          this._device = null;
          this._passes = null;
          this._shaders = null;
          this._subMesh = null;
          this._patches = null;
          this._priority = RenderPriority.DEFAULT;
          this._inputAssembler = null;
          this._descriptorSet = null;
          this._worldBoundDescriptorSet = null;
          this._reflectionTex = null;
          this._reflectionSampler = null;
          this._instancedAttributeBlock = {
            buffer: null,
            views: [],
            attributes: []
          };
          this._instancedWorldMatrixIndex = -1;
          this._instancedSHIndex = -1;
          this._useReflectionProbeType = 0;
        }
        var _proto = SubModel.prototype;
        _proto.initialize = function initialize(subMesh, passes, patches) {
          if (patches === void 0) {
            patches = null;
          }
          var root = legacyCC.director.root;
          this._device = deviceManager.gfxDevice;
          _dsInfo$1.layout = passes[0].localSetLayout;
          this._inputAssembler = this._device.createInputAssembler(subMesh.iaInfo);
          this._descriptorSet = this._device.createDescriptorSet(_dsInfo$1);
          var pipeline = legacyCC.director.root.pipeline;
          var occlusionPass = pipeline.pipelineSceneData.getOcclusionQueryPass();
          if (occlusionPass) {
            var occlusionDSInfo = new DescriptorSetInfo(null);
            occlusionDSInfo.layout = occlusionPass.localSetLayout;
            this._worldBoundDescriptorSet = this._device.createDescriptorSet(occlusionDSInfo);
          }
          this._subMesh = subMesh;
          this._patches = patches ? patches.sort() : null;
          this._passes = passes;
          this._flushPassInfo();
          this.priority = RenderPriority.DEFAULT;
          var r = legacyCC.rendering;
          if ((!r || !r.enableEffectImport) && passes[0].phase === getPhaseID('reflection') || isEnableEffect() && passes[0].phaseID === r.getPhaseID(r.getPassID('default'), 'reflection')) {
            var texWidth = root.mainWindow.width;
            var texHeight = root.mainWindow.height;
            var minSize = 512;
            if (texHeight < texWidth) {
              texWidth = minSize * texWidth / texHeight;
              texHeight = minSize;
            } else {
              texWidth = minSize;
              texHeight = minSize * texHeight / texWidth;
            }
            this._reflectionTex = this._device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.STORAGE | TextureUsageBit.TRANSFER_SRC | TextureUsageBit.SAMPLED, Format.RGBA8, texWidth, texHeight));
            this.descriptorSet.bindTexture(UNIFORM_REFLECTION_TEXTURE_BINDING, this._reflectionTex);
            this._reflectionSampler = this._device.getSampler(new SamplerInfo(Filter$1.LINEAR, Filter$1.LINEAR, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP));
            this.descriptorSet.bindSampler(UNIFORM_REFLECTION_TEXTURE_BINDING, this._reflectionSampler);
            this.descriptorSet.bindTexture(UNIFORM_REFLECTION_STORAGE_BINDING, this._reflectionTex);
          }
        };
        _proto.destroy = function destroy() {
          var _this$_worldBoundDesc;
          this._descriptorSet.destroy();
          this._descriptorSet = null;
          this._inputAssembler.destroy();
          this._inputAssembler = null;
          (_this$_worldBoundDesc = this._worldBoundDescriptorSet) === null || _this$_worldBoundDesc === void 0 ? void 0 : _this$_worldBoundDesc.destroy();
          this._worldBoundDescriptorSet = null;
          this.priority = RenderPriority.DEFAULT;
          this._patches = null;
          this._subMesh = null;
          this._passes = null;
          this._shaders = null;
          if (this._reflectionTex) this._reflectionTex.destroy();
          this._reflectionTex = null;
          this._reflectionSampler = null;
        };
        _proto.update = function update() {
          var _this$_worldBoundDesc2;
          for (var i = 0; i < this._passes.length; ++i) {
            var pass = this._passes[i];
            pass.update();
          }
          this._descriptorSet.update();
          (_this$_worldBoundDesc2 = this._worldBoundDescriptorSet) === null || _this$_worldBoundDesc2 === void 0 ? void 0 : _this$_worldBoundDesc2.update();
        };
        _proto.onPipelineStateChanged = function onPipelineStateChanged() {
          var passes = this._passes;
          if (!passes) {
            return;
          }
          for (var i = 0; i < passes.length; i++) {
            var pass = passes[i];
            pass.beginChangeStatesSilently();
            pass.tryCompile();
            pass.endChangeStatesSilently();
          }
          this._flushPassInfo();
        };
        _proto.onMacroPatchesStateChanged = function onMacroPatchesStateChanged(patches) {
          if (!patches && !this._patches) {
            return;
          } else if (patches) {
            patches = patches.sort();
            if (this._patches && patches.length === this._patches.length) {
              var patchesStateUnchanged = JSON.stringify(patches) === JSON.stringify(this._patches);
              if (patchesStateUnchanged) return;
            }
          }
          this._patches = patches;
          var passes = this._passes;
          if (!passes) {
            return;
          }
          for (var i = 0; i < passes.length; i++) {
            var pass = passes[i];
            pass.beginChangeStatesSilently();
            pass.tryCompile();
            pass.endChangeStatesSilently();
          }
          this._flushPassInfo();
        };
        _proto.onGeometryChanged = function onGeometryChanged() {
          if (!this._subMesh) {
            return;
          }
          var drawInfo = this._subMesh.drawInfo;
          if (this._inputAssembler && drawInfo) {
            var dirtyDrawInfo = this._inputAssembler.drawInfo;
            Object.keys(drawInfo).forEach(function (key) {
              dirtyDrawInfo[key] = drawInfo[key];
            });
            this._inputAssembler.drawInfo = dirtyDrawInfo;
          }
        };
        _proto.getInstancedAttributeIndex = function getInstancedAttributeIndex(name) {
          var attributes = this.instancedAttributeBlock.attributes;
          for (var i = 0; i < attributes.length; i++) {
            if (attributes[i].name === name) {
              return i;
            }
          }
          return -1;
        };
        _proto.updateInstancedWorldMatrix = function updateInstancedWorldMatrix(mat, idx) {
          var attrs = this.instancedAttributeBlock.views;
          var v1 = attrs[idx];
          var v2 = attrs[idx + 1];
          var v3 = attrs[idx + 2];
          v1[0] = mat.m00;
          v1[1] = mat.m01;
          v1[2] = mat.m02;
          v1[3] = mat.m12;
          v2[0] = mat.m04;
          v2[1] = mat.m05;
          v2[2] = mat.m06;
          v2[3] = mat.m13;
          v3[0] = mat.m08;
          v3[1] = mat.m09;
          v3[2] = mat.m10;
          v3[3] = mat.m14;
        };
        _proto.updateInstancedSH = function updateInstancedSH(data, idx) {
          var attrs = this.instancedAttributeBlock.views;
          var count = (UBOSH.SH_QUADRATIC_R_OFFSET - UBOSH.SH_LINEAR_CONST_R_OFFSET) / 4;
          var offset = 0;
          for (var i = idx; i < idx + count; i++) {
            for (var k = 0; k < 4; k++) {
              attrs[i][k] = data[offset++];
            }
          }
        };
        _proto.UpdateInstancedAttributes = function UpdateInstancedAttributes(attributes) {
          this.instancedWorldMatrixIndex = -1;
          this.instancedSHIndex = -1;
          var pass = this.passes[0];
          if (!pass.device.hasFeature(Feature.INSTANCED_ARRAYS)) {
            return;
          }
          var size = 0;
          for (var j = 0; j < attributes.length; j++) {
            var attribute = attributes[j];
            if (!attribute.isInstanced) {
              continue;
            }
            size += FormatInfos[attribute.format].size;
          }
          var attrs = this.instancedAttributeBlock;
          attrs.buffer = new Uint8Array(size);
          attrs.views.length = attrs.attributes.length = 0;
          var offset = 0;
          for (var _j = 0; _j < attributes.length; _j++) {
            var _attribute = attributes[_j];
            if (!_attribute.isInstanced) {
              continue;
            }
            var attr = new Attribute();
            attr.format = _attribute.format;
            attr.name = _attribute.name;
            attr.isNormalized = _attribute.isNormalized;
            attr.location = _attribute.location;
            attrs.attributes.push(attr);
            var info = FormatInfos[_attribute.format];
            var typeViewArray = new (getTypedArrayConstructor(info))(attrs.buffer.buffer, offset, info.count);
            attrs.views.push(typeViewArray);
            offset += info.size;
          }
          if (pass.batchingScheme === BatchingSchemes.INSTANCING) {
            pass.getInstancedBuffer().destroy();
          }
          this.instancedWorldMatrixIndex = this.getInstancedAttributeIndex(INST_MAT_WORLD);
          this.instancedSHIndex = this.getInstancedAttributeIndex(INST_SH);
        };
        _proto._flushPassInfo = function _flushPassInfo() {
          var passes = this._passes;
          if (!passes) {
            return;
          }
          if (!this._shaders) {
            this._shaders = [];
          }
          this._shaders.length = passes.length;
          for (var i = 0, len = passes.length; i < len; i++) {
            this._shaders[i] = passes[i].getShaderVariant(this.patches);
          }
        };
        _createClass(SubModel, [{
          key: "passes",
          get: function get() {
            return this._passes;
          },
          set: function set(passes) {
            var passLengh = passes.length;
            if (passLengh > MAX_PASS_COUNT) {
              errorID(12004, MAX_PASS_COUNT);
              return;
            }
            this._passes = passes;
            this._flushPassInfo();
            if (this._descriptorSet) {
              this._descriptorSet.destroy();
              _dsInfo$1.layout = passes[0].localSetLayout;
              this._descriptorSet = this._device.createDescriptorSet(_dsInfo$1);
            }
          }
        }, {
          key: "shaders",
          get: function get() {
            return this._shaders;
          }
        }, {
          key: "subMesh",
          get: function get() {
            return this._subMesh;
          },
          set: function set(subMesh) {
            this._inputAssembler.destroy();
            this._inputAssembler = this._device.createInputAssembler(subMesh.iaInfo);
            this._subMesh = subMesh;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(val) {
            this._priority = val;
          }
        }, {
          key: "inputAssembler",
          get: function get() {
            return this._inputAssembler;
          }
        }, {
          key: "descriptorSet",
          get: function get() {
            return this._descriptorSet;
          }
        }, {
          key: "worldBoundDescriptorSet",
          get: function get() {
            return this._worldBoundDescriptorSet;
          }
        }, {
          key: "patches",
          get: function get() {
            return this._patches;
          }
        }, {
          key: "instancedAttributeBlock",
          get: function get() {
            return this._instancedAttributeBlock;
          }
        }, {
          key: "instancedWorldMatrixIndex",
          get: function get() {
            return this._instancedWorldMatrixIndex;
          },
          set: function set(val) {
            this._instancedWorldMatrixIndex = val;
          }
        }, {
          key: "instancedSHIndex",
          get: function get() {
            return this._instancedSHIndex;
          },
          set: function set(val) {
            this._instancedSHIndex = val;
          }
        }, {
          key: "useReflectionProbeType",
          get: function get() {
            return this._useReflectionProbeType;
          },
          set: function set(val) {
            this._useReflectionProbeType = val;
          }
        }]);
        return SubModel;
      }();

      var ReflectionProbeType; exports('ap', ReflectionProbeType);
      (function (ReflectionProbeType) {
        ReflectionProbeType[ReflectionProbeType["NONE"] = 0] = "NONE";
        ReflectionProbeType[ReflectionProbeType["BAKED_CUBEMAP"] = 1] = "BAKED_CUBEMAP";
        ReflectionProbeType[ReflectionProbeType["PLANAR_REFLECTION"] = 2] = "PLANAR_REFLECTION";
        ReflectionProbeType[ReflectionProbeType["BLEND_PROBES"] = 3] = "BLEND_PROBES";
        ReflectionProbeType[ReflectionProbeType["BLEND_PROBES_AND_SKYBOX"] = 4] = "BLEND_PROBES_AND_SKYBOX";
      })(ReflectionProbeType || (exports('ap', ReflectionProbeType = {})));

      var m4_1$6 = new Mat4();
      var shadowMapPatches = [{
        name: 'CC_RECEIVE_SHADOW',
        value: true
      }];
      var staticLightMapPatches = [{
        name: 'CC_USE_LIGHTMAP',
        value: 1
      }];
      var stationaryLightMapPatches = [{
        name: 'CC_USE_LIGHTMAP',
        value: 2
      }];
      var highpLightMapPatches = [{
        name: 'CC_LIGHT_MAP_VERSION',
        value: 2
      }];
      var lightProbePatches = [{
        name: 'CC_USE_LIGHT_PROBE',
        value: true
      }];
      var CC_USE_REFLECTION_PROBE = 'CC_USE_REFLECTION_PROBE';
      var CC_DISABLE_DIRECTIONAL_LIGHT = 'CC_DISABLE_DIRECTIONAL_LIGHT';
      var ModelType;
      (function (ModelType) {
        ModelType[ModelType["DEFAULT"] = 0] = "DEFAULT";
        ModelType[ModelType["SKINNING"] = 1] = "SKINNING";
        ModelType[ModelType["BAKED_SKINNING"] = 2] = "BAKED_SKINNING";
        ModelType[ModelType["BATCH_2D"] = 3] = "BATCH_2D";
        ModelType[ModelType["PARTICLE_BATCH"] = 4] = "PARTICLE_BATCH";
        ModelType[ModelType["LINE"] = 5] = "LINE";
      })(ModelType || (ModelType = {}));
      var lightmapSamplerHash = new SamplerInfo(Filter$1.LINEAR, Filter$1.LINEAR, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP);
      var lightmapSamplerWithMipHash = new SamplerInfo(Filter$1.LINEAR, Filter$1.LINEAR, Filter$1.LINEAR, Address.CLAMP, Address.CLAMP, Address.CLAMP);
      var Model = function () {
        function Model() {
          this.type = ModelType.DEFAULT;
          this.scene = null;
          this.isDynamicBatching = false;
          this._worldBounds = null;
          this._modelBounds = null;
          this._subModels = [];
          this._node = null;
          this._transform = null;
          this._device = void 0;
          this._inited = false;
          this._descriptorSetCount = 1;
          this._updateStamp = -1;
          this._localDataUpdated = true;
          this._localData = new Float32Array(UBOLocal.COUNT);
          this._localBuffer = null;
          this._localSHData = null;
          this._localSHBuffer = null;
          this._lightmap = null;
          this._lightmapUVParam = new Vec4();
          this._tetrahedronIndex = -1;
          this._lastWorldBoundCenter = new Vec3(Infinity, Infinity, Infinity);
          this._useLightProbe = false;
          this._worldBoundBuffer = null;
          this._receiveShadow = false;
          this._castShadow = false;
          this._receiveDirLight = true;
          this._shadowBias = 0;
          this._shadowNormalBias = 0;
          this._reflectionProbeId = -1;
          this._reflectionProbeBlendId = -1;
          this._reflectionProbeBlendWeight = 0;
          this._enabled = true;
          this._visFlags = Layers.Enum.NONE;
          this._priority = 0;
          this._bakeToReflectionProbe = true;
          this._reflectionProbeType = ReflectionProbeType.NONE;
          this._device = deviceManager.gfxDevice;
        }
        var _proto = Model.prototype;
        _proto.initialize = function initialize() {
          if (this._inited) {
            return;
          }
          this._receiveShadow = true;
          this.castShadow = false;
          this.enabled = true;
          this.visFlags = Layers.Enum.NONE;
          this._inited = true;
          this._bakeToReflectionProbe = true;
          this._reflectionProbeType = ReflectionProbeType.NONE;
        };
        _proto.destroy = function destroy() {
          var subModels = this._subModels;
          for (var i = 0; i < subModels.length; i++) {
            this._subModels[i].destroy();
          }
          if (this._localBuffer) {
            this._localBuffer.destroy();
            this._localBuffer = null;
          }
          if (this._localSHBuffer) {
            this._localSHBuffer.destroy();
            this._localSHBuffer = null;
          }
          if (this._worldBoundBuffer) {
            this._worldBoundBuffer.destroy();
            this._worldBoundBuffer = null;
          }
          this._worldBounds = null;
          this._modelBounds = null;
          this._subModels.length = 0;
          this._inited = false;
          this._localDataUpdated = true;
          this._transform = null;
          this._node = null;
          this.isDynamicBatching = false;
        };
        _proto.attachToScene = function attachToScene(scene) {
          this.scene = scene;
          this._localDataUpdated = true;
        };
        _proto.detachFromScene = function detachFromScene() {
          this.scene = null;
        };
        _proto.updateTransform = function updateTransform(stamp) {
          var node = this.transform;
          if (node.hasChangedFlags || node.isTransformDirty()) {
            node.updateWorldTransform();
            this._localDataUpdated = true;
            var worldBounds = this._worldBounds;
            if (this._modelBounds && worldBounds) {
              this._modelBounds.transform(node._mat, node._pos, node._rot, node._scale, worldBounds);
            }
          }
        };
        _proto.updateWorldBound = function updateWorldBound() {
          var node = this.transform;
          if (node !== null) {
            node.updateWorldTransform();
            this._localDataUpdated = true;
            var worldBounds = this._worldBounds;
            if (this._modelBounds && worldBounds) {
              this._modelBounds.transform(node._mat, node._pos, node._rot, node._scale, worldBounds);
            }
          }
        };
        _proto.updateUBOs = function updateUBOs(stamp) {
          var subModels = this._subModels;
          for (var i = 0; i < subModels.length; i++) {
            subModels[i].update();
          }
          this._updateStamp = stamp;
          this.updateSHUBOs();
          var forceUpdateUBO = this.node.scene.globals.shadows.enabled && this.node.scene.globals.shadows.type === ShadowType.Planar;
          if (!this._localDataUpdated) {
            return;
          }
          this._localDataUpdated = false;
          var worldMatrix = this.transform._mat;
          var hasNonInstancingPass = false;
          for (var _i = 0; _i < subModels.length; _i++) {
            var subModel = subModels[_i];
            var idx = subModel.instancedWorldMatrixIndex;
            if (idx >= 0) {
              subModel.updateInstancedWorldMatrix(worldMatrix, idx);
            } else {
              hasNonInstancingPass = true;
            }
          }
          if ((hasNonInstancingPass || forceUpdateUBO) && this._localBuffer) {
            Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET);
            Mat4.invert(m4_1$6, worldMatrix);
            Mat4.transpose(m4_1$6, m4_1$6);
            Mat4.toArray(this._localData, m4_1$6, UBOLocal.MAT_WORLD_IT_OFFSET);
            this._localBuffer.update(this._localData);
          }
        };
        _proto.invalidateLocalData = function invalidateLocalData() {
          this._localDataUpdated = true;
        };
        _proto.showTetrahedron = function showTetrahedron() {
          return this.isLightProbeAvailable();
        };
        _proto.isLightProbeAvailable = function isLightProbeAvailable() {
          if (!this._useLightProbe) {
            return false;
          }
          var lightProbes = legacyCC.director.root.pipeline.pipelineSceneData.lightProbes;
          if (!lightProbes || lightProbes.empty()) {
            return false;
          }
          if (!this._worldBounds) {
            return false;
          }
          return true;
        };
        _proto.updateSHBuffer = function updateSHBuffer() {
          if (!this._localSHData) {
            return;
          }
          var subModels = this._subModels;
          var hasNonInstancingPass = false;
          for (var i = 0; i < subModels.length; i++) {
            var subModel = subModels[i];
            var idx = subModel.instancedSHIndex;
            if (idx >= 0) {
              subModel.updateInstancedSH(this._localSHData, idx);
            } else {
              hasNonInstancingPass = true;
            }
          }
          if (hasNonInstancingPass && this._localSHBuffer) {
            this._localSHBuffer.update(this._localSHData);
          }
        };
        _proto.clearSHUBOs = function clearSHUBOs() {
          if (!this._localSHData) {
            return;
          }
          for (var i = 0; i < UBOSH.COUNT; i++) {
            this._localSHData[i] = 0.0;
          }
          this.updateSHBuffer();
        };
        _proto.updateSHUBOs = function updateSHUBOs() {
          if (!this.isLightProbeAvailable()) {
            return;
          }
          var center = this._worldBounds.center;
          if (center.equals(this._lastWorldBoundCenter, EPSILON$3)) {
            return;
          }
          var coefficients = [];
          var weights = new Vec4(0.0, 0.0, 0.0, 0.0);
          var lightProbes = legacyCC.director.root.pipeline.pipelineSceneData.lightProbes;
          this._lastWorldBoundCenter.set(center);
          this._tetrahedronIndex = lightProbes.data.getInterpolationWeights(center, this._tetrahedronIndex, weights);
          var result = lightProbes.data.getInterpolationSHCoefficients(this._tetrahedronIndex, weights, coefficients);
          if (!result) {
            return;
          }
          if (!this._localSHData) {
            return;
          }
          legacyCC.internal.SH.reduceRinging(coefficients, lightProbes.reduceRinging);
          legacyCC.internal.SH.updateUBOData(this._localSHData, UBOSH.SH_LINEAR_CONST_R_OFFSET, coefficients);
          this.updateSHBuffer();
        };
        _proto.createBoundingShape = function createBoundingShape(minPos, maxPos) {
          if (!minPos || !maxPos) {
            return;
          }
          if (!this._modelBounds) {
            this._modelBounds = AABB.create();
          }
          if (!this._worldBounds) {
            this._worldBounds = AABB.create();
          }
          AABB.fromPoints(this._modelBounds, minPos, maxPos);
          AABB.copy(this._worldBounds, this._modelBounds);
        };
        _proto._createSubModel = function _createSubModel() {
          return new SubModel();
        };
        _proto.initSubModel = function initSubModel(idx, subMeshData, mat) {
          this.initialize();
          if (this._subModels[idx] == null) {
            this._subModels[idx] = this._createSubModel();
          } else {
            this._subModels[idx].destroy();
          }
          this._subModels[idx].initialize(subMeshData, mat.passes, this.getMacroPatches(idx));
          this._updateAttributesAndBinding(idx);
        };
        _proto.setSubModelMesh = function setSubModelMesh(idx, subMesh) {
          if (!this._subModels[idx]) {
            return;
          }
          this._subModels[idx].subMesh = subMesh;
        };
        _proto.setSubModelMaterial = function setSubModelMaterial(idx, mat) {
          if (!this._subModels[idx]) {
            return;
          }
          this._subModels[idx].passes = mat.passes;
          this._updateAttributesAndBinding(idx);
        };
        _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {
          var subModels = this._subModels;
          for (var i = 0; i < subModels.length; i++) {
            subModels[i].onPipelineStateChanged();
          }
        };
        _proto.onMacroPatchesStateChanged = function onMacroPatchesStateChanged() {
          var subModels = this._subModels;
          for (var i = 0; i < subModels.length; i++) {
            subModels[i].onMacroPatchesStateChanged(this.getMacroPatches(i));
          }
        };
        _proto.onGeometryChanged = function onGeometryChanged() {
          var subModels = this._subModels;
          for (var i = 0; i < subModels.length; i++) {
            subModels[i].onGeometryChanged();
          }
        };
        _proto.initLightingmap = function initLightingmap(texture, uvParam) {
          this._lightmap = texture;
          this._lightmapUVParam = uvParam;
        };
        _proto.updateLightingmap = function updateLightingmap(texture, uvParam) {
          Vec4.toArray(this._localData, uvParam, UBOLocal.LIGHTINGMAP_UVPARAM);
          this._localDataUpdated = true;
          this._lightmap = texture;
          this._lightmapUVParam = uvParam;
          this.onMacroPatchesStateChanged();
          if (!texture) {
            texture = builtinResMgr.get('empty-texture');
          }
          var gfxTexture = texture.getGFXTexture();
          if (gfxTexture) {
            var sampler = this._device.getSampler(texture.mipmaps.length > 1 ? lightmapSamplerWithMipHash : lightmapSamplerHash);
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              var descriptorSet = subModels[i].descriptorSet;
              descriptorSet.bindTexture(UNIFORM_LIGHTMAP_TEXTURE_BINDING, gfxTexture);
              descriptorSet.bindSampler(UNIFORM_LIGHTMAP_TEXTURE_BINDING, sampler);
              descriptorSet.update();
            }
          }
        };
        _proto.updateReflectionProbeCubemap = function updateReflectionProbeCubemap(texture) {
          this._localDataUpdated = true;
          this.onMacroPatchesStateChanged();
          if (!texture) {
            texture = builtinResMgr.get('default-cube-texture');
          }
          var gfxTexture = texture.getGFXTexture();
          if (gfxTexture) {
            var reflectionSampler = this._device.getSampler(texture.getSamplerInfo());
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              var descriptorSet = subModels[i].descriptorSet;
              if (descriptorSet) {
                descriptorSet.bindSampler(UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, reflectionSampler);
                descriptorSet.bindTexture(UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, gfxTexture);
                descriptorSet.update();
              }
            }
          }
        };
        _proto.updateReflectionProbeBlendCubemap = function updateReflectionProbeBlendCubemap(texture) {
          this._localDataUpdated = true;
          this.onMacroPatchesStateChanged();
          if (!texture) {
            texture = builtinResMgr.get('default-cube-texture');
          }
          var gfxTexture = texture.getGFXTexture();
          if (gfxTexture) {
            var reflectionSampler = this._device.getSampler(texture.getSamplerInfo());
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              var descriptorSet = subModels[i].descriptorSet;
              if (descriptorSet) {
                descriptorSet.bindSampler(UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, reflectionSampler);
                descriptorSet.bindTexture(UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, gfxTexture);
                descriptorSet.update();
              }
            }
          }
        };
        _proto.updateReflectionProbePlanarMap = function updateReflectionProbePlanarMap(texture) {
          this._localDataUpdated = true;
          this.onMacroPatchesStateChanged();
          var sampler = this._device.getSampler(new SamplerInfo(Filter$1.LINEAR, Filter$1.LINEAR, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP));
          if (!texture) {
            texture = builtinResMgr.get('empty-texture').getGFXTexture();
          }
          if (texture) {
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              var descriptorSet = subModels[i].descriptorSet;
              if (descriptorSet) {
                descriptorSet.bindTexture(UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, texture);
                descriptorSet.bindSampler(UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, sampler);
                descriptorSet.update();
              }
            }
          }
        };
        _proto.updateReflectionProbeDataMap = function updateReflectionProbeDataMap(texture) {
          this._localDataUpdated = true;
          this.onMacroPatchesStateChanged();
          if (!texture) {
            texture = builtinResMgr.get('empty-texture');
          }
          var gfxTexture = texture.getGFXTexture();
          if (gfxTexture) {
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              var descriptorSet = subModels[i].descriptorSet;
              if (descriptorSet) {
                descriptorSet.bindTexture(UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, gfxTexture);
                descriptorSet.bindSampler(UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, texture.getGFXSampler());
                descriptorSet.update();
              }
            }
          }
        };
        _proto.updateLocalShadowBias = function updateLocalShadowBias() {
          var sv = this._localData;
          sv[UBOLocal.LOCAL_SHADOW_BIAS + 0] = this._shadowBias;
          sv[UBOLocal.LOCAL_SHADOW_BIAS + 1] = this._shadowNormalBias;
          this._localDataUpdated = true;
        };
        _proto.updateReflectionProbeId = function updateReflectionProbeId() {
          var sv = this._localData;
          sv[UBOLocal.LOCAL_SHADOW_BIAS + 2] = this._reflectionProbeId;
          sv[UBOLocal.LOCAL_SHADOW_BIAS + 3] = this._reflectionProbeBlendId;
          var probe = null;
          var blendProbe = null;
          if (legacyCC.internal.reflectionProbeManager) {
            probe = legacyCC.internal.reflectionProbeManager.getProbeById(this._reflectionProbeId);
            blendProbe = legacyCC.internal.reflectionProbeManager.getProbeById(this._reflectionProbeBlendId);
          }
          if (probe) {
            if (probe.probeType === ProbeType.PLANAR) {
              sv[UBOLocal.REFLECTION_PROBE_DATA1] = probe.node.up.x;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 1] = probe.node.up.y;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 2] = probe.node.up.z;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 3] = 1.0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2] = 1.0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 1] = 0.0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 2] = 0.0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 3] = 1.0;
            } else {
              sv[UBOLocal.REFLECTION_PROBE_DATA1] = probe.node.worldPosition.x;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 1] = probe.node.worldPosition.y;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 2] = probe.node.worldPosition.z;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 3] = 0.0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2] = probe.size.x;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 1] = probe.size.y;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 2] = probe.size.z;
              var mipAndUseRGBE = probe.isRGBE() ? 1000 : 0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 3] = probe.cubemap ? probe.cubemap.mipmapLevel + mipAndUseRGBE : 1.0 + mipAndUseRGBE;
            }
            if (this._reflectionProbeType === ReflectionProbeType.BLEND_PROBES || this._reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
              if (blendProbe) {
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1] = blendProbe.node.worldPosition.x;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 1] = blendProbe.node.worldPosition.y;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 2] = blendProbe.node.worldPosition.z;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 3] = this.reflectionProbeBlendWeight;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2] = blendProbe.size.x;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2 + 1] = blendProbe.size.y;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2 + 2] = blendProbe.size.z;
                var _mipAndUseRGBE = blendProbe.isRGBE() ? 1000 : 0;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2 + 3] = blendProbe.cubemap ? blendProbe.cubemap.mipmapLevel + _mipAndUseRGBE : 1.0 + _mipAndUseRGBE;
              } else if (this._reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 3] = this.reflectionProbeBlendWeight;
              }
            }
          }
          this._localDataUpdated = true;
        };
        _proto.getMacroPatches = function getMacroPatches(subModelIndex) {
          var patches = this.receiveShadow ? shadowMapPatches : null;
          if (this._lightmap != null) {
            if (this.node && this.node.scene && !this.node.scene.globals.disableLightmap) {
              var mainLightIsStationary = this.node.scene.globals.bakedWithStationaryMainLight;
              var lightmapPathes = mainLightIsStationary ? stationaryLightMapPatches : staticLightMapPatches;
              patches = patches ? patches.concat(lightmapPathes) : lightmapPathes;
              if (this.node.scene.globals.bakedWithHighpLightmap) {
                patches = patches.concat(highpLightMapPatches);
              }
            }
          }
          if (this._useLightProbe) {
            patches = patches ? patches.concat(lightProbePatches) : lightProbePatches;
          }
          var reflectionProbePatches = [{
            name: CC_USE_REFLECTION_PROBE,
            value: this._reflectionProbeType
          }];
          patches = patches ? patches.concat(reflectionProbePatches) : reflectionProbePatches;
          var receiveDirLightPatches = [{
            name: CC_DISABLE_DIRECTIONAL_LIGHT,
            value: !this._receiveDirLight
          }];
          patches = patches ? patches.concat(receiveDirLightPatches) : receiveDirLightPatches;
          return patches;
        };
        _proto._updateAttributesAndBinding = function _updateAttributesAndBinding(subModelIndex) {
          var subModel = this._subModels[subModelIndex];
          if (!subModel) {
            return;
          }
          this._initLocalDescriptors(subModelIndex);
          this._updateLocalDescriptors(subModelIndex, subModel.descriptorSet);
          this._initLocalSHDescriptors(subModelIndex);
          this._updateLocalSHDescriptors(subModelIndex, subModel.descriptorSet);
          this._initWorldBoundDescriptors(subModelIndex);
          if (subModel.worldBoundDescriptorSet) {
            this._updateWorldBoundDescriptors(subModelIndex, subModel.worldBoundDescriptorSet);
          }
          var attributes = [];
          var attributeSet = new Set();
          for (var _iterator = _createForOfIteratorHelperLoose(subModel.passes), _step; !(_step = _iterator()).done;) {
            var pass = _step.value;
            var shader = pass.getShaderVariant(subModel.patches);
            for (var _iterator2 = _createForOfIteratorHelperLoose(shader.attributes), _step2; !(_step2 = _iterator2()).done;) {
              var attr = _step2.value;
              if (!attributeSet.has(attr.name)) {
                attributes.push(attr);
                attributeSet.add(attr.name);
              }
            }
          }
          this._updateInstancedAttributes(attributes, subModel);
        };
        _proto._updateInstancedAttributes = function _updateInstancedAttributes(attributes, subModel) {
          subModel.UpdateInstancedAttributes(attributes);
          this._localDataUpdated = true;
        };
        _proto._initLocalDescriptors = function _initLocalDescriptors(subModelIndex) {
          if (!this._localBuffer) {
            this._localBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOLocal.SIZE, UBOLocal.SIZE));
          }
        };
        _proto._initLocalSHDescriptors = function _initLocalSHDescriptors(subModelIndex) {
          if (!this._useLightProbe) {
            return;
          }
          if (!this._localSHData) {
            this._localSHData = new Float32Array(UBOSH.COUNT);
          }
          if (!this._localSHBuffer) {
            this._localSHBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOSH.SIZE, UBOSH.SIZE));
          }
        };
        _proto._initWorldBoundDescriptors = function _initWorldBoundDescriptors(subModelIndex) {
          if (!this._worldBoundBuffer) {
            this._worldBoundBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOWorldBound.SIZE, UBOWorldBound.SIZE));
          }
        };
        _proto._updateLocalDescriptors = function _updateLocalDescriptors(subModelIndex, descriptorSet) {
          if (this._localBuffer) descriptorSet.bindBuffer(UBOLocal.BINDING, this._localBuffer);
        };
        _proto._updateLocalSHDescriptors = function _updateLocalSHDescriptors(subModelIndex, descriptorSet) {
          if (this._localSHBuffer) descriptorSet.bindBuffer(UBOSH.BINDING, this._localSHBuffer);
        };
        _proto._updateWorldBoundDescriptors = function _updateWorldBoundDescriptors(subModelIndex, descriptorSet) {
          if (this._worldBoundBuffer) descriptorSet.bindBuffer(UBOWorldBound.BINDING, this._worldBoundBuffer);
        };
        _createClass(Model, [{
          key: "subModels",
          get: function get() {
            return this._subModels;
          }
        }, {
          key: "inited",
          get: function get() {
            return this._inited;
          }
        }, {
          key: "worldBounds",
          get: function get() {
            return this._worldBounds;
          }
        }, {
          key: "modelBounds",
          get: function get() {
            return this._modelBounds;
          }
        }, {
          key: "localBuffer",
          get: function get() {
            return this._localBuffer;
          }
        }, {
          key: "localSHBuffer",
          get: function get() {
            return this._localSHBuffer;
          }
        }, {
          key: "worldBoundBuffer",
          get: function get() {
            return this._worldBoundBuffer;
          }
        }, {
          key: "updateStamp",
          get: function get() {
            return this._updateStamp;
          }
        }, {
          key: "useLightProbe",
          get: function get() {
            return this._useLightProbe;
          },
          set: function set(val) {
            this._useLightProbe = val;
            this.onMacroPatchesStateChanged();
          }
        }, {
          key: "tetrahedronIndex",
          get: function get() {
            return this._tetrahedronIndex;
          },
          set: function set(index) {
            this._tetrahedronIndex = index;
          }
        }, {
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
          }
        }, {
          key: "receiveShadow",
          get: function get() {
            return this._receiveShadow;
          },
          set: function set(val) {
            this._receiveShadow = val;
            this.onMacroPatchesStateChanged();
          }
        }, {
          key: "castShadow",
          get: function get() {
            return this._castShadow;
          },
          set: function set(val) {
            this._castShadow = val;
          }
        }, {
          key: "receiveDirLight",
          get: function get() {
            return this._receiveDirLight;
          },
          set: function set(val) {
            this._receiveDirLight = val;
            this.onMacroPatchesStateChanged();
          }
        }, {
          key: "node",
          get: function get() {
            return this._node;
          },
          set: function set(n) {
            this._node = n;
          }
        }, {
          key: "transform",
          get: function get() {
            return this._transform;
          },
          set: function set(n) {
            this._transform = n;
          }
        }, {
          key: "visFlags",
          get: function get() {
            return this._visFlags;
          },
          set: function set(val) {
            this._visFlags = val;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(val) {
            this._priority = val;
          }
        }, {
          key: "bakeToReflectionProbe",
          get: function get() {
            return this._bakeToReflectionProbe;
          },
          set: function set(val) {
            this._bakeToReflectionProbe = val;
          }
        }, {
          key: "reflectionProbeType",
          get: function get() {
            return this._reflectionProbeType;
          },
          set: function set(val) {
            this._reflectionProbeType = val;
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              subModels[i].useReflectionProbeType = val;
            }
            this.onMacroPatchesStateChanged();
          }
        }, {
          key: "reflectionProbeId",
          get: function get() {
            return this._reflectionProbeId;
          },
          set: function set(val) {
            this._reflectionProbeId = val;
          }
        }, {
          key: "reflectionProbeBlendId",
          get: function get() {
            return this._reflectionProbeBlendId;
          },
          set: function set(val) {
            this._reflectionProbeBlendId = val;
          }
        }, {
          key: "reflectionProbeBlendWeight",
          get: function get() {
            return this._reflectionProbeBlendWeight;
          },
          set: function set(val) {
            this._reflectionProbeBlendWeight = val;
          }
        }]);
        return Model;
      }();

      var _forward$2 = new Vec3(0, 0, -1);
      var _v3 = new Vec3();
      var DirectionalLight$1 = function (_Light) {
        _inheritsLoose(DirectionalLight, _Light);
        function DirectionalLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._dir = new Vec3(1.0, -1.0, -1.0);
          _this._illuminanceHDR = Ambient.SUN_ILLUM;
          _this._illuminanceLDR = 1.0;
          _this._shadowEnabled = false;
          _this._shadowPcf = PCFType.HARD;
          _this._shadowBias = 0.00001;
          _this._shadowNormalBias = 0.0;
          _this._shadowSaturation = 1.0;
          _this._shadowDistance = 50;
          _this._shadowInvisibleOcclusionRange = 200;
          _this._csmLevel = CSMLevel.LEVEL_4;
          _this._csmNeedUpdate = false;
          _this._csmLayerLambda = 0.75;
          _this._csmOptimizationMode = CSMOptimizationMode.DisableRotationFix;
          _this._csmLayersTransition = false;
          _this._csmTransitionRange = 0.05;
          _this._shadowFixedArea = false;
          _this._shadowNear = 0.1;
          _this._shadowFar = 10.0;
          _this._shadowOrthoSize = 5;
          _this._type = LightType.DIRECTIONAL;
          return _this;
        }
        var _proto = DirectionalLight.prototype;
        _proto.initialize = function initialize() {
          _Light.prototype.initialize.call(this);
          this.illuminance = Ambient.SUN_ILLUM;
          this.direction = new Vec3(1.0, -1.0, -1.0);
        };
        _proto.update = function update() {
          if (this._node && this._node.hasChangedFlags) {
            this.direction = Vec3.transformQuat(_v3, _forward$2, this._node.worldRotation);
          }
        };
        _proto.activate = function activate() {
          var root = legacyCC.director.root;
          var pipeline = root.pipeline;
          if (this._shadowEnabled) {
            if (this._shadowFixedArea || !pipeline.pipelineSceneData.csmSupported) {
              pipeline.macros.CC_DIR_LIGHT_SHADOW_TYPE = 1;
            } else if (this.csmLevel > 1 && pipeline.pipelineSceneData.csmSupported) {
              pipeline.macros.CC_DIR_LIGHT_SHADOW_TYPE = 2;
              pipeline.macros.CC_CASCADED_LAYERS_TRANSITION = this._csmLayersTransition;
            } else {
              pipeline.macros.CC_DIR_LIGHT_SHADOW_TYPE = 1;
            }
            pipeline.macros.CC_DIR_SHADOW_PCF_TYPE = this._shadowPcf;
          } else {
            pipeline.macros.CC_DIR_LIGHT_SHADOW_TYPE = 0;
          }
          root.onGlobalPipelineStateChanged();
        };
        _createClass(DirectionalLight, [{
          key: "direction",
          get: function get() {
            return this._dir;
          },
          set: function set(dir) {
            Vec3.normalize(this._dir, dir);
          }
        }, {
          key: "illuminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._illuminanceHDR;
            } else {
              return this._illuminanceLDR;
            }
          },
          set: function set(value) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.illuminanceHDR = value;
            } else {
              this.illuminanceLDR = value;
            }
          }
        }, {
          key: "illuminanceHDR",
          get: function get() {
            return this._illuminanceHDR;
          },
          set: function set(value) {
            this._illuminanceHDR = value;
          }
        }, {
          key: "illuminanceLDR",
          get: function get() {
            return this._illuminanceLDR;
          },
          set: function set(value) {
            this._illuminanceLDR = value;
          }
        }, {
          key: "shadowEnabled",
          get: function get() {
            return this._shadowEnabled;
          },
          set: function set(val) {
            this._shadowEnabled = val;
            this.activate();
          }
        }, {
          key: "shadowPcf",
          get: function get() {
            return this._shadowPcf;
          },
          set: function set(val) {
            this._shadowPcf = val;
            this.activate();
          }
        }, {
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
          }
        }, {
          key: "shadowSaturation",
          get: function get() {
            return this._shadowSaturation;
          },
          set: function set(val) {
            this._shadowSaturation = val;
          }
        }, {
          key: "shadowDistance",
          get: function get() {
            return this._shadowDistance;
          },
          set: function set(val) {
            this._shadowDistance = Math.min(val, Shadows.MAX_FAR);
          }
        }, {
          key: "shadowInvisibleOcclusionRange",
          get: function get() {
            return this._shadowInvisibleOcclusionRange;
          },
          set: function set(val) {
            this._shadowInvisibleOcclusionRange = Math.min(val, Shadows.MAX_FAR);
          }
        }, {
          key: "csmLevel",
          get: function get() {
            return this._csmLevel;
          },
          set: function set(val) {
            this._csmLevel = val;
            this.activate();
          }
        }, {
          key: "csmNeedUpdate",
          get: function get() {
            return this._csmNeedUpdate;
          },
          set: function set(val) {
            this._csmNeedUpdate = val;
          }
        }, {
          key: "csmLayerLambda",
          get: function get() {
            return this._csmLayerLambda;
          },
          set: function set(val) {
            this._csmLayerLambda = val;
          }
        }, {
          key: "csmOptimizationMode",
          get: function get() {
            return this._csmOptimizationMode;
          },
          set: function set(val) {
            this._csmOptimizationMode = val;
          }
        }, {
          key: "shadowFixedArea",
          get: function get() {
            return this._shadowFixedArea;
          },
          set: function set(val) {
            this._shadowFixedArea = val;
            this.activate();
          }
        }, {
          key: "shadowNear",
          get: function get() {
            return this._shadowNear;
          },
          set: function set(val) {
            this._shadowNear = val;
          }
        }, {
          key: "shadowFar",
          get: function get() {
            return this._shadowFar;
          },
          set: function set(val) {
            this._shadowFar = Math.min(val, Shadows.MAX_FAR);
          }
        }, {
          key: "shadowOrthoSize",
          get: function get() {
            return this._shadowOrthoSize;
          },
          set: function set(val) {
            this._shadowOrthoSize = val;
          }
        }, {
          key: "csmLayersTransition",
          get: function get() {
            return this._csmLayersTransition;
          },
          set: function set(val) {
            this._csmLayersTransition = val;
            this.activate();
          }
        }, {
          key: "csmTransitionRange",
          get: function get() {
            return this._csmTransitionRange;
          },
          set: function set(val) {
            this._csmTransitionRange = val;
          }
        }]);
        return DirectionalLight;
      }(Light$1);

      var SphereLight$1 = function (_Light) {
        _inheritsLoose(SphereLight, _Light);
        function SphereLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._needUpdate = false;
          _this._size = 0.15;
          _this._range = 1.0;
          _this._luminanceHDR = 0;
          _this._luminanceLDR = 0;
          _this._pos = void 0;
          _this._aabb = void 0;
          _this._aabb = AABB.create();
          _this._pos = new Vec3();
          _this._type = LightType.SPHERE;
          return _this;
        }
        var _proto = SphereLight.prototype;
        _proto.initialize = function initialize() {
          _Light.prototype.initialize.call(this);
          var size = 0.15;
          this.size = size;
          this.range = 1.0;
          this.luminanceHDR = 1700 / nt2lm(size);
          this.luminanceLDR = 1.0;
        };
        _proto.update = function update() {
          if (this._node && (this._node.hasChangedFlags || this._needUpdate)) {
            this._node.getWorldPosition(this._pos);
            var range = this._range;
            AABB.set(this._aabb, this._pos.x, this._pos.y, this._pos.z, range, range, range);
            this._needUpdate = false;
          }
        };
        _createClass(SphereLight, [{
          key: "position",
          get: function get() {
            return this._pos;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(size) {
            this._size = size;
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(range) {
            this._range = range;
            this._needUpdate = true;
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(value) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.luminanceHDR = value;
            } else {
              this.luminanceLDR = value;
            }
          }
        }, {
          key: "luminanceHDR",
          get: function get() {
            return this._luminanceHDR;
          },
          set: function set(value) {
            this._luminanceHDR = value;
          }
        }, {
          key: "luminanceLDR",
          set: function set(value) {
            this._luminanceLDR = value;
          }
        }, {
          key: "aabb",
          get: function get() {
            return this._aabb;
          }
        }]);
        return SphereLight;
      }(Light$1);

      var _forward$1 = new Vec3(0, 0, -1);
      var _qt = new Quat();
      var _matView = new Mat4();
      var _matProj = new Mat4();
      var _matViewProj = new Mat4();
      var _matViewProjInv = new Mat4();
      var SpotLight$1 = function (_Light) {
        _inheritsLoose(SpotLight, _Light);
        function SpotLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._dir = new Vec3(1.0, -1.0, -1.0);
          _this._range = 5.0;
          _this._spotAngle = Math.cos(Math.PI / 6);
          _this._angleAttenuationStrength = 0;
          _this._pos = void 0;
          _this._aabb = void 0;
          _this._frustum = void 0;
          _this._angle = 0;
          _this._needUpdate = false;
          _this._size = 0.15;
          _this._luminanceHDR = 0;
          _this._luminanceLDR = 0;
          _this._shadowEnabled = false;
          _this._shadowPcf = PCFType.HARD;
          _this._shadowBias = 0.00001;
          _this._shadowNormalBias = 0.0;
          _this._aabb = AABB.create();
          _this._frustum = Frustum.create();
          _this._pos = new Vec3();
          _this._type = LightType.SPOT;
          return _this;
        }
        var _proto = SpotLight.prototype;
        _proto.initialize = function initialize() {
          _Light.prototype.initialize.call(this);
          var size = 0.15;
          this.size = size;
          this.luminanceHDR = 1700 / nt2lm(size);
          this.luminanceLDR = 1.0;
          this.range = Math.cos(Math.PI / 6);
          this._dir.set(new Vec3(1.0, -1.0, -1.0));
        };
        _proto.update = function update() {
          if (this._node && (this._node.hasChangedFlags || this._needUpdate)) {
            this._node.getWorldPosition(this._pos);
            Vec3.transformQuat(this._dir, _forward$1, this._node.getWorldRotation(_qt));
            Vec3.normalize(this._dir, this._dir);
            AABB.set(this._aabb, this._pos.x, this._pos.y, this._pos.z, this._range, this._range, this._range);
            this._node.getWorldRT(_matView);
            Mat4.invert(_matView, _matView);
            Mat4.perspective(_matProj, this._angle, 1.0, 0.001, this._range);
            Mat4.multiply(_matViewProj, _matProj, _matView);
            this._frustum.update(_matViewProj, _matViewProjInv);
            this._needUpdate = false;
          }
        };
        _createClass(SpotLight, [{
          key: "position",
          get: function get() {
            return this._pos;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(size) {
            this._size = size;
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(range) {
            this._range = range;
            this._needUpdate = true;
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(value) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.luminanceHDR = value;
            } else {
              this.luminanceLDR = value;
            }
          }
        }, {
          key: "luminanceHDR",
          get: function get() {
            return this._luminanceHDR;
          },
          set: function set(value) {
            this._luminanceHDR = value;
          }
        }, {
          key: "luminanceLDR",
          get: function get() {
            return this._luminanceLDR;
          },
          set: function set(value) {
            this._luminanceLDR = value;
          }
        }, {
          key: "direction",
          get: function get() {
            return this._dir;
          }
        }, {
          key: "spotAngle",
          get: function get() {
            return this._spotAngle;
          },
          set: function set(val) {
            this._angle = val;
            this._spotAngle = Math.cos(val * 0.5);
            this._needUpdate = true;
          }
        }, {
          key: "angleAttenuationStrength",
          get: function get() {
            return this._angleAttenuationStrength;
          },
          set: function set(val) {
            this._angleAttenuationStrength = val;
            this._needUpdate = true;
          }
        }, {
          key: "angle",
          get: function get() {
            return this._angle;
          }
        }, {
          key: "aabb",
          get: function get() {
            return this._aabb;
          }
        }, {
          key: "frustum",
          get: function get() {
            return this._frustum;
          }
        }, {
          key: "shadowEnabled",
          get: function get() {
            return this._shadowEnabled;
          },
          set: function set(val) {
            this._shadowEnabled = val;
          }
        }, {
          key: "shadowPcf",
          get: function get() {
            return this._shadowPcf;
          },
          set: function set(val) {
            this._shadowPcf = val;
          }
        }, {
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
          }
        }]);
        return SpotLight;
      }(Light$1);

      var PointLight$1 = function (_Light) {
        _inheritsLoose(PointLight, _Light);
        function PointLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._needUpdate = false;
          _this._range = 1.0;
          _this._luminanceHDR = 0;
          _this._luminanceLDR = 0;
          _this._pos = void 0;
          _this._aabb = void 0;
          _this._aabb = AABB.create();
          _this._pos = new Vec3();
          _this._type = LightType.POINT;
          return _this;
        }
        var _proto = PointLight.prototype;
        _proto.initialize = function initialize() {
          _Light.prototype.initialize.call(this);
          this.range = 1.0;
          this.luminanceHDR = 1700 / nt2lm(1.0);
          this.luminanceLDR = 1.0;
        };
        _proto.update = function update() {
          if (this._node && (this._node.hasChangedFlags || this._needUpdate)) {
            this._node.getWorldPosition(this._pos);
            var range = this._range;
            AABB.set(this._aabb, this._pos.x, this._pos.y, this._pos.z, range, range, range);
            this._needUpdate = false;
          }
        };
        _createClass(PointLight, [{
          key: "position",
          get: function get() {
            return this._pos;
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(range) {
            this._range = range;
            this._needUpdate = true;
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(value) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.luminanceHDR = value;
            } else {
              this.luminanceLDR = value;
            }
          }
        }, {
          key: "luminanceHDR",
          get: function get() {
            return this._luminanceHDR;
          },
          set: function set(value) {
            this._luminanceHDR = value;
          }
        }, {
          key: "luminanceLDR",
          set: function set(value) {
            this._luminanceLDR = value;
          }
        }, {
          key: "aabb",
          get: function get() {
            return this._aabb;
          }
        }]);
        return PointLight;
      }(Light$1);

      var _forward = new Vec3(0, 0, -1);
      var RangedDirectionalLight$1 = function (_Light) {
        _inheritsLoose(RangedDirectionalLight, _Light);
        function RangedDirectionalLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._dir = new Vec3(0, 0, -1);
          _this._pos = new Vec3(0, 0, 0);
          _this._scale = new Vec3(1, 1, 1);
          _this._right = new Vec3(1, 0, 0);
          _this._illuminanceHDR = Ambient.SUN_ILLUM;
          _this._illuminanceLDR = 1.0;
          _this._type = LightType.RANGED_DIRECTIONAL;
          return _this;
        }
        var _proto = RangedDirectionalLight.prototype;
        _proto.initialize = function initialize() {
          _Light.prototype.initialize.call(this);
          this.illuminance = Ambient.SUN_ILLUM;
        };
        _proto.update = function update() {
          if (this._node && this._node.hasChangedFlags) {
            this._node.getWorldPosition(this._pos);
            this._node.getWorldScale(this._scale);
            Vec3.transformQuat(this._dir, _forward, this._node.worldRotation);
            Vec3.transformQuat(this._right, Vec3.RIGHT, this._node.worldRotation);
          }
        };
        _createClass(RangedDirectionalLight, [{
          key: "direction",
          get: function get() {
            return this._dir;
          }
        }, {
          key: "right",
          get: function get() {
            return this._right;
          }
        }, {
          key: "position",
          get: function get() {
            return this._pos;
          }
        }, {
          key: "scale",
          get: function get() {
            return this._scale;
          }
        }, {
          key: "illuminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._illuminanceHDR;
            } else {
              return this._illuminanceLDR;
            }
          },
          set: function set(value) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.illuminanceHDR = value;
            } else {
              this.illuminanceLDR = value;
            }
          }
        }, {
          key: "illuminanceHDR",
          get: function get() {
            return this._illuminanceHDR;
          },
          set: function set(value) {
            this._illuminanceHDR = value;
          }
        }, {
          key: "illuminanceLDR",
          get: function get() {
            return this._illuminanceLDR;
          },
          set: function set(value) {
            this._illuminanceLDR = value;
          }
        }]);
        return RangedDirectionalLight;
      }(Light$1);

      var LODData = function () {
        function LODData() {
          this.screenUsagePercentage = 1.0;
          this._models = [];
        }
        var _proto = LODData.prototype;
        _proto.addModel = function addModel(model) {
          this._models.splice(0, 0, model);
        };
        _proto.eraseModel = function eraseModel(model) {
          var removeIndex = this._models.indexOf(model);
          if (removeIndex >= 0) {
            this._models.splice(removeIndex, 1);
          }
        };
        _proto.clearModels = function clearModels() {
          this._models.length = 0;
        };
        _createClass(LODData, [{
          key: "models",
          get: function get() {
            return this._models;
          }
        }]);
        return LODData;
      }();
      var LODGroup$1 = function () {
        function LODGroup() {
          this.scene = void 0;
          this.node = null;
          this._device = void 0;
          this.enabled = true;
          this._localBoundaryCenter = new Vec3(0, 0, 0);
          this._objectSize = 1;
          this._lodDataArray = [];
          this._lockedLODLevelVec = [];
          this._isLockLevelChanged = false;
          this._device = deviceManager.gfxDevice;
        }
        var _proto2 = LODGroup.prototype;
        _proto2.attachToScene = function attachToScene(scene) {
          this.scene = scene;
        };
        _proto2.detachFromScene = function detachFromScene() {
          this.scene = null;
        };
        _proto2.lockLODLevels = function lockLODLevels(lockLev) {
          if (lockLev.length !== this._lockedLODLevelVec.length) {
            this._isLockLevelChanged = true;
          } else {
            var size = lockLev.length;
            var index = 0;
            for (; index < size; index++) {
              if (lockLev[index] !== this._lockedLODLevelVec[index]) {
                this._isLockLevelChanged = true;
                break;
              }
            }
          }
          this._lockedLODLevelVec = lockLev.slice();
        };
        _proto2.isLockLevelChanged = function isLockLevelChanged() {
          return this._isLockLevelChanged;
        };
        _proto2.resetLockChangeFlag = function resetLockChangeFlag() {
          this._isLockLevelChanged = false;
        };
        _proto2.getLockedLODLevels = function getLockedLODLevels() {
          return this._lockedLODLevelVec;
        };
        _proto2.clearLODs = function clearLODs() {
          this._lodDataArray.length = 0;
        };
        _proto2.insertLOD = function insertLOD(index, lod) {
          this._lodDataArray.splice(index, 0, lod);
        };
        _proto2.updateLOD = function updateLOD(index, lod) {
          this._lodDataArray[index] = lod;
        };
        _proto2.eraseLOD = function eraseLOD(index) {
          this._lodDataArray.splice(index, 1);
        };
        _proto2.getVisibleLODLevel = function getVisibleLODLevel(camera) {
          var screenUsagePercentage = this.getScreenUsagePercentage(camera);
          var lodIndex = -1;
          for (var i = 0; i < this.lodCount; ++i) {
            var lod = this.lodDataArray[i];
            if (screenUsagePercentage >= lod.screenUsagePercentage) {
              lodIndex = i;
              break;
            }
          }
          return lodIndex;
        };
        _proto2.getScreenUsagePercentage = function getScreenUsagePercentage(camera) {
          if (!this.node) return 0;
          var distance;
          if (camera.projectionType === CameraProjection.PERSPECTIVE) {
            distance = Vec3.len(this.localBoundaryCenter.transformMat4(this.node.worldMatrix).subtract(camera.node.worldPosition));
          }
          return this.distanceToScreenUsagePercentage(camera, distance, this.getWorldSpaceSize());
        };
        _proto2.distanceToScreenUsagePercentage = function distanceToScreenUsagePercentage(camera, distance, size) {
          if (camera.projectionType === CameraProjection.PERSPECTIVE) {
            assertIsTrue(typeof distance === 'number', 'distance must be present for perspective projection');
            return size * camera.matProj.m05 / (distance * 2.0);
          } else {
            return size * camera.matProj.m05 * 0.5;
          }
        };
        _proto2.getWorldSpaceSize = function getWorldSpaceSize() {
          var scale = this.node.scale;
          var maxScale = Math.max(Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z));
          return maxScale * this.objectSize;
        };
        _createClass(LODGroup, [{
          key: "localBoundaryCenter",
          get: function get() {
            return this._localBoundaryCenter.clone();
          },
          set: function set(val) {
            this._localBoundaryCenter.set(val);
          }
        }, {
          key: "lodCount",
          get: function get() {
            return this._lodDataArray.length;
          }
        }, {
          key: "objectSize",
          get: function get() {
            return this._objectSize;
          },
          set: function set(val) {
            this._objectSize = val;
          }
        }, {
          key: "lodDataArray",
          get: function get() {
            return this._lodDataArray;
          }
        }]);
        return LODGroup;
      }();

      var index$2 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get CameraFOVAxis () { return CameraFOVAxis; },
        get CameraProjection () { return CameraProjection; },
        get CameraAperture () { return CameraAperture; },
        get CameraISO () { return CameraISO; },
        get CameraShutter () { return CameraShutter; },
        get CameraType () { return CameraType; },
        get TrackingType () { return TrackingType; },
        get CameraUsage () { return CameraUsage; },
        SKYBOX_FLAG: SKYBOX_FLAG,
        Camera: Camera$1,
        get ModelType () { return ModelType; },
        Model: Model,
        SubModel: SubModel,
        Ambient: Ambient,
        EnvironmentLightingType: EnvironmentLightingType,
        Skybox: Skybox,
        ShadowSize: ShadowSize,
        ShadowType: ShadowType,
        PCFType: PCFType,
        CSMLevel: CSMLevel,
        CSMOptimizationMode: CSMOptimizationMode,
        Shadows: Shadows,
        FogType: FogType,
        FOG_TYPE_NONE: FOG_TYPE_NONE,
        Fog: Fog,
        Octree: Octree,
        Skin: Skin,
        ColorTemperatureToRGB: ColorTemperatureToRGB,
        get LightType () { return LightType; },
        nt2lm: nt2lm,
        Light: Light$1,
        DirectionalLight: DirectionalLight$1,
        SphereLight: SphereLight$1,
        SpotLight: SpotLight$1,
        PointLight: PointLight$1,
        RangedDirectionalLight: RangedDirectionalLight$1,
        get ProbeClearFlag () { return ProbeClearFlag; },
        get ProbeType () { return ProbeType; },
        ReflectionProbe: ReflectionProbe$1,
        LODData: LODData,
        LODGroup: LODGroup$1,
        ToneMappingType: ToneMappingType,
        PostSettings: PostSettings
      });

      var RenderScene = function () {
        RenderScene.registerCreateFunc = function registerCreateFunc(root) {
          root._createSceneFun = function (_root) {
            return new RenderScene(_root);
          };
        };
        function RenderScene(root) {
          this._root = void 0;
          this._name = '';
          this._cameras = [];
          this._models = [];
          this._lodGroups = [];
          this._batches = [];
          this._directionalLights = [];
          this._sphereLights = [];
          this._spotLights = [];
          this._pointLights = [];
          this._rangedDirLights = [];
          this._mainLight = null;
          this._modelId = 0;
          this._lodStateCache = null;
          this._root = root;
        }
        var _proto = RenderScene.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name;
          this._lodStateCache = new LodStateCache(this);
          return true;
        };
        _proto.update = function update(stamp) {
          var mainLight = this._mainLight;
          if (mainLight) {
            mainLight.update();
          }
          var sphereLights = this._sphereLights;
          for (var i = 0; i < sphereLights.length; i++) {
            var light = sphereLights[i];
            light.update();
          }
          var spotLights = this._spotLights;
          for (var _i = 0; _i < spotLights.length; _i++) {
            var _light = spotLights[_i];
            _light.update();
          }
          var pointLights = this._pointLights;
          for (var _i2 = 0; _i2 < pointLights.length; _i2++) {
            var _light2 = pointLights[_i2];
            _light2.update();
          }
          var rangedDirLights = this._rangedDirLights;
          for (var _i3 = 0; _i3 < rangedDirLights.length; _i3++) {
            var _light3 = rangedDirLights[_i3];
            _light3.update();
          }
          var models = this._models;
          for (var _i4 = 0; _i4 < models.length; _i4++) {
            var model = models[_i4];
            if (model.enabled) {
              model.updateTransform(stamp);
              model.updateUBOs(stamp);
            }
          }
          this._lodStateCache.updateLodState();
        };
        _proto.destroy = function destroy() {
          this.removeCameras();
          this.removeSphereLights();
          this.removeSpotLights();
          this.removeRangedDirLights();
          this.removeModels();
          this.removeLODGroups();
          this._lodStateCache.clearCache();
        };
        _proto.isCulledByLod = function isCulledByLod(camera, model) {
          return this._lodStateCache.isLodModelCulled(camera, model);
        };
        _proto.addCamera = function addCamera(cam) {
          cam.attachToScene(this);
          this._cameras.push(cam);
          this._lodStateCache.addCamera(cam);
        };
        _proto.removeCamera = function removeCamera(camera) {
          for (var i = 0; i < this._cameras.length; ++i) {
            if (this._cameras[i] === camera) {
              this._cameras.splice(i, 1);
              camera.detachFromScene();
              this._lodStateCache.removeCamera(camera);
              return;
            }
          }
        };
        _proto.removeCameras = function removeCameras() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._cameras), _step; !(_step = _iterator()).done;) {
            var camera = _step.value;
            camera.detachFromScene();
            this._lodStateCache.removeCamera(camera);
          }
          this._cameras.splice(0);
        };
        _proto.setMainLight = function setMainLight(dl) {
          this._mainLight = dl;
          if (this._mainLight) this._mainLight.activate();
        };
        _proto.unsetMainLight = function unsetMainLight(dl) {
          if (this._mainLight === dl) {
            var dlList = this._directionalLights;
            if (dlList.length) {
              this.setMainLight(dlList[dlList.length - 1]);
              if (this._mainLight.node) {
                this._mainLight.node.hasChangedFlags |= TransformBit.ROTATION;
              }
              return;
            }
            this.setMainLight(null);
          }
        };
        _proto.addDirectionalLight = function addDirectionalLight(dl) {
          dl.attachToScene(this);
          this._directionalLights.push(dl);
        };
        _proto.removeDirectionalLight = function removeDirectionalLight(dl) {
          for (var i = 0; i < this._directionalLights.length; ++i) {
            if (this._directionalLights[i] === dl) {
              dl.detachFromScene();
              this._directionalLights.splice(i, 1);
              return;
            }
          }
        };
        _proto.addSphereLight = function addSphereLight(pl) {
          pl.attachToScene(this);
          this._sphereLights.push(pl);
        };
        _proto.removeSphereLight = function removeSphereLight(pl) {
          for (var i = 0; i < this._sphereLights.length; ++i) {
            if (this._sphereLights[i] === pl) {
              pl.detachFromScene();
              this._sphereLights.splice(i, 1);
              return;
            }
          }
        };
        _proto.addSpotLight = function addSpotLight(sl) {
          sl.attachToScene(this);
          this._spotLights.push(sl);
        };
        _proto.removeSpotLight = function removeSpotLight(sl) {
          for (var i = 0; i < this._spotLights.length; ++i) {
            if (this._spotLights[i] === sl) {
              sl.detachFromScene();
              this._spotLights.splice(i, 1);
              return;
            }
          }
        };
        _proto.removeSphereLights = function removeSphereLights() {
          for (var i = 0; i < this._sphereLights.length; ++i) {
            this._sphereLights[i].detachFromScene();
          }
          this._sphereLights.length = 0;
        };
        _proto.removeSpotLights = function removeSpotLights() {
          for (var i = 0; i < this._spotLights.length; ++i) {
            this._spotLights[i].detachFromScene();
          }
          this._spotLights.length = 0;
        };
        _proto.addPointLight = function addPointLight(pl) {
          pl.attachToScene(this);
          this._pointLights.push(pl);
        };
        _proto.removePointLight = function removePointLight(pl) {
          for (var i = 0; i < this._pointLights.length; ++i) {
            if (this._pointLights[i] === pl) {
              pl.detachFromScene();
              this._pointLights.splice(i, 1);
              return;
            }
          }
        };
        _proto.removePointLights = function removePointLights() {
          for (var i = 0; i < this._pointLights.length; ++i) {
            this._pointLights[i].detachFromScene();
          }
          this._pointLights.length = 0;
        };
        _proto.addRangedDirLight = function addRangedDirLight(l) {
          l.attachToScene(this);
          this._rangedDirLights.push(l);
        };
        _proto.removeRangedDirLight = function removeRangedDirLight(l) {
          for (var i = 0; i < this._rangedDirLights.length; ++i) {
            if (this._rangedDirLights[i] === l) {
              l.detachFromScene();
              this._rangedDirLights.splice(i, 1);
              return;
            }
          }
        };
        _proto.removeRangedDirLights = function removeRangedDirLights() {
          for (var i = 0; i < this._rangedDirLights.length; ++i) {
            this._rangedDirLights[i].detachFromScene();
          }
          this._rangedDirLights.length = 0;
        };
        _proto.addModel = function addModel(m) {
          m.attachToScene(this);
          this._models.push(m);
        };
        _proto.removeModel = function removeModel(model) {
          for (var i = 0; i < this._models.length; ++i) {
            if (this._models[i] === model) {
              this._lodStateCache.removeModel(model);
              model.detachFromScene();
              this._models.splice(i, 1);
              return;
            }
          }
        };
        _proto.removeModels = function removeModels() {
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._models), _step2; !(_step2 = _iterator2()).done;) {
            var m = _step2.value;
            this._lodStateCache.removeModel(m);
            m.detachFromScene();
            m.destroy();
          }
          this._models.length = 0;
        };
        _proto.addBatch = function addBatch(batch) {
          this._batches.push(batch);
        };
        _proto.removeBatch = function removeBatch(batch) {
          for (var i = 0; i < this._batches.length; ++i) {
            if (this._batches[i] === batch) {
              this._batches.splice(i, 1);
              return;
            }
          }
        };
        _proto.removeBatches = function removeBatches() {
          this._batches.length = 0;
        };
        _proto.addLODGroup = function addLODGroup(lodGroup) {
          this._lodGroups.push(lodGroup);
          lodGroup.attachToScene(this);
          this._lodStateCache.addLodGroup(lodGroup);
        };
        _proto.removeLODGroup = function removeLODGroup(lodGroup) {
          var index = this._lodGroups.indexOf(lodGroup);
          if (index >= 0) {
            this._lodGroups.splice(index, 1);
            lodGroup.detachFromScene();
            this._lodStateCache.removeLodGroup(lodGroup);
          }
        };
        _proto.removeLODGroups = function removeLODGroups() {
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._lodGroups), _step3; !(_step3 = _iterator3()).done;) {
            var group = _step3.value;
            this._lodStateCache.removeLodGroup(group);
          }
          this._lodGroups.length = 0;
        };
        _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {
          for (var _iterator4 = _createForOfIteratorHelperLoose(this._models), _step4; !(_step4 = _iterator4()).done;) {
            var m = _step4.value;
            m.onGlobalPipelineStateChanged();
          }
        };
        _proto.generateModelId = function generateModelId() {
          return this._modelId++;
        };
        _createClass(RenderScene, [{
          key: "root",
          get: function get() {
            return this._root;
          }
        }, {
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "cameras",
          get: function get() {
            return this._cameras;
          }
        }, {
          key: "mainLight",
          get: function get() {
            return this._mainLight;
          }
        }, {
          key: "sphereLights",
          get: function get() {
            return this._sphereLights;
          }
        }, {
          key: "spotLights",
          get: function get() {
            return this._spotLights;
          }
        }, {
          key: "pointLights",
          get: function get() {
            return this._pointLights;
          }
        }, {
          key: "rangedDirLights",
          get: function get() {
            return this._rangedDirLights;
          }
        }, {
          key: "models",
          get: function get() {
            return this._models;
          }
        }, {
          key: "batches",
          get: function get() {
            return this._batches;
          }
        }, {
          key: "lodGroups",
          get: function get() {
            return this._lodGroups;
          }
        }]);
        return RenderScene;
      }();
      var LODInfo = function LODInfo() {
        this.usedLevel = -1;
        this.lastUsedLevel = -1;
        this.transformDirty = true;
      };
      var LodStateCache = function () {
        function LodStateCache(scene) {
          this._renderScene = null;
          this._modelsInLODGroup = new Map();
          this._lodStateInCamera = new Map();
          this._newAddedLodGroupVec = new Array();
          this._levelModels = new Map();
          this._renderScene = scene;
        }
        var _proto2 = LodStateCache.prototype;
        _proto2.addCamera = function addCamera(camera) {
          for (var _iterator5 = _createForOfIteratorHelperLoose(this._renderScene.lodGroups), _step5; !(_step5 = _iterator5()).done;) {
            var lodGroup = _step5.value;
            var layer = lodGroup.node.layer;
            if ((camera.visibility & layer) === layer) {
              if (!this._lodStateInCamera.has(camera)) {
                this._lodStateInCamera.set(camera, new Map());
              }
              break;
            }
          }
        };
        _proto2.removeCamera = function removeCamera(camera) {
          if (this._lodStateInCamera.has(camera)) {
            this._lodStateInCamera["delete"](camera);
          }
        };
        _proto2.addLodGroup = function addLodGroup(lodGroup) {
          this._newAddedLodGroupVec.push(lodGroup);
          for (var _iterator6 = _createForOfIteratorHelperLoose(this._renderScene.cameras), _step6; !(_step6 = _iterator6()).done;) {
            var camera = _step6.value;
            if (this._lodStateInCamera.has(camera)) {
              continue;
            }
            var layer = lodGroup.node.layer;
            if ((camera.visibility & layer) === layer) {
              this._lodStateInCamera.set(camera, new Map());
            }
          }
        };
        _proto2.removeLodGroup = function removeLodGroup(lodGroup) {
          for (var index = 0; index < lodGroup.lodCount; index++) {
            var lod = lodGroup.lodDataArray[index];
            for (var _iterator7 = _createForOfIteratorHelperLoose(lod.models), _step7; !(_step7 = _iterator7()).done;) {
              var model = _step7.value;
              this._modelsInLODGroup["delete"](model);
            }
          }
          for (var _iterator8 = _createForOfIteratorHelperLoose(this._lodStateInCamera), _step8; !(_step8 = _iterator8()).done;) {
            var visibleCamera = _step8.value;
            visibleCamera[1]["delete"](lodGroup);
          }
          this._levelModels["delete"](lodGroup);
        };
        _proto2.removeModel = function removeModel(model) {
          if (this._modelsInLODGroup.has(model)) {
            this._modelsInLODGroup["delete"](model);
          }
        };
        _proto2.updateLodState = function updateLodState() {
          var _this = this;
          for (var _iterator9 = _createForOfIteratorHelperLoose(this._newAddedLodGroupVec), _step9; !(_step9 = _iterator9()).done;) {
            var addedLodGroup = _step9.value;
            var levelModels = this._levelModels.get(addedLodGroup);
            if (!levelModels) {
              levelModels = new Map();
              this._levelModels.set(addedLodGroup, levelModels);
            }
            for (var index = 0; index < addedLodGroup.lodCount; index++) {
              var lodModels = levelModels.get(index);
              if (!lodModels) {
                lodModels = new Array();
              }
              var lod = addedLodGroup.lodDataArray[index];
              for (var _iterator11 = _createForOfIteratorHelperLoose(lod.models), _step11; !(_step11 = _iterator11()).done;) {
                var model = _step11.value;
                var modelInfo = this._modelsInLODGroup.get(model);
                if (!modelInfo) {
                  modelInfo = new Map();
                }
                this._modelsInLODGroup.set(model, modelInfo);
                lodModels.push(model);
              }
              levelModels.set(index, lodModels);
            }
          }
          this._newAddedLodGroupVec.length = 0;
          var _loop = function _loop() {
              var lodGroup = _step10.value;
              if (lodGroup.enabled) {
                var lodLevels = lodGroup.getLockedLODLevels();
                var count = lodLevels.length;
                if (count > 0) {
                  if (lodGroup.node.hasChangedFlags > 0) {
                    for (var _iterator12 = _createForOfIteratorHelperLoose(_this._lodStateInCamera), _step12; !(_step12 = _iterator12()).done;) {
                      var visibleCamera = _step12.value;
                      var lodInfo = visibleCamera[1].get(lodGroup);
                      if (!lodInfo) {
                        lodInfo = new LODInfo();
                        visibleCamera[1].set(lodGroup, lodInfo);
                      }
                      lodInfo.transformDirty = true;
                    }
                  }
                  if (lodGroup.isLockLevelChanged()) {
                    lodGroup.resetLockChangeFlag();
                    var _lodModels = _this._levelModels.get(lodGroup);
                    if (_lodModels) {
                      _lodModels.forEach(function (vecArray, index) {
                        vecArray.forEach(function (model) {
                          var modelInfo = _this._modelsInLODGroup.get(model);
                          if (modelInfo) {
                            modelInfo.clear();
                          }
                        });
                      });
                      for (var _iterator13 = _createForOfIteratorHelperLoose(lodLevels), _step13; !(_step13 = _iterator13()).done;) {
                        var visibleIndex = _step13.value;
                        var vecModels = _lodModels.get(visibleIndex);
                        if (vecModels) {
                          vecModels.forEach(function (model) {
                            var modelInfo = _this._modelsInLODGroup.get(model);
                            if (modelInfo && model.node && model.node.active) {
                              for (var _iterator14 = _createForOfIteratorHelperLoose(_this._lodStateInCamera), _step14; !(_step14 = _iterator14()).done;) {
                                var _visibleCamera = _step14.value;
                                modelInfo.set(_visibleCamera[0], true);
                              }
                            }
                          });
                        }
                      }
                    }
                  }
                  return 0;
                }
                var hasUpdated = false;
                for (var _iterator15 = _createForOfIteratorHelperLoose(_this._lodStateInCamera), _step15; !(_step15 = _iterator15()).done;) {
                  var _visibleCamera2 = _step15.value;
                  var _lodInfo = _visibleCamera2[1].get(lodGroup);
                  if (!_lodInfo) {
                    _lodInfo = new LODInfo();
                    _visibleCamera2[1].set(lodGroup, _lodInfo);
                  }
                  var cameraChangeFlags = _visibleCamera2[0].node.hasChangedFlags;
                  var lodChangeFlags = lodGroup.node.hasChangedFlags;
                  if (cameraChangeFlags > 0 || lodChangeFlags > 0 || _lodInfo.transformDirty) {
                    if (_lodInfo.transformDirty) {
                      _lodInfo.transformDirty = false;
                    }
                    var _index = lodGroup.getVisibleLODLevel(_visibleCamera2[0]);
                    if (_index !== _lodInfo.usedLevel) {
                      _lodInfo.lastUsedLevel = _lodInfo.usedLevel;
                      _lodInfo.usedLevel = _index;
                      hasUpdated = true;
                    }
                  }
                }
                var _lodModels2 = _this._levelModels.get(lodGroup);
                if (!_lodModels2) {
                  return 0;
                }
                if (lodGroup.isLockLevelChanged()) {
                  lodGroup.resetLockChangeFlag();
                  _lodModels2.forEach(function (vecArray, index) {
                    vecArray.forEach(function (model) {
                      var modelInfo = _this._modelsInLODGroup.get(model);
                      if (modelInfo) {
                        modelInfo.clear();
                      }
                    });
                  });
                  hasUpdated = true;
                } else if (hasUpdated) {
                  _this._lodStateInCamera.forEach(function (lodState, camera) {
                    var lodInfo = lodState.get(lodGroup);
                    if (lodInfo && lodInfo.usedLevel !== lodInfo.lastUsedLevel) {
                      var _vecModels = _lodModels2.get(lodInfo.lastUsedLevel);
                      if (_vecModels) {
                        _vecModels.forEach(function (model) {
                          var modelInfo = _this._modelsInLODGroup.get(model);
                          if (modelInfo) {
                            modelInfo.clear();
                          }
                        });
                      }
                    }
                  });
                }
                if (hasUpdated) {
                  _this._lodStateInCamera.forEach(function (lodState, camera) {
                    var lodInfo = lodState.get(lodGroup);
                    if (lodInfo) {
                      var usedLevel = lodInfo.usedLevel;
                      var _vecModels2 = _lodModels2.get(usedLevel);
                      if (_vecModels2) {
                        _vecModels2.forEach(function (model) {
                          var modelInfo = _this._modelsInLODGroup.get(model);
                          if (modelInfo && model.node && model.node.active) {
                            modelInfo.set(camera, true);
                          }
                        });
                      }
                    }
                  });
                }
              }
            },
            _ret;
          for (var _iterator10 = _createForOfIteratorHelperLoose(this._renderScene.lodGroups), _step10; !(_step10 = _iterator10()).done;) {
            _ret = _loop();
            if (_ret === 0) continue;
          }
        };
        _proto2.isLodModelCulled = function isLodModelCulled(camera, model) {
          var modelInfo = this._modelsInLODGroup.get(model);
          if (!modelInfo) {
            return false;
          }
          return !modelInfo.has(camera);
        };
        _proto2.clearCache = function clearCache() {
          this._levelModels.clear();
          this._modelsInLODGroup.clear();
          this._lodStateInCamera.clear();
          this._newAddedLodGroupVec.length = 0;
        };
        _proto2.isLodGroupVisibleByCamera = function isLodGroupVisibleByCamera(lodGroup, camera) {
          var layer = lodGroup.node.layer;
          return (camera.visibility & layer) === layer;
        };
        return LodStateCache;
      }();

      var _orientationMap$1;
      var orientationMap$1 = (_orientationMap$1 = {}, _orientationMap$1[Orientation$1.PORTRAIT] = SurfaceTransform.IDENTITY, _orientationMap$1[Orientation$1.LANDSCAPE_RIGHT] = SurfaceTransform.ROTATE_90, _orientationMap$1[Orientation$1.PORTRAIT_UPSIDE_DOWN] = SurfaceTransform.ROTATE_180, _orientationMap$1[Orientation$1.LANDSCAPE_LEFT] = SurfaceTransform.ROTATE_270, _orientationMap$1);
      var RenderWindow = function () {
        RenderWindow.registerCreateFunc = function registerCreateFunc(root) {
          root._createWindowFun = function (_root) {
            return new RenderWindow();
          };
        };
        function RenderWindow(root) {
          this._title = '';
          this._width = 1;
          this._height = 1;
          this._swapchain = null;
          this._renderPass = null;
          this._colorTextures = [];
          this._depthStencilTexture = null;
          this._cameras = [];
          this._hasOnScreenAttachments = false;
          this._hasOffScreenAttachments = false;
          this._framebuffer = null;
          this._device = null;
        }
        var _proto = RenderWindow.prototype;
        _proto.initialize = function initialize(device, info) {
          if (info.title !== undefined) {
            this._title = info.title;
          }
          if (info.swapchain !== undefined) {
            this._swapchain = info.swapchain;
          }
          this._width = info.width;
          this._height = info.height;
          this._device = device;
          this._renderPass = device.createRenderPass(info.renderPassInfo);
          if (info.swapchain) {
            this._swapchain = info.swapchain;
            this._colorTextures.push(info.swapchain.colorTexture);
            this._depthStencilTexture = info.swapchain.depthStencilTexture;
          } else {
            for (var i = 0; i < info.renderPassInfo.colorAttachments.length; i++) {
              var textureInfo = new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_SRC, info.renderPassInfo.colorAttachments[i].format, this._width, this._height);
              if (info.externalFlag && (info.externalFlag & TextureFlagBit.EXTERNAL_NORMAL || info.externalFlag & TextureFlagBit.EXTERNAL_OES)) {
                textureInfo.flags |= info.externalFlag;
                textureInfo.externalRes = info.externalResLow ? info.externalResLow : 0;
              }
              this._colorTextures.push(device.createTexture(textureInfo));
            }
            if (info.renderPassInfo.depthStencilAttachment.format !== Format.UNKNOWN) {
              this._depthStencilTexture = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.DEPTH_STENCIL_ATTACHMENT | TextureUsageBit.SAMPLED, info.renderPassInfo.depthStencilAttachment.format, this._width, this._height));
              this._hasOffScreenAttachments = true;
            }
          }
          this._framebuffer = device.createFramebuffer(new FramebufferInfo(this._renderPass, this._colorTextures, this._depthStencilTexture));
          return true;
        };
        _proto.destroy = function destroy() {
          this.clearCameras();
          if (this._framebuffer) {
            this._framebuffer.destroy();
            this._framebuffer = null;
          }
          if (this._depthStencilTexture) {
            this._depthStencilTexture.destroy();
            this._depthStencilTexture = null;
          }
          for (var i = 0; i < this._colorTextures.length; i++) {
            var colorTexture = this._colorTextures[i];
            if (colorTexture) {
              colorTexture.destroy();
            }
          }
          this._colorTextures.length = 0;
          this._device = null;
        };
        _proto.resize = function resize(width, height) {
          if (this._swapchain) {
            this._swapchain.resize(width, height, orientationMap$1[screenAdapter.orientation]);
            this._width = this._swapchain.width;
            this._height = this._swapchain.height;
          } else {
            for (var i = 0; i < this._colorTextures.length; i++) {
              this._colorTextures[i].resize(width, height);
            }
            if (this._depthStencilTexture) {
              this._depthStencilTexture.resize(width, height);
            }
            this._width = width;
            this._height = height;
          }
          if (this.framebuffer) {
            this.framebuffer.destroy();
            this._framebuffer = this._device.createFramebuffer(new FramebufferInfo(this._renderPass, this._colorTextures, this._depthStencilTexture));
          }
          for (var _iterator = _createForOfIteratorHelperLoose(this._cameras), _step; !(_step = _iterator()).done;) {
            var camera = _step.value;
            camera.resize(width, height);
          }
        };
        _proto.extractRenderCameras = function extractRenderCameras(cameras) {
          for (var j = 0; j < this._cameras.length; j++) {
            var camera = this._cameras[j];
            if (camera.enabled) {
              camera.update();
              cameras.push(camera);
            }
          }
        };
        _proto.attachCamera = function attachCamera(camera) {
          for (var i = 0; i < this._cameras.length; i++) {
            if (this._cameras[i] === camera) {
              return;
            }
          }
          this._cameras.push(camera);
          this.sortCameras();
        };
        _proto.detachCamera = function detachCamera(camera) {
          for (var i = 0; i < this._cameras.length; ++i) {
            if (this._cameras[i] === camera) {
              this._cameras.splice(i, 1);
              return;
            }
          }
        };
        _proto.clearCameras = function clearCameras() {
          this._cameras.length = 0;
        };
        _proto.sortCameras = function sortCameras() {
          this._cameras.sort(function (a, b) {
            return a.priority - b.priority;
          });
        };
        _createClass(RenderWindow, [{
          key: "width",
          get: function get() {
            return this._width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          }
        }, {
          key: "swapchain",
          get: function get() {
            return this._swapchain;
          }
        }, {
          key: "framebuffer",
          get: function get() {
            return this._framebuffer;
          }
        }, {
          key: "cameras",
          get: function get() {
            return this._cameras;
          }
        }]);
        return RenderWindow;
      }();

      var XREye;
      (function (XREye) {
        XREye[XREye["NONE"] = -1] = "NONE";
        XREye[XREye["LEFT"] = 0] = "LEFT";
        XREye[XREye["RIGHT"] = 1] = "RIGHT";
      })(XREye || (XREye = {}));
      var XRConfigKey;
      (function (XRConfigKey) {
        XRConfigKey[XRConfigKey["SESSION_RUNNING"] = 2] = "SESSION_RUNNING";
        XRConfigKey[XRConfigKey["VIEW_COUNT"] = 6] = "VIEW_COUNT";
        XRConfigKey[XRConfigKey["SWAPCHAIN_WIDTH"] = 7] = "SWAPCHAIN_WIDTH";
        XRConfigKey[XRConfigKey["SWAPCHAIN_HEIGHT"] = 8] = "SWAPCHAIN_HEIGHT";
        XRConfigKey[XRConfigKey["DEVICE_IPD"] = 37] = "DEVICE_IPD";
        XRConfigKey[XRConfigKey["SPLIT_AR_GLASSES"] = 42] = "SPLIT_AR_GLASSES";
      })(XRConfigKey || (XRConfigKey = {}));
      var XRPoseType;
      (function (XRPoseType) {
        XRPoseType[XRPoseType["VIEW_LEFT"] = 0] = "VIEW_LEFT";
        XRPoseType[XRPoseType["HAND_LEFT"] = 1] = "HAND_LEFT";
        XRPoseType[XRPoseType["AIM_LEFT"] = 2] = "AIM_LEFT";
        XRPoseType[XRPoseType["VIEW_RIGHT"] = 3] = "VIEW_RIGHT";
        XRPoseType[XRPoseType["HAND_RIGHT"] = 4] = "HAND_RIGHT";
        XRPoseType[XRPoseType["AIM_RIGHT"] = 5] = "AIM_RIGHT";
        XRPoseType[XRPoseType["HEAD_MIDDLE"] = 6] = "HEAD_MIDDLE";
      })(XRPoseType || (XRPoseType = {}));

      var Root = exports('aH', function () {
        function Root(device) {
          var _this = this;
          this._createSceneFun = null;
          this._createWindowFun = null;
          this._device = void 0;
          this._windows = [];
          this._mainWindow = null;
          this._curWindow = null;
          this._tempWindow = null;
          this._usesCustomPipeline = true;
          this._pipeline = null;
          this._pipelineEvent = null;
          this._classicPipeline = null;
          this._customPipeline = null;
          this._batcher = null;
          this._dataPoolMgr = void 0;
          this._scenes = [];
          this._modelPools = new Map();
          this._cameraPool = null;
          this._lightPools = new Map();
          this._debugView = new DebugView();
          this._fpsTime = 0;
          this._frameCount = 0;
          this._fps = 0;
          this._fixedFPS = 0;
          this._useDeferredPipeline = false;
          this._fixedFPSFrameTime = 0;
          this._cumulativeTime = 0;
          this._frameTime = 0;
          this._cameraList = [];
          this._device = device;
          this._dataPoolMgr = legacyCC.internal.DataPoolManager && new legacyCC.internal.DataPoolManager(device);
          RenderScene.registerCreateFunc(this);
          RenderWindow.registerCreateFunc(this);
          this._cameraPool = new Pool(function () {
            return new Camera$1(_this._device);
          }, 4, function (cam) {
            return cam.destroy();
          });
        }
        var _proto = Root.prototype;
        _proto.initialize = function initialize(info) {
          var _this$_dataPoolMgr;
          var swapchain = deviceManager.swapchain;
          var colorAttachment = new ColorAttachment();
          colorAttachment.format = swapchain.colorTexture.format;
          var depthStencilAttachment = new DepthStencilAttachment();
          depthStencilAttachment.format = swapchain.depthStencilTexture.format;
          depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;
          depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
          var renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment);
          this._mainWindow = this.createWindow({
            title: 'rootMainWindow',
            width: swapchain.width,
            height: swapchain.height,
            renderPassInfo: renderPassInfo,
            swapchain: swapchain
          });
          this._curWindow = this._mainWindow;
          var customJointTextureLayouts = settings.querySettings(Settings.Category.ANIMATION, 'customJointTextureLayouts') || [];
          (_this$_dataPoolMgr = this._dataPoolMgr) === null || _this$_dataPoolMgr === void 0 ? void 0 : _this$_dataPoolMgr.jointTexturePool.registerCustomTextureLayouts(customJointTextureLayouts);
          this._resizeMaxJointForDS();
        };
        _proto.destroy = function destroy() {
          this.destroyScenes();
          if (this._pipeline) {
            this._pipeline.destroy();
            this._pipeline = null;
            this._pipelineEvent = null;
          }
          if (this._batcher) {
            this._batcher.destroy();
            this._batcher = null;
          }
          this._curWindow = null;
          this._mainWindow = null;
          this.dataPoolManager.clear();
          if (legacyCC.rendering) {
            legacyCC.rendering.destroy();
          }
        };
        _proto.resize = function resize(width, height, windowId) {
          for (var _iterator = _createForOfIteratorHelperLoose(this._windows), _step; !(_step = _iterator()).done;) {
            var window = _step.value;
            if (window.swapchain) {
              window.resize(width, height);
            }
          }
        };
        _proto.setRenderPipeline = function setRenderPipeline(rppl) {
          var internal = legacyCC.internal,
            director = legacyCC.director,
            rendering = legacyCC.rendering;
          if (rppl instanceof DeferredPipeline) {
            this._useDeferredPipeline = true;
          }
          var isCreateDefaultPipeline = false;
          if (!rppl) {
            rppl = createDefaultPipeline();
            isCreateDefaultPipeline = true;
          }
          if (!this._useDeferredPipeline || !this.device.hasFeature(Feature.COMPUTE_SHADER)) {
            rppl.clusterEnabled = false;
          }
          rppl.bloomEnabled = false;
          if (macro.CUSTOM_PIPELINE_NAME !== '' && rendering && this.usesCustomPipeline) {
            this._customPipeline = rendering.createCustomPipeline();
            isCreateDefaultPipeline = true;
            this._pipeline = this._customPipeline;
            this._pipelineEvent = rppl;
            log('Using custom pipeline');
          } else {
            this._classicPipeline = rppl;
            this._pipeline = this._classicPipeline;
            this._pipelineEvent = this._classicPipeline;
            this._usesCustomPipeline = false;
          }
          var renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode');
          if (renderMode !== LegacyRenderMode.HEADLESS || this._classicPipeline) {
            if (!this._pipeline.activate(this._mainWindow.swapchain)) {
              if (isCreateDefaultPipeline) {
                this._pipeline.destroy();
              }
              this._classicPipeline = null;
              this._customPipeline = null;
              this._pipeline = null;
              this._pipelineEvent = null;
              return false;
            }
          }
          var scene = director.getScene();
          if (scene) {
            scene.globals.activate();
          }
          this.onGlobalPipelineStateChanged();
          if (!this._batcher && internal.Batcher2D) {
            this._batcher = new internal.Batcher2D(this);
            if (!this._batcher.initialize()) {
              this.destroy();
              return false;
            }
          }
          return true;
        };
        _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {
          for (var i = 0; i < this._scenes.length; i++) {
            this._scenes[i].onGlobalPipelineStateChanged();
          }
          if (this._pipeline.pipelineSceneData.skybox.enabled) {
            this._pipeline.pipelineSceneData.skybox.model.onGlobalPipelineStateChanged();
          }
          this._pipeline.onGlobalPipelineStateChanged();
        };
        _proto.activeWindow = function activeWindow(window) {
          this._curWindow = window;
        };
        _proto.resetCumulativeTime = function resetCumulativeTime() {
          this._cumulativeTime = 0;
        };
        _proto.frameMove = function frameMove(deltaTime) {
          var _globalThis$__globalX;
          this._frameTime = deltaTime;
          ++this._frameCount;
          this._cumulativeTime += deltaTime;
          this._fpsTime += deltaTime;
          if (this._fpsTime > 1.0) {
            this._fps = this._frameCount;
            this._frameCount = 0;
            this._fpsTime = 0.0;
          }
          if ((_globalThis$__globalX = globalThis.__globalXR) !== null && _globalThis$__globalX !== void 0 && _globalThis$__globalX.isWebXR) {
            this._doWebXRFrameMove();
          } else {
            this._frameMoveBegin();
            this._frameMoveProcess();
            this._frameMoveEnd();
          }
        };
        _proto.createWindow = function createWindow(info) {
          var window = this._createWindowFun(this);
          window.initialize(this.device, info);
          this._windows.push(window);
          return window;
        };
        _proto.destroyWindow = function destroyWindow(window) {
          for (var i = 0; i < this._windows.length; ++i) {
            if (this._windows[i] === window) {
              window.destroy();
              this._windows.splice(i, 1);
              return;
            }
          }
        };
        _proto.destroyWindows = function destroyWindows() {
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._windows), _step2; !(_step2 = _iterator2()).done;) {
            var window = _step2.value;
            window.destroy();
          }
          this._windows.length = 0;
        };
        _proto.createScene = function createScene(info) {
          var scene = this._createSceneFun(this);
          scene.initialize(info);
          this._scenes.push(scene);
          return scene;
        };
        _proto.destroyScene = function destroyScene(scene) {
          for (var i = 0; i < this._scenes.length; ++i) {
            if (this._scenes[i] === scene) {
              scene.destroy();
              this._scenes.splice(i, 1);
              return;
            }
          }
        };
        _proto.destroyScenes = function destroyScenes() {
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._scenes), _step3; !(_step3 = _iterator3()).done;) {
            var scene = _step3.value;
            scene.destroy();
          }
          this._scenes.length = 0;
        };
        _proto.createModel = function createModel(ModelCtor) {
          var p = this._modelPools.get(ModelCtor);
          if (!p) {
            this._modelPools.set(ModelCtor, new Pool(function () {
              return new ModelCtor();
            }, 10, function (obj) {
              return obj.destroy();
            }));
            p = this._modelPools.get(ModelCtor);
          }
          var model = p.alloc();
          model.initialize();
          return model;
        };
        _proto.destroyModel = function destroyModel(m) {
          var p = this._modelPools.get(m.constructor);
          if (p) {
            p.free(m);
            if (m.scene) {
              m.scene.removeModel(m);
            }
          } else {
            warnID(1300, m.constructor.name);
          }
          m.destroy();
        };
        _proto.createCamera = function createCamera() {
          return this._cameraPool.alloc();
        };
        _proto.createLight = function createLight(LightCtor) {
          var l = this._lightPools.get(LightCtor);
          if (!l) {
            this._lightPools.set(LightCtor, new Pool(function () {
              return new LightCtor();
            }, 4, function (obj) {
              return obj.destroy();
            }));
            l = this._lightPools.get(LightCtor);
          }
          var light = l.alloc();
          light.initialize();
          return light;
        };
        _proto.destroyLight = function destroyLight(l) {
          if (l.scene) {
            switch (l.type) {
              case LightType.DIRECTIONAL:
                l.scene.removeDirectionalLight(l);
                break;
              case LightType.SPHERE:
                l.scene.removeSphereLight(l);
                break;
              case LightType.SPOT:
                l.scene.removeSpotLight(l);
                break;
              case LightType.POINT:
                l.scene.removePointLight(l);
                break;
              case LightType.RANGED_DIRECTIONAL:
                l.scene.removeRangedDirLight(l);
                break;
            }
          }
          l.destroy();
        };
        _proto.recycleLight = function recycleLight(l) {
          var p = this._lightPools.get(l.constructor);
          if (p) {
            p.free(l);
            if (l.scene) {
              switch (l.type) {
                case LightType.DIRECTIONAL:
                  l.scene.removeDirectionalLight(l);
                  break;
                case LightType.SPHERE:
                  l.scene.removeSphereLight(l);
                  break;
                case LightType.SPOT:
                  l.scene.removeSpotLight(l);
                  break;
                case LightType.POINT:
                  l.scene.removePointLight(l);
                  break;
                case LightType.RANGED_DIRECTIONAL:
                  l.scene.removeRangedDirLight(l);
                  break;
              }
            }
          }
        };
        _proto._doWebXRFrameMove = function _doWebXRFrameMove() {
          var xr = globalThis.__globalXR;
          if (!xr) {
            return;
          }
          var windows = this._windows;
          var cameraList = this._cameraList;
          var viewCount = xr.webXRMatProjs ? xr.webXRMatProjs.length : 1;
          if (!xr.webXRWindowMap) {
            xr.webXRWindowMap = new Map();
          }
          var allcameras = [];
          var webxrHmdPoseInfos = xr.webxrHmdPoseInfos;
          for (var xrEye = 0; xrEye < viewCount; xrEye++) {
            for (var _iterator4 = _createForOfIteratorHelperLoose(windows), _step4; !(_step4 = _iterator4()).done;) {
              var window = _step4.value;
              allcameras = allcameras.concat(window.cameras);
              if (window.swapchain) {
                xr.webXRWindowMap.set(window, xrEye);
              }
            }
            if (webxrHmdPoseInfos) {
              var cameraPosition = [0, 0, 0];
              for (var i = 0; i < webxrHmdPoseInfos.length; i++) {
                var info = webxrHmdPoseInfos[i];
                if (info.code === XRPoseType.VIEW_LEFT && xrEye === XREye.LEFT || info.code === XRPoseType.VIEW_RIGHT && xrEye === XREye.RIGHT) {
                  cameraPosition[0] = info.position.x;
                  cameraPosition[1] = info.position.y;
                  cameraPosition[2] = info.position.z;
                  break;
                }
              }
              for (var _iterator5 = _createForOfIteratorHelperLoose(allcameras), _step5; !(_step5 = _iterator5()).done;) {
                var cam = _step5.value;
                if (cam.trackingType !== TrackingType.NO_TRACKING && cam.node) {
                  var isTrackingRotation = cam.trackingType === TrackingType.ROTATION;
                  if (isTrackingRotation) {
                    cameraPosition = [0, 0, 0];
                  }
                  cam.node.setPosition(cameraPosition[0], cameraPosition[1], cameraPosition[2]);
                }
              }
            }
            allcameras.length = 0;
            this._frameMoveBegin();
            this._frameMoveProcess();
            for (var _i = cameraList.length - 1; _i >= 0; _i--) {
              var camera = cameraList[_i];
              var isMismatchedCam = xrEye === XREye.LEFT && camera.cameraType === CameraType.RIGHT_EYE || xrEye === XREye.RIGHT && camera.cameraType === CameraType.LEFT_EYE;
              if (isMismatchedCam) {
                cameraList.splice(_i, 1);
              }
            }
            this._frameMoveEnd();
          }
        };
        _proto._frameMoveBegin = function _frameMoveBegin() {
          for (var i = 0; i < this._scenes.length; ++i) {
            this._scenes[i].removeBatches();
          }
          this._cameraList.length = 0;
        };
        _proto._frameMoveProcess = function _frameMoveProcess() {
          var director = legacyCC.director;
          var windows = this._windows;
          var cameraList = this._cameraList;
          for (var i = 0; i < windows.length; i++) {
            var window = windows[i];
            window.extractRenderCameras(cameraList);
          }
          if (this._pipeline && cameraList.length > 0) {
            this._device.acquire([deviceManager.swapchain]);
            var scenes = this._scenes;
            var stamp = director.getTotalFrames();
            if (this._batcher) {
              this._batcher.update();
              this._batcher.uploadBuffers();
            }
            for (var _i2 = 0; _i2 < scenes.length; _i2++) {
              scenes[_i2].update(stamp);
            }
          }
        };
        _proto._frameMoveEnd = function _frameMoveEnd() {
          var director = legacyCC.director,
            Director = legacyCC.Director;
          var cameraList = this._cameraList;
          if (this._pipeline && cameraList.length > 0) {
            director.emit(Director.EVENT_BEFORE_COMMIT);
            cameraList.sort(function (a, b) {
              return a.priority - b.priority;
            });
            for (var i = 0; i < cameraList.length; ++i) {
              var _cameraList$i$geometr;
              (_cameraList$i$geometr = cameraList[i].geometryRenderer) === null || _cameraList$i$geometr === void 0 ? void 0 : _cameraList$i$geometr.update();
            }
            director.emit(Director.EVENT_BEFORE_RENDER);
            this._pipeline.render(cameraList);
            director.emit(Director.EVENT_AFTER_RENDER);
            this._device.present();
          }
          if (this._batcher) this._batcher.reset();
        };
        _proto._resizeMaxJointForDS = function _resizeMaxJointForDS() {
          var usedUBOVectorCount = Math.max((UBOGlobal.COUNT + UBOCamera.COUNT + UBOShadow.COUNT + UBOLocal.COUNT + UBOWorldBound.COUNT) / 4, 100);
          var maxJoints = Math.floor((deviceManager.gfxDevice.capabilities.maxVertexUniformVectors - usedUBOVectorCount) / 3);
          maxJoints = maxJoints < 256 ? maxJoints : 256;
          localDescriptorSetLayout_ResizeMaxJoints(maxJoints);
        };
        _createClass(Root, [{
          key: "device",
          get: function get() {
            return this._device;
          }
        }, {
          key: "mainWindow",
          get: function get() {
            return this._mainWindow;
          }
        }, {
          key: "curWindow",
          get: function get() {
            return this._curWindow;
          },
          set: function set(window) {
            this._curWindow = window;
          }
        }, {
          key: "tempWindow",
          get: function get() {
            return this._tempWindow;
          },
          set: function set(window) {
            this._tempWindow = window;
          }
        }, {
          key: "windows",
          get: function get() {
            return this._windows;
          }
        }, {
          key: "usesCustomPipeline",
          get: function get() {
            return this._usesCustomPipeline;
          }
        }, {
          key: "pipeline",
          get: function get() {
            return this._pipeline;
          }
        }, {
          key: "customPipeline",
          get: function get() {
            return this._customPipeline;
          }
        }, {
          key: "pipelineEvent",
          get: function get() {
            return this._pipelineEvent;
          }
        }, {
          key: "batcher2D",
          get: function get() {
            return this._batcher;
          }
        }, {
          key: "scenes",
          get: function get() {
            return this._scenes;
          }
        }, {
          key: "debugView",
          get: function get() {
            return this._debugView;
          }
        }, {
          key: "cumulativeTime",
          get: function get() {
            return this._cumulativeTime;
          }
        }, {
          key: "frameTime",
          get: function get() {
            return this._frameTime;
          }
        }, {
          key: "frameCount",
          get: function get() {
            return this._frameCount;
          }
        }, {
          key: "fps",
          get: function get() {
            return this._fps;
          }
        }, {
          key: "fixedFPS",
          get: function get() {
            return this._fixedFPS;
          },
          set: function set(fps) {
            if (fps > 0) {
              this._fixedFPS = fps;
              this._fixedFPSFrameTime = 1000.0 / fps;
            } else {
              this._fixedFPSFrameTime = 0;
            }
          }
        }, {
          key: "dataPoolManager",
          get: function get() {
            return this._dataPoolMgr;
          }
        }, {
          key: "useDeferredPipeline",
          get: function get() {
            return this._useDeferredPipeline;
          }
        }, {
          key: "cameraList",
          get: function get() {
            return this._cameraList;
          }
        }]);
        return Root;
      }());
      legacyCC.Root = Root;

      CCClass.Attr.setClassAttr(EventHandler, 'target', 'type', 'Object');
      CCClass.Attr.setClassAttr(EventHandler, 'target', 'ctor', Node$1);

      var _cachedArray = new Array(16);
      var _currentHovered = null;
      var pos = new Vec2();
      var _touchEvents = [NodeEventType.TOUCH_START, NodeEventType.TOUCH_MOVE, NodeEventType.TOUCH_END, NodeEventType.TOUCH_CANCEL];
      var _mouseEvents = [NodeEventType.MOUSE_DOWN, NodeEventType.MOUSE_ENTER, NodeEventType.MOUSE_MOVE, NodeEventType.MOUSE_LEAVE, NodeEventType.MOUSE_UP, NodeEventType.MOUSE_WHEEL];
      var DispatcherEventType;
      (function (DispatcherEventType) {
        DispatcherEventType[DispatcherEventType["ADD_POINTER_EVENT_PROCESSOR"] = 0] = "ADD_POINTER_EVENT_PROCESSOR";
        DispatcherEventType[DispatcherEventType["REMOVE_POINTER_EVENT_PROCESSOR"] = 1] = "REMOVE_POINTER_EVENT_PROCESSOR";
        DispatcherEventType[DispatcherEventType["MARK_LIST_DIRTY"] = 2] = "MARK_LIST_DIRTY";
      })(DispatcherEventType || (DispatcherEventType = {}));
      var NodeEventProcessor = function () {
        function NodeEventProcessor(node) {
          this.claimedTouchIdList = [];
          this.maskList = null;
          this.cachedCameraPriority = 0;
          this.previousMouseIn = false;
          this.bubblingTarget = null;
          this.capturingTarget = null;
          this.shouldHandleEventMouse = false;
          this.shouldHandleEventTouch = false;
          this._dispatchingTouch = null;
          this._isEnabled = false;
          this._node = void 0;
          this._node = node;
        }
        var _proto = NodeEventProcessor.prototype;
        _proto.setEnabled = function setEnabled(value, recursive) {
          if (recursive === void 0) {
            recursive = false;
          }
          if (this._isEnabled === value) {
            return;
          }
          this._isEnabled = value;
          var node = this.node;
          var children = node.children;
          if (value) {
            this._attachMask();
          }
          NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.MARK_LIST_DIRTY);
          if (recursive && children.length > 0) {
            for (var i = 0; i < children.length; ++i) {
              var child = children[i];
              child.eventProcessor.setEnabled(value, true);
            }
          }
        };
        _proto.reattach = function reattach() {
          var _this = this;
          var currentMaskList;
          this.node.walk(function (node) {
            if (!currentMaskList) {
              currentMaskList = _this._searchComponentsInParent(NodeEventProcessor._maskComp);
            }
            node.eventProcessor.maskList = currentMaskList;
          });
        };
        _proto.destroy = function destroy() {
          if (_currentHovered === this._node) {
            _currentHovered = null;
          }
          if (this.capturingTarget) this.capturingTarget.clear();
          if (this.bubblingTarget) this.bubblingTarget.clear();
          NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, this);
          if (this._dispatchingTouch) {
            var cancelEvent = new EventTouch([this._dispatchingTouch], true, InputEventType.TOUCH_CANCEL);
            cancelEvent.touch = this._dispatchingTouch;
            this.dispatchEvent(cancelEvent);
            this._dispatchingTouch = null;
          }
        };
        _proto.on = function on(type, callback, target, useCapture) {
          this._tryEmittingAddEvent(type);
          useCapture = !!useCapture;
          var invoker;
          if (useCapture) {
            var _this$capturingTarget;
            invoker = (_this$capturingTarget = this.capturingTarget) !== null && _this$capturingTarget !== void 0 ? _this$capturingTarget : this.capturingTarget = this._newCallbacksInvoker();
          } else {
            var _this$bubblingTarget;
            invoker = (_this$bubblingTarget = this.bubblingTarget) !== null && _this$bubblingTarget !== void 0 ? _this$bubblingTarget : this.bubblingTarget = this._newCallbacksInvoker();
          }
          invoker.on(type, callback, target);
          return callback;
        };
        _proto.once = function once(type, callback, target, useCapture) {
          this._tryEmittingAddEvent(type);
          useCapture = !!useCapture;
          var invoker;
          if (useCapture) {
            var _this$capturingTarget2;
            invoker = (_this$capturingTarget2 = this.capturingTarget) !== null && _this$capturingTarget2 !== void 0 ? _this$capturingTarget2 : this.capturingTarget = this._newCallbacksInvoker();
          } else {
            var _this$bubblingTarget2;
            invoker = (_this$bubblingTarget2 = this.bubblingTarget) !== null && _this$bubblingTarget2 !== void 0 ? _this$bubblingTarget2 : this.bubblingTarget = this._newCallbacksInvoker();
          }
          invoker.on(type, callback, target, true);
          return callback;
        };
        _proto.off = function off(type, callback, target, useCapture) {
          var _invoker;
          useCapture = !!useCapture;
          var invoker;
          if (useCapture) {
            invoker = this.capturingTarget;
          } else {
            invoker = this.bubblingTarget;
          }
          (_invoker = invoker) === null || _invoker === void 0 ? void 0 : _invoker.off(type, callback, target);
        };
        _proto.targetOff = function targetOff(target) {
          var _this$capturingTarget3, _this$bubblingTarget3;
          (_this$capturingTarget3 = this.capturingTarget) === null || _this$capturingTarget3 === void 0 ? void 0 : _this$capturingTarget3.removeAll(target);
          (_this$bubblingTarget3 = this.bubblingTarget) === null || _this$bubblingTarget3 === void 0 ? void 0 : _this$bubblingTarget3.removeAll(target);
          if (this.shouldHandleEventTouch && !this._hasTouchListeners()) {
            this.shouldHandleEventTouch = false;
          }
          if (this.shouldHandleEventMouse && !this._hasMouseListeners()) {
            this.shouldHandleEventMouse = false;
          }
          if (!this._hasPointerListeners()) {
            NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, this);
          }
        };
        _proto.emit = function emit(type, arg0, arg1, arg2, arg3, arg4) {
          var _this$bubblingTarget4;
          (_this$bubblingTarget4 = this.bubblingTarget) === null || _this$bubblingTarget4 === void 0 ? void 0 : _this$bubblingTarget4.emit(type, arg0, arg1, arg2, arg3, arg4);
        };
        _proto.dispatchEvent = function dispatchEvent(event) {
          var owner = this.node;
          var target;
          var i = 0;
          event.target = owner;
          _cachedArray.length = 0;
          this.getCapturingTargets(event.type, _cachedArray);
          event.eventPhase = 1;
          for (i = _cachedArray.length - 1; i >= 0; --i) {
            target = _cachedArray[i];
            if (target.eventProcessor.capturingTarget) {
              event.currentTarget = target;
              target.eventProcessor.capturingTarget.emit(event.type, event, _cachedArray);
              if (event.propagationStopped) {
                _cachedArray.length = 0;
                return;
              }
            }
          }
          _cachedArray.length = 0;
          event.eventPhase = 2;
          event.currentTarget = owner;
          if (this.capturingTarget) {
            this.capturingTarget.emit(event.type, event);
          }
          if (!event.propagationImmediateStopped && this.bubblingTarget) {
            this.bubblingTarget.emit(event.type, event);
          }
          if (!event.propagationStopped && event.bubbles) {
            this.getBubblingTargets(event.type, _cachedArray);
            event.eventPhase = 3;
            for (i = 0; i < _cachedArray.length; ++i) {
              target = _cachedArray[i];
              if (target.eventProcessor.bubblingTarget) {
                event.currentTarget = target;
                target.eventProcessor.bubblingTarget.emit(event.type, event);
                if (event.propagationStopped) {
                  _cachedArray.length = 0;
                  return;
                }
              }
            }
          }
          _cachedArray.length = 0;
        };
        _proto.hasEventListener = function hasEventListener(type, callback, target) {
          var has = false;
          if (this.bubblingTarget) {
            has = this.bubblingTarget.hasEventListener(type, callback, target);
          }
          if (!has && this.capturingTarget) {
            has = this.capturingTarget.hasEventListener(type, callback, target);
          }
          return has;
        };
        _proto.getCapturingTargets = function getCapturingTargets(type, targets) {
          var parent = this._node.parent;
          while (parent) {
            var _parent$eventProcesso;
            if ((_parent$eventProcesso = parent.eventProcessor.capturingTarget) !== null && _parent$eventProcesso !== void 0 && _parent$eventProcesso.hasEventListener(type)) {
              targets.push(parent);
            }
            parent = parent.parent;
          }
        };
        _proto.getBubblingTargets = function getBubblingTargets(type, targets) {
          var parent = this._node.parent;
          while (parent) {
            var _parent$eventProcesso2;
            if ((_parent$eventProcesso2 = parent.eventProcessor.bubblingTarget) !== null && _parent$eventProcesso2 !== void 0 && _parent$eventProcesso2.hasEventListener(type)) {
              targets.push(parent);
            }
            parent = parent.parent;
          }
        };
        _proto.onUpdatingSiblingIndex = function onUpdatingSiblingIndex() {
          NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.MARK_LIST_DIRTY);
        };
        _proto._searchComponentsInParent = function _searchComponentsInParent(ctor) {
          var node = this.node;
          if (ctor) {
            var index = 0;
            var list = [];
            for (var curr = node; curr && Node$1.isNode(curr); curr = curr.parent, ++index) {
              var comp = curr.getComponent(ctor);
              if (comp) {
                var next = {
                  index: index,
                  comp: comp
                };
                if (list) {
                  list.push(next);
                } else {
                  list = [next];
                }
              }
            }
            return list.length > 0 ? list : null;
          }
          return null;
        };
        _proto._attachMask = function _attachMask() {
          this.maskList = this._searchComponentsInParent(NodeEventProcessor._maskComp);
        };
        _proto._isTouchEvent = function _isTouchEvent(type) {
          var index = _touchEvents.indexOf(type);
          return index !== -1;
        };
        _proto._isMouseEvent = function _isMouseEvent(type) {
          var index = _mouseEvents.indexOf(type);
          return index !== -1;
        };
        _proto._hasTouchListeners = function _hasTouchListeners() {
          for (var i = 0; i < _touchEvents.length; ++i) {
            var eventType = _touchEvents[i];
            if (this.hasEventListener(eventType)) {
              return true;
            }
          }
          return false;
        };
        _proto._hasMouseListeners = function _hasMouseListeners() {
          for (var i = 0; i < _mouseEvents.length; ++i) {
            var eventType = _mouseEvents[i];
            if (this.hasEventListener(eventType)) {
              return true;
            }
          }
          return false;
        };
        _proto._hasPointerListeners = function _hasPointerListeners() {
          var has = this._hasTouchListeners();
          if (has) {
            return true;
          }
          return this._hasMouseListeners();
        };
        _proto._tryEmittingAddEvent = function _tryEmittingAddEvent(typeToAdd) {
          var isTouchEvent = this._isTouchEvent(typeToAdd);
          var isMouseEvent = this._isMouseEvent(typeToAdd);
          if (isTouchEvent) {
            this.shouldHandleEventTouch = true;
          } else if (isMouseEvent) {
            this.shouldHandleEventMouse = true;
          }
          if ((isTouchEvent || isMouseEvent) && !this._hasPointerListeners()) {
            NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.ADD_POINTER_EVENT_PROCESSOR, this);
          }
        };
        _proto._newCallbacksInvoker = function _newCallbacksInvoker() {
          var _this2 = this;
          var callbacksInvoker = new CallbacksInvoker();
          callbacksInvoker._registerOffCallback(function () {
            if (_this2.shouldHandleEventTouch && !_this2._hasTouchListeners()) {
              _this2.shouldHandleEventTouch = false;
            }
            if (_this2.shouldHandleEventMouse && !_this2._hasMouseListeners()) {
              _this2.shouldHandleEventMouse = false;
            }
            if (!_this2._hasPointerListeners()) {
              NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, _this2);
            }
          });
          return callbacksInvoker;
        };
        _proto._handleEventMouse = function _handleEventMouse(eventMouse) {
          switch (eventMouse.type) {
            case InputEventType.MOUSE_DOWN:
              return this._handleMouseDown(eventMouse);
            case InputEventType.MOUSE_MOVE:
              return this._handleMouseMove(eventMouse);
            case InputEventType.MOUSE_UP:
              return this._handleMouseUp(eventMouse);
            case InputEventType.MOUSE_WHEEL:
              return this._handleMouseWheel(eventMouse);
            default:
              return false;
          }
        };
        _proto._handleMouseDown = function _handleMouseDown(event) {
          var node = this._node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = NodeEventType.MOUSE_DOWN;
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          }
          return false;
        };
        _proto._handleMouseMove = function _handleMouseMove(event) {
          var node = this._node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          var hit = node._uiProps.uiTransformComp.hitTest(pos, event.windowId);
          if (hit) {
            if (!this.previousMouseIn) {
              if (_currentHovered && _currentHovered !== node) {
                event.type = NodeEventType.MOUSE_LEAVE;
                _currentHovered.dispatchEvent(event);
                _currentHovered.eventProcessor.previousMouseIn = false;
              }
              _currentHovered = node;
              event.type = NodeEventType.MOUSE_ENTER;
              node.dispatchEvent(event);
              this.previousMouseIn = true;
            }
            event.type = NodeEventType.MOUSE_MOVE;
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          } else if (this.previousMouseIn) {
            event.type = NodeEventType.MOUSE_LEAVE;
            node.dispatchEvent(event);
            this.previousMouseIn = false;
            _currentHovered = null;
          }
          return false;
        };
        _proto._handleMouseUp = function _handleMouseUp(event) {
          var node = this._node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = NodeEventType.MOUSE_UP;
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          }
          return false;
        };
        _proto._handleMouseWheel = function _handleMouseWheel(event) {
          var node = this._node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = NodeEventType.MOUSE_WHEEL;
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          }
          return false;
        };
        _proto._handleEventTouch = function _handleEventTouch(eventTouch) {
          switch (eventTouch.type) {
            case InputEventType.TOUCH_START:
              return this._handleTouchStart(eventTouch);
            case InputEventType.TOUCH_MOVE:
              return this._handleTouchMove(eventTouch);
            case InputEventType.TOUCH_END:
              return this._handleTouchEnd(eventTouch);
            case InputEventType.TOUCH_CANCEL:
              return this._handleTouchCancel(eventTouch);
            default:
              return false;
          }
        };
        _proto._handleTouchStart = function _handleTouchStart(event) {
          var node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = NodeEventType.TOUCH_START;
            event.bubbles = true;
            this._dispatchingTouch = event.touch;
            node.dispatchEvent(event);
            return true;
          }
          return false;
        };
        _proto._handleTouchMove = function _handleTouchMove(event) {
          var node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.type = NodeEventType.TOUCH_MOVE;
          event.bubbles = true;
          this._dispatchingTouch = event.touch;
          node.dispatchEvent(event);
          return true;
        };
        _proto._handleTouchEnd = function _handleTouchEnd(event) {
          var node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = NodeEventType.TOUCH_END;
          } else {
            event.type = NodeEventType.TOUCH_CANCEL;
          }
          event.bubbles = true;
          node.dispatchEvent(event);
          this._dispatchingTouch = null;
        };
        _proto._handleTouchCancel = function _handleTouchCancel(event) {
          var node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return;
          }
          event.type = NodeEventType.TOUCH_CANCEL;
          event.bubbles = true;
          node.dispatchEvent(event);
          this._dispatchingTouch = null;
        };
        _createClass(NodeEventProcessor, [{
          key: "isEnabled",
          get: function get() {
            return this._isEnabled;
          }
        }, {
          key: "node",
          get: function get() {
            return this._node;
          }
        }]);
        return NodeEventProcessor;
      }();
      NodeEventProcessor._maskComp = null;
      NodeEventProcessor.callbacksInvoker = new CallbacksInvoker();
      legacyCC.NodeEventProcessor = NodeEventProcessor;

      var _dec$34, _class$31;
      replaceProperty(Node$1.prototype, 'Node', [{
        name: 'childrenCount',
        newName: 'children.length',
        customGetter: function customGetter() {
          return this.children.length;
        }
      }]);
      replaceProperty(Node$1.prototype, 'Node', [{
        name: 'width',
        targetName: 'node.getComponent(UITransform)',
        customGetter: function customGetter() {
          return this._uiProps.uiTransformComp.width;
        },
        customSetter: function customSetter(value) {
          this._uiProps.uiTransformComp.width = value;
        }
      }, {
        name: 'height',
        targetName: 'node.getComponent(UITransform)',
        customGetter: function customGetter() {
          return this._uiProps.uiTransformComp.height;
        },
        customSetter: function customSetter(value) {
          this._uiProps.uiTransformComp.height = value;
        }
      }, {
        name: 'anchorX',
        targetName: 'node.getComponent(UITransform)',
        customGetter: function customGetter() {
          return this._uiProps.uiTransformComp.anchorX;
        },
        customSetter: function customSetter(value) {
          this._uiProps.uiTransformComp.anchorX = value;
        }
      }, {
        name: 'anchorY',
        targetName: 'node.getComponent(UITransform)',
        customGetter: function customGetter() {
          return this._uiProps.uiTransformComp.anchorY;
        },
        customSetter: function customSetter(value) {
          this._uiProps.uiTransformComp.anchorY = value;
        }
      }, {
        name: 'getAnchorPoint',
        targetName: 'node.getComponent(UITransform)',
        customFunction: function customFunction(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._uiProps.uiTransformComp.anchorPoint);
          return out;
        }
      }, {
        name: 'setAnchorPoint',
        targetName: 'node.getComponent(UITransform)',
        customFunction: function customFunction(point, y) {
          this._uiProps.uiTransformComp.setAnchorPoint(point, y);
        }
      }, {
        name: 'getContentSize',
        targetName: 'node.getComponent(UITransform)',
        customFunction: function customFunction(out) {
          if (!out) {
            out = new Size$1();
          }
          out.set(this._uiProps.uiTransformComp.contentSize);
          return out;
        }
      }, {
        name: 'setContentSize',
        targetName: 'node.getComponent(UITransform)',
        customFunction: function customFunction(size, height) {
          if (typeof size === 'number') {
            this._uiProps.uiTransformComp.setContentSize(size, height);
          } else {
            this._uiProps.uiTransformComp.setContentSize(size);
          }
        }
      }]);
      removeProperty(SceneGlobals.prototype, 'SceneGlobals.prototype', [{
        name: 'aspect'
      }, {
        name: 'selfShadow'
      }, {
        name: 'linear'
      }, {
        name: 'packing'
      }, {
        name: 'autoAdapt'
      }, {
        name: 'fixedArea'
      }, {
        name: 'pcf'
      }, {
        name: 'bias'
      }, {
        name: 'normalBias'
      }, {
        name: 'near'
      }, {
        name: 'far'
      }, {
        name: 'shadowDistance'
      }, {
        name: 'invisibleOcclusionRange'
      }, {
        name: 'orthoSize'
      }, {
        name: 'saturation'
      }]);
      replaceProperty(SceneGlobals.prototype, 'SceneGlobals.prototype', [{
        name: 'distance',
        newName: 'planeHeight'
      }, {
        name: 'normal',
        newName: 'planeDirection'
      }, {
        name: 'size',
        newName: 'shadowMapSize'
      }]);
      removeProperty(Node$1.prototype, 'Node.prototype', [{
        name: 'addLayer'
      }, {
        name: 'removeLayer'
      }]);
      replaceProperty(NodeUIProperties.prototype, 'NodeUIProperties', [{
        name: 'opacityDirty',
        newName: 'colorDirty'
      }]);
      removeProperty(Layers, 'Layers', [{
        name: 'All'
      }, {
        name: 'RaycastMask'
      }, {
        name: 'check'
      }]);
      replaceProperty(Layers, 'Layers', [{
        name: 'Default',
        newName: 'DEFAULT',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'Always',
        newName: 'ALWAYS',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'IgnoreRaycast',
        newName: 'IGNORE_RAYCAST',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'Gizmos',
        newName: 'GIZMOS',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'Editor',
        newName: 'EDITOR',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'UI',
        newName: 'UI_3D',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'UI2D',
        newName: 'UI_2D',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'SceneGizmo',
        newName: 'SCENE_GIZMO',
        target: Layers.Enum,
        targetName: 'Layers.Enum'
      }, {
        name: 'makeInclusiveMask',
        newName: 'makeMaskInclude',
        target: Layers,
        targetName: 'Layers'
      }, {
        name: 'makeExclusiveMask',
        newName: 'makeMaskExclude',
        target: Layers,
        targetName: 'Layers'
      }]);
      removeProperty(Layers.Enum, 'Layers.Enum', [{
        name: 'ALWAYS'
      }]);
      removeProperty(Layers.BitMask, 'Layers.BitMask', [{
        name: 'ALWAYS'
      }]);
      var HideInHierarchy = CCObject.Flags.HideInHierarchy;
      var DontSave = CCObject.Flags.DontSave;
      var PrivateNode = exports('d_', (_dec$34 = ccclass$M('cc.PrivateNode'), _dec$34(_class$31 = function (_Node) {
        _inheritsLoose(PrivateNode, _Node);
        function PrivateNode(name) {
          var _this;
          _this = _Node.call(this, name) || this;
          warnID(12003, _this.name);
          _this.hideFlags |= DontSave | HideInHierarchy;
          return _this;
        }
        return PrivateNode;
      }(Node$1)) || _class$31));
      replaceProperty(SystemEventType, 'SystemEventType', ['MOUSE_ENTER', 'MOUSE_LEAVE', 'TRANSFORM_CHANGED', 'SCENE_CHANGED_FOR_PERSISTS', 'SIZE_CHANGED', 'ANCHOR_CHANGED', 'COLOR_CHANGED', 'CHILD_ADDED', 'CHILD_REMOVED', 'PARENT_CHANGED', 'NODE_DESTROYED', 'LAYER_CHANGED', 'SIBLING_ORDER_CHANGED'].map(function (name) {
        return {
          name: name,
          target: Node$1.EventType,
          targetName: 'Node.EventType'
        };
      }));
      replaceProperty(Node$1.EventType, 'Node.EventType', [{
        name: 'DEVICEMOTION',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }, {
        name: 'KEY_DOWN',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }, {
        name: 'KEY_UP',
        target: SystemEvent.EventType,
        targetName: 'SystemEvent.EventType'
      }]);
      legacyCC.PrivateNode = PrivateNode;

      deprecateModuleExportedName({
        BaseNode: {
          newName: 'Node',
          since: '3.7.0',
          removed: false
        }
      });

      function find(path, referenceNode) {
        if (!referenceNode) {
          var scene = legacyCC.director.getScene();
          if (!scene) {
            return null;
          }
          referenceNode = scene;
        }
        return referenceNode.getChildByPath(path);
      }
      legacyCC.find = find;

      var fastRemoveAt = fastRemoveAt$2;
      var IsStartCalled = CCObject.Flags.IsStartCalled;
      var IsOnEnableCalled$1 = CCObject.Flags.IsOnEnableCalled;
      CCObject.Flags.IsEditorOnEnableCalled;
      function sortedIndex(array, comp) {
        var order = comp.constructor._executionOrder;
        var id = comp._id;
        var l = 0;
        for (var h = array.length - 1, m = h >>> 1; l <= h; m = l + h >>> 1) {
          var test = array[m];
          var testOrder = test.constructor._executionOrder;
          if (testOrder > order) {
            h = m - 1;
          } else if (testOrder < order) {
            l = m + 1;
          } else {
            var testId = test._id;
            if (testId > id) {
              h = m - 1;
            } else if (testId < id) {
              l = m + 1;
            } else {
              return m;
            }
          }
        }
        return ~l;
      }
      function stableRemoveInactive(iterator, flagToClear) {
        var array = iterator.array;
        var next = iterator.i + 1;
        while (next < array.length) {
          var comp = array[next];
          if (comp.node._activeInHierarchy) {
            ++next;
          } else {
            iterator.removeAt(next);
            if (flagToClear) {
              comp._objFlags &= ~flagToClear;
            }
          }
        }
      }
      var LifeCycleInvoker = function () {
        function LifeCycleInvoker(invokeFunc) {
          this._zero = void 0;
          this._neg = void 0;
          this._pos = void 0;
          this._invoke = void 0;
          var Iterator = MutableForwardIterator;
          this._zero = new Iterator([]);
          this._neg = new Iterator([]);
          this._pos = new Iterator([]);
          this._invoke = invokeFunc;
        }
        _createClass(LifeCycleInvoker, [{
          key: "zero",
          get: function get() {
            return this._zero;
          }
        }, {
          key: "neg",
          get: function get() {
            return this._neg;
          }
        }, {
          key: "pos",
          get: function get() {
            return this._pos;
          }
        }]);
        return LifeCycleInvoker;
      }();
      LifeCycleInvoker.stableRemoveInactive = stableRemoveInactive;
      function compareOrder(a, b) {
        return a.constructor._executionOrder - b.constructor._executionOrder;
      }
      var OneOffInvoker = function (_LifeCycleInvoker) {
        _inheritsLoose(OneOffInvoker, _LifeCycleInvoker);
        function OneOffInvoker() {
          return _LifeCycleInvoker.apply(this, arguments) || this;
        }
        var _proto = OneOffInvoker.prototype;
        _proto.add = function add(comp) {
          var order = comp.constructor._executionOrder;
          (order === 0 ? this._zero : order < 0 ? this._neg : this._pos).array.push(comp);
        };
        _proto.remove = function remove(comp) {
          var order = comp.constructor._executionOrder;
          (order === 0 ? this._zero : order < 0 ? this._neg : this._pos).fastRemove(comp);
        };
        _proto.cancelInactive = function cancelInactive(flagToClear) {
          stableRemoveInactive(this._zero, flagToClear);
          stableRemoveInactive(this._neg, flagToClear);
          stableRemoveInactive(this._pos, flagToClear);
        };
        _proto.invoke = function invoke() {
          var compsNeg = this._neg;
          if (compsNeg.array.length > 0) {
            compsNeg.array.sort(compareOrder);
            this._invoke(compsNeg);
            compsNeg.array.length = 0;
          }
          this._invoke(this._zero);
          this._zero.array.length = 0;
          var compsPos = this._pos;
          if (compsPos.array.length > 0) {
            compsPos.array.sort(compareOrder);
            this._invoke(compsPos);
            compsPos.array.length = 0;
          }
        };
        return OneOffInvoker;
      }(LifeCycleInvoker);
      var ReusableInvoker = function (_LifeCycleInvoker2) {
        _inheritsLoose(ReusableInvoker, _LifeCycleInvoker2);
        function ReusableInvoker() {
          return _LifeCycleInvoker2.apply(this, arguments) || this;
        }
        var _proto2 = ReusableInvoker.prototype;
        _proto2.add = function add(comp) {
          var order = comp.constructor._executionOrder;
          if (order === 0) {
            this._zero.array.push(comp);
          } else {
            var _array = order < 0 ? this._neg.array : this._pos.array;
            var i = sortedIndex(_array, comp);
            if (i < 0) {
              _array.splice(~i, 0, comp);
            }
          }
        };
        _proto2.remove = function remove(comp) {
          var order = comp.constructor._executionOrder;
          if (order === 0) {
            this._zero.fastRemove(comp);
          } else {
            var _iterator = order < 0 ? this._neg : this._pos;
            var i = sortedIndex(_iterator.array, comp);
            if (i >= 0) {
              _iterator.removeAt(i);
            }
          }
        };
        _proto2.invoke = function invoke(dt) {
          if (this._neg.array.length > 0) {
            this._invoke(this._neg, dt);
          }
          this._invoke(this._zero, dt);
          if (this._pos.array.length > 0) {
            this._invoke(this._pos, dt);
          }
        };
        return ReusableInvoker;
      }(LifeCycleInvoker);
      function createInvokeImplJit(code, useDt, ensureFlag) {
        var body = "" + ('var a=it.array;' + 'for(it.i=0;it.i<a.length;++it.i){' + 'var c=a[it.i];') + code + "}";
        var fastPath = useDt ? Function('it', 'dt', body) : Function('it', body);
        var singleInvoke = Function('c', 'dt', code);
        return createInvokeImpl(singleInvoke, fastPath, ensureFlag);
      }
      function createInvokeImpl(singleInvoke, fastPath, ensureFlag) {
        return function (iterator, dt) {
          try {
            fastPath(iterator, dt);
          } catch (e) {
            legacyCC._throw(e);
            var _array2 = iterator.array;
            if (ensureFlag) {
              _array2[iterator.i]._objFlags |= ensureFlag;
            }
            ++iterator.i;
            for (; iterator.i < _array2.length; ++iterator.i) {
              try {
                singleInvoke(_array2[iterator.i], dt);
              } catch (e) {
                legacyCC._throw(e);
                if (ensureFlag) {
                  _array2[iterator.i]._objFlags |= ensureFlag;
                }
              }
            }
          }
        };
      }
      var invokeStart = createInvokeImplJit("c.start();c._objFlags|=" + IsStartCalled, false, IsStartCalled) ;
      var invokeUpdate = createInvokeImplJit('c.update(dt)', true) ;
      var invokeLateUpdate = createInvokeImplJit('c.lateUpdate(dt)', true) ;
      var invokeOnEnable = function (iterator) {
        var compScheduler = legacyCC.director._compScheduler;
        var array = iterator.array;
        for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
          var comp = array[iterator.i];
          if (comp._enabled) {
            comp.onEnable();
            var deactivatedDuringOnEnable = !comp.node._activeInHierarchy;
            if (!deactivatedDuringOnEnable) {
              compScheduler._onEnabled(comp);
            }
          }
        }
      };
      var ComponentScheduler = function () {
        function ComponentScheduler() {
          this.startInvoker = void 0;
          this.updateInvoker = void 0;
          this.lateUpdateInvoker = void 0;
          this._deferredComps = [];
          this._updating = void 0;
          this.unscheduleAll();
        }
        var _proto3 = ComponentScheduler.prototype;
        _proto3.unscheduleAll = function unscheduleAll() {
          this.startInvoker = new OneOffInvoker(invokeStart);
          this.updateInvoker = new ReusableInvoker(invokeUpdate);
          this.lateUpdateInvoker = new ReusableInvoker(invokeLateUpdate);
          this._updating = false;
        };
        _proto3._onEnabled = function _onEnabled(comp) {
          legacyCC.director.getScheduler().resumeTarget(comp);
          comp._objFlags |= IsOnEnableCalled$1;
          if (this._updating) {
            this._deferredComps.push(comp);
          } else {
            this._scheduleImmediate(comp);
          }
        };
        _proto3._onDisabled = function _onDisabled(comp) {
          legacyCC.director.getScheduler().pauseTarget(comp);
          comp._objFlags &= ~IsOnEnableCalled$1;
          var index = this._deferredComps.indexOf(comp);
          if (index >= 0) {
            fastRemoveAt(this._deferredComps, index);
            return;
          }
          if (comp.internalStart && !(comp._objFlags & IsStartCalled)) {
            this.startInvoker.remove(comp);
          }
          if (comp.internalUpdate) {
            this.updateInvoker.remove(comp);
          }
          if (comp.internalLateUpdate) {
            this.lateUpdateInvoker.remove(comp);
          }
        };
        _proto3.enableComp = function enableComp(comp, invoker) {
          if (!(comp._objFlags & IsOnEnableCalled$1)) {
            if (comp.internalOnEnable) {
              if (invoker) {
                invoker.add(comp);
                return;
              } else {
                comp.internalOnEnable();
                var deactivatedDuringOnEnable = !comp.node.activeInHierarchy;
                if (deactivatedDuringOnEnable) {
                  return;
                }
              }
            }
            this._onEnabled(comp);
          }
        };
        _proto3.disableComp = function disableComp(comp) {
          if (comp._objFlags & IsOnEnableCalled$1) {
            if (comp.internalOnDisable) {
              comp.internalOnDisable();
            }
            this._onDisabled(comp);
          }
        };
        _proto3.startPhase = function startPhase() {
          this._updating = true;
          this.startInvoker.invoke();
          this._startForNewComps();
        };
        _proto3.updatePhase = function updatePhase(dt) {
          this.updateInvoker.invoke(dt);
        };
        _proto3.lateUpdatePhase = function lateUpdatePhase(dt) {
          this.lateUpdateInvoker.invoke(dt);
          this._updating = false;
          this._startForNewComps();
        };
        _proto3._startForNewComps = function _startForNewComps() {
          if (this._deferredComps.length > 0) {
            this._deferredSchedule();
            this.startInvoker.invoke();
          }
        };
        _proto3._scheduleImmediate = function _scheduleImmediate(comp) {
          if (typeof comp.internalStart === 'function' && !(comp._objFlags & IsStartCalled)) {
            this.startInvoker.add(comp);
          }
          if (typeof comp.internalUpdate === 'function') {
            this.updateInvoker.add(comp);
          }
          if (typeof comp.internalLateUpdate === 'function') {
            this.lateUpdateInvoker.add(comp);
          }
        };
        _proto3._deferredSchedule = function _deferredSchedule() {
          var comps = this._deferredComps;
          for (var i = 0, len = comps.length; i < len; i++) {
            this._scheduleImmediate(comps[i]);
          }
          comps.length = 0;
        };
        return ComponentScheduler;
      }();

      var MAX_POOL_SIZE = 4;
      var IsPreloadStarted = CCObject.Flags.IsPreloadStarted;
      var IsOnLoadStarted = CCObject.Flags.IsOnLoadStarted;
      var IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled;
      var IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled;
      var Deactivating = CCObject.Flags.Deactivating;
      var UnsortedInvoker = function (_LifeCycleInvoker) {
        _inheritsLoose(UnsortedInvoker, _LifeCycleInvoker);
        function UnsortedInvoker() {
          return _LifeCycleInvoker.apply(this, arguments) || this;
        }
        var _proto = UnsortedInvoker.prototype;
        _proto.add = function add(comp) {
          this._zero.array.push(comp);
        };
        _proto.remove = function remove(comp) {
          this._zero.fastRemove(comp);
        };
        _proto.cancelInactive = function cancelInactive(flagToClear) {
          LifeCycleInvoker.stableRemoveInactive(this._zero, flagToClear);
        };
        _proto.invoke = function invoke() {
          this._invoke(this._zero);
          this._zero.array.length = 0;
        };
        return UnsortedInvoker;
      }(LifeCycleInvoker);
      var invokePreload = createInvokeImplJit('c.__preload();') ;
      var invokeOnLoad = createInvokeImplJit("c.onLoad();c._objFlags|=" + IsOnLoadCalled, false, IsOnLoadCalled) ;
      var activateTasksPool = new Pool$1(MAX_POOL_SIZE);
      activateTasksPool.get = function getActivateTask() {
        var task = this._get() || {
          preload: new UnsortedInvoker(invokePreload),
          onLoad: new OneOffInvoker(invokeOnLoad),
          onEnable: new OneOffInvoker(invokeOnEnable)
        };
        task.preload.zero.i = -1;
        var invoker = task.onLoad;
        invoker.zero.i = -1;
        invoker.neg.i = -1;
        invoker.pos.i = -1;
        invoker = task.onEnable;
        invoker.zero.i = -1;
        invoker.neg.i = -1;
        invoker.pos.i = -1;
        return task;
      };
      function _componentCorrupted(node, comp, index) {
        errorID(3817, node.name, index);
        console.log('Corrupted component value:', comp);
        if (comp) {
          node._removeComponent(comp);
        } else {
          removeAt(node.getWritableComponents(), index);
        }
      }
      var NodeActivator = exports('dI', function () {
        function NodeActivator() {
          this._activatingStack = void 0;
          this.reset();
        }
        var _proto2 = NodeActivator.prototype;
        _proto2.reset = function reset() {
          this._activatingStack = [];
        };
        _proto2.activateNode = function activateNode(node, active) {
          if (active) {
            var task = activateTasksPool.get();
            if (task) {
              this._activatingStack.push(task);
              this._activateNodeRecursively(node, task.preload, task.onLoad, task.onEnable);
              task.preload.invoke();
              task.onLoad.invoke();
              task.onEnable.invoke();
              this._activatingStack.pop();
              activateTasksPool.put(task);
            }
          } else {
            this._deactivateNodeRecursively(node);
            var stack = this._activatingStack;
            for (var _iterator = _createForOfIteratorHelperLoose(stack), _step; !(_step = _iterator()).done;) {
              var lastTask = _step.value;
              lastTask.preload.cancelInactive(IsPreloadStarted);
              lastTask.onLoad.cancelInactive(IsOnLoadStarted);
              lastTask.onEnable.cancelInactive(IsOnEnableCalled);
            }
          }
          node.emit(NodeEventType.ACTIVE_IN_HIERARCHY_CHANGED, node);
        };
        _proto2.activateComp = function activateComp(comp, preloadInvoker, onLoadInvoker, onEnableInvoker) {
          if (!isValid(comp, true)) {
            return;
          }
          if (!(comp._objFlags & IsPreloadStarted)) {
            comp._objFlags |= IsPreloadStarted;
            if (comp.internalPreload) {
              if (preloadInvoker) {
                preloadInvoker.add(comp);
              } else {
                comp.internalPreload();
              }
            }
          }
          if (!(comp._objFlags & IsOnLoadStarted)) {
            comp._objFlags |= IsOnLoadStarted;
            if (comp.internalOnLoad) {
              if (onLoadInvoker) {
                onLoadInvoker.add(comp);
              } else {
                comp.internalOnLoad();
                comp._objFlags |= IsOnLoadCalled;
              }
            } else {
              comp._objFlags |= IsOnLoadCalled;
            }
          }
          if (comp._enabled) {
            {
              assertIsTrue(comp.node, getError(3823, comp.uuid, comp.name));
            }
            var deactivatedOnLoading = !comp.node.activeInHierarchy;
            if (deactivatedOnLoading) {
              return;
            }
            legacyCC.director._compScheduler.enableComp(comp, onEnableInvoker);
          }
        };
        _proto2.destroyComp = function destroyComp(comp) {
          legacyCC.director._compScheduler.disableComp(comp);
          if (comp.internalOnDestroy && comp._objFlags & IsOnLoadCalled) {
            comp.internalOnDestroy();
          }
        };
        _proto2._activateNodeRecursively = function _activateNodeRecursively(node, preloadInvoker, onLoadInvoker, onEnableInvoker) {
          if (node._objFlags & Deactivating) {
            errorID(3816, node.name);
            return;
          }
          node._setActiveInHierarchy(true);
          var originCount = node.components.length;
          for (var i = 0; i < originCount; ++i) {
            var component = node.components[i];
            if (component instanceof legacyCC.Component) {
              this.activateComp(component, preloadInvoker, onLoadInvoker, onEnableInvoker);
            } else {
              _componentCorrupted(node, component, i);
              --i;
              --originCount;
            }
          }
          for (var _i = 0, len = node.children.length; _i < len; ++_i) {
            var child = node.children[_i];
            if (child.active) {
              this._activateNodeRecursively(child, preloadInvoker, onLoadInvoker, onEnableInvoker);
            }
          }
          node._onPostActivated(true);
        };
        _proto2._deactivateNodeRecursively = function _deactivateNodeRecursively(node) {
          node._objFlags |= Deactivating;
          node._setActiveInHierarchy(false);
          var originCount = node.components.length;
          for (var c = 0; c < originCount; ++c) {
            var component = node.components[c];
            if (component._enabled) {
              legacyCC.director._compScheduler.disableComp(component);
              if (node.activeInHierarchy) {
                node._objFlags &= ~Deactivating;
                return;
              }
            }
          }
          for (var i = 0, len = node.children.length; i < len; ++i) {
            var child = node.children[i];
            if (child.activeInHierarchy) {
              this._deactivateNodeRecursively(child);
              if (node.activeInHierarchy) {
                node._objFlags &= ~Deactivating;
                return;
              }
            }
          }
          node._onPostActivated(false);
          node._objFlags &= ~Deactivating;
        };
        return NodeActivator;
      }());

      var Destroyed$1 = CCObject.Flags.Destroyed;
      var PersistentMask$1 = CCObject.Flags.PersistentMask;
      var DEFAULT = CCClass.Attr.DELIMETER + "default";
      var IDENTIFIER_RE = CCClass.IDENTIFIER_RE;
      var VAR = 'var ';
      var LOCAL_OBJ = 'o';
      var LOCAL_TEMP_OBJ = 't';
      var LOCAL_ARRAY = 'a';
      var LINE_INDEX_OF_NEW_OBJ = 0;
      var DEFAULT_MODULE_CACHE = {
        'cc.ClickEvent': false,
        'cc.PrefabInfo': false
      };
      var escapeForJS = CCClass.escapeForJS;
      var Declaration = function () {
        function Declaration(varName, expression) {
          this.varName = void 0;
          this.expression = void 0;
          this.varName = varName;
          this.expression = expression;
        }
        var _proto = Declaration.prototype;
        _proto.toString = function toString() {
          return VAR + this.varName + "=" + this.expression + ";";
        };
        return Declaration;
      }();
      function mergeDeclaration(statement, expression) {
        if (expression instanceof Declaration) {
          return new Declaration(expression.varName, statement + expression.expression);
        } else {
          return statement + expression;
        }
      }
      function writeAssignment(codeArray, statement, expression) {
        if (Array.isArray(expression)) {
          expression[0] = mergeDeclaration(statement, expression[0]);
          codeArray.push(expression);
        } else {
          codeArray.push(mergeDeclaration(statement, expression) + ";");
        }
      }
      var Assignments = function () {
        function Assignments(targetExpression) {
          this._exps = void 0;
          this._targetExp = void 0;
          this._exps = [];
          this._targetExp = targetExpression;
        }
        var _proto2 = Assignments.prototype;
        _proto2.append = function append(key, expression) {
          this._exps.push([key, expression]);
        };
        _proto2.writeCode = function writeCode(codeArray) {
          var targetVar;
          if (this._exps.length > 1) {
            codeArray.push(LOCAL_TEMP_OBJ + "=" + this._targetExp + ";");
            targetVar = LOCAL_TEMP_OBJ;
          } else if (this._exps.length === 1) {
            targetVar = this._targetExp;
          } else {
            return;
          }
          for (var i = 0; i < this._exps.length; i++) {
            var pair = this._exps[i];
            writeAssignment(codeArray, targetVar + getPropAccessor(pair[0]) + "=", pair[1]);
          }
        };
        return Assignments;
      }();
      Assignments.pool = void 0;
      Assignments.pool = new Pool$1(function (obj) {
        obj._exps.length = 0;
        obj._targetExp = null;
      }, 1);
      Assignments.pool.get = function (targetExpression) {
        var cache = this._get() || new Assignments();
        cache._targetExp = targetExpression;
        return cache;
      };
      function getPropAccessor(key) {
        return IDENTIFIER_RE.test(key) ? "." + key : "[" + escapeForJS(key) + "]";
      }
      var Parser = function () {
        function Parser(obj, parent) {
          this.parent = void 0;
          this.objsToClear_iN$t = void 0;
          this.codeArray = void 0;
          this.objs = void 0;
          this.funcs = void 0;
          this.funcModuleCache = void 0;
          this.globalVariables = void 0;
          this.globalVariableId = void 0;
          this.localVariableId = void 0;
          this.result = void 0;
          this.parent = parent;
          this.objsToClear_iN$t = [];
          this.codeArray = [];
          this.objs = [];
          this.funcs = [];
          this.funcModuleCache = createMap();
          mixin(this.funcModuleCache, DEFAULT_MODULE_CACHE);
          this.globalVariables = [];
          this.globalVariableId = 0;
          this.localVariableId = 0;
          this.codeArray.push(VAR + LOCAL_OBJ + "," + LOCAL_TEMP_OBJ + ";", 'if(R){', LOCAL_OBJ + "=R;", '}else{', LOCAL_OBJ + "=R=new " + this.getFuncModule(obj.constructor, true) + "();", '}');
          obj._iN$t = {
            globalVar: 'R'
          };
          this.objsToClear_iN$t.push(obj);
          this.enumerateObject(this.codeArray, obj);
          var globalVariablesDeclaration;
          if (this.globalVariables.length > 0) {
            globalVariablesDeclaration = VAR + this.globalVariables.join(',') + ";";
          }
          var code = flattenCodeArray(['return (function(R){', globalVariablesDeclaration || [], this.codeArray, 'return o;', '})']);
          this.result = Function('O', 'F', code)(this.objs, this.funcs);
          for (var i = 0, len = this.objsToClear_iN$t.length; i < len; ++i) {
            this.objsToClear_iN$t[i]._iN$t = null;
          }
          this.objsToClear_iN$t.length = 0;
        }
        var _proto3 = Parser.prototype;
        _proto3.getFuncModule = function getFuncModule(func, usedInNew) {
          var clsName = getClassName(func);
          if (clsName) {
            var cache = this.funcModuleCache[clsName];
            if (cache) {
              return cache;
            } else if (cache === undefined) {
              var clsNameIsModule = clsName.indexOf('.') !== -1;
              if (clsNameIsModule) {
                try {
                  clsNameIsModule = func === Function("return " + clsName)();
                  if (clsNameIsModule) {
                    this.funcModuleCache[clsName] = clsName;
                    return clsName;
                  }
                } catch (e) {}
              }
            }
          }
          var index = this.funcs.indexOf(func);
          if (index < 0) {
            index = this.funcs.length;
            this.funcs.push(func);
          }
          var res = "F[" + index + "]";
          if (usedInNew) {
            res = "(" + res + ")";
          }
          this.funcModuleCache[clsName] = res;
          return res;
        };
        _proto3.getObjRef = function getObjRef(obj) {
          var index = this.objs.indexOf(obj);
          if (index < 0) {
            index = this.objs.length;
            this.objs.push(obj);
          }
          return "O[" + index + "]";
        };
        _proto3.setValueType = function setValueType(codeArray, defaultValue, srcValue, targetExpression) {
          var assignments = Assignments.pool.get(targetExpression);
          var fastDefinedProps = defaultValue.constructor.__props__;
          if (!fastDefinedProps) {
            fastDefinedProps = Object.keys(defaultValue);
          }
          for (var i = 0; i < fastDefinedProps.length; i++) {
            var propName = fastDefinedProps[i];
            var prop = srcValue[propName];
            if (defaultValue[propName] === prop) {
              continue;
            }
            var expression = this.enumerateField(srcValue, propName, prop);
            assignments.append(propName, expression);
          }
          assignments.writeCode(codeArray);
          Assignments.pool.put(assignments);
        };
        _proto3.enumerateCCClass = function enumerateCCClass(codeArray, obj, klass) {
          var props = klass.__values__;
          var attrs = CCClass.Attr.getClassAttrs(klass);
          for (var p = 0; p < props.length; p++) {
            var key = props[p];
            var val = obj[key];
            var defaultValue = attrs[key + DEFAULT];
            if (equalsToDefault(defaultValue, val)) {
              continue;
            }
            if (typeof val === 'object' && val instanceof legacyCC.ValueType) {
              defaultValue = CCClass.getDefault(defaultValue);
              if (defaultValue && defaultValue.constructor === val.constructor) {
                var targetExpression = LOCAL_OBJ + getPropAccessor(key);
                this.setValueType(codeArray, defaultValue, val, targetExpression);
                continue;
              }
            }
            this.setObjProp(codeArray, obj, key, val);
          }
        };
        _proto3.instantiateArray = function instantiateArray(value) {
          if (value.length === 0) {
            return '[]';
          }
          var arrayVar = LOCAL_ARRAY + ++this.localVariableId;
          var declaration = new Declaration(arrayVar, "new Array(" + value.length + ")");
          var codeArray = [declaration];
          value._iN$t = {
            globalVar: '',
            source: codeArray
          };
          this.objsToClear_iN$t.push(value);
          for (var i = 0; i < value.length; ++i) {
            var statement = arrayVar + "[" + i + "]=";
            var expression = this.enumerateField(value, i, value[i]);
            writeAssignment(codeArray, statement, expression);
          }
          return codeArray;
        };
        _proto3.instantiateTypedArray = function instantiateTypedArray(value) {
          var type = value.constructor.name;
          if (value.length === 0) {
            return "new " + type;
          }
          var arrayVar = LOCAL_ARRAY + ++this.localVariableId;
          var declaration = new Declaration(arrayVar, "new " + type + "(" + value.length + ")");
          var codeArray = [declaration];
          value._iN$t = {
            globalVar: '',
            source: codeArray
          };
          this.objsToClear_iN$t.push(value);
          for (var i = 0; i < value.length; ++i) {
            if (value[i] !== 0) {
              var statement = arrayVar + "[" + i + "]=";
              writeAssignment(codeArray, statement, value[i]);
            }
          }
          return codeArray;
        };
        _proto3.enumerateField = function enumerateField(obj, key, value) {
          if (typeof value === 'object' && value) {
            var _iN$t = value._iN$t;
            if (_iN$t) {
              var globalVar = _iN$t.globalVar;
              if (!globalVar) {
                globalVar = _iN$t.globalVar = "v" + ++this.globalVariableId;
                this.globalVariables.push(globalVar);
                var line = _iN$t.source[LINE_INDEX_OF_NEW_OBJ];
                _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = mergeDeclaration(globalVar + "=", line);
              }
              return globalVar;
            } else if (ArrayBuffer.isView(value)) {
              return this.instantiateTypedArray(value);
            } else if (Array.isArray(value)) {
              return this.instantiateArray(value);
            } else {
              return this.instantiateObj(value);
            }
          } else if (typeof value === 'function') {
            return this.getFuncModule(value);
          } else if (typeof value === 'string') {
            return escapeForJS(value);
          } else {
            if (key === '_objFlags' && isCCObject(obj)) {
              value &= PersistentMask$1;
            }
            return value;
          }
        };
        _proto3.setObjProp = function setObjProp(codeArray, obj, key, value) {
          var statement = LOCAL_OBJ + getPropAccessor(key) + "=";
          var expression = this.enumerateField(obj, key, value);
          writeAssignment(codeArray, statement, expression);
        };
        _proto3.enumerateObject = function enumerateObject(codeArray, obj) {
          var klass = obj.constructor;
          if (isCCClassOrFastDefined(klass)) {
            this.enumerateCCClass(codeArray, obj, klass);
          } else {
            for (var key in obj) {
              if (!obj.hasOwnProperty(key) || key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && key !== '__type__') {
                continue;
              }
              var value = obj[key];
              if (typeof value === 'object' && value && value === obj._iN$t) {
                continue;
              }
              this.setObjProp(codeArray, obj, key, value);
            }
          }
        };
        _proto3.instantiateObj = function instantiateObj(obj) {
          if (obj instanceof legacyCC.ValueType) {
            return CCClass.getNewValueTypeCode(obj);
          }
          if (obj instanceof legacyCC.Asset) {
            return this.getObjRef(obj);
          }
          if (obj._objFlags & Destroyed$1) {
            return null;
          }
          var createCode;
          var ctor = obj.constructor;
          if (isCCClassOrFastDefined(ctor)) {
            if (this.parent) {
              if (this.parent instanceof legacyCC.Component) {
                if (obj instanceof legacyCC.Node || obj instanceof legacyCC.Component) {
                  return this.getObjRef(obj);
                }
              } else if (this.parent instanceof legacyCC.Node) {
                if (obj instanceof legacyCC.Node) {
                  if (!obj.isChildOf(this.parent)) {
                    return this.getObjRef(obj);
                  }
                } else if (obj instanceof legacyCC.Component) {
                  var _obj$node;
                  if (!((_obj$node = obj.node) !== null && _obj$node !== void 0 && _obj$node.isChildOf(this.parent))) {
                    return this.getObjRef(obj);
                  }
                }
              }
            }
            createCode = new Declaration(LOCAL_OBJ, "new " + this.getFuncModule(ctor, true) + "()");
          } else if (ctor === Object) {
            createCode = new Declaration(LOCAL_OBJ, '{}');
          } else if (!ctor) {
            createCode = new Declaration(LOCAL_OBJ, 'Object.create(null)');
          } else {
            return this.getObjRef(obj);
          }
          var codeArray = [createCode];
          obj._iN$t = {
            globalVar: '',
            source: codeArray
          };
          this.objsToClear_iN$t.push(obj);
          this.enumerateObject(codeArray, obj);
          return ['(function(){', codeArray, 'return o;})();'];
        };
        return Parser;
      }();
      function equalsToDefault(def, value) {
        if (typeof def === 'function') {
          try {
            def = def();
          } catch (e) {
            return false;
          }
        }
        if (def === value) {
          return true;
        }
        if (def && value && typeof def === 'object' && typeof value === 'object' && def.constructor === value.constructor) {
          if (def instanceof legacyCC.ValueType) {
            if (def.equals(value)) {
              return true;
            }
          } else if (Array.isArray(def)) {
            return def.length === 0 && value.length === 0;
          } else if (def.constructor === Object) {
            return isEmptyObject(def) && isEmptyObject(value);
          }
        }
        return false;
      }
      function compile(node) {
        var root = node instanceof legacyCC.Node && node;
        var parser = new Parser(node, root);
        return parser.result;
      }

      var _dec$33, _class$30, _class2$2I, _initializer$2y, _initializer2$26, _initializer3$1z, _class3$N;
      var OptimizationPolicy = Enum({
        AUTO: 0,
        SINGLE_INSTANCE: 1,
        MULTI_INSTANCE: 2
      });
      var Prefab = exports('dJ', (_dec$33 = ccclass$M('cc.Prefab'), _dec$33(_class$30 = (_class2$2I = (_class3$N = function (_Asset) {
        _inheritsLoose(Prefab, _Asset);
        function Prefab() {
          var _this;
          _this = _Asset.call(this) || this;
          _this.data = _initializer$2y && _initializer$2y();
          _this.optimizationPolicy = _initializer2$26 && _initializer2$26();
          _this.persistent = _initializer3$1z && _initializer3$1z();
          _this._createFunction = void 0;
          _this._instantiatedTimes = void 0;
          _this._createFunction = null;
          _this._instantiatedTimes = 0;
          return _this;
        }
        var _proto = Prefab.prototype;
        _proto.createNode = function createNode(cb) {
          var node = legacyCC.instantiate(this);
          node.name = this.name;
          cb(null, node);
        };
        _proto.compileCreateFunction = function compileCreateFunction() {
          this._createFunction = compile(this.data);
        };
        _proto._doInstantiate = function _doInstantiate(rootToRedirect) {
          if (!this.data._prefab) {
            warnID(3700);
          }
          if (!this._createFunction) {
            this.compileCreateFunction();
          }
          return this._createFunction(rootToRedirect);
        };
        _proto._instantiate = function _instantiate() {
          var node;
          var useJit = false;
          {
            if (this.optimizationPolicy === OptimizationPolicy.SINGLE_INSTANCE) {
              useJit = false;
            } else if (this.optimizationPolicy === OptimizationPolicy.MULTI_INSTANCE) {
              useJit = true;
            } else {
              useJit = this._instantiatedTimes + 1 >= Prefab.OptimizationPolicyThreshold;
            }
          }
          if (useJit) {
            node = this._doInstantiate();
            this.data._instantiate(node);
          } else {
            node = this.data._instantiate();
          }
          ++this._instantiatedTimes;
          return node;
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          this.data = new Node$1();
          this.data.name = '(Missing Node)';
          var prefabInfo = new legacyCC._PrefabInfo();
          prefabInfo.asset = this;
          prefabInfo.root = this.data;
          this.data._prefab = prefabInfo;
        };
        _proto.validate = function validate() {
          return !!this.data;
        };
        _proto.onLoaded = function onLoaded() {
          var rootNode = this.data;
          expandNestedPrefabInstanceNode(rootNode);
          applyTargetOverrides(rootNode);
        };
        return Prefab;
      }(Asset), _class3$N.OptimizationPolicy = OptimizationPolicy, _class3$N.OptimizationPolicyThreshold = 3, _class3$N), (_initializer$2y = applyDecoratedInitializer(_class2$2I.prototype, "data", [serializable$p], function () {
        return null;
      }), _initializer2$26 = applyDecoratedInitializer(_class2$2I.prototype, "optimizationPolicy", [serializable$p], function () {
        return OptimizationPolicy.AUTO;
      }), _initializer3$1z = applyDecoratedInitializer(_class2$2I.prototype, "persistent", [serializable$p], function () {
        return false;
      })), _class2$2I)) || _class$30));
      value(Prefab, '_utils', utils$1);
      legacyCC.Prefab = Prefab;
      {
        obsolete(legacyCC, 'cc._Prefab', 'Prefab');
      }

      var UIRendererManager = function () {
        function UIRendererManager() {
          this._allRenderers = [];
          this._dirtyRenderers = [];
          this._dirtyVersion = 0;
        }
        var _proto = UIRendererManager.prototype;
        _proto.addRenderer = function addRenderer(uiRenderer) {
          if (uiRenderer._internalId === -1) {
            uiRenderer._internalId = this._allRenderers.length;
            this._allRenderers.push(uiRenderer);
          }
        };
        _proto.removeRenderer = function removeRenderer(uiRenderer) {
          if (uiRenderer._internalId !== -1) {
            {
              assert(this._allRenderers[uiRenderer._internalId] === uiRenderer);
            }
            var id = uiRenderer._internalId;
            this._allRenderers[this._allRenderers.length - 1]._internalId = id;
            fastRemoveAt$2(this._allRenderers, id);
            uiRenderer._internalId = -1;
            if (uiRenderer._dirtyVersion === this._dirtyVersion) {
              fastRemove(this._dirtyRenderers, uiRenderer);
              uiRenderer._dirtyVersion = -1;
            }
          }
        };
        _proto.markDirtyRenderer = function markDirtyRenderer(uiRenderer) {
          if (uiRenderer._dirtyVersion !== this._dirtyVersion && uiRenderer._internalId !== -1) {
            this._dirtyRenderers.push(uiRenderer);
            uiRenderer._dirtyVersion = this._dirtyVersion;
          }
        };
        _proto.updateAllDirtyRenderers = function updateAllDirtyRenderers() {
          var length = this._dirtyRenderers.length;
          var dirtyRenderers = this._dirtyRenderers;
          for (var i = 0; i < length; i++) {
            {
              assert(dirtyRenderers[i]._internalId !== -1);
            }
            dirtyRenderers[i].updateRenderer();
          }
          this._dirtyRenderers.length = 0;
          this._dirtyVersion++;
        };
        return UIRendererManager;
      }();
      var uiRendererManager = new UIRendererManager();

      var ImageFmts = ['.png', '.jpg', '.bmp', '.jpeg', '.gif', '.ico', '.tiff', '.webp', '.image', '.pvr', '.pkm', '.astc'];
      var AudioFmts = ['.mp3', '.ogg', '.wav', '.m4a'];
      function GetTrue() {
        return true;
      }
      var md5Pipe = {
        transformURL: function transformURL(url) {
          var uuid = getUuidFromURL(url);
          if (!uuid) {
            return url;
          }
          var bundle = bundles.find(function (b) {
            return !!b.getAssetInfo(uuid);
          });
          if (!bundle) {
            return url;
          }
          var hashValue = '';
          var info = bundle.getAssetInfo(uuid);
          if (url.startsWith(bundle.base + bundle.config.nativeBase)) {
            hashValue = info.nativeVer || '';
          } else {
            hashValue = info.ver || '';
          }
          if (!hashValue || url.indexOf(hashValue) !== -1) {
            return url;
          }
          var hashPatchInFolder = false;
          if (extname(url) === '.ttf') {
            hashPatchInFolder = true;
          }
          if (hashPatchInFolder) {
            var dirname$1 = dirname(url);
            var basename$1 = basename(url);
            url = dirname$1 + "." + hashValue + "/" + basename$1;
          } else {
            url = url.replace(/.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,})/, function (match, uuid) {
              return match + "." + hashValue;
            });
          }
          return url;
        }
      };
      var CCLoader = exports('et', function () {
        function CCLoader() {
          this._autoReleaseSetting = Object.create(null);
          this._parseLoadResArgs = parseLoadResArgs;
        }
        var _proto = CCLoader.prototype;
        _proto.load = function load(res, progressCallback, completeCallback) {
          if (completeCallback === undefined) {
            if (progressCallback !== undefined) {
              completeCallback = progressCallback;
              progressCallback = null;
            }
          }
          var requests = Array.isArray(res) ? res : [res];
          for (var i = 0; i < requests.length; i++) {
            var _item = requests[i];
            if (typeof _item === 'string') {
              requests[i] = {
                url: _item,
                __isNative__: true
              };
            } else {
              if (_item.type) {
                _item.ext = "." + _item.type;
                _item.type = undefined;
              }
              if (_item.url) {
                _item.__isNative__ = true;
              }
            }
          }
          var images = [];
          var audios = [];
          assetManager.loadAny(requests, null, function (finish, total, item) {
            if (item.content) {
              if (ImageFmts.includes(item.ext)) {
                images.push(item.content);
              } else if (AudioFmts.includes(item.ext)) {
                audios.push(item.content);
              }
            }
            if (progressCallback) {
              progressCallback(finish, total, item);
            }
          }, function (err, _native) {
            var out = null;
            if (!err) {
              _native = Array.isArray(_native) ? _native : [_native];
              var _loop = function _loop(_i) {
                var item = _native[_i];
                if (!(item instanceof Asset)) {
                  var _asset = item;
                  var _url = requests[_i].url;
                  if (images.includes(_asset)) {
                    factory.create(_url, item, '.png', {}, function (err, image) {
                      _asset = _native[_i] = image;
                    });
                  } else if (audios.includes(_asset)) {
                    factory.create(_url, item, '.mp3', {}, function (err, audio) {
                      _asset = _native[_i] = audio;
                    });
                  }
                  assets.add(_url, _asset);
                }
              };
              for (var _i = 0; _i < _native.length; _i++) {
                _loop(_i);
              }
              if (_native.length > 1) {
                var map = Object.create(null);
                _native.forEach(function (asset) {
                  map[asset._uuid] = asset;
                });
                out = {
                  isCompleted: GetTrue,
                  _map: map
                };
              } else {
                out = _native[0];
              }
            }
            if (completeCallback) {
              completeCallback(err, out);
            }
          });
        };
        _proto.getXMLHttpRequest = function getXMLHttpRequest() {
          return new XMLHttpRequest();
        };
        _proto.getItem = function getItem(id) {
          return assetManager.assets.has(id) ? {
            content: assetManager.assets.get(id)
          } : null;
        };
        _proto.loadRes = function loadRes(url, type, progressCallback, completeCallback) {
          var _this$_parseLoadResAr = this._parseLoadResArgs(type, progressCallback, completeCallback),
            _type = _this$_parseLoadResAr.type,
            onProgress = _this$_parseLoadResAr.onProgress,
            onComplete = _this$_parseLoadResAr.onComplete;
          var extname$1 = extname(url);
          if (extname$1 && !resources.getInfoWithPath(url, _type)) {
            url = url.slice(0, -extname$1.length);
          }
          resources.load(url, _type, onProgress, onComplete);
        };
        _proto.loadResArray = function loadResArray(urls, type, progressCallback, completeCallback) {
          var _this$_parseLoadResAr2 = this._parseLoadResArgs(type, progressCallback, completeCallback),
            _type = _this$_parseLoadResAr2.type,
            onProgress = _this$_parseLoadResAr2.onProgress,
            onComplete = _this$_parseLoadResAr2.onComplete;
          urls.forEach(function (url, i) {
            var extname$1 = extname(url);
            if (extname$1 && !resources.getInfoWithPath(url, _type)) {
              urls[i] = url.slice(0, -extname$1.length);
            }
          });
          resources.load(urls, _type, onProgress, onComplete);
        };
        _proto.loadResDir = function loadResDir(url, type, progressCallback, completeCallback) {
          var _this$_parseLoadResAr3 = this._parseLoadResArgs(type, progressCallback, completeCallback),
            _type = _this$_parseLoadResAr3.type,
            onProgress = _this$_parseLoadResAr3.onProgress,
            onComplete = _this$_parseLoadResAr3.onComplete;
          resources.loadDir(url, _type, onProgress, function (err, out) {
            var urls = [];
            if (!err) {
              var infos = resources.getDirWithPath(url, _type);
              urls = infos.map(function (info) {
                return info.path;
              });
            }
            if (onComplete) {
              onComplete(err, out, urls);
            }
          });
        };
        _proto.getRes = function getRes(url, type) {
          return assets.has(url) ? assets.get(url) : resources.get(url, type);
        };
        _proto.getResCount = function getResCount() {
          return assets.count;
        };
        _proto.getDependsRecursively = function getDependsRecursively(owner) {
          if (!owner) {
            return [];
          }
          var uuid = typeof owner === 'string' ? owner : owner._uuid;
          return dependUtil.getDepsRecursively(uuid).concat([uuid]);
        };
        _proto.addDownloadHandlers = function addDownloadHandlers(extMap) {
          var handler = Object.create(null);
          var _loop2 = function _loop2() {
            var func = extMap[_type2];
            handler["." + _type2] = function (url, options, onComplete) {
              func({
                url: url
              }, onComplete);
            };
          };
          for (var _type2 in extMap) {
            _loop2();
          }
          downloader$1.register(handler);
        };
        _proto.addLoadHandlers = function addLoadHandlers(extMap) {
          var handler = Object.create(null);
          var _loop3 = function _loop3() {
            var func = extMap[_type3];
            handler["." + _type3] = function (file, options, onComplete) {
              func({
                content: file
              }, onComplete);
            };
          };
          for (var _type3 in extMap) {
            _loop3();
          }
          parser.register(handler);
        };
        _proto.release = function release(asset) {
          if (Array.isArray(asset)) {
            for (var i = 0; i < asset.length; i++) {
              var key = asset[i];
              if (typeof key === 'string') {
                key = assets.get(key);
              }
              assetManager.releaseAsset(key);
            }
          } else if (asset) {
            if (typeof asset === 'string') {
              asset = assets.get(asset);
            }
            assetManager.releaseAsset(asset);
          }
        };
        _proto.releaseAsset = function releaseAsset(asset) {
          assetManager.releaseAsset(asset);
        };
        _proto.releaseRes = function releaseRes(res, type) {
          resources.release(res, type);
        };
        _proto.releaseAll = function releaseAll() {
          assetManager.releaseAll();
          assets.clear();
        };
        _proto.removeItem = function removeItem(id) {
          return !!assets.remove(id);
        };
        _proto.setAutoRelease = function setAutoRelease(asset, autoRelease) {
          if (typeof asset === 'object') {
            asset = asset._uuid;
          }
          this._autoReleaseSetting[asset] = !!autoRelease;
        };
        _proto.setAutoReleaseRecursively = function setAutoReleaseRecursively(asset, autoRelease) {
          if (typeof asset === 'object') {
            asset = asset._uuid;
          }
          autoRelease = !!autoRelease;
          this._autoReleaseSetting[asset] = autoRelease;
          var depends = dependUtil.getDepsRecursively(asset);
          for (var i = 0; i < depends.length; i++) {
            this._autoReleaseSetting[depends[i]] = autoRelease;
          }
        };
        _proto.isAutoRelease = function isAutoRelease(asset) {
          if (typeof asset === 'object') {
            asset = asset._uuid;
          }
          return !!this._autoReleaseSetting[asset];
        };
        _createClass(CCLoader, [{
          key: "onProgress",
          set: function set(val) {
            setDefaultProgressCallback(val);
          }
        }, {
          key: "_cache",
          get: function get() {
            if (assets instanceof Cache) {
              return assets.map;
            } else {
              var map = {};
              assets.forEach(function (val, key) {
                map[key] = val;
              });
              return map;
            }
          }
        }, {
          key: "md5Pipe",
          get: function get() {
            return md5Pipe;
          }
        }, {
          key: "downloader",
          get: function get() {
            return downloader$1;
          }
        }, {
          key: "loader",
          get: function get() {
            return assetManager.parser;
          }
        }]);
        return CCLoader;
      }());
      var loader = exports('eu', new CCLoader());
      var AssetLibrary = exports('ev', {
        init: function init(options) {
          options.importBase = options.libraryPath;
          options.nativeBase = options.rawAssetsBase ;
          assetManager.init(options);
          if (options.rawAssets) {
            resources.init({
              base: '',
              deps: [],
              scenes: {},
              redirect: [],
              debug: true,
              packs: {},
              types: [],
              versions: {
                "import": [],
                "native": []
              },
              name: BuiltinBundleName.RESOURCES,
              importBase: options.importBase,
              nativeBase: options.nativeBase,
              paths: options.rawAssets.assets,
              uuids: Object.keys(options.rawAssets.assets),
              extensionMap: {}
            });
          }
        },
        loadAsset: function loadAsset(uuid, callback, options) {
          assetManager.loadAny(uuid, callback);
        }
      });
      var url = exports('ew', {});
      replaceProperty(url, 'url', [{
        name: 'normalize',
        target: assetManager.utils,
        targetName: 'assetManager.utils',
        newName: 'normalize'
      }, {
        name: 'raw',
        targetName: 'Asset.prototype',
        newName: 'nativeUrl',
        customFunction: function customFunction(url) {
          if (url.startsWith('resources/')) {
            return transform({
              path: changeExtname(url.substr(10)),
              bundle: BuiltinBundleName.RESOURCES,
              __isNative__: true,
              ext: extname(url)
            });
          }
          return '';
        }
      }]);
      removeProperty(AssetLibrary, 'AssetLibrary', [{
        name: 'getLibUrlNoExt',
        suggest: 'AssetLibrary.getLibUrlNoExt was removed, if you want to transform url, please use assetManager.utils.getUrlWithUuid instead'
      }, {
        name: 'queryAssetInfo',
        suggest: 'AssetLibrary.queryAssetInfo was removed'
      }]);
      removeProperty(loader, 'loader', [{
        name: 'releaseResDir',
        suggest: 'loader.releaseResDir was removed, please use assetManager.releaseAsset instead'
      }, {
        name: 'flowInDeps',
        suggest: 'loader.flowInDeps was removed'
      }, {
        name: 'assetLoader',
        suggest: 'loader.assetLoader was removed, assetLoader and md5Pipe were merged into assetManager.transformPipeline'
      }]);
      replaceProperty(legacyCC, 'cc', [{
        name: 'loader',
        newName: 'assetManager',
        logTimes: 1,
        customGetter: function customGetter() {
          return loader;
        }
      }, {
        name: 'AssetLibrary',
        newName: 'assetManager',
        logTimes: 1,
        customGetter: function customGetter() {
          return AssetLibrary;
        }
      }, {
        name: 'Pipeline',
        target: AssetManager,
        targetName: 'AssetManager',
        newName: 'Pipeline',
        logTimes: 1
      }, {
        name: 'url',
        targetName: 'assetManager',
        newName: 'utils',
        logTimes: 1,
        customGetter: function customGetter() {
          return url;
        }
      }]);
      removeProperty(legacyCC, 'cc', [{
        name: 'LoadingItems',
        suggest: getError(1400, 'LoadingItems', 'AssetManager.Task')
      }]);
      replaceProperty(macro, 'macro', [{
        name: 'DOWNLOAD_MAX_CONCURRENT',
        target: downloader$1,
        targetName: 'assetManager.downloader',
        newName: 'maxConcurrency'
      }]);
      var _autoRelease = releaseManager._autoRelease;
      releaseManager._autoRelease = function (oldScene, newScene, persistNodes) {
        _autoRelease.call(releaseManager, oldScene, newScene, persistNodes);
        var releaseSettings = loader._autoReleaseSetting;
        var keys = Object.keys(releaseSettings);
        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];
          if (releaseSettings[key] === true) {
            var _asset2 = assets.get(key);
            if (_asset2) {
              releaseManager.tryRelease(_asset2);
            }
          }
        }
      };

      var Director = exports('e4', function (_EventTarget) {
        _inheritsLoose(Director, _EventTarget);
        function Director() {
          var _this;
          _this = _EventTarget.call(this) || this;
          _this._compScheduler = void 0;
          _this._nodeActivator = void 0;
          _this._invalid = void 0;
          _this._paused = void 0;
          _this._root = void 0;
          _this._loadingScene = void 0;
          _this._scene = void 0;
          _this._totalFrames = void 0;
          _this._scheduler = void 0;
          _this._systems = void 0;
          _this._persistRootNodes = {};
          _this._invalid = false;
          _this._paused = false;
          _this._root = null;
          _this._loadingScene = '';
          _this._scene = null;
          _this._totalFrames = 0;
          _this._scheduler = new Scheduler();
          _this._compScheduler = new ComponentScheduler();
          _this._nodeActivator = new NodeActivator();
          _this._systems = [];
          return _this;
        }
        var _proto = Director.prototype;
        _proto.calculateDeltaTime = function calculateDeltaTime(now) {};
        _proto.end = function end() {
          var _this2 = this;
          this.once(Director.EVENT_END_FRAME, function () {
            _this2.purgeDirector();
          });
        };
        _proto.pause = function pause() {
          if (this._paused) {
            return;
          }
          this._paused = true;
        };
        _proto.purgeDirector = function purgeDirector() {
          this._scheduler.unscheduleAll();
          this._compScheduler.unscheduleAll();
          this._nodeActivator.reset();
          {
            if (isValid(this._scene)) {
              this._scene.destroy();
            }
            this._scene = null;
          }
          this.stopAnimation();
          assetManager.releaseAll();
        };
        _proto.reset = function reset() {
          var _this$getScene;
          this.purgeDirector();
          for (var id in this._persistRootNodes) {
            this.removePersistRootNode(this._persistRootNodes[id]);
          }
          (_this$getScene = this.getScene()) === null || _this$getScene === void 0 ? void 0 : _this$getScene.destroy();
          this.emit(Director.EVENT_RESET);
          this.startAnimation();
        };
        _proto.runSceneImmediate = function runSceneImmediate(scene, onBeforeLoadScene, onLaunched) {
          var _this3 = this;
          if (scene instanceof SceneAsset) scene = scene.scene;
          assertID(scene instanceof Scene, 1216);
          {
            console.time('InitScene');
          }
          scene._load();
          {
            console.timeEnd('InitScene');
          }
          {
            console.time('AttachPersist');
          }
          var persistNodeList = Object.keys(this._persistRootNodes).map(function (x) {
            return _this3._persistRootNodes[x];
          });
          for (var i = 0; i < persistNodeList.length; i++) {
            var node = persistNodeList[i];
            node.emit(Node$1.EventType.SCENE_CHANGED_FOR_PERSISTS, scene.renderScene);
            var existNode = scene.uuid === node._originalSceneId && scene.getChildByUuid(node.uuid);
            if (existNode) {
              var index = existNode.getSiblingIndex();
              node.hideFlags &= ~CCObject.Flags.DontSave;
              node.hideFlags |= CCObject.Flags.DontSave & existNode.hideFlags;
              existNode._destroyImmediate();
              scene.insertChild(node, index);
            } else {
              node.hideFlags |= CCObject.Flags.DontSave;
              node.parent = scene;
            }
          }
          {
            console.timeEnd('AttachPersist');
          }
          var oldScene = this._scene;
          {
            console.time('Destroy');
          }
          if (isValid(oldScene)) {
            oldScene.destroy();
          }
          {
            {
              console.time('AutoRelease');
            }
            releaseManager._autoRelease(oldScene, scene, this._persistRootNodes);
            {
              console.timeEnd('AutoRelease');
            }
          }
          this._scene = null;
          CCObject._deferredDestroy();
          {
            console.timeEnd('Destroy');
          }
          if (onBeforeLoadScene) {
            onBeforeLoadScene();
          }
          this.emit(Director.EVENT_BEFORE_SCENE_LAUNCH, scene);
          this._scene = scene;
          {
            console.time('Activate');
          }
          scene._activate();
          {
            console.timeEnd('Activate');
          }
          if (this._root) {
            this._root.resetCumulativeTime();
          }
          this.startAnimation();
          if (onLaunched) {
            onLaunched(null, scene);
          }
          this.emit(Director.EVENT_AFTER_SCENE_LAUNCH, scene);
        };
        _proto.runScene = function runScene(scene, onBeforeLoadScene, onLaunched) {
          var _this4 = this;
          if (scene instanceof SceneAsset) scene = scene.scene;
          assertID(Boolean(scene), 1205);
          assertID(scene instanceof Scene, 1216);
          this.once(Director.EVENT_END_FRAME, function () {
            _this4.runSceneImmediate(scene, onBeforeLoadScene, onLaunched);
          });
        };
        _proto.loadScene = function loadScene(sceneName, onLaunched, onUnloaded) {
          var _this5 = this;
          if (this._loadingScene) {
            warnID(1208, sceneName, this._loadingScene);
            return false;
          }
          var bundle = assetManager.bundles.find(function (bundle) {
            return !!bundle.getSceneInfo(sceneName);
          });
          if (bundle) {
            this.emit(Director.EVENT_BEFORE_SCENE_LOADING, sceneName);
            this._loadingScene = sceneName;
            console.time("LoadScene " + sceneName);
            bundle.loadScene(sceneName, function (err, scene) {
              console.timeEnd("LoadScene " + sceneName);
              _this5._loadingScene = '';
              if (err) {
                error(err);
                if (onLaunched) {
                  onLaunched(err);
                }
              } else {
                _this5.runSceneImmediate(scene, onUnloaded, onLaunched);
              }
            });
            return true;
          } else {
            errorID(1209, sceneName);
            return false;
          }
        };
        _proto.preloadScene = function preloadScene(sceneName, onProgress, onLoaded) {
          var bundle = assetManager.bundles.find(function (bundle) {
            return !!bundle.getSceneInfo(sceneName);
          });
          if (bundle) {
            bundle.preloadScene(sceneName, null, onProgress, onLoaded);
          } else {
            var _err = "Can not preload the scene \"" + sceneName + "\" because it is not in the build settings.";
            if (onLoaded) {
              onLoaded(new Error(_err));
            }
            error("preloadScene: " + _err);
          }
        };
        _proto.resume = function resume() {
          if (!this._paused) {
            return;
          }
          this._paused = false;
        };
        _proto.getScene = function getScene() {
          return this._scene;
        };
        _proto.getDeltaTime = function getDeltaTime() {
          return legacyCC.game.deltaTime;
        };
        _proto.getTotalTime = function getTotalTime() {
          return legacyCC.game.totalTime;
        };
        _proto.getCurrentTime = function getCurrentTime() {
          return legacyCC.game.frameStartTime;
        };
        _proto.getTotalFrames = function getTotalFrames() {
          return this._totalFrames;
        };
        _proto.isPaused = function isPaused() {
          return this._paused;
        };
        _proto.getScheduler = function getScheduler() {
          return this._scheduler;
        };
        _proto.setScheduler = function setScheduler(scheduler) {
          if (this._scheduler !== scheduler) {
            this.unregisterSystem(this._scheduler);
            this._scheduler = scheduler;
            this.registerSystem(Scheduler.ID, scheduler, 200);
          }
        };
        _proto.registerSystem = function registerSystem(name, sys, priority) {
          sys.id = name;
          sys.priority = priority;
          this._systems.push(sys);
          this._systems.sort(System.sortByPriority);
        };
        _proto.unregisterSystem = function unregisterSystem(sys) {
          fastRemove(this._systems, sys);
          this._systems.sort(System.sortByPriority);
        };
        _proto.getSystem = function getSystem(name) {
          return this._systems.find(function (sys) {
            return sys.id === name;
          });
        };
        _proto.getAnimationManager = function getAnimationManager() {
          return this.getSystem(legacyCC.AnimationManager.ID);
        };
        _proto.startAnimation = function startAnimation() {
          this._invalid = false;
        };
        _proto.stopAnimation = function stopAnimation() {
          this._invalid = true;
        };
        _proto.mainLoop = function mainLoop(now) {
          var dt;
          {
            dt = legacyCC.game._calculateDT(now);
          }
          this.tick(dt);
        };
        _proto.tick = function tick(dt) {
          if (!this._invalid) {
            this.emit(Director.EVENT_BEGIN_FRAME);
            {
              input$1._frameDispatchEvents();
            }
            if (!this._paused) {
              this.emit(Director.EVENT_BEFORE_UPDATE);
              this._compScheduler.startPhase();
              this._compScheduler.updatePhase(dt);
              for (var i = 0; i < this._systems.length; ++i) {
                this._systems[i].update(dt);
              }
              this._compScheduler.lateUpdatePhase(dt);
              this.emit(Director.EVENT_AFTER_UPDATE);
              CCObject._deferredDestroy();
              for (var _i = 0; _i < this._systems.length; ++_i) {
                this._systems[_i].postUpdate(dt);
              }
            }
            this.emit(Director.EVENT_BEFORE_DRAW);
            uiRendererManager.updateAllDirtyRenderers();
            this._root.frameMove(dt);
            this.emit(Director.EVENT_AFTER_DRAW);
            Node$1.resetHasChangedFlags();
            Node$1.clearNodeArray();
            scalableContainerManager.update(dt);
            this.emit(Director.EVENT_END_FRAME);
            this._totalFrames++;
          }
        };
        _proto.buildRenderPipeline = function buildRenderPipeline() {
          if (this._root) {
            this._root.customPipeline.beginSetup();
            var builder = legacyCC.rendering.getCustomPipeline(macro.CUSTOM_PIPELINE_NAME);
            builder.setup(this._root.cameraList, this._root.customPipeline);
            this._root.customPipeline.endSetup();
          }
        };
        _proto.setupRenderPipelineBuilder = function setupRenderPipelineBuilder() {
          if (macro.CUSTOM_PIPELINE_NAME !== '' && legacyCC.rendering && this._root && this._root.usesCustomPipeline) {
            this.on(Director.EVENT_BEFORE_RENDER, this.buildRenderPipeline, this);
          }
        };
        _proto.init = function init() {
          this._totalFrames = 0;
          this._paused = false;
          this.registerSystem(Scheduler.ID, this._scheduler, 200);
          this._root = new Root(deviceManager.gfxDevice);
          var rootInfo = {};
          this._root.initialize(rootInfo);
          this.setupRenderPipelineBuilder();
          for (var i = 0; i < this._systems.length; i++) {
            this._systems[i].init();
          }
          this.emit(Director.EVENT_INIT);
        };
        _proto.addPersistRootNode = function addPersistRootNode(node) {
          if (!Node$1.isNode(node) || !node.uuid) {
            warnID(3800);
            return;
          }
          var id = node.uuid;
          if (!this._persistRootNodes[id]) {
            var _scene = this._scene;
            if (isValid(_scene)) {
              if (!node.parent) {
                node.parent = _scene;
                node._originalSceneId = _scene.uuid;
              } else if (!(node.parent instanceof Scene)) {
                warnID(3801);
                return;
              } else if (node.parent !== _scene) {
                warnID(3802);
                return;
              } else {
                node._originalSceneId = _scene.uuid;
              }
            }
            this._persistRootNodes[id] = node;
            node._persistNode = true;
            releaseManager._addPersistNodeRef(node);
          }
        };
        _proto.removePersistRootNode = function removePersistRootNode(node) {
          var id = node.uuid || '';
          if (node === this._persistRootNodes[id]) {
            delete this._persistRootNodes[id];
            node._persistNode = false;
            node._originalSceneId = '';
            releaseManager._removePersistNodeRef(node);
          }
        };
        _proto.isPersistRootNode = function isPersistRootNode(node) {
          return !!node._persistNode;
        };
        _createClass(Director, [{
          key: "root",
          get: function get() {
            return this._root;
          }
        }]);
        return Director;
      }(EventTarget));
      Director.EVENT_INIT = 'director_init';
      Director.EVENT_RESET = 'director_reset';
      Director.EVENT_BEFORE_SCENE_LOADING = 'director_before_scene_loading';
      Director.EVENT_BEFORE_SCENE_LAUNCH = 'director_before_scene_launch';
      Director.EVENT_AFTER_SCENE_LAUNCH = 'director_after_scene_launch';
      Director.EVENT_BEFORE_UPDATE = 'director_before_update';
      Director.EVENT_AFTER_UPDATE = 'director_after_update';
      Director.EVENT_BEFORE_DRAW = 'director_before_draw';
      Director.EVENT_AFTER_DRAW = 'director_after_draw';
      Director.EVENT_BEFORE_COMMIT = 'director_before_commit';
      Director.EVENT_BEFORE_RENDER = 'director_before_render';
      Director.EVENT_AFTER_RENDER = 'director_after_render';
      Director.EVENT_BEFORE_PHYSICS = 'director_before_physics';
      Director.EVENT_AFTER_PHYSICS = 'director_after_physics';
      Director.EVENT_BEGIN_FRAME = 'director_begin_frame';
      Director.EVENT_END_FRAME = 'director_end_frame';
      Director.instance = void 0;
      legacyCC.Director = Director;
      var director = exports('e5', Director.instance = legacyCC.director = new Director());

      function findCanvas() {
        var frame = document.querySelector('#GameDiv');
        var container = document.querySelector('#Cocos3dGameContainer');
        var canvas = document.querySelector('#GameCanvas');
        return {
          frame: frame,
          container: container,
          canvas: canvas
        };
      }
      function loadJsFile(path) {
        return new Promise(function (resolve, reject) {
          var err;
          function windowErrorListener(evt) {
            if (evt.filename === path) {
              err = evt.error;
            }
          }
          window.addEventListener('error', windowErrorListener);
          var script = document.createElement('script');
          script.charset = 'utf-8';
          script.async = true;
          script.crossOrigin = 'anonymous';
          script.addEventListener('error', function () {
            window.removeEventListener('error', windowErrorListener);
            reject(Error("Error loading " + path));
          });
          script.addEventListener('load', function () {
            window.removeEventListener('error', windowErrorListener);
            document.head.removeChild(script);
            if (err) {
              reject(err);
            } else {
              resolve();
            }
          });
          script.src = path.replace('#', '%23');
          document.head.appendChild(script);
        });
      }

      var Pacer = function () {
        function Pacer() {
          var _this = this;
          this._stHandle = 0;
          this._onTick = null;
          this._targetFrameRate = 60;
          this._frameTime = 0;
          this._startTime = 0;
          this._isPlaying = false;
          this._frameCount = 0;
          this._callback = null;
          this._rAF = void 0;
          this._cAF = void 0;
          this._handleRAF = function (stamp) {
            var currTime = performance.now();
            var elapseTime = currTime - _this._startTime;
            var elapseFrame = Math.floor(elapseTime / _this._frameTime);
            if (elapseFrame < 0) {
              _this._startTime = currTime;
              _this._frameCount = 0;
            }
            if (elapseFrame < _this._frameCount) {
              _this._stHandle = _this._rAF.call(window, _this._handleRAF);
            } else {
              _this._frameCount = elapseFrame + 1;
              if (_this._callback) {
                _this._callback();
              }
            }
          };
          this._frameTime = 1000 / this._targetFrameRate;
          this._rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame;
          this._cAF = window.cancelAnimationFrame || window.cancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.ocancelAnimationFrame;
        }
        var _proto = Pacer.prototype;
        _proto.start = function start() {
          var _globalThis$__globalX,
            _this2 = this;
          if (this._isPlaying) return;
          var recordStartTime = this._rAF === undefined || ((_globalThis$__globalX = globalThis.__globalXR) === null || _globalThis$__globalX === void 0 ? void 0 : _globalThis$__globalX.isWebXR);
          var updateCallback = function updateCallback() {
            if (recordStartTime) _this2._startTime = performance.now();
            if (_this2._isPlaying) {
              _this2._stHandle = _this2._stTime(updateCallback);
            }
            if (_this2._onTick) {
              _this2._onTick();
            }
          };
          this._startTime = performance.now();
          this._stHandle = this._stTime(updateCallback);
          this._isPlaying = true;
          this._frameCount = 0;
        };
        _proto.stop = function stop() {
          if (!this._isPlaying) return;
          this._ctTime(this._stHandle);
          this._stHandle = 0;
          this._isPlaying = false;
          this._frameCount = 0;
        };
        _proto._stTime = function _stTime(callback) {
          var _globalThis$__globalX2;
          if (this._rAF === undefined || (_globalThis$__globalX2 = globalThis.__globalXR) !== null && _globalThis$__globalX2 !== void 0 && _globalThis$__globalX2.isWebXR) {
            var currTime = performance.now();
            var elapseTime = Math.max(0, currTime - this._startTime);
            var timeToCall = Math.max(0, this._frameTime - elapseTime);
            return setTimeout(callback, timeToCall);
          }
          this._callback = callback;
          return this._rAF.call(window, this._handleRAF);
        };
        _proto._ctTime = function _ctTime(id) {
          var _globalThis$__globalX3;
          if (this._cAF === undefined || (_globalThis$__globalX3 = globalThis.__globalXR) !== null && _globalThis$__globalX3 !== void 0 && _globalThis$__globalX3.isWebXR) {
            clearTimeout(id);
          } else if (id) {
            this._cAF.call(window, id);
          }
        };
        _createClass(Pacer, [{
          key: "targetFrameRate",
          get: function get() {
            return this._targetFrameRate;
          },
          set: function set(val) {
            if (this._targetFrameRate !== val) {
              assertIsTrue(val > 0);
              this._targetFrameRate = val;
              this._frameTime = 1000 / this._targetFrameRate;
              if (this._isPlaying) {
                this.stop();
                this.start();
              }
            }
          }
        }, {
          key: "onTick",
          get: function get() {
            return this._onTick;
          },
          set: function set(val) {
            this._onTick = val;
          }
        }]);
        return Pacer;
      }();

      markAsWarning(RenderPipeline.prototype, 'RenderPipeline.prototype', [{
        name: 'geometryRenderer',
        suggest: 'please use camera.geometryRenderer instead.'
      }]);

      var v2_0 = new Vec2();
      var SplashScreen = function () {
        var _proto = SplashScreen.prototype;
        _proto.init = function init() {
          var _settings$querySettin,
            _settings$querySettin2,
            _settings$querySettin3,
            _settings$querySettin4,
            _settings$querySettin5,
            _settings$querySettin6,
            _this = this;
          this.settings = {
            displayRatio: (_settings$querySettin = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'displayRatio')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : 0.4,
            totalTime: (_settings$querySettin2 = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'totalTime')) !== null && _settings$querySettin2 !== void 0 ? _settings$querySettin2 : 3000,
            watermarkLocation: (_settings$querySettin3 = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'watermarkLocation')) !== null && _settings$querySettin3 !== void 0 ? _settings$querySettin3 : 'default',
            autoFit: (_settings$querySettin4 = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'autoFit')) !== null && _settings$querySettin4 !== void 0 ? _settings$querySettin4 : true,
            logo: (_settings$querySettin5 = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'logo')) !== null && _settings$querySettin5 !== void 0 ? _settings$querySettin5 : undefined,
            background: (_settings$querySettin6 = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'background')) !== null && _settings$querySettin6 !== void 0 ? _settings$querySettin6 : undefined
          };
          this._curTime = 0;
          if (this.settings.totalTime <= 0 || this.settings.logo === undefined || this.settings.background === undefined) {
            this.settings.totalTime = 0;
          } else {
            this.device = legacyCC.director.root.device;
            this.swapchain = legacyCC.director.root.mainWindow.swapchain;
            this.preInit();
            this.initLayout();
            if (this.settings.logo.type === 'default') {
              this.initWaterMark();
            }
            var bgPromise = Promise.resolve();
            var logoPromise = Promise.resolve();
            if (this.settings.background.type === 'custom') {
              bgPromise = new Promise(function (resolve, reject) {
                _this.bgImage = new ccwindow.Image();
                _this.bgImage.onload = function () {
                  _this.initBG();
                  resolve();
                };
                _this.bgImage.onerror = function () {
                  reject();
                };
                _this.bgImage.src = _this.settings.background.base64;
              });
            }
            if (this.settings.logo.type !== 'none') {
              logoPromise = new Promise(function (resolve, reject) {
                _this.logoImage = new ccwindow.Image();
                _this.logoImage.onload = function () {
                  _this.initLogo();
                  resolve();
                };
                _this.logoImage.onerror = function () {
                  reject();
                };
                _this.logoImage.src = _this.settings.logo.base64;
              });
            }
            return Promise.all([bgPromise, logoPromise]);
          }
          return Promise.resolve([]);
        };
        _proto.preInit = function preInit() {
          var _this$settings$backgr;
          var clearColor = (_this$settings$backgr = this.settings.background) === null || _this$settings$backgr === void 0 ? void 0 : _this$settings$backgr.color;
          this.clearColors = clearColor ? [new Color(clearColor.x, clearColor.y, clearColor.z, clearColor.w)] : [new Color(0, 0, 0, 1)];
          var device = this.device,
            swapchain = this.swapchain;
          this.renderArea = new Rect(0, 0, swapchain.width, swapchain.height);
          this.cmdBuff = device.commandBuffer;
          var verts = new Float32Array([0.5, 0.5, 1, 0, -0.5, 0.5, 0, 0, 0.5, -0.5, 1, 1, -0.5, -0.5, 0, 1]);
          var vbStride = Float32Array.BYTES_PER_ELEMENT * 4;
          var vbSize = vbStride * 4;
          this.vertexBuffers = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, vbSize, vbStride));
          this.vertexBuffers.update(verts);
          var indices = new Uint16Array([0, 1, 2, 1, 3, 2]);
          var ibStride = Uint16Array.BYTES_PER_ELEMENT;
          var ibSize = ibStride * 6;
          this.indicesBuffers = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibSize, ibStride));
          this.indicesBuffers.update(indices);
          var attributes = [new Attribute('a_position', Format.RG32F), new Attribute('a_texCoord', Format.RG32F)];
          var IAInfo = new InputAssemblerInfo(attributes, [this.vertexBuffers], this.indicesBuffers);
          this.quadAssmebler = device.createInputAssembler(IAInfo);
          this.projection = new Mat4();
          Mat4.ortho(this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY, swapchain.surfaceTransform);
          this.isMobile = sys.isMobile;
        };
        _proto.initLayout = function initLayout() {
          if (this.isMobile) {
            this.bgWidth = 812;
            this.bgHeight = 375;
            this.logoWidthTemp = 70;
            this.logoHeightTemp = 100;
            this.textSize = 12;
            this.textHeight = this.textSize + this.textExpandSize;
            this.textXTrans = 1 / 2;
            this.textYExtraTrans = 16;
          } else {
            this.bgWidth = 1920;
            this.bgHeight = 1080;
            this.logoWidthTemp = 140;
            this.logoHeightTemp = 200;
            this.textSize = 24;
            this.textHeight = this.textSize + this.textExpandSize;
            this.textXTrans = 1 / 2;
            this.textYExtraTrans = 32;
          }
          this.logoXTrans = 1 / 2;
          this.logoYTrans = 1 / 6 + 2.5 / 6;
          this.initScale();
        };
        _proto.initScale = function initScale() {
          var dw = this.swapchain.width;
          var dh = this.swapchain.height;
          var desiredWidth = this.isMobile ? 375 : 1080;
          var desiredHeight = this.isMobile ? 812 : 1920;
          if (dw > dh) {
            var temp = desiredHeight;
            desiredHeight = desiredWidth;
            desiredWidth = temp;
          }
          if (dw / dh > 16 / 9) {
            this.scaleSize = dh / desiredHeight;
          } else {
            this.scaleSize = dw / desiredWidth;
          }
        };
        _proto.update = function update(deltaTime) {
          var settings = this.settings;
          var device = this.device,
            swapchain = this.swapchain;
          Mat4.ortho(this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY, swapchain.surfaceTransform);
          var dw = swapchain.width;
          var dh = swapchain.height;
          this.initScale();
          this._curTime += deltaTime * 1000;
          var percent = clamp01(this._curTime / settings.totalTime);
          var u_p = cubicOut(percent);
          var scaleX = 1;
          var scaleY = 1;
          if (this.settings.background.type === 'custom') {
            if (dw < dh) {
              scaleX = dh * this.bgRatio;
              scaleY = dh;
            } else {
              scaleX = dw;
              scaleY = dw * this.bgRatio;
            }
            this.bgMat.setProperty('resolution', v2_0.set(dw, dh), 0);
            this.bgMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0);
            this.bgMat.setProperty('translate', v2_0.set(dw * 0.5, dh * 0.5), 0);
            this.bgMat.setProperty('percent', 1.0);
            this.bgMat.setProperty('u_projection', this.projection);
            this.bgMat.passes[0].update();
          }
          var logoYTrans = dh * this.logoYTrans;
          if (this.settings.logo.type !== 'none') {
            scaleX = this.logoWidth * this.scaleSize * settings.displayRatio;
            scaleY = this.logoHeight * this.scaleSize * settings.displayRatio;
            this.logoMat.setProperty('resolution', v2_0.set(dw, dh), 0);
            this.logoMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0);
            this.logoMat.setProperty('translate', v2_0.set(dw * this.logoXTrans, logoYTrans), 0);
            this.logoMat.setProperty('percent', u_p);
            this.logoMat.setProperty('u_projection', this.projection);
            this.logoMat.passes[0].update();
          }
          if (this.settings.logo.type === 'default' && this.watermarkMat) {
            var watermarkTW = this.watermarkTexture.width;
            var watermarkTH = this.watermarkTexture.height;
            scaleX = watermarkTW;
            scaleY = watermarkTH;
            var textYTrans = logoYTrans - (this.logoHeight * 0.5 * settings.displayRatio + this.textYExtraTrans) * this.scaleSize - watermarkTH * 0.5;
            this.watermarkMat.setProperty('resolution', v2_0.set(dw, dh), 0);
            this.watermarkMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0);
            this.watermarkMat.setProperty('translate', v2_0.set(dw * this.textXTrans, textYTrans), 0);
            this.watermarkMat.setProperty('percent', u_p);
            this.watermarkMat.setProperty('u_projection', this.projection);
            this.watermarkMat.passes[0].update();
          }
          this.frame();
        };
        _proto.initBG = function initBG() {
          var device = this.device;
          this.bgMat = new Material();
          this.bgMat.initialize({
            effectName: 'util/splash-screen'
          });
          var samplerInfo = new SamplerInfo();
          samplerInfo.addressU = Address.CLAMP;
          samplerInfo.addressV = Address.CLAMP;
          samplerInfo.addressW = Address.CLAMP;
          this.sampler = device.getSampler(samplerInfo);
          this.bgTexture = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, this.bgImage.width, this.bgImage.height));
          var pass = this.bgMat.passes[0];
          var binding = pass.getBinding('mainTexture');
          pass.bindTexture(binding, this.bgTexture);
          this.shader = pass.getShaderVariant();
          var descriptorSet = pass.descriptorSet;
          descriptorSet.bindSampler(binding, this.sampler);
          descriptorSet.update();
          var region = new BufferTextureCopy();
          region.texExtent.width = this.bgImage.width;
          region.texExtent.height = this.bgImage.height;
          region.texExtent.depth = 1;
          device.copyTexImagesToTexture([this.bgImage], this.bgTexture, [region]);
        };
        _proto.initLogo = function initLogo() {
          var device = this.device;
          this.logoMat = new Material();
          this.logoMat.initialize({
            effectName: 'util/splash-screen'
          });
          var samplerInfo = new SamplerInfo();
          samplerInfo.addressU = Address.CLAMP;
          samplerInfo.addressV = Address.CLAMP;
          samplerInfo.addressW = Address.CLAMP;
          this.sampler = device.getSampler(samplerInfo);
          this.logoTexture = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, this.logoImage.width, this.logoImage.height));
          var pass = this.logoMat.passes[0];
          var binding = pass.getBinding('mainTexture');
          pass.bindTexture(binding, this.logoTexture);
          this.shader = pass.getShaderVariant();
          var descriptorSet = pass.descriptorSet;
          descriptorSet.bindSampler(binding, this.sampler);
          descriptorSet.update();
          var region = new BufferTextureCopy();
          region.texExtent.width = this.logoImage.width;
          region.texExtent.height = this.logoImage.height;
          region.texExtent.depth = 1;
          device.copyTexImagesToTexture([this.logoImage], this.logoTexture, [region]);
          var logoRatio = this.logoImage.width / this.logoImage.height;
          if (logoRatio < 1) {
            this.logoWidth = this.logoWidthTemp;
            this.logoHeight = this.logoWidthTemp / logoRatio;
          } else {
            this.logoWidth = this.logoHeightTemp * logoRatio;
            this.logoHeight = this.logoHeightTemp;
          }
        };
        _proto.initWaterMark = function initWaterMark() {
          var watermarkImg = ccwindow.document.createElement('canvas');
          watermarkImg.height = this.textHeight * this.scaleSize;
          watermarkImg.style.width = "" + watermarkImg.width;
          watermarkImg.style.height = "" + watermarkImg.height;
          var text = 'Created with Cocos';
          var ctx = watermarkImg.getContext('2d');
          ctx.font = this.textSize * this.scaleSize + "px Arial";
          ctx.textBaseline = 'top';
          ctx.textAlign = 'center';
          ctx.fillStyle = '#707070';
          var textLength = ctx.measureText(text).width + 10;
          watermarkImg.width = textLength;
          ctx.font = this.textSize * this.scaleSize + "px Arial";
          ctx.textBaseline = 'top';
          ctx.textAlign = 'center';
          ctx.fillStyle = '#707070';
          ctx.fillText(text, watermarkImg.width / 2, 0);
          var region = new BufferTextureCopy();
          region.texExtent.width = watermarkImg.width;
          region.texExtent.height = watermarkImg.height;
          region.texExtent.depth = 1;
          this.watermarkTexture = this.device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, watermarkImg.width, watermarkImg.height));
          this.device.copyTexImagesToTexture([watermarkImg], this.watermarkTexture, [region]);
          this.watermarkMat = new Material();
          this.watermarkMat.initialize({
            effectName: 'util/splash-screen'
          });
          var pass = this.watermarkMat.passes[0];
          var binding = pass.getBinding('mainTexture');
          pass.bindTexture(binding, this.watermarkTexture);
          pass.descriptorSet.update();
        };
        _proto.frame = function frame() {
          var device = this.device,
            swapchain = this.swapchain;
          if (!sys.isXR || xr.entry.isRenderAllowable()) {
            var renderSize = sys.isXR ? 2 : 1;
            for (var xrEye = 0; xrEye < renderSize; xrEye++) {
              if (sys.isXR) {
                xr.entry.renderLoopStart(xrEye);
                var xrFov = xr.entry.getEyeFov(xrEye);
                var radioLeft = 1.0;
                var radioRight = 1.0;
                if (xrEye === XREye.LEFT) {
                  radioLeft = Math.abs(Math.tan(xrFov[0])) / Math.abs(Math.tan(xrFov[1]));
                } else if (xrEye === XREye.RIGHT) {
                  radioRight = Math.abs(Math.tan(xrFov[1])) / Math.abs(Math.tan(xrFov[0]));
                }
                Mat4.ortho(this.projection, -radioLeft, radioRight, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY, swapchain.surfaceTransform);
                this.projection.m00 = preTransforms[swapchain.surfaceTransform][0];
                this.projection.m05 = preTransforms[swapchain.surfaceTransform][3] * device.capabilities.clipSpaceSignY;
                if (this.settings.background.type === 'custom') {
                  this.bgMat.setProperty('u_projection', this.projection);
                  this.bgMat.passes[0].update();
                }
                if (this.settings.logo.type !== 'none') {
                  this.logoMat.setProperty('u_projection', this.projection);
                  this.logoMat.passes[0].update();
                }
                if (this.settings.logo.type === 'default' && this.watermarkMat) {
                  this.watermarkMat.setProperty('u_projection', this.projection);
                  this.watermarkMat.passes[0].update();
                }
              }
              device.enableAutoBarrier(true);
              device.acquire([swapchain]);
              var cmdBuff = this.cmdBuff;
              var framebuffer = legacyCC.director.root.mainWindow.framebuffer;
              var renderArea = this.renderArea;
              renderArea.width = swapchain.width;
              renderArea.height = swapchain.height;
              cmdBuff.begin();
              cmdBuff.beginRenderPass(framebuffer.renderPass, framebuffer, renderArea, this.clearColors, 1.0, 0);
              if (this.settings.background.type === 'custom') {
                var bgPass = this.bgMat.passes[0];
                var bgPso = PipelineStateManager.getOrCreatePipelineState(device, bgPass, this.shader, framebuffer.renderPass, this.quadAssmebler);
                cmdBuff.bindPipelineState(bgPso);
                cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, bgPass.descriptorSet);
                cmdBuff.bindInputAssembler(this.quadAssmebler);
                cmdBuff.draw(this.quadAssmebler);
              }
              if (this.settings.logo.type !== 'none') {
                var logoPass = this.logoMat.passes[0];
                var logoPso = PipelineStateManager.getOrCreatePipelineState(device, logoPass, this.shader, framebuffer.renderPass, this.quadAssmebler);
                cmdBuff.bindPipelineState(logoPso);
                cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, logoPass.descriptorSet);
                cmdBuff.bindInputAssembler(this.quadAssmebler);
                cmdBuff.draw(this.quadAssmebler);
              }
              if (this.settings.logo.type === 'default' && this.watermarkMat) {
                var wartermarkPass = this.watermarkMat.passes[0];
                var watermarkPso = PipelineStateManager.getOrCreatePipelineState(device, wartermarkPass, this.shader, framebuffer.renderPass, this.quadAssmebler);
                cmdBuff.bindPipelineState(watermarkPso);
                cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, wartermarkPass.descriptorSet);
                cmdBuff.bindInputAssembler(this.quadAssmebler);
                cmdBuff.draw(this.quadAssmebler);
              }
              cmdBuff.endRenderPass();
              cmdBuff.end();
              device.flushCommands([cmdBuff]);
              device.queue.submit([cmdBuff]);
              device.present();
              device.enableAutoBarrier(!legacyCC.rendering);
              if (sys.isXR) {
                xr.entry.renderLoopEnd(xrEye);
              }
            }
          }
        };
        _proto.destroy = function destroy() {
          this.device = null;
          this.swapchain = null;
          this.clearColors = null;
          if (this.settings.background.type === 'custom') {
            if (this.bgImage.destroy) this.bgImage.destroy();
            this.bgImage = null;
            this.bgMat.destroy();
            this.bgMat = null;
            this.bgTexture.destroy();
            this.bgTexture = null;
          }
          if (this.settings.logo.type !== 'none') {
            if (this.logoImage.destroy) this.logoImage.destroy();
            this.logoImage = null;
            this.logoMat.destroy();
            this.logoMat = null;
            this.logoTexture.destroy();
            this.logoTexture = null;
          }
          this.renderArea = null;
          this.cmdBuff = null;
          this.shader = null;
          this.quadAssmebler.destroy();
          this.quadAssmebler = null;
          this.vertexBuffers.destroy();
          this.vertexBuffers = null;
          this.indicesBuffers.destroy();
          this.indicesBuffers = null;
          this.sampler = null;
          if (this.settings.logo.type === 'default' && this.watermarkTexture) {
            this.watermarkMat.destroy();
            this.watermarkMat = null;
            this.watermarkTexture.destroy();
            this.watermarkTexture = null;
          }
          this.settings = null;
        };
        function SplashScreen() {
          this.settings = void 0;
          this._curTime = 0;
          this.device = void 0;
          this.swapchain = void 0;
          this.shader = void 0;
          this.sampler = void 0;
          this.cmdBuff = void 0;
          this.quadAssmebler = void 0;
          this.vertexBuffers = void 0;
          this.indicesBuffers = void 0;
          this.renderArea = void 0;
          this.clearColors = void 0;
          this.projection = void 0;
          this.isMobile = false;
          this.bgMat = void 0;
          this.bgImage = void 0;
          this.bgTexture = void 0;
          this.logoMat = void 0;
          this.logoImage = void 0;
          this.logoTexture = void 0;
          this.watermarkMat = void 0;
          this.watermarkTexture = void 0;
          this.bgWidth = 1920;
          this.bgHeight = 1080;
          this.bgRatio = 16 / 9;
          this.logoWidthTemp = 140;
          this.logoHeightTemp = 200;
          this.logoWidth = 0;
          this.logoHeight = 0;
          this.logoXTrans = 1 / 2;
          this.logoYTrans = 1 / 6 + 2.5 / 6;
          this.textSize = 24;
          this.textHeight = 24;
          this.textXTrans = 1 / 2;
          this.textYExtraTrans = 32;
          this.textExpandSize = 4;
          this.scaleSize = 1;
        }
        _createClass(SplashScreen, [{
          key: "isFinished",
          get: function get() {
            return this._curTime >= this.settings.totalTime;
          }
        }, {
          key: "curTime",
          get: function get() {
            return this._curTime;
          },
          set: function set(val) {
            this._curTime = val;
          }
        }], [{
          key: "instance",
          get: function get() {
            if (!SplashScreen._ins) {
              SplashScreen._ins = new SplashScreen();
            }
            return SplashScreen._ins;
          }
        }]);
        return SplashScreen;
      }();
      SplashScreen._ins = void 0;
      legacyCC.internal.SplashScreen = SplashScreen;

      var EffectSettings = function () {
        function EffectSettings() {
          this._data = null;
        }
        var _proto = EffectSettings.prototype;
        _proto.init = function init(path) {
          var _this = this;
          if (path === void 0) {
            path = '';
          }
          if (!legacyCC.rendering || !legacyCC.rendering.enableEffectImport || !path) {
            return Promise.resolve();
          }
          return new Promise(function (resolve, reject) {
            {
              var xhr = new XMLHttpRequest();
              xhr.open('GET', path);
              xhr.responseType = 'arraybuffer';
              xhr.onload = function () {
                _this._data = xhr.response;
                resolve();
              };
              xhr.onerror = function () {
                reject(new Error('request effect settings failed!'));
              };
              xhr.send(null);
            }
          });
        };
        _createClass(EffectSettings, [{
          key: "data",
          get: function get() {
            return this._data;
          }
        }]);
        return EffectSettings;
      }();
      var effectSettings = new EffectSettings();
      legacyCC.effectSettings = effectSettings;

      var Game = exports('e6', function (_EventTarget) {
        _inheritsLoose(Game, _EventTarget);
        function Game() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EventTarget.call.apply(_EventTarget, [this].concat(args)) || this;
          _this.frame = null;
          _this.container = null;
          _this.canvas = null;
          _this.renderType = -1;
          _this.eventTargetOn = _EventTarget.prototype.on;
          _this.eventTargetOnce = _EventTarget.prototype.once;
          _this.config = {};
          _this.onStart = null;
          _this.frameTime = 1000 / 60;
          _this._isCloning = false;
          _this._inited = false;
          _this._engineInited = false;
          _this._rendererInitialized = false;
          _this._paused = true;
          _this._pausedByEngine = false;
          _this._frameRate = 60;
          _this._pacer = null;
          _this._initTime = 0;
          _this._startTime = 0;
          _this._deltaTime = 0.0;
          _this._useFixedDeltaTime = false;
          _this._shouldLoadLaunchScene = true;
          _this.onPreBaseInitDelegate = new AsyncDelegate();
          _this.onPostBaseInitDelegate = new AsyncDelegate();
          _this.onPreInfrastructureInitDelegate = new AsyncDelegate();
          _this.onPostInfrastructureInitDelegate = new AsyncDelegate();
          _this.onPreSubsystemInitDelegate = new AsyncDelegate();
          _this.onPostSubsystemInitDelegate = new AsyncDelegate();
          _this.onPreProjectInitDelegate = new AsyncDelegate();
          _this.onPostProjectInitDelegate = new AsyncDelegate();
          return _this;
        }
        var _proto = Game.prototype;
        _proto.setFrameRate = function setFrameRate(frameRate) {
          this.frameRate = frameRate;
        };
        _proto.getFrameRate = function getFrameRate() {
          return this.frameRate;
        };
        _proto.step = function step() {
          director.tick(this._calculateDT(true));
        };
        _proto.pauseByEngine = function pauseByEngine() {
          if (this._paused) {
            return;
          }
          this._pausedByEngine = true;
          this.pause();
        };
        _proto.resumeByEngine = function resumeByEngine() {
          if (this._pausedByEngine) {
            this.resume();
            this._pausedByEngine = false;
          }
        };
        _proto.pause = function pause() {
          var _this$_pacer;
          if (this._paused) {
            return;
          }
          this._paused = true;
          (_this$_pacer = this._pacer) === null || _this$_pacer === void 0 ? void 0 : _this$_pacer.stop();
          this.emit(Game.EVENT_PAUSE);
        };
        _proto.resume = function resume() {
          var _this$_pacer2;
          if (!this._paused) {
            return;
          }
          input$1._clearEvents();
          this._paused = false;
          (_this$_pacer2 = this._pacer) === null || _this$_pacer2 === void 0 ? void 0 : _this$_pacer2.start();
          this.emit(Game.EVENT_RESUME);
        };
        _proto.isPaused = function isPaused() {
          return this._paused;
        };
        _proto.restart = function restart() {
          var _this2 = this;
          var endFramePromise = new Promise(function (resolve) {
            director.once(Director.EVENT_END_FRAME, function () {
              return resolve();
            });
          });
          return endFramePromise.then(function () {
            director.reset();
            legacyCC.Object._deferredDestroy();
            _this2.pause();
            _this2.resume();
            _this2._shouldLoadLaunchScene = true;
            SplashScreen.instance.curTime = 0;
            _this2._safeEmit(Game.EVENT_RESTART);
          });
        };
        _proto.end = function end() {
          systemInfo.close();
        };
        _proto.on = function on(type, callback, target, once) {
          if (this.canRegisterEvent(type)) {
            callback.call(target);
          }
          return this.eventTargetOn(type, callback, target, once);
        };
        _proto.once = function once(type, callback, target) {
          if (this.canRegisterEvent(type)) {
            return callback.call(target);
          }
          return this.eventTargetOnce(type, callback, target);
        };
        _proto.canRegisterEvent = function canRegisterEvent(type) {
          return this._engineInited && type === Game.EVENT_ENGINE_INITED || this._inited && type === Game.EVENT_GAME_INITED || this._rendererInitialized && type === Game.EVENT_RENDERER_INITED;
        };
        _proto.init = function init(config) {
          var _this3 = this;
          this._compatibleWithOldParams(config);
          return Promise.resolve().then(function () {
            _this3.emit(Game.EVENT_PRE_BASE_INIT);
            return _this3.onPreBaseInitDelegate.dispatch();
          }).then(function () {
            {
              console.time('Init Base');
            }
            var debugMode = config.debugMode || DebugMode.NONE;
            _resetDebugSetting(debugMode);
          }).then(function () {
            return sys.init();
          }).then(function () {
            _this3._initEvents();
          }).then(function () {
            return settings.init(config.settingsPath, config.overrideSettings);
          }).then(function () {
            {
              console.timeEnd('Init Base');
            }
            _this3.emit(Game.EVENT_POST_BASE_INIT);
            return _this3.onPostBaseInitDelegate.dispatch();
          }).then(function () {
            _this3.emit(Game.EVENT_PRE_INFRASTRUCTURE_INIT);
            return _this3.onPreInfrastructureInitDelegate.dispatch();
          }).then(function () {
            {
              console.time('Init Infrastructure');
            }
            macro.init();
            _this3._initXR();
            var adapter = findCanvas();
            if (adapter) {
              _this3.canvas = adapter.canvas;
              _this3.frame = adapter.frame;
              _this3.container = adapter.container;
            }
            screen$1.init();
            garbageCollectionManager.init();
            deviceManager.init(_this3.canvas, bindingMappingInfo);
            var renderPipelineUuid = settings.querySettings(Settings.Category.RENDERING, 'renderPipeline');
            if (renderPipelineUuid === 'ca127c79-69d6-4afd-8183-d712d7b80e14') {
              if (!macro.CUSTOM_PIPELINE_NAME) {
                macro.CUSTOM_PIPELINE_NAME = 'Forward';
              }
            }
            if (macro.CUSTOM_PIPELINE_NAME === '') {
              legacyCC.rendering = undefined;
            }
            assetManager.init();
            builtinResMgr.init();
            Layers.init();
            _this3.initPacer();
            {
              console.timeEnd('Init Infrastructure');
            }
          }).then(function () {
            _this3.emit(Game.EVENT_POST_INFRASTRUCTURE_INIT);
            return _this3.onPostInfrastructureInitDelegate.dispatch();
          }).then(function () {
            _this3.emit(Game.EVENT_PRE_SUBSYSTEM_INIT);
            return _this3.onPreSubsystemInitDelegate.dispatch();
          }).then(function () {
            return effectSettings.init(settings.querySettings(Settings.Category.RENDERING, 'effectSettingsPath'));
          }).then(function () {
            if (!legacyCC.rendering || !legacyCC.rendering.enableEffectImport) {
              return;
            }
            var renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode');
            if (renderMode === LegacyRenderMode.HEADLESS) {
              legacyCC.rendering.init(deviceManager.gfxDevice, null);
              return;
            }
            var data = effectSettings.data;
            if (data === null) {
              errorID(1102);
              return;
            }
            legacyCC.rendering.init(deviceManager.gfxDevice, data);
          }).then(function () {
            var scriptPackages = settings.querySettings(Settings.Category.SCRIPTING, 'scriptPackages');
            if (scriptPackages) {
              return Promise.all(scriptPackages.map(function (pack) {
                return module.import(pack);
              }));
            }
            return Promise.resolve([]);
          }).then(function () {
            {
              console.time('Init SubSystem');
            }
            director.init();
            return builtinResMgr.loadBuiltinAssets();
          }).then(function () {
            {
              console.timeEnd('Init SubSystem');
            }
            _this3.emit(Game.EVENT_POST_SUBSYSTEM_INIT);
            return _this3.onPostSubsystemInitDelegate.dispatch();
          }).then(function () {
            log("Cocos Creator v" + engineVersion);
            _this3.emit(Game.EVENT_ENGINE_INITED);
            _this3._engineInited = true;
          }).then(function () {
            _this3.emit(Game.EVENT_PRE_PROJECT_INIT);
            return _this3.onPreProjectInitDelegate.dispatch();
          }).then(function () {
            {
              console.time('Init Project');
            }
            var jsList = settings.querySettings(Settings.Category.PLUGINS, 'jsList');
            var promise = Promise.resolve();
            if (jsList) {
              jsList.forEach(function (jsListFile) {
                promise = promise.then(function () {
                  return loadJsFile(('src') + "/" + jsListFile);
                });
              });
            }
            return promise;
          }).then(function () {
            return _this3._loadProjectBundles();
          }).then(function () {
            return _this3._loadCCEScripts();
          }).then(function () {
            return _this3._setupRenderPipeline();
          }).then(function () {
            return _this3._loadPreloadAssets();
          }).then(function () {
            builtinResMgr.compileBuiltinMaterial();
            return SplashScreen.instance.init();
          }).then(function () {
            {
              console.timeEnd('Init Project');
            }
            _this3.emit(Game.EVENT_POST_PROJECT_INIT);
            return _this3.onPostProjectInitDelegate.dispatch();
          }).then(function () {
            _this3._inited = true;
            _this3._safeEmit(Game.EVENT_GAME_INITED);
          });
        };
        _proto._initXR = function _initXR() {
          var _settings$querySettin;
          if (typeof globalThis.__globalXR === 'undefined') {
            globalThis.__globalXR = {};
          }
          var globalXR = globalThis.__globalXR;
          globalXR.webxrCompatible = (_settings$querySettin = settings.querySettings(Settings.Category.XR, 'webxrCompatible')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : false;
          if (sys.isXR) {
            var _settings$querySettin2, _settings$querySettin3;
            xr.entry = xr.XrEntry.getInstance();
            var xrMSAA = (_settings$querySettin2 = settings.querySettings(Settings.Category.RENDERING, 'msaa')) !== null && _settings$querySettin2 !== void 0 ? _settings$querySettin2 : 1;
            var xrRenderingScale = (_settings$querySettin3 = settings.querySettings(Settings.Category.RENDERING, 'renderingScale')) !== null && _settings$querySettin3 !== void 0 ? _settings$querySettin3 : 1.0;
            xr.entry.setMultisamplesRTT(xrMSAA);
            xr.entry.setRenderingScale(xrRenderingScale);
          }
        };
        _proto._compatibleWithOldParams = function _compatibleWithOldParams(config) {
          var overrideSettings = config.overrideSettings = config.overrideSettings || {};
          if ('showFPS' in config) {
            overrideSettings.profiling = overrideSettings.profiling || {};
            overrideSettings.profiling.showFPS = config.showFPS;
          }
          if ('frameRate' in config) {
            overrideSettings.screen = overrideSettings.screen || {};
            overrideSettings.screen.frameRate = config.frameRate;
          }
          if ('renderMode' in config) {
            overrideSettings.rendering = overrideSettings.rendering || {};
            overrideSettings.rendering.renderMode = config.renderMode;
          }
          if ('renderPipeline' in config) {
            overrideSettings.rendering = overrideSettings.rendering || {};
            overrideSettings.rendering.renderPipeline = config.renderPipeline;
          }
          if ('assetOptions' in config) {
            overrideSettings.assets = overrideSettings.assets || {};
            Object.assign(overrideSettings.assets, config.assetOptions);
          }
          if ('customJointTextureLayouts' in config) {
            overrideSettings.animation = overrideSettings.animation || {};
            overrideSettings.animation.customJointTextureLayouts = config.customJointTextureLayouts;
          }
          if ('physics' in config) {
            overrideSettings.physics = overrideSettings.physics || {};
            Object.assign(overrideSettings.physics, config.physics);
          }
          if ('orientation' in config) {
            overrideSettings.screen = overrideSettings.screen || {};
            overrideSettings.screen.orientation = config.orientation;
          }
          if ('exactFitScreen' in config) {
            overrideSettings.screen = overrideSettings.screen || {};
            overrideSettings.screen.exactFitScreen = config.exactFitScreen;
          }
        };
        _proto._loadPreloadAssets = function _loadPreloadAssets() {
          var preloadAssets = settings.querySettings(Settings.Category.ASSETS, 'preloadAssets');
          if (!preloadAssets) return Promise.resolve([]);
          return Promise.all(preloadAssets.map(function (uuid) {
            return new Promise(function (resolve, reject) {
              assetManager.loadAny(uuid, function (err) {
                if (err) {
                  reject(err);
                  return;
                }
                resolve();
              });
            });
          }));
        };
        _proto._loadCCEScripts = function _loadCCEScripts() {
          return new Promise(function (resolve, reject) {
            {
              resolve();
            }
          });
        };
        _proto._loadProjectBundles = function _loadProjectBundles() {
          var preloadBundles = settings.querySettings(Settings.Category.ASSETS, 'preloadBundles');
          if (!preloadBundles) return Promise.resolve([]);
          return Promise.all(preloadBundles.map(function (_ref) {
            var bundle = _ref.bundle,
              version = _ref.version;
            return new Promise(function (resolve, reject) {
              var opts = {};
              if (version) opts.version = version;
              assetManager.loadBundle(bundle, opts, function (err) {
                if (err) {
                  reject(err);
                  return;
                }
                resolve();
              });
            });
          }));
        };
        _proto.run = function run(onStart) {
          if (onStart) {
            this.onStart = onStart;
          }
          if (!this._inited || EDITOR_NOT_IN_PREVIEW) {
            return;
          }
          this.resume();
        };
        _proto._calculateDT = function _calculateDT(useFixedDeltaTime) {
          this._useFixedDeltaTime = useFixedDeltaTime;
          if (useFixedDeltaTime) {
            this._startTime = performance.now();
            return this.frameTime / 1000;
          }
          var now = performance.now();
          this._deltaTime = now > this._startTime ? (now - this._startTime) / 1000 : 0;
          if (this._deltaTime > Game.DEBUG_DT_THRESHOLD) {
            this._deltaTime = this.frameTime / 1000;
          }
          this._startTime = now;
          return this._deltaTime;
        };
        _proto._updateCallback = function _updateCallback() {
          var _this4 = this;
          if (!this._inited) return;
          if (!SplashScreen.instance.isFinished) {
            SplashScreen.instance.update(this._calculateDT(false));
          } else if (this._shouldLoadLaunchScene) {
            this._shouldLoadLaunchScene = false;
            var launchScene = settings.querySettings(Settings.Category.LAUNCH, 'launchScene');
            if (launchScene) {
              director.loadScene(launchScene, function () {
                var _this4$onStart;
                logID(1103, launchScene);
                _this4._initTime = performance.now();
                director.startAnimation();
                (_this4$onStart = _this4.onStart) === null || _this4$onStart === void 0 ? void 0 : _this4$onStart.call(_this4);
              });
            } else {
              var _this$onStart;
              this._initTime = performance.now();
              director.startAnimation();
              (_this$onStart = this.onStart) === null || _this$onStart === void 0 ? void 0 : _this$onStart.call(this);
            }
          } else {
            director.tick(this._calculateDT(false));
          }
        };
        _proto.initPacer = function initPacer() {
          var _settings$querySettin4;
          var frameRate = (_settings$querySettin4 = settings.querySettings(Settings.Category.SCREEN, 'frameRate')) !== null && _settings$querySettin4 !== void 0 ? _settings$querySettin4 : 60;
          assert(typeof frameRate === 'number');
          this._pacer = new Pacer();
          this._pacer.onTick = this._updateCallback.bind(this);
          this.frameRate = frameRate;
        };
        _proto._initEvents = function _initEvents() {
          systemInfo.on('show', this._onShow, this);
          systemInfo.on('hide', this._onHide, this);
          systemInfo.on('close', this._onClose, this);
        };
        _proto._onHide = function _onHide() {
          this.emit(Game.EVENT_HIDE);
          this.pauseByEngine();
        };
        _proto._onShow = function _onShow() {
          this.emit(Game.EVENT_SHOW);
          this.resumeByEngine();
        };
        _proto._onClose = function _onClose() {
          this.emit(Game.EVENT_CLOSE);
          systemInfo.exit();
        };
        _proto.addPersistRootNode = function addPersistRootNode(node) {
          director.addPersistRootNode(node);
        };
        _proto.removePersistRootNode = function removePersistRootNode(node) {
          director.removePersistRootNode(node);
        };
        _proto.isPersistRootNode = function isPersistRootNode(node) {
          return director.isPersistRootNode(node);
        };
        _proto._setupRenderPipeline = function _setupRenderPipeline() {
          var _this5 = this;
          var renderPipeline = settings.querySettings(Settings.Category.RENDERING, 'renderPipeline');
          if (!renderPipeline || renderPipeline === 'ca127c79-69d6-4afd-8183-d712d7b80e14') {
            return this._setRenderPipeline();
          }
          return new Promise(function (resolve, reject) {
            assetManager.loadAny(renderPipeline, function (err, asset) {
              return err || !(asset instanceof RenderPipeline) ? reject(err) : resolve(asset);
            });
          }).then(function (asset) {
            _this5._setRenderPipeline(asset);
          })["catch"](function (reason) {
            warn(reason);
            warn("Failed load render pipeline: " + renderPipeline + ", engine failed to initialize, will fallback to default pipeline");
            _this5._setRenderPipeline();
          });
        };
        _proto._setRenderPipeline = function _setRenderPipeline(rppl) {
          if (!director.root.setRenderPipeline(rppl)) {
            this._setRenderPipeline();
          }
          this._rendererInitialized = true;
          this._safeEmit(Game.EVENT_RENDERER_INITED);
        };
        _proto._safeEmit = function _safeEmit(event) {
          {
            this.emit(event);
          }
        };
        _createClass(Game, [{
          key: "inited",
          get: function get() {
            return this._inited;
          }
        }, {
          key: "frameRate",
          get: function get() {
            return this._frameRate;
          },
          set: function set(frameRate) {
            if (typeof frameRate !== 'number') {
              frameRate = parseInt(frameRate, 10);
              if (Number.isNaN(frameRate)) {
                frameRate = 60;
              }
            }
            this._frameRate = frameRate;
            this.frameTime = 1000 / frameRate;
            if (this._pacer) this._pacer.targetFrameRate = this._frameRate;
          }
        }, {
          key: "deltaTime",
          get: function get() {
            return this._useFixedDeltaTime ? this.frameTime / 1000 : this._deltaTime;
          }
        }, {
          key: "totalTime",
          get: function get() {
            return performance.now() - this._initTime;
          }
        }, {
          key: "frameStartTime",
          get: function get() {
            return this._startTime;
          }
        }]);
        return Game;
      }(EventTarget));
      Game.EVENT_HIDE = 'game_on_hide';
      Game.EVENT_SHOW = 'game_on_show';
      Game.EVENT_LOW_MEMORY = 'game_on_low_memory';
      Game.EVENT_GAME_INITED = 'game_inited';
      Game.EVENT_ENGINE_INITED = 'engine_inited';
      Game.EVENT_RENDERER_INITED = 'renderer_inited';
      Game.EVENT_PRE_BASE_INIT = 'pre_base_init';
      Game.EVENT_POST_BASE_INIT = 'post_base_init';
      Game.EVENT_PRE_INFRASTRUCTURE_INIT = 'pre_infrastructure_init';
      Game.EVENT_POST_INFRASTRUCTURE_INIT = 'post_infrastructure_init';
      Game.EVENT_PRE_SUBSYSTEM_INIT = 'pre_subsystem_init';
      Game.EVENT_POST_SUBSYSTEM_INIT = 'post_subsystem_init';
      Game.EVENT_PRE_PROJECT_INIT = 'pre_project_init';
      Game.EVENT_POST_PROJECT_INIT = 'post_project_init';
      Game.EVENT_RESTART = 'game_on_restart';
      Game.EVENT_PAUSE = 'game_on_pause';
      Game.EVENT_RESUME = 'game_on_resume';
      Game.EVENT_CLOSE = 'game_on_close';
      Game.RENDER_TYPE_CANVAS = 0;
      Game.RENDER_TYPE_WEBGL = 1;
      Game.RENDER_TYPE_OPENGL = 2;
      Game.RENDER_TYPE_HEADLESS = 3;
      Game.DEBUG_DT_THRESHOLD = 1;
      legacyCC.Game = Game;
      var game = exports('e7', legacyCC.game = new Game());

      markAsWarning(Director.prototype, 'director', [{
        name: 'calculateDeltaTime'
      }, {
        name: 'getDeltaTime',
        suggest: 'Use game.deltaTime instead'
      }, {
        name: 'getTotalTime',
        suggest: 'Use game.totalTime instead'
      }, {
        name: 'getCurrentTime',
        suggest: 'Use game.frameStartTime instead'
      }]);
      removeProperty(Director.prototype, 'director', [{
        name: 'setAnimationInterval',
        suggest: 'please use game.frameRate instead'
      }, {
        name: 'getAnimationInterval',
        suggest: 'please use game.frameRate instead'
      }, {
        name: 'getRunningScene',
        suggest: 'please use getScene instead'
      }, {
        name: 'setDepthTest',
        suggest: 'please use camera API instead'
      }, {
        name: 'setClearColor',
        suggest: 'please use camera API instead'
      }, {
        name: 'getWinSize',
        suggest: 'please use view.getVisibleSize instead'
      }, {
        name: 'getWinSizeInPixels'
      }, {
        name: 'purgeCachedData',
        suggest: 'please use assetManager.releaseAll instead'
      }, {
        name: 'convertToGL'
      }, {
        name: 'convertToUI'
      }]);
      replaceProperty(director, 'director', [{
        name: '_getSceneUuid',
        targetName: 'assetManager.main',
        newName: 'getSceneInfo',
        customFunction: function customFunction(sceneName) {
          if (assetManager.main) {
            var _assetManager$main$ge;
            return (_assetManager$main$ge = assetManager.main.getSceneInfo(sceneName)) === null || _assetManager$main$ge === void 0 ? void 0 : _assetManager$main$ge.uuid;
          }
          return '';
        }
      }]);
      markAsWarning(game, 'game', [{
        name: 'collisionMatrix'
      }, {
        name: 'groupList'
      }]);
      replaceProperty(game, 'game', [{
        name: '_sceneInfos',
        targetName: 'assetManager.main',
        newName: 'getSceneInfo',
        customGetter: function customGetter() {
          var scenes = [];
          if (assetManager.main) {
            assetManager.main.config.scenes.forEach(function (val) {
              scenes.push(val);
            });
          }
          return scenes;
        }
      }]);

      var DynamicAtlasManager = exports('a3', function (_System) {
        _inheritsLoose(DynamicAtlasManager, _System);
        function DynamicAtlasManager() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _System.call.apply(_System, [this].concat(args)) || this;
          _this._atlases = [];
          _this._atlasIndex = -1;
          _this._maxAtlasCount = 5;
          _this._textureSize = 2048;
          _this._maxFrameSize = 512;
          _this._textureBleeding = true;
          _this._enabled = false;
          return _this;
        }
        var _proto = DynamicAtlasManager.prototype;
        _proto.newAtlas = function newAtlas() {
          var atlas = this._atlases[++this._atlasIndex];
          if (!atlas) {
            atlas = new Atlas(this._textureSize, this._textureSize);
            this._atlases.push(atlas);
          }
          return atlas;
        };
        _proto.beforeSceneLoad = function beforeSceneLoad() {
          this.reset();
        };
        _proto.init = function init() {
          this.enabled = !macro.CLEANUP_IMAGE_CACHE;
        };
        _proto.insertSpriteFrame = function insertSpriteFrame(spriteFrame) {
          if (!this._enabled || this._atlasIndex === this._maxAtlasCount || !spriteFrame || spriteFrame._original) return null;
          if (!spriteFrame.packable) return null;
          var sampler = spriteFrame.texture.getSamplerInfo();
          if (sampler.minFilter !== Filter.LINEAR || sampler.magFilter !== Filter.LINEAR || sampler.mipFilter !== Filter.NONE) {
            return null;
          }
          var atlas = this._atlases[this._atlasIndex];
          if (!atlas) {
            atlas = this.newAtlas();
          }
          var frame = atlas.insertSpriteFrame(spriteFrame);
          if (!frame && this._atlasIndex !== this._maxAtlasCount) {
            atlas = this.newAtlas();
            return atlas.insertSpriteFrame(spriteFrame);
          }
          return frame;
        };
        _proto.reset = function reset() {
          for (var i = 0, l = this._atlases.length; i < l; i++) {
            this._atlases[i].destroy();
          }
          this._atlases.length = 0;
          this._atlasIndex = -1;
        };
        _proto.deleteAtlasSpriteFrame = function deleteAtlasSpriteFrame(spriteFrame) {
          if (!spriteFrame._original) return;
          var atlas;
          for (var i = this._atlases.length - 1; i >= 0; i--) {
            atlas = this._atlases[i];
            fastRemove(atlas._innerSpriteFrames, spriteFrame);
          }
          var texture = spriteFrame._original._texture;
          this.deleteAtlasTexture(texture);
        };
        _proto.deleteAtlasTexture = function deleteAtlasTexture(texture) {
          if (texture) {
            for (var i = this._atlases.length - 1; i >= 0; i--) {
              this._atlases[i].deleteInnerTexture(texture);
              if (this._atlases[i].isEmpty()) {
                this._atlases[i].destroy();
                this._atlases.splice(i, 1);
                this._atlasIndex--;
              }
            }
          }
        };
        _proto.packToDynamicAtlas = function packToDynamicAtlas(comp, frame) {
          if (!this._enabled) return;
          if (frame && !frame._original && frame.packable && frame.texture && frame.texture.width > 0 && frame.texture.height > 0) {
            var packedFrame = this.insertSpriteFrame(frame);
            if (packedFrame) {
              frame._setDynamicAtlasFrame(packedFrame);
            }
          }
        };
        _createClass(DynamicAtlasManager, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(value) {
            if (this._enabled === value) return;
            if (value) {
              this.reset();
              legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this);
            } else {
              this.reset();
              legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this);
            }
            this._enabled = value;
          }
        }, {
          key: "maxAtlasCount",
          get: function get() {
            return this._maxAtlasCount;
          },
          set: function set(value) {
            this._maxAtlasCount = value;
          }
        }, {
          key: "atlasCount",
          get: function get() {
            return this._atlases.length;
          }
        }, {
          key: "textureBleeding",
          get: function get() {
            return this._textureBleeding;
          },
          set: function set(enable) {
            this._textureBleeding = enable;
          }
        }, {
          key: "textureSize",
          get: function get() {
            return this._textureSize;
          },
          set: function set(value) {
            this._textureSize = value;
          }
        }, {
          key: "maxFrameSize",
          get: function get() {
            return this._maxFrameSize;
          },
          set: function set(value) {
            this._maxFrameSize = value;
          }
        }]);
        return DynamicAtlasManager;
      }(System));
      DynamicAtlasManager.instance = void 0;
      var dynamicAtlasManager = exports('a4', DynamicAtlasManager.instance = new DynamicAtlasManager());
      director.registerSystem('dynamicAtlasManager', dynamicAtlasManager, 0);
      legacyCC.internal.dynamicAtlasManager = dynamicAtlasManager;

      function toPPM(buffer, w, h) {
        return "P3 " + w + " " + h + " 255\n" + buffer.filter(function (e, i) {
          return i % 4 < 3;
        }).toString() + "\n";
      }

      var _keyMap;
      (function (_keyMap) {
        _keyMap[_keyMap["positions"] = AttributeName.ATTR_POSITION] = "positions";
        _keyMap[_keyMap["normals"] = AttributeName.ATTR_NORMAL] = "normals";
        _keyMap[_keyMap["uvs"] = AttributeName.ATTR_TEX_COORD] = "uvs";
        _keyMap[_keyMap["colors"] = AttributeName.ATTR_COLOR] = "colors";
      })(_keyMap || (_keyMap = {}));
      function readMesh(mesh, iPrimitive) {
        if (iPrimitive === void 0) {
          iPrimitive = 0;
        }
        var out = {
          positions: []
        };
        var dataView = new DataView(mesh.data.buffer, mesh.data.byteOffset, mesh.data.byteLength);
        var struct = mesh.struct;
        var primitive = struct.primitives[iPrimitive];
        for (var _iterator = _createForOfIteratorHelperLoose(primitive.vertexBundelIndices), _step; !(_step = _iterator()).done;) {
          var idx = _step.value;
          var bundle = struct.vertexBundles[idx];
          var offset = bundle.view.offset;
          var _bundle$view = bundle.view,
            length = _bundle$view.length,
            stride = _bundle$view.stride;
          for (var _iterator2 = _createForOfIteratorHelperLoose(bundle.attributes), _step2; !(_step2 = _iterator2()).done;) {
            var attr = _step2.value;
            var name = _keyMap[attr.name];
            if (name) {
              out[name] = (out[name] || []).concat(readBuffer(dataView, attr.format, offset, length, stride));
            }
            offset += FormatInfos[attr.format].size;
          }
        }
        var view = primitive.indexView;
        out.indices = readBuffer(dataView, Format["R" + view.stride * 8 + "UI"], view.offset, view.length);
        return out;
      }

      var BufferBlob = function () {
        function BufferBlob() {
          this._arrayBufferOrPaddings = [];
          this._length = 0;
        }
        var _proto = BufferBlob.prototype;
        _proto.setNextAlignment = function setNextAlignment(align) {
          if (align !== 0) {
            var remainder = this._length % align;
            if (remainder !== 0) {
              var padding = align - remainder;
              this._arrayBufferOrPaddings.push(padding);
              this._length += padding;
            }
          }
        };
        _proto.addBuffer = function addBuffer(arrayBuffer) {
          var result = this._length;
          this._arrayBufferOrPaddings.push(arrayBuffer);
          this._length += arrayBuffer.byteLength;
          return result;
        };
        _proto.getLength = function getLength() {
          return this._length;
        };
        _proto.getCombined = function getCombined() {
          var result = new Uint8Array(this._length);
          var counter = 0;
          this._arrayBufferOrPaddings.forEach(function (arrayBufferOrPadding) {
            if (typeof arrayBufferOrPadding === 'number') {
              counter += arrayBufferOrPadding;
            } else {
              result.set(new Uint8Array(arrayBufferOrPadding), counter);
              counter += arrayBufferOrPadding.byteLength;
            }
          });
          return result.buffer;
        };
        return BufferBlob;
      }();

      function createMorphRendering(mesh, gfxDevice) {
        return new StdMorphRendering(mesh, gfxDevice);
      }
      var StdMorphRendering = function () {
        function StdMorphRendering(mesh, gfxDevice) {
          this._mesh = void 0;
          this._subMeshRenderings = [];
          this._mesh = mesh;
          if (!this._mesh.struct.morph) {
            return;
          }
          var nSubMeshes = this._mesh.struct.primitives.length;
          this._subMeshRenderings = new Array(nSubMeshes).fill(null);
          for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
            var subMeshMorph = this._mesh.struct.morph.subMeshMorphs[iSubMesh];
            if (!subMeshMorph) {
              continue;
            }
            if (subMeshMorph.targets.length > UBOMorph.MAX_MORPH_TARGET_COUNT) {
              this._subMeshRenderings[iSubMesh] = new CpuComputing(this._mesh, iSubMesh, this._mesh.struct.morph, gfxDevice);
            } else {
              this._subMeshRenderings[iSubMesh] = new GpuComputing(this._mesh, iSubMesh, this._mesh.struct.morph, gfxDevice);
            }
          }
        }
        var _proto = StdMorphRendering.prototype;
        _proto.createInstance = function createInstance() {
          var _this = this;
          var nSubMeshes = this._mesh.struct.primitives.length;
          var subMeshInstances = new Array(nSubMeshes);
          for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
            var _this$_subMeshRenderi, _this$_subMeshRenderi2;
            subMeshInstances[iSubMesh] = (_this$_subMeshRenderi = (_this$_subMeshRenderi2 = this._subMeshRenderings[iSubMesh]) === null || _this$_subMeshRenderi2 === void 0 ? void 0 : _this$_subMeshRenderi2.createInstance()) !== null && _this$_subMeshRenderi !== void 0 ? _this$_subMeshRenderi : null;
          }
          return {
            setWeights: function setWeights(subMeshIndex, weights) {
              var _subMeshInstances$sub;
              (_subMeshInstances$sub = subMeshInstances[subMeshIndex]) === null || _subMeshInstances$sub === void 0 ? void 0 : _subMeshInstances$sub.setWeights(weights);
            },
            requiredPatches: function requiredPatches(subMeshIndex) {
              assertIsNonNullable(_this._mesh.struct.morph);
              var subMeshMorph = _this._mesh.struct.morph.subMeshMorphs[subMeshIndex];
              var subMeshRenderingInstance = subMeshInstances[subMeshIndex];
              if (subMeshRenderingInstance === null) {
                return null;
              }
              assertIsNonNullable(subMeshMorph);
              var patches = [{
                name: 'CC_USE_MORPH',
                value: true
              }, {
                name: 'CC_MORPH_TARGET_COUNT',
                value: subMeshMorph.targets.length
              }];
              if (subMeshMorph.attributes.includes(AttributeName.ATTR_POSITION)) {
                patches.push({
                  name: 'CC_MORPH_TARGET_HAS_POSITION',
                  value: true
                });
              }
              if (subMeshMorph.attributes.includes(AttributeName.ATTR_NORMAL)) {
                patches.push({
                  name: 'CC_MORPH_TARGET_HAS_NORMAL',
                  value: true
                });
              }
              if (subMeshMorph.attributes.includes(AttributeName.ATTR_TANGENT)) {
                patches.push({
                  name: 'CC_MORPH_TARGET_HAS_TANGENT',
                  value: true
                });
              }
              patches.push.apply(patches, subMeshRenderingInstance.requiredPatches());
              return patches;
            },
            adaptPipelineState: function adaptPipelineState(subMeshIndex, descriptorSet) {
              var _subMeshInstances$sub2;
              (_subMeshInstances$sub2 = subMeshInstances[subMeshIndex]) === null || _subMeshInstances$sub2 === void 0 ? void 0 : _subMeshInstances$sub2.adaptPipelineState(descriptorSet);
            },
            destroy: function destroy() {
              for (var _i = 0, _subMeshInstances = subMeshInstances; _i < _subMeshInstances.length; _i++) {
                var subMeshInstance = _subMeshInstances[_i];
                subMeshInstance === null || subMeshInstance === void 0 ? void 0 : subMeshInstance.destroy();
              }
            }
          };
        };
        return StdMorphRendering;
      }();
      var GpuComputing = function () {
        function GpuComputing(mesh, subMeshIndex, morph, gfxDevice) {
          this._gfxDevice = void 0;
          this._subMeshMorph = void 0;
          this._textureInfo = void 0;
          this._attributes = void 0;
          this._verticesCount = void 0;
          this._gfxDevice = gfxDevice;
          var subMeshMorph = morph.subMeshMorphs[subMeshIndex];
          assertIsNonNullable(subMeshMorph);
          this._subMeshMorph = subMeshMorph;
          enableVertexId(mesh, subMeshIndex, gfxDevice);
          var nVertices = mesh.struct.vertexBundles[mesh.struct.primitives[subMeshIndex].vertexBundelIndices[0]].view.count;
          this._verticesCount = nVertices;
          var nTargets = subMeshMorph.targets.length;
          var vec4Required = nVertices * nTargets;
          var vec4TextureFactory = createVec4TextureFactory(gfxDevice, vec4Required);
          this._textureInfo = {
            width: vec4TextureFactory.width,
            height: vec4TextureFactory.height
          };
          this._attributes = subMeshMorph.attributes.map(function (attributeName, attributeIndex) {
            var vec4Tex = vec4TextureFactory.create();
            var valueView = vec4Tex.valueView;
            subMeshMorph.targets.forEach(function (morphTarget, morphTargetIndex) {
              var displacementsView = morphTarget.displacements[attributeIndex];
              var displacements = new Float32Array(mesh.data.buffer, mesh.data.byteOffset + displacementsView.offset, displacementsView.count);
              var displacementsOffset = nVertices * morphTargetIndex * 4;
              for (var iVertex = 0; iVertex < nVertices; ++iVertex) {
                valueView[displacementsOffset + 4 * iVertex + 0] = displacements[3 * iVertex + 0];
                valueView[displacementsOffset + 4 * iVertex + 1] = displacements[3 * iVertex + 1];
                valueView[displacementsOffset + 4 * iVertex + 2] = displacements[3 * iVertex + 2];
              }
            });
            vec4Tex.updatePixels();
            return {
              name: attributeName,
              morphTexture: vec4Tex
            };
          });
        }
        var _proto2 = GpuComputing.prototype;
        _proto2.destroy = function destroy() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._attributes), _step; !(_step = _iterator()).done;) {
            var attribute = _step.value;
            attribute.morphTexture.destroy();
          }
        };
        _proto2.createInstance = function createInstance() {
          var _this2 = this;
          var morphUniforms = new MorphUniforms(this._gfxDevice, this._subMeshMorph.targets.length);
          morphUniforms.setMorphTextureInfo(this._textureInfo.width, this._textureInfo.height);
          morphUniforms.setVerticesCount(this._verticesCount);
          morphUniforms.commit();
          return {
            setWeights: function setWeights(weights) {
              morphUniforms.setWeights(weights);
              morphUniforms.commit();
            },
            requiredPatches: function requiredPatches() {
              return [{
                name: 'CC_MORPH_TARGET_USE_TEXTURE',
                value: true
              }];
            },
            adaptPipelineState: function adaptPipelineState(descriptorSet) {
              for (var _iterator2 = _createForOfIteratorHelperLoose(_this2._attributes), _step2; !(_step2 = _iterator2()).done;) {
                var attribute = _step2.value;
                var binding = void 0;
                switch (attribute.name) {
                  case AttributeName.ATTR_POSITION:
                    binding = UNIFORM_POSITION_MORPH_TEXTURE_BINDING;
                    break;
                  case AttributeName.ATTR_NORMAL:
                    binding = UNIFORM_NORMAL_MORPH_TEXTURE_BINDING;
                    break;
                  case AttributeName.ATTR_TANGENT:
                    binding = UNIFORM_TANGENT_MORPH_TEXTURE_BINDING;
                    break;
                  default:
                    warn('Unexpected attribute!');
                    break;
                }
                if (binding !== undefined) {
                  descriptorSet.bindSampler(binding, attribute.morphTexture.sampler);
                  descriptorSet.bindTexture(binding, attribute.morphTexture.texture);
                }
              }
              descriptorSet.bindBuffer(UBOMorph.BINDING, morphUniforms.buffer);
              descriptorSet.update();
            },
            destroy: function destroy() {}
          };
        };
        return GpuComputing;
      }();
      var CpuComputing = function () {
        function CpuComputing(mesh, subMeshIndex, morph, gfxDevice) {
          this._gfxDevice = void 0;
          this._attributes = [];
          this._gfxDevice = gfxDevice;
          var subMeshMorph = morph.subMeshMorphs[subMeshIndex];
          assertIsNonNullable(subMeshMorph);
          enableVertexId(mesh, subMeshIndex, gfxDevice);
          this._attributes = subMeshMorph.attributes.map(function (attributeName, attributeIndex) {
            return {
              name: attributeName,
              targets: subMeshMorph.targets.map(function (attributeDisplacement) {
                return {
                  displacements: new Float32Array(mesh.data.buffer, mesh.data.byteOffset + attributeDisplacement.displacements[attributeIndex].offset, attributeDisplacement.displacements[attributeIndex].count)
                };
              })
            };
          });
        }
        var _proto3 = CpuComputing.prototype;
        _proto3.createInstance = function createInstance() {
          return new CpuComputingRenderingInstance(this, this._attributes[0].targets[0].displacements.length / 3, this._gfxDevice);
        };
        _createClass(CpuComputing, [{
          key: "data",
          get: function get() {
            return this._attributes;
          }
        }]);
        return CpuComputing;
      }();
      var CpuComputingRenderingInstance = function () {
        function CpuComputingRenderingInstance(owner, nVertices, gfxDevice) {
          this._attributes = void 0;
          this._owner = void 0;
          this._morphUniforms = void 0;
          this._owner = owner;
          this._morphUniforms = new MorphUniforms(gfxDevice, 0);
          var vec4TextureFactory = createVec4TextureFactory(gfxDevice, nVertices);
          this._morphUniforms.setMorphTextureInfo(vec4TextureFactory.width, vec4TextureFactory.height);
          this._morphUniforms.commit();
          this._attributes = this._owner.data.map(function (attributeMorph, attributeIndex) {
            var morphTexture = vec4TextureFactory.create();
            return {
              attributeName: attributeMorph.name,
              morphTexture: morphTexture
            };
          });
        }
        var _proto4 = CpuComputingRenderingInstance.prototype;
        _proto4.setWeights = function setWeights(weights) {
          for (var iAttribute = 0; iAttribute < this._attributes.length; ++iAttribute) {
            var myAttribute = this._attributes[iAttribute];
            var valueView = myAttribute.morphTexture.valueView;
            var attributeMorph = this._owner.data[iAttribute];
            assertIsTrue(weights.length === attributeMorph.targets.length);
            for (var iTarget = 0; iTarget < attributeMorph.targets.length; ++iTarget) {
              var targetDisplacements = attributeMorph.targets[iTarget].displacements;
              var weight = weights[iTarget];
              var nVertices = targetDisplacements.length / 3;
              if (iTarget === 0) {
                for (var iVertex = 0; iVertex < nVertices; ++iVertex) {
                  valueView[4 * iVertex + 0] = targetDisplacements[3 * iVertex + 0] * weight;
                  valueView[4 * iVertex + 1] = targetDisplacements[3 * iVertex + 1] * weight;
                  valueView[4 * iVertex + 2] = targetDisplacements[3 * iVertex + 2] * weight;
                }
              } else if (weight !== 0.0) {
                for (var _iVertex = 0; _iVertex < nVertices; ++_iVertex) {
                  valueView[4 * _iVertex + 0] += targetDisplacements[3 * _iVertex + 0] * weight;
                  valueView[4 * _iVertex + 1] += targetDisplacements[3 * _iVertex + 1] * weight;
                  valueView[4 * _iVertex + 2] += targetDisplacements[3 * _iVertex + 2] * weight;
                }
              }
            }
            myAttribute.morphTexture.updatePixels();
          }
        };
        _proto4.requiredPatches = function requiredPatches() {
          return [{
            name: 'CC_MORPH_TARGET_USE_TEXTURE',
            value: true
          }, {
            name: 'CC_MORPH_PRECOMPUTED',
            value: true
          }];
        };
        _proto4.adaptPipelineState = function adaptPipelineState(descriptorSet) {
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._attributes), _step3; !(_step3 = _iterator3()).done;) {
            var attribute = _step3.value;
            var attributeName = attribute.attributeName;
            var binding = void 0;
            switch (attributeName) {
              case AttributeName.ATTR_POSITION:
                binding = UNIFORM_POSITION_MORPH_TEXTURE_BINDING;
                break;
              case AttributeName.ATTR_NORMAL:
                binding = UNIFORM_NORMAL_MORPH_TEXTURE_BINDING;
                break;
              case AttributeName.ATTR_TANGENT:
                binding = UNIFORM_TANGENT_MORPH_TEXTURE_BINDING;
                break;
              default:
                warn('Unexpected attribute!');
                break;
            }
            if (binding !== undefined) {
              descriptorSet.bindSampler(binding, attribute.morphTexture.sampler);
              descriptorSet.bindTexture(binding, attribute.morphTexture.texture);
            }
          }
          descriptorSet.bindBuffer(UBOMorph.BINDING, this._morphUniforms.buffer);
          descriptorSet.update();
        };
        _proto4.destroy = function destroy() {
          this._morphUniforms.destroy();
          for (var iAttribute = 0; iAttribute < this._attributes.length; ++iAttribute) {
            var myAttribute = this._attributes[iAttribute];
            myAttribute.morphTexture.destroy();
          }
        };
        return CpuComputingRenderingInstance;
      }();
      var MorphUniforms = function () {
        function MorphUniforms(gfxDevice, targetCount) {
          this._targetCount = void 0;
          this._localBuffer = void 0;
          this._remoteBuffer = void 0;
          this._targetCount = targetCount;
          this._localBuffer = new DataView(new ArrayBuffer(UBOMorph.SIZE));
          this._remoteBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOMorph.SIZE, UBOMorph.SIZE));
        }
        var _proto5 = MorphUniforms.prototype;
        _proto5.destroy = function destroy() {
          this._remoteBuffer.destroy();
        };
        _proto5.setWeights = function setWeights(weights) {
          assertIsTrue(weights.length === this._targetCount);
          for (var iWeight = 0; iWeight < weights.length; ++iWeight) {
            this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_WEIGHTS + 4 * iWeight, weights[iWeight], legacyCC.sys.isLittleEndian);
          }
        };
        _proto5.setMorphTextureInfo = function setMorphTextureInfo(width, height) {
          this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH, width, legacyCC.sys.isLittleEndian);
          this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT, height, legacyCC.sys.isLittleEndian);
        };
        _proto5.setVerticesCount = function setVerticesCount(count) {
          this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_VERTICES_COUNT, count, legacyCC.sys.isLittleEndian);
        };
        _proto5.commit = function commit() {
          this._remoteBuffer.update(this._localBuffer.buffer);
        };
        _createClass(MorphUniforms, [{
          key: "buffer",
          get: function get() {
            return this._remoteBuffer;
          }
        }]);
        return MorphUniforms;
      }();
      function createVec4TextureFactory(gfxDevice, vec4Capacity) {
        var hasFeatureFloatTexture = gfxDevice.getFormatFeatures(Format.RGBA32F) & FormatFeatureBit.SAMPLED_TEXTURE;
        var pixelRequired;
        var pixelFormat;
        var pixelBytes;
        var UpdateViewConstructor;
        if (hasFeatureFloatTexture) {
          pixelRequired = vec4Capacity;
          pixelBytes = 16;
          pixelFormat = Texture2D.PixelFormat.RGBA32F;
          UpdateViewConstructor = Float32Array;
        } else {
          pixelRequired = 4 * vec4Capacity;
          pixelBytes = 4;
          pixelFormat = Texture2D.PixelFormat.RGBA8888;
          UpdateViewConstructor = Uint8Array;
        }
        var _bestSizeToHavePixels = bestSizeToHavePixels(pixelRequired),
          width = _bestSizeToHavePixels.width,
          height = _bestSizeToHavePixels.height;
        assertIsTrue(width * height >= pixelRequired);
        return {
          width: width,
          height: height,
          create: function create() {
            var arrayBuffer = new ArrayBuffer(width * height * pixelBytes);
            var valueView = new Float32Array(arrayBuffer);
            var updateView = UpdateViewConstructor === Float32Array ? valueView : new UpdateViewConstructor(arrayBuffer);
            var image = new ImageAsset({
              width: width,
              height: height,
              _data: updateView,
              _compressed: false,
              format: pixelFormat
            });
            var textureAsset = new Texture2D();
            textureAsset.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
            textureAsset.setMipFilter(Texture2D.Filter.NONE);
            textureAsset.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE);
            textureAsset.image = image;
            if (!textureAsset.getGFXTexture()) {
              warn('Unexpected: failed to create morph texture?');
            }
            var sampler = gfxDevice.getSampler(textureAsset.getSamplerInfo());
            return {
              get texture() {
                return textureAsset.getGFXTexture();
              },
              get sampler() {
                return sampler;
              },
              get valueView() {
                return valueView;
              },
              destroy: function destroy() {
                textureAsset.destroy();
              },
              updatePixels: function updatePixels() {
                textureAsset.uploadData(updateView);
              }
            };
          }
        };
      }
      function enableVertexId(mesh, subMeshIndex, gfxDevice) {
        mesh.renderingSubMeshes[subMeshIndex].enableVertexIdChannel(gfxDevice);
      }
      function bestSizeToHavePixels(nPixels) {
        if (nPixels < 5) {
          nPixels = 5;
        }
        var aligned = nextPow2(nPixels);
        var epxSum = log2(aligned);
        var h = epxSum >> 1;
        var w = epxSum & 1 ? h + 1 : h;
        return {
          width: 1 << w,
          height: 1 << h
        };
      }

      function instantiateWasm(wasmUrl, importObject) {
        return fetchBuffer(wasmUrl).then(function (arrayBuffer) {
          return WebAssembly.instantiate(arrayBuffer, importObject);
        });
      }
      function fetchBuffer(binaryUrl) {
        return new Promise(function (resolve, reject) {
          try {
            if (EDITOR) ; else if (PREVIEW) ;
            binaryUrl = new URL(binaryUrl, module.meta.url).href;
            fetch(binaryUrl).then(function (response) {
              return response.arrayBuffer().then(resolve);
            })["catch"](function (e) {});
          } catch (e) {
            reject(e);
          }
        });
      }
      function ensureWasmModuleReady() {
        return Promise.resolve();
      }

      var MeshoptDecoder = {};
      function initDecoderASM(asm_factory) {
        return Promise.all([asm_factory.ready]).then(function () {
          MeshoptDecoder.supported = asm_factory.supported;
          MeshoptDecoder.ready = Promise.resolve();
          MeshoptDecoder.decodeVertexBuffer = asm_factory.decodeVertexBuffer;
          MeshoptDecoder.decodeIndexBuffer = asm_factory.decodeIndexBuffer;
          MeshoptDecoder.decodeIndexSequence = asm_factory.decodeIndexSequence;
          MeshoptDecoder.decodeGltfBuffer = asm_factory.decodeGltfBuffer;
          MeshoptDecoder.useWorkers = asm_factory.useWorkers;
          MeshoptDecoder.decodeGltfBufferAsync = asm_factory.decodeGltfBufferAsync;
          logID(14202);
        });
      }
      function initDecoderWASM(wasm_factory, wasm_url) {
        function instantiate(importObject) {
          return instantiateWasm(wasm_url, importObject);
        }
        return Promise.all([wasm_factory.ready(instantiate)]).then(function () {
          MeshoptDecoder.supported = wasm_factory.supported;
          MeshoptDecoder.ready = Promise.resolve();
          MeshoptDecoder.decodeVertexBuffer = wasm_factory.decodeVertexBuffer;
          MeshoptDecoder.decodeIndexBuffer = wasm_factory.decodeIndexBuffer;
          MeshoptDecoder.decodeIndexSequence = wasm_factory.decodeIndexSequence;
          MeshoptDecoder.decodeGltfBuffer = wasm_factory.decodeGltfBuffer;
          MeshoptDecoder.useWorkers = wasm_factory.useWorkers;
          MeshoptDecoder.decodeGltfBufferAsync = wasm_factory.decodeGltfBufferAsync;
          logID(14203);
        });
      }
      function shouldUseWasmModule$2() {
        {
          return sys.hasFeature(sys.Feature.WASM);
        }
      }
      function InitDecoder() {
        var errorReport = function errorReport(msg) {
          error(msg);
        };
        return ensureWasmModuleReady().then(function () {
          if (shouldUseWasmModule$2()) {
            return Promise.all([module.import('./meshopt_decoder.wasm-ebbcb6df.js'), module.import('./meshopt_decoder.wasm-43855155.js')]).then(function (_ref) {
              var meshopt_wasm_factory = _ref[0]["default"],
                meshopt_wasm_url = _ref[1]["default"];
              return initDecoderWASM(meshopt_wasm_factory, meshopt_wasm_url);
            });
          } else {
            return module.import('./meshopt_decoder.asm-a0c75b48.js').then(function (_ref2) {
              var meshopt_asm_factory = _ref2["default"];
              return initDecoderASM(meshopt_asm_factory);
            });
          }
        })["catch"](errorReport);
      }
      {
        game.onPostInfrastructureInitDelegate.add(InitDecoder);
      }

      /** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */
      var window$1 = {};
      (function () {

        function i(a) {
          throw a;
        }
        var r = void 0,
          v = !0,
          aa = this;
        function y(a, c) {
          var b = a.split("."),
            e = aa;
          !(b[0] in e) && e.execScript && e.execScript("var " + b[0]);
          for (var f; b.length && (f = b.shift());) !b.length && c !== r ? e[f] = c : e = e[f] ? e[f] : e[f] = {};
        }
        var H = "undefined" !== typeof Uint8Array && "undefined" !== typeof Uint16Array && "undefined" !== typeof Uint32Array;
        function ba(a) {
          if ("string" === typeof a) {
            var c = a.split(""),
              b,
              e;
            b = 0;
            for (e = c.length; b < e; b++) c[b] = (c[b].charCodeAt(0) & 255) >>> 0;
            a = c;
          }
          for (var f = 1, d = 0, g = a.length, h, m = 0; 0 < g;) {
            h = 1024 < g ? 1024 : g;
            g -= h;
            do f += a[m++], d += f; while (--h);
            f %= 65521;
            d %= 65521;
          }
          return (d << 16 | f) >>> 0;
        }
        function J(a, c) {
          this.index = "number" === typeof c ? c : 0;
          this.i = 0;
          this.buffer = a instanceof (H ? Uint8Array : Array) ? a : new (H ? Uint8Array : Array)(32768);
          2 * this.buffer.length <= this.index && i(Error("invalid index"));
          this.buffer.length <= this.index && this.f();
        }
        J.prototype.f = function () {
          var a = this.buffer,
            c,
            b = a.length,
            e = new (H ? Uint8Array : Array)(b << 1);
          if (H) e.set(a);else for (c = 0; c < b; ++c) e[c] = a[c];
          return this.buffer = e;
        };
        J.prototype.d = function (a, c, b) {
          var e = this.buffer,
            f = this.index,
            d = this.i,
            g = e[f],
            h;
          b && 1 < c && (a = 8 < c ? (N[a & 255] << 24 | N[a >>> 8 & 255] << 16 | N[a >>> 16 & 255] << 8 | N[a >>> 24 & 255]) >> 32 - c : N[a] >> 8 - c);
          if (8 > c + d) g = g << c | a, d += c;else for (h = 0; h < c; ++h) g = g << 1 | a >> c - h - 1 & 1, 8 === ++d && (d = 0, e[f++] = N[g], g = 0, f === e.length && (e = this.f()));
          e[f] = g;
          this.buffer = e;
          this.i = d;
          this.index = f;
        };
        J.prototype.finish = function () {
          var a = this.buffer,
            c = this.index,
            b;
          0 < this.i && (a[c] <<= 8 - this.i, a[c] = N[a[c]], c++);
          H ? b = a.subarray(0, c) : (a.length = c, b = a);
          return b;
        };
        var ca = new (H ? Uint8Array : Array)(256),
          ha;
        for (ha = 0; 256 > ha; ++ha) {
          for (var R = ha, ia = R, ja = 7, R = R >>> 1; R; R >>>= 1) ia <<= 1, ia |= R & 1, --ja;
          ca[ha] = (ia << ja & 255) >>> 0;
        }
        var N = ca;
        function la(a) {
          this.buffer = new (H ? Uint16Array : Array)(2 * a);
          this.length = 0;
        }
        la.prototype.getParent = function (a) {
          return 2 * ((a - 2) / 4 | 0);
        };
        la.prototype.push = function (a, c) {
          var b,
            e,
            f = this.buffer,
            d;
          b = this.length;
          f[this.length++] = c;
          for (f[this.length++] = a; 0 < b;) if (e = this.getParent(b), f[b] > f[e]) d = f[b], f[b] = f[e], f[e] = d, d = f[b + 1], f[b + 1] = f[e + 1], f[e + 1] = d, b = e;else break;
          return this.length;
        };
        la.prototype.pop = function () {
          var a,
            c,
            b = this.buffer,
            e,
            f,
            d;
          c = b[0];
          a = b[1];
          this.length -= 2;
          b[0] = b[this.length];
          b[1] = b[this.length + 1];
          for (d = 0;;) {
            f = 2 * d + 2;
            if (f >= this.length) break;
            f + 2 < this.length && b[f + 2] > b[f] && (f += 2);
            if (b[f] > b[d]) e = b[d], b[d] = b[f], b[f] = e, e = b[d + 1], b[d + 1] = b[f + 1], b[f + 1] = e;else break;
            d = f;
          }
          return {
            index: a,
            value: c,
            length: this.length
          };
        };
        function S(a) {
          var c = a.length,
            b = 0,
            e = Number.POSITIVE_INFINITY,
            f,
            d,
            g,
            h,
            m,
            j,
            s,
            n,
            l;
          for (n = 0; n < c; ++n) a[n] > b && (b = a[n]), a[n] < e && (e = a[n]);
          f = 1 << b;
          d = new (H ? Uint32Array : Array)(f);
          g = 1;
          h = 0;
          for (m = 2; g <= b;) {
            for (n = 0; n < c; ++n) if (a[n] === g) {
              j = 0;
              s = h;
              for (l = 0; l < g; ++l) j = j << 1 | s & 1, s >>= 1;
              for (l = j; l < f; l += m) d[l] = g << 16 | n;
              ++h;
            }
            ++g;
            h <<= 1;
            m <<= 1;
          }
          return [d, b, e];
        }
        function ma(a, c) {
          this.h = pa;
          this.w = 0;
          this.input = a;
          this.b = 0;
          c && (c.lazy && (this.w = c.lazy), "number" === typeof c.compressionType && (this.h = c.compressionType), c.outputBuffer && (this.a = H && c.outputBuffer instanceof Array ? new Uint8Array(c.outputBuffer) : c.outputBuffer), "number" === typeof c.outputIndex && (this.b = c.outputIndex));
          this.a || (this.a = new (H ? Uint8Array : Array)(32768));
        }
        var pa = 2,
          qa = {
            NONE: 0,
            r: 1,
            j: pa,
            N: 3
          },
          ra = [],
          T;
        for (T = 0; 288 > T; T++) switch (v) {
          case 143 >= T:
            ra.push([T + 48, 8]);
            break;
          case 255 >= T:
            ra.push([T - 144 + 400, 9]);
            break;
          case 279 >= T:
            ra.push([T - 256 + 0, 7]);
            break;
          case 287 >= T:
            ra.push([T - 280 + 192, 8]);
            break;
          default:
            i("invalid literal: " + T);
        }
        ma.prototype.n = function () {
          var a,
            c,
            b,
            e,
            f = this.input;
          switch (this.h) {
            case 0:
              b = 0;
              for (e = f.length; b < e;) {
                c = H ? f.subarray(b, b + 65535) : f.slice(b, b + 65535);
                b += c.length;
                var d = c,
                  g = b === e,
                  h = r,
                  m = r,
                  j = r,
                  s = r,
                  n = r,
                  l = this.a,
                  q = this.b;
                if (H) {
                  for (l = new Uint8Array(this.a.buffer); l.length <= q + d.length + 5;) l = new Uint8Array(l.length << 1);
                  l.set(this.a);
                }
                h = g ? 1 : 0;
                l[q++] = h | 0;
                m = d.length;
                j = ~m + 65536 & 65535;
                l[q++] = m & 255;
                l[q++] = m >>> 8 & 255;
                l[q++] = j & 255;
                l[q++] = j >>> 8 & 255;
                if (H) l.set(d, q), q += d.length, l = l.subarray(0, q);else {
                  s = 0;
                  for (n = d.length; s < n; ++s) l[q++] = d[s];
                  l.length = q;
                }
                this.b = q;
                this.a = l;
              }
              break;
            case 1:
              var E = new J(new Uint8Array(this.a.buffer), this.b);
              E.d(1, 1, v);
              E.d(1, 2, v);
              var t = sa(this, f),
                z,
                K,
                A;
              z = 0;
              for (K = t.length; z < K; z++) if (A = t[z], J.prototype.d.apply(E, ra[A]), 256 < A) E.d(t[++z], t[++z], v), E.d(t[++z], 5), E.d(t[++z], t[++z], v);else if (256 === A) break;
              this.a = E.finish();
              this.b = this.a.length;
              break;
            case pa:
              var x = new J(new Uint8Array(this.a), this.b),
                B,
                k,
                p,
                D,
                C,
                da = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15],
                W,
                Ma,
                ea,
                Na,
                na,
                va = Array(19),
                Oa,
                $,
                oa,
                F,
                Pa;
              B = pa;
              x.d(1, 1, v);
              x.d(B, 2, v);
              k = sa(this, f);
              W = ta(this.L, 15);
              Ma = ua(W);
              ea = ta(this.K, 7);
              Na = ua(ea);
              for (p = 286; 257 < p && 0 === W[p - 1]; p--);
              for (D = 30; 1 < D && 0 === ea[D - 1]; D--);
              var Qa = p,
                Ra = D,
                M = new (H ? Uint32Array : Array)(Qa + Ra),
                u,
                O,
                w,
                fa,
                L = new (H ? Uint32Array : Array)(316),
                I,
                G,
                P = new (H ? Uint8Array : Array)(19);
              for (u = O = 0; u < Qa; u++) M[O++] = W[u];
              for (u = 0; u < Ra; u++) M[O++] = ea[u];
              if (!H) {
                u = 0;
                for (fa = P.length; u < fa; ++u) P[u] = 0;
              }
              u = I = 0;
              for (fa = M.length; u < fa; u += O) {
                for (O = 1; u + O < fa && M[u + O] === M[u]; ++O);
                w = O;
                if (0 === M[u]) {
                  if (3 > w) for (; 0 < w--;) L[I++] = 0, P[0]++;else for (; 0 < w;) G = 138 > w ? w : 138, G > w - 3 && G < w && (G = w - 3), 10 >= G ? (L[I++] = 17, L[I++] = G - 3, P[17]++) : (L[I++] = 18, L[I++] = G - 11, P[18]++), w -= G;
                } else if (L[I++] = M[u], P[M[u]]++, w--, 3 > w) for (; 0 < w--;) L[I++] = M[u], P[M[u]]++;else for (; 0 < w;) G = 6 > w ? w : 6, G > w - 3 && G < w && (G = w - 3), L[I++] = 16, L[I++] = G - 3, P[16]++, w -= G;
              }
              a = H ? L.subarray(0, I) : L.slice(0, I);
              na = ta(P, 7);
              for (F = 0; 19 > F; F++) va[F] = na[da[F]];
              for (C = 19; 4 < C && 0 === va[C - 1]; C--);
              Oa = ua(na);
              x.d(p - 257, 5, v);
              x.d(D - 1, 5, v);
              x.d(C - 4, 4, v);
              for (F = 0; F < C; F++) x.d(va[F], 3, v);
              F = 0;
              for (Pa = a.length; F < Pa; F++) if ($ = a[F], x.d(Oa[$], na[$], v), 16 <= $) {
                F++;
                switch ($) {
                  case 16:
                    oa = 2;
                    break;
                  case 17:
                    oa = 3;
                    break;
                  case 18:
                    oa = 7;
                    break;
                  default:
                    i("invalid code: " + $);
                }
                x.d(a[F], oa, v);
              }
              var Sa = [Ma, W],
                Ta = [Na, ea],
                Q,
                Ua,
                ga,
                ya,
                Va,
                Wa,
                Xa,
                Ya;
              Va = Sa[0];
              Wa = Sa[1];
              Xa = Ta[0];
              Ya = Ta[1];
              Q = 0;
              for (Ua = k.length; Q < Ua; ++Q) if (ga = k[Q], x.d(Va[ga], Wa[ga], v), 256 < ga) x.d(k[++Q], k[++Q], v), ya = k[++Q], x.d(Xa[ya], Ya[ya], v), x.d(k[++Q], k[++Q], v);else if (256 === ga) break;
              this.a = x.finish();
              this.b = this.a.length;
              break;
            default:
              i("invalid compression type");
          }
          return this.a;
        };
        function wa(a, c) {
          this.length = a;
          this.G = c;
        }
        function xa() {
          var a = za;
          switch (v) {
            case 3 === a:
              return [257, a - 3, 0];
            case 4 === a:
              return [258, a - 4, 0];
            case 5 === a:
              return [259, a - 5, 0];
            case 6 === a:
              return [260, a - 6, 0];
            case 7 === a:
              return [261, a - 7, 0];
            case 8 === a:
              return [262, a - 8, 0];
            case 9 === a:
              return [263, a - 9, 0];
            case 10 === a:
              return [264, a - 10, 0];
            case 12 >= a:
              return [265, a - 11, 1];
            case 14 >= a:
              return [266, a - 13, 1];
            case 16 >= a:
              return [267, a - 15, 1];
            case 18 >= a:
              return [268, a - 17, 1];
            case 22 >= a:
              return [269, a - 19, 2];
            case 26 >= a:
              return [270, a - 23, 2];
            case 30 >= a:
              return [271, a - 27, 2];
            case 34 >= a:
              return [272, a - 31, 2];
            case 42 >= a:
              return [273, a - 35, 3];
            case 50 >= a:
              return [274, a - 43, 3];
            case 58 >= a:
              return [275, a - 51, 3];
            case 66 >= a:
              return [276, a - 59, 3];
            case 82 >= a:
              return [277, a - 67, 4];
            case 98 >= a:
              return [278, a - 83, 4];
            case 114 >= a:
              return [279, a - 99, 4];
            case 130 >= a:
              return [280, a - 115, 4];
            case 162 >= a:
              return [281, a - 131, 5];
            case 194 >= a:
              return [282, a - 163, 5];
            case 226 >= a:
              return [283, a - 195, 5];
            case 257 >= a:
              return [284, a - 227, 5];
            case 258 === a:
              return [285, a - 258, 0];
            default:
              i("invalid length: " + a);
          }
        }
        var Aa = [],
          za,
          Ba;
        for (za = 3; 258 >= za; za++) Ba = xa(), Aa[za] = Ba[2] << 24 | Ba[1] << 16 | Ba[0];
        var Ca = H ? new Uint32Array(Aa) : Aa;
        function sa(a, c) {
          function b(a, c) {
            var b = a.G,
              d = [],
              e = 0,
              f;
            f = Ca[a.length];
            d[e++] = f & 65535;
            d[e++] = f >> 16 & 255;
            d[e++] = f >> 24;
            var g;
            switch (v) {
              case 1 === b:
                g = [0, b - 1, 0];
                break;
              case 2 === b:
                g = [1, b - 2, 0];
                break;
              case 3 === b:
                g = [2, b - 3, 0];
                break;
              case 4 === b:
                g = [3, b - 4, 0];
                break;
              case 6 >= b:
                g = [4, b - 5, 1];
                break;
              case 8 >= b:
                g = [5, b - 7, 1];
                break;
              case 12 >= b:
                g = [6, b - 9, 2];
                break;
              case 16 >= b:
                g = [7, b - 13, 2];
                break;
              case 24 >= b:
                g = [8, b - 17, 3];
                break;
              case 32 >= b:
                g = [9, b - 25, 3];
                break;
              case 48 >= b:
                g = [10, b - 33, 4];
                break;
              case 64 >= b:
                g = [11, b - 49, 4];
                break;
              case 96 >= b:
                g = [12, b - 65, 5];
                break;
              case 128 >= b:
                g = [13, b - 97, 5];
                break;
              case 192 >= b:
                g = [14, b - 129, 6];
                break;
              case 256 >= b:
                g = [15, b - 193, 6];
                break;
              case 384 >= b:
                g = [16, b - 257, 7];
                break;
              case 512 >= b:
                g = [17, b - 385, 7];
                break;
              case 768 >= b:
                g = [18, b - 513, 8];
                break;
              case 1024 >= b:
                g = [19, b - 769, 8];
                break;
              case 1536 >= b:
                g = [20, b - 1025, 9];
                break;
              case 2048 >= b:
                g = [21, b - 1537, 9];
                break;
              case 3072 >= b:
                g = [22, b - 2049, 10];
                break;
              case 4096 >= b:
                g = [23, b - 3073, 10];
                break;
              case 6144 >= b:
                g = [24, b - 4097, 11];
                break;
              case 8192 >= b:
                g = [25, b - 6145, 11];
                break;
              case 12288 >= b:
                g = [26, b - 8193, 12];
                break;
              case 16384 >= b:
                g = [27, b - 12289, 12];
                break;
              case 24576 >= b:
                g = [28, b - 16385, 13];
                break;
              case 32768 >= b:
                g = [29, b - 24577, 13];
                break;
              default:
                i("invalid distance");
            }
            f = g;
            d[e++] = f[0];
            d[e++] = f[1];
            d[e++] = f[2];
            var h, j;
            h = 0;
            for (j = d.length; h < j; ++h) l[q++] = d[h];
            t[d[0]]++;
            z[d[3]]++;
            E = a.length + c - 1;
            n = null;
          }
          var e,
            f,
            d,
            g,
            h,
            m = {},
            j,
            s,
            n,
            l = H ? new Uint16Array(2 * c.length) : [],
            q = 0,
            E = 0,
            t = new (H ? Uint32Array : Array)(286),
            z = new (H ? Uint32Array : Array)(30),
            K = a.w,
            A;
          if (!H) {
            for (d = 0; 285 >= d;) t[d++] = 0;
            for (d = 0; 29 >= d;) z[d++] = 0;
          }
          t[256] = 1;
          e = 0;
          for (f = c.length; e < f; ++e) {
            d = h = 0;
            for (g = 3; d < g && e + d !== f; ++d) h = h << 8 | c[e + d];
            m[h] === r && (m[h] = []);
            j = m[h];
            if (!(0 < E--)) {
              for (; 0 < j.length && 32768 < e - j[0];) j.shift();
              if (e + 3 >= f) {
                n && b(n, -1);
                d = 0;
                for (g = f - e; d < g; ++d) A = c[e + d], l[q++] = A, ++t[A];
                break;
              }
              if (0 < j.length) {
                var x = r,
                  B = r,
                  k = 0,
                  p = r,
                  D = r,
                  C = r,
                  da = r,
                  W = c.length,
                  D = 0,
                  da = j.length;
                a: for (; D < da; D++) {
                  x = j[da - D - 1];
                  p = 3;
                  if (3 < k) {
                    for (C = k; 3 < C; C--) if (c[x + C - 1] !== c[e + C - 1]) continue a;
                    p = k;
                  }
                  for (; 258 > p && e + p < W && c[x + p] === c[e + p];) ++p;
                  p > k && (B = x, k = p);
                  if (258 === p) break;
                }
                s = new wa(k, e - B);
                n ? n.length < s.length ? (A = c[e - 1], l[q++] = A, ++t[A], b(s, 0)) : b(n, -1) : s.length < K ? n = s : b(s, 0);
              } else n ? b(n, -1) : (A = c[e], l[q++] = A, ++t[A]);
            }
            j.push(e);
          }
          l[q++] = 256;
          t[256]++;
          a.L = t;
          a.K = z;
          return H ? l.subarray(0, q) : l;
        }
        function ta(a, c) {
          function b(a) {
            var c = z[a][K[a]];
            c === n ? (b(a + 1), b(a + 1)) : --E[c];
            ++K[a];
          }
          var e = a.length,
            f = new la(572),
            d = new (H ? Uint8Array : Array)(e),
            g,
            h,
            m,
            j,
            s;
          if (!H) for (j = 0; j < e; j++) d[j] = 0;
          for (j = 0; j < e; ++j) 0 < a[j] && f.push(j, a[j]);
          g = Array(f.length / 2);
          h = new (H ? Uint32Array : Array)(f.length / 2);
          if (1 === g.length) return d[f.pop().index] = 1, d;
          j = 0;
          for (s = f.length / 2; j < s; ++j) g[j] = f.pop(), h[j] = g[j].value;
          var n = h.length,
            l = new (H ? Uint16Array : Array)(c),
            q = new (H ? Uint8Array : Array)(c),
            E = new (H ? Uint8Array : Array)(n),
            t = Array(c),
            z = Array(c),
            K = Array(c),
            A = (1 << c) - n,
            x = 1 << c - 1,
            B,
            k,
            p,
            D,
            C;
          l[c - 1] = n;
          for (k = 0; k < c; ++k) A < x ? q[k] = 0 : (q[k] = 1, A -= x), A <<= 1, l[c - 2 - k] = (l[c - 1 - k] / 2 | 0) + n;
          l[0] = q[0];
          t[0] = Array(l[0]);
          z[0] = Array(l[0]);
          for (k = 1; k < c; ++k) l[k] > 2 * l[k - 1] + q[k] && (l[k] = 2 * l[k - 1] + q[k]), t[k] = Array(l[k]), z[k] = Array(l[k]);
          for (B = 0; B < n; ++B) E[B] = c;
          for (p = 0; p < l[c - 1]; ++p) t[c - 1][p] = h[p], z[c - 1][p] = p;
          for (B = 0; B < c; ++B) K[B] = 0;
          1 === q[c - 1] && (--E[0], ++K[c - 1]);
          for (k = c - 2; 0 <= k; --k) {
            D = B = 0;
            C = K[k + 1];
            for (p = 0; p < l[k]; p++) D = t[k + 1][C] + t[k + 1][C + 1], D > h[B] ? (t[k][p] = D, z[k][p] = n, C += 2) : (t[k][p] = h[B], z[k][p] = B, ++B);
            K[k] = 0;
            1 === q[k] && b(k);
          }
          m = E;
          j = 0;
          for (s = g.length; j < s; ++j) d[g[j].index] = m[j];
          return d;
        }
        function ua(a) {
          var c = new (H ? Uint16Array : Array)(a.length),
            b = [],
            e = [],
            f = 0,
            d,
            g,
            h,
            m;
          d = 0;
          for (g = a.length; d < g; d++) b[a[d]] = (b[a[d]] | 0) + 1;
          d = 1;
          for (g = 16; d <= g; d++) e[d] = f, f += b[d] | 0, f > 1 << d && i("overcommitted"), f <<= 1;
          65536 > f && i("undercommitted");
          d = 0;
          for (g = a.length; d < g; d++) {
            f = e[a[d]];
            e[a[d]] += 1;
            h = c[d] = 0;
            for (m = a[d]; h < m; h++) c[d] = c[d] << 1 | f & 1, f >>>= 1;
          }
          return c;
        }
        function Da(a, c) {
          this.input = a;
          this.a = new (H ? Uint8Array : Array)(32768);
          this.h = U.j;
          var b = {},
            e;
          if ((c || !(c = {})) && "number" === typeof c.compressionType) this.h = c.compressionType;
          for (e in c) b[e] = c[e];
          b.outputBuffer = this.a;
          this.z = new ma(this.input, b);
        }
        var U = qa;
        Da.prototype.n = function () {
          var a,
            c,
            b,
            e,
            f,
            d,
            g,
            h = 0;
          g = this.a;
          a = Ea;
          switch (a) {
            case Ea:
              c = Math.LOG2E * Math.log(32768) - 8;
              break;
            default:
              i(Error("invalid compression method"));
          }
          b = c << 4 | a;
          g[h++] = b;
          switch (a) {
            case Ea:
              switch (this.h) {
                case U.NONE:
                  f = 0;
                  break;
                case U.r:
                  f = 1;
                  break;
                case U.j:
                  f = 2;
                  break;
                default:
                  i(Error("unsupported compression type"));
              }
              break;
            default:
              i(Error("invalid compression method"));
          }
          e = f << 6 | 0;
          g[h++] = e | 31 - (256 * b + e) % 31;
          d = ba(this.input);
          this.z.b = h;
          g = this.z.n();
          h = g.length;
          H && (g = new Uint8Array(g.buffer), g.length <= h + 4 && (this.a = new Uint8Array(g.length + 4), this.a.set(g), g = this.a), g = g.subarray(0, h + 4));
          g[h++] = d >> 24 & 255;
          g[h++] = d >> 16 & 255;
          g[h++] = d >> 8 & 255;
          g[h++] = d & 255;
          return g;
        };
        y("Zlib.Deflate", Da);
        y("Zlib.Deflate.compress", function (a, c) {
          return new Da(a, c).n();
        });
        y("Zlib.Deflate.CompressionType", U);
        y("Zlib.Deflate.CompressionType.NONE", U.NONE);
        y("Zlib.Deflate.CompressionType.FIXED", U.r);
        y("Zlib.Deflate.CompressionType.DYNAMIC", U.j);
        function V(a, c) {
          this.k = [];
          this.l = 32768;
          this.e = this.g = this.c = this.q = 0;
          this.input = H ? new Uint8Array(a) : a;
          this.s = !1;
          this.m = Fa;
          this.B = !1;
          if (c || !(c = {})) c.index && (this.c = c.index), c.bufferSize && (this.l = c.bufferSize), c.bufferType && (this.m = c.bufferType), c.resize && (this.B = c.resize);
          switch (this.m) {
            case Ga:
              this.b = 32768;
              this.a = new (H ? Uint8Array : Array)(32768 + this.l + 258);
              break;
            case Fa:
              this.b = 0;
              this.a = new (H ? Uint8Array : Array)(this.l);
              this.f = this.J;
              this.t = this.H;
              this.o = this.I;
              break;
            default:
              i(Error("invalid inflate mode"));
          }
        }
        var Ga = 0,
          Fa = 1,
          Ha = {
            D: Ga,
            C: Fa
          };
        V.prototype.p = function () {
          for (; !this.s;) {
            var a = X(this, 3);
            a & 1 && (this.s = v);
            a >>>= 1;
            switch (a) {
              case 0:
                var c = this.input,
                  b = this.c,
                  e = this.a,
                  f = this.b,
                  d = r,
                  g = r,
                  h = r,
                  m = e.length,
                  j = r;
                this.e = this.g = 0;
                d = c[b++];
                d === r && i(Error("invalid uncompressed block header: LEN (first byte)"));
                g = d;
                d = c[b++];
                d === r && i(Error("invalid uncompressed block header: LEN (second byte)"));
                g |= d << 8;
                d = c[b++];
                d === r && i(Error("invalid uncompressed block header: NLEN (first byte)"));
                h = d;
                d = c[b++];
                d === r && i(Error("invalid uncompressed block header: NLEN (second byte)"));
                h |= d << 8;
                g === ~h && i(Error("invalid uncompressed block header: length verify"));
                b + g > c.length && i(Error("input buffer is broken"));
                switch (this.m) {
                  case Ga:
                    for (; f + g > e.length;) {
                      j = m - f;
                      g -= j;
                      if (H) e.set(c.subarray(b, b + j), f), f += j, b += j;else for (; j--;) e[f++] = c[b++];
                      this.b = f;
                      e = this.f();
                      f = this.b;
                    }
                    break;
                  case Fa:
                    for (; f + g > e.length;) e = this.f({
                      v: 2
                    });
                    break;
                  default:
                    i(Error("invalid inflate mode"));
                }
                if (H) e.set(c.subarray(b, b + g), f), f += g, b += g;else for (; g--;) e[f++] = c[b++];
                this.c = b;
                this.b = f;
                this.a = e;
                break;
              case 1:
                this.o(Ia, Ja);
                break;
              case 2:
                Ka(this);
                break;
              default:
                i(Error("unknown BTYPE: " + a));
            }
          }
          return this.t();
        };
        var La = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15],
          Za = H ? new Uint16Array(La) : La,
          $a = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 258, 258],
          ab = H ? new Uint16Array($a) : $a,
          bb = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0],
          cb = H ? new Uint8Array(bb) : bb,
          db = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577],
          eb = H ? new Uint16Array(db) : db,
          fb = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13],
          gb = H ? new Uint8Array(fb) : fb,
          hb = new (H ? Uint8Array : Array)(288),
          Y,
          ib;
        Y = 0;
        for (ib = hb.length; Y < ib; ++Y) hb[Y] = 143 >= Y ? 8 : 255 >= Y ? 9 : 279 >= Y ? 7 : 8;
        var Ia = S(hb),
          jb = new (H ? Uint8Array : Array)(30),
          kb,
          lb;
        kb = 0;
        for (lb = jb.length; kb < lb; ++kb) jb[kb] = 5;
        var Ja = S(jb);
        function X(a, c) {
          for (var b = a.g, e = a.e, f = a.input, d = a.c, g; e < c;) g = f[d++], g === r && i(Error("input buffer is broken")), b |= g << e, e += 8;
          g = b & (1 << c) - 1;
          a.g = b >>> c;
          a.e = e - c;
          a.c = d;
          return g;
        }
        function mb(a, c) {
          for (var b = a.g, e = a.e, f = a.input, d = a.c, g = c[0], h = c[1], m, j, s; e < h;) m = f[d++], m === r && i(Error("input buffer is broken")), b |= m << e, e += 8;
          j = g[b & (1 << h) - 1];
          s = j >>> 16;
          a.g = b >> s;
          a.e = e - s;
          a.c = d;
          return j & 65535;
        }
        function Ka(a) {
          function c(a, b, c) {
            var d, e, f, g;
            for (g = 0; g < a;) switch (d = mb(this, b), d) {
              case 16:
                for (f = 3 + X(this, 2); f--;) c[g++] = e;
                break;
              case 17:
                for (f = 3 + X(this, 3); f--;) c[g++] = 0;
                e = 0;
                break;
              case 18:
                for (f = 11 + X(this, 7); f--;) c[g++] = 0;
                e = 0;
                break;
              default:
                e = c[g++] = d;
            }
            return c;
          }
          var b = X(a, 5) + 257,
            e = X(a, 5) + 1,
            f = X(a, 4) + 4,
            d = new (H ? Uint8Array : Array)(Za.length),
            g,
            h,
            m,
            j;
          for (j = 0; j < f; ++j) d[Za[j]] = X(a, 3);
          g = S(d);
          h = new (H ? Uint8Array : Array)(b);
          m = new (H ? Uint8Array : Array)(e);
          a.o(S(c.call(a, b, g, h)), S(c.call(a, e, g, m)));
        }
        V.prototype.o = function (a, c) {
          var b = this.a,
            e = this.b;
          this.u = a;
          for (var f = b.length - 258, d, g, h, m; 256 !== (d = mb(this, a));) if (256 > d) e >= f && (this.b = e, b = this.f(), e = this.b), b[e++] = d;else {
            g = d - 257;
            m = ab[g];
            0 < cb[g] && (m += X(this, cb[g]));
            d = mb(this, c);
            h = eb[d];
            0 < gb[d] && (h += X(this, gb[d]));
            e >= f && (this.b = e, b = this.f(), e = this.b);
            for (; m--;) b[e] = b[e++ - h];
          }
          for (; 8 <= this.e;) this.e -= 8, this.c--;
          this.b = e;
        };
        V.prototype.I = function (a, c) {
          var b = this.a,
            e = this.b;
          this.u = a;
          for (var f = b.length, d, g, h, m; 256 !== (d = mb(this, a));) if (256 > d) e >= f && (b = this.f(), f = b.length), b[e++] = d;else {
            g = d - 257;
            m = ab[g];
            0 < cb[g] && (m += X(this, cb[g]));
            d = mb(this, c);
            h = eb[d];
            0 < gb[d] && (h += X(this, gb[d]));
            e + m > f && (b = this.f(), f = b.length);
            for (; m--;) b[e] = b[e++ - h];
          }
          for (; 8 <= this.e;) this.e -= 8, this.c--;
          this.b = e;
        };
        V.prototype.f = function () {
          var a = new (H ? Uint8Array : Array)(this.b - 32768),
            c = this.b - 32768,
            b,
            e,
            f = this.a;
          if (H) a.set(f.subarray(32768, a.length));else {
            b = 0;
            for (e = a.length; b < e; ++b) a[b] = f[b + 32768];
          }
          this.k.push(a);
          this.q += a.length;
          if (H) f.set(f.subarray(c, c + 32768));else for (b = 0; 32768 > b; ++b) f[b] = f[c + b];
          this.b = 32768;
          return f;
        };
        V.prototype.J = function (a) {
          var c,
            b = this.input.length / this.c + 1 | 0,
            e,
            f,
            d,
            g = this.input,
            h = this.a;
          a && ("number" === typeof a.v && (b = a.v), "number" === typeof a.F && (b += a.F));
          2 > b ? (e = (g.length - this.c) / this.u[2], d = 258 * (e / 2) | 0, f = d < h.length ? h.length + d : h.length << 1) : f = h.length * b;
          H ? (c = new Uint8Array(f), c.set(h)) : c = h;
          return this.a = c;
        };
        V.prototype.t = function () {
          var a = 0,
            c = this.a,
            b = this.k,
            e,
            f = new (H ? Uint8Array : Array)(this.q + (this.b - 32768)),
            d,
            g,
            h,
            m;
          if (0 === b.length) return H ? this.a.subarray(32768, this.b) : this.a.slice(32768, this.b);
          d = 0;
          for (g = b.length; d < g; ++d) {
            e = b[d];
            h = 0;
            for (m = e.length; h < m; ++h) f[a++] = e[h];
          }
          d = 32768;
          for (g = this.b; d < g; ++d) f[a++] = c[d];
          this.k = [];
          return this.buffer = f;
        };
        V.prototype.H = function () {
          var a,
            c = this.b;
          H ? this.B ? (a = new Uint8Array(c), a.set(this.a.subarray(0, c))) : a = this.a.subarray(0, c) : (this.a.length > c && (this.a.length = c), a = this.a);
          return this.buffer = a;
        };
        function nb(a, c) {
          var b, e;
          this.input = a;
          this.c = 0;
          if (c || !(c = {})) c.index && (this.c = c.index), c.verify && (this.M = c.verify);
          b = a[this.c++];
          e = a[this.c++];
          switch (b & 15) {
            case Ea:
              this.method = Ea;
              break;
            default:
              i(Error("unsupported compression method"));
          }
          0 !== ((b << 8) + e) % 31 && i(Error("invalid fcheck flag:" + ((b << 8) + e) % 31));
          e & 32 && i(Error("fdict flag is not supported"));
          this.A = new V(a, {
            index: this.c,
            bufferSize: c.bufferSize,
            bufferType: c.bufferType,
            resize: c.resize
          });
        }
        nb.prototype.p = function () {
          var a = this.input,
            c,
            b;
          c = this.A.p();
          this.c = this.A.c;
          this.M && (b = (a[this.c++] << 24 | a[this.c++] << 16 | a[this.c++] << 8 | a[this.c++]) >>> 0, b !== ba(c) && i(Error("invalid adler-32 checksum")));
          return c;
        };
        y("Zlib.Inflate", nb);
        y("Zlib.Inflate.BufferType", Ha);
        Ha.ADAPTIVE = Ha.C;
        Ha.BLOCK = Ha.D;
        y("Zlib.Inflate.prototype.decompress", nb.prototype.p);
        var tb = new (H ? Uint8Array : Array)(288),
          Z,
          ub;
        Z = 0;
        for (ub = tb.length; Z < ub; ++Z) tb[Z] = 143 >= Z ? 8 : 255 >= Z ? 9 : 279 >= Z ? 7 : 8;
        S(tb);
        var vb = new (H ? Uint8Array : Array)(30),
          wb,
          xb;
        wb = 0;
        for (xb = vb.length; wb < xb; ++wb) vb[wb] = 5;
        S(vb);
        var Ea = 8;
      }).call(window$1);
      var _p = window$1.Zlib;
      _p.Deflate = _p["Deflate"];
      _p.Deflate.compress = _p.Deflate["compress"];
      _p.Inflate = _p["Inflate"];
      _p.Inflate.BufferType = _p.Inflate["BufferType"];
      _p.Inflate.prototype.decompress = _p.Inflate.prototype["decompress"];

      var _dec$32, _class$2$, _class2$2H, _initializer$2x, _initializer2$25, _initializer3$1y;
      function getIndexStrideCtor(stride) {
        switch (stride) {
          case 1:
            return Uint8Array;
          case 2:
            return Uint16Array;
          case 4:
            return Uint32Array;
          default:
            return Uint8Array;
        }
      }
      var v3_1$6 = new Vec3();
      var v3_2$2 = new Vec3();
      var globalEmptyMeshBuffer = new Uint8Array();
      var Mesh = exports('a9', (_dec$32 = ccclass$M('cc.Mesh'), _dec$32(_class$2$ = (_class2$2H = function (_Asset) {
        _inheritsLoose(Mesh, _Asset);
        function Mesh() {
          var _this;
          _this = _Asset.call(this) || this;
          _this.morphRendering = null;
          _this._struct = _initializer$2x && _initializer$2x();
          _this._hash = _initializer2$25 && _initializer2$25();
          _this._data = globalEmptyMeshBuffer;
          _this._initialized = false;
          _this._allowDataAccess = _initializer3$1y && _initializer3$1y();
          _this._isMeshDataUploaded = false;
          _this._renderingSubMeshes = null;
          _this._boneSpaceBounds = new Map();
          _this._jointBufferIndices = null;
          return _this;
        }
        var _proto = Mesh.prototype;
        _proto.onLoaded = function onLoaded() {
          this.initialize();
        };
        _proto.initialize = function initialize() {
          if (this._initialized) {
            return;
          }
          this._initialized = true;
          var info = {
            struct: this.struct,
            data: this.data
          };
          if (info.struct.compressed) {
            info = inflateMesh(info);
          }
          if (this.struct.encoded) {
            info = decodeMesh(info);
          }
          if (this.struct.quantized && !(deviceManager.gfxDevice.getFormatFeatures(Format.RGB16F) & FormatFeatureBit.VERTEX_ATTRIBUTE)) {
            info = dequantizeMesh(info);
          }
          this._struct = info.struct;
          this._data = info.data;
          if (this._struct.dynamic) {
            var device = deviceManager.gfxDevice;
            var vertexBuffers = [];
            var subMeshes = [];
            for (var i = 0; i < this._struct.vertexBundles.length; i++) {
              var _vertexBundle = this._struct.vertexBundles[i];
              var vertexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, _vertexBundle.view.length, _vertexBundle.view.stride));
              vertexBuffers.push(vertexBuffer);
            }
            for (var _i = 0; _i < this._struct.primitives.length; _i++) {
              var primitive = this._struct.primitives[_i];
              var indexView = primitive.indexView;
              var indexBuffer = null;
              if (indexView) {
                indexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, indexView.length, indexView.stride));
              }
              var subVBs = [];
              for (var k = 0; k < primitive.vertexBundelIndices.length; k++) {
                var idx = primitive.vertexBundelIndices[k];
                subVBs.push(vertexBuffers[idx]);
              }
              var attributes = [];
              for (var _k = 0; _k < primitive.vertexBundelIndices.length; _k++) {
                var _idx = primitive.vertexBundelIndices[_k];
                var _vertexBundle2 = this._struct.vertexBundles[_idx];
                for (var _iterator = _createForOfIteratorHelperLoose(_vertexBundle2.attributes), _step; !(_step = _iterator()).done;) {
                  var attr = _step.value;
                  var attribute = new Attribute();
                  attribute.copy(attr);
                  attributes.push(attribute);
                }
              }
              var subMesh = new RenderingSubMesh(subVBs, attributes, primitive.primitiveMode, indexBuffer);
              subMesh.drawInfo = new DrawInfo();
              subMesh.mesh = this;
              subMesh.subMeshIdx = _i;
              subMeshes.push(subMesh);
            }
            this._renderingSubMeshes = subMeshes;
          } else {
            var buffer = this._data.buffer;
            var gfxDevice = deviceManager.gfxDevice;
            var _vertexBuffers = this._createVertexBuffers(gfxDevice, buffer);
            var indexBuffers = [];
            var _subMeshes = [];
            for (var _i2 = 0; _i2 < this._struct.primitives.length; _i2++) {
              var prim = this._struct.primitives[_i2];
              if (prim.vertexBundelIndices.length === 0) {
                continue;
              }
              var _indexBuffer = null;
              var ib = void 0;
              if (prim.indexView) {
                var idxView = prim.indexView;
                var dstStride = idxView.stride;
                var dstSize = idxView.length;
                if (dstStride === 4 && !gfxDevice.hasFeature(Feature.ELEMENT_INDEX_UINT)) {
                  var vertexCount = this._struct.vertexBundles[prim.vertexBundelIndices[0]].view.count;
                  if (vertexCount >= 65536) {
                    warnID(10001, vertexCount, 65536);
                    continue;
                  } else {
                    dstStride >>= 1;
                    dstSize >>= 1;
                  }
                }
                _indexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.INDEX, MemoryUsageBit.DEVICE, dstSize, dstStride));
                indexBuffers.push(_indexBuffer);
                ib = new (getIndexStrideCtor(idxView.stride))(buffer, idxView.offset, idxView.count);
                if (idxView.stride !== dstStride) {
                  ib = getIndexStrideCtor(dstStride).from(ib);
                }
                _indexBuffer.update(ib);
              }
              var vbReference = prim.vertexBundelIndices.map(function (idx) {
                return _vertexBuffers[idx];
              });
              var gfxAttributes = [];
              if (prim.vertexBundelIndices.length > 0) {
                var _idx2 = prim.vertexBundelIndices[0];
                var _vertexBundle3 = this._struct.vertexBundles[_idx2];
                var attrs = _vertexBundle3.attributes;
                for (var j = 0; j < attrs.length; ++j) {
                  var _attr = attrs[j];
                  gfxAttributes[j] = new Attribute(_attr.name, _attr.format, _attr.isNormalized, _attr.stream, _attr.isInstanced, _attr.location);
                }
              }
              var _subMesh = new RenderingSubMesh(vbReference, gfxAttributes, prim.primitiveMode, _indexBuffer);
              _subMesh.mesh = this;
              _subMesh.subMeshIdx = _i2;
              _subMeshes.push(_subMesh);
            }
            this._renderingSubMeshes = _subMeshes;
            if (this._struct.morph) {
              this.morphRendering = createMorphRendering(this, gfxDevice);
            }
            this._isMeshDataUploaded = true;
            if (!this._allowDataAccess && !EDITOR) {
              this.releaseData();
            }
          }
        };
        _proto.updateSubMesh = function updateSubMesh(primitiveIndex, dynamicGeometry) {
          if (!this._struct.dynamic) {
            warnID(14200);
            return;
          }
          if (primitiveIndex >= this._struct.primitives.length) {
            warnID(14201);
            return;
          }
          var buffers = [];
          if (dynamicGeometry.positions.length > 0) {
            buffers.push(dynamicGeometry.positions);
          }
          if (dynamicGeometry.normals && dynamicGeometry.normals.length > 0) {
            buffers.push(dynamicGeometry.normals);
          }
          if (dynamicGeometry.uvs && dynamicGeometry.uvs.length > 0) {
            buffers.push(dynamicGeometry.uvs);
          }
          if (dynamicGeometry.tangents && dynamicGeometry.tangents.length > 0) {
            buffers.push(dynamicGeometry.tangents);
          }
          if (dynamicGeometry.colors && dynamicGeometry.colors.length > 0) {
            buffers.push(dynamicGeometry.colors);
          }
          if (dynamicGeometry.customAttributes) {
            for (var k = 0; k < dynamicGeometry.customAttributes.length; k++) {
              buffers.push(dynamicGeometry.customAttributes[k].values);
            }
          }
          var dynamic = this._struct.dynamic;
          var info = dynamic.info;
          var primitive = this._struct.primitives[primitiveIndex];
          var subMesh = this._renderingSubMeshes[primitiveIndex];
          var drawInfo = subMesh.drawInfo;
          for (var index = 0; index < buffers.length; index++) {
            var vertices = buffers[index];
            var bundle = this._struct.vertexBundles[primitive.vertexBundelIndices[index]];
            var stride = bundle.view.stride;
            var vertexCount = vertices.byteLength / stride;
            var updateSize = vertices.byteLength;
            var dstBuffer = new Uint8Array(this._data.buffer, bundle.view.offset, updateSize);
            var srcBuffer = new Uint8Array(vertices.buffer, vertices.byteOffset, updateSize);
            var vertexBuffer = subMesh.vertexBuffers[index];
            assertIsTrue(vertexCount <= info.maxSubMeshVertices, 'Too many vertices.');
            if (updateSize > 0) {
              dstBuffer.set(srcBuffer);
              vertexBuffer.update(srcBuffer, updateSize);
            }
            bundle.view.count = vertexCount;
            drawInfo.vertexCount = vertexCount;
          }
          if (primitive.indexView) {
            var indexView = primitive.indexView;
            var _stride = indexView.stride;
            var indexCount = _stride === 2 ? dynamicGeometry.indices16.length : dynamicGeometry.indices32.length;
            var _updateSize = indexCount * _stride;
            var _dstBuffer = new Uint8Array(this._data.buffer, indexView.offset, _updateSize);
            var _srcBuffer = _stride === 2 ? new Uint8Array(dynamicGeometry.indices16.buffer, dynamicGeometry.indices16.byteOffset, _updateSize) : new Uint8Array(dynamicGeometry.indices32.buffer, dynamicGeometry.indices32.byteOffset, _updateSize);
            var indexBuffer = subMesh.indexBuffer;
            assertIsTrue(indexCount <= info.maxSubMeshIndices, 'Too many indices.');
            if (_updateSize > 0) {
              _dstBuffer.set(_srcBuffer);
              indexBuffer.update(_srcBuffer, _updateSize);
            }
            indexView.count = indexCount;
            drawInfo.indexCount = indexCount;
          }
          if (dynamicGeometry.minPos && dynamicGeometry.maxPos) {
            var minPos = new Vec3(dynamicGeometry.minPos.x, dynamicGeometry.minPos.y, dynamicGeometry.minPos.z);
            var maxPos = new Vec3(dynamicGeometry.maxPos.x, dynamicGeometry.maxPos.y, dynamicGeometry.maxPos.z);
            if (!dynamic.bounds[primitiveIndex]) {
              dynamic.bounds[primitiveIndex] = new AABB();
            }
            AABB.fromPoints(dynamic.bounds[primitiveIndex], minPos, maxPos);
            var subMin = new Vec3();
            var subMax = new Vec3();
            for (var _iterator2 = _createForOfIteratorHelperLoose(dynamic.bounds), _step2; !(_step2 = _iterator2()).done;) {
              var bound = _step2.value;
              if (bound) {
                bound.getBoundary(subMin, subMax);
                Vec3.min(minPos, subMin, minPos);
                Vec3.max(maxPos, subMax, maxPos);
              }
            }
            this._struct.minPosition = new Vec3(minPos.x, minPos.y, minPos.z);
            this._struct.maxPosition = new Vec3(maxPos.x, maxPos.y, maxPos.z);
          }
          subMesh.invalidateGeometricInfo();
        };
        _proto.destroy = function destroy() {
          this.destroyRenderingMesh();
          return _Asset.prototype.destroy.call(this);
        };
        _proto.destroyRenderingMesh = function destroyRenderingMesh() {
          if (this._renderingSubMeshes) {
            for (var i = 0; i < this._renderingSubMeshes.length; i++) {
              this._renderingSubMeshes[i].destroy();
            }
            this._renderingSubMeshes = null;
            this._initialized = false;
            this._isMeshDataUploaded = false;
          }
        };
        _proto.assign = function assign(struct, data) {
          this.reset({
            struct: struct,
            data: data
          });
        };
        _proto.reset = function reset(info) {
          this.destroyRenderingMesh();
          this._struct = info.struct;
          this._data = info.data;
          this._hash = 0;
        };
        _proto.getBoneSpaceBounds = function getBoneSpaceBounds(skeleton) {
          if (this._boneSpaceBounds.has(skeleton.hash)) {
            return this._boneSpaceBounds.get(skeleton.hash);
          }
          var bounds = [];
          this._boneSpaceBounds.set(skeleton.hash, bounds);
          var valid = [];
          var bindposes = skeleton.bindposes;
          for (var i = 0; i < bindposes.length; i++) {
            bounds.push(new AABB(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity));
            valid.push(false);
          }
          var primitives = this._struct.primitives;
          for (var p = 0; p < primitives.length; p++) {
            var joints = this.readAttribute(p, AttributeName.ATTR_JOINTS);
            var weights = this.readAttribute(p, AttributeName.ATTR_WEIGHTS);
            var positions = this.readAttribute(p, AttributeName.ATTR_POSITION);
            if (!joints || !weights || !positions) {
              continue;
            }
            var vertCount = Math.min(joints.length / 4, weights.length / 4, positions.length / 3);
            for (var _i3 = 0; _i3 < vertCount; _i3++) {
              Vec3.set(v3_1$6, positions[3 * _i3 + 0], positions[3 * _i3 + 1], positions[3 * _i3 + 2]);
              for (var j = 0; j < 4; ++j) {
                var idx = 4 * _i3 + j;
                var joint = joints[idx];
                if (weights[idx] === 0 || joint >= bindposes.length) {
                  continue;
                }
                Vec3.transformMat4(v3_2$2, v3_1$6, bindposes[joint]);
                valid[joint] = true;
                var b = bounds[joint];
                Vec3.min(b.center, b.center, v3_2$2);
                Vec3.max(b.halfExtents, b.halfExtents, v3_2$2);
              }
            }
          }
          for (var _i4 = 0; _i4 < bindposes.length; _i4++) {
            var _b = bounds[_i4];
            if (!valid[_i4]) {
              bounds[_i4] = null;
            } else {
              AABB.fromPoints(_b, _b.center, _b.halfExtents);
            }
          }
          return bounds;
        };
        _proto.merge = function merge(mesh, worldMatrix, validate) {
          if (validate) {
            if (!this.validateMergingMesh(mesh)) {
              return false;
            }
          }
          var vec3_temp = new Vec3();
          var rotate = worldMatrix && new Quat();
          var boundingBox = worldMatrix && new AABB();
          if (rotate) {
            worldMatrix.getRotation(rotate);
          }
          if (!this._initialized) {
            var struct = JSON.parse(JSON.stringify(mesh._struct));
            var data = mesh._data.slice();
            if (worldMatrix) {
              if (struct.maxPosition && struct.minPosition) {
                Vec3.add(boundingBox.center, struct.maxPosition, struct.minPosition);
                Vec3.multiplyScalar(boundingBox.center, boundingBox.center, 0.5);
                Vec3.subtract(boundingBox.halfExtents, struct.maxPosition, struct.minPosition);
                Vec3.multiplyScalar(boundingBox.halfExtents, boundingBox.halfExtents, 0.5);
                AABB.transform(boundingBox, boundingBox, worldMatrix);
                Vec3.add(struct.maxPosition, boundingBox.center, boundingBox.halfExtents);
                Vec3.subtract(struct.minPosition, boundingBox.center, boundingBox.halfExtents);
              }
              for (var i = 0; i < struct.vertexBundles.length; i++) {
                var vtxBdl = struct.vertexBundles[i];
                for (var j = 0; j < vtxBdl.attributes.length; j++) {
                  if (vtxBdl.attributes[j].name === AttributeName.ATTR_POSITION || vtxBdl.attributes[j].name === AttributeName.ATTR_NORMAL) {
                    var format = vtxBdl.attributes[j].format;
                    var inputView = new DataView(data.buffer, vtxBdl.view.offset + getOffset(vtxBdl.attributes, j));
                    var reader = getReader(inputView, format);
                    var writer = getWriter(inputView, format);
                    if (!reader || !writer) {
                      continue;
                    }
                    var vertexCount = vtxBdl.view.count;
                    var vertexStride = vtxBdl.view.stride;
                    var attrComponentByteLength = getComponentByteLength(format);
                    for (var vtxIdx = 0; vtxIdx < vertexCount; vtxIdx++) {
                      var xOffset = vtxIdx * vertexStride;
                      var yOffset = xOffset + attrComponentByteLength;
                      var zOffset = yOffset + attrComponentByteLength;
                      vec3_temp.set(reader(xOffset), reader(yOffset), reader(zOffset));
                      switch (vtxBdl.attributes[j].name) {
                        case AttributeName.ATTR_POSITION:
                          vec3_temp.transformMat4(worldMatrix);
                          break;
                        case AttributeName.ATTR_NORMAL:
                          Vec3.transformQuat(vec3_temp, vec3_temp, rotate);
                          break;
                      }
                      writer(xOffset, vec3_temp.x);
                      writer(yOffset, vec3_temp.y);
                      writer(zOffset, vec3_temp.z);
                    }
                  }
                }
              }
            }
            this.reset({
              struct: struct,
              data: data
            });
            this.initialize();
            return true;
          }
          var bufferBlob = new BufferBlob();
          var vertCount = 0;
          var vertStride = 0;
          var srcOffset = 0;
          var dstOffset = 0;
          var vb;
          var vbView;
          var srcVBView;
          var dstVBView;
          var srcAttrOffset = 0;
          var srcVBOffset = 0;
          var dstVBOffset = 0;
          var attrSize = 0;
          var dstAttrView;
          var hasAttr = false;
          var vertexBundles = new Array(this._struct.vertexBundles.length);
          for (var _i5 = 0; _i5 < this._struct.vertexBundles.length; ++_i5) {
            var bundle = this._struct.vertexBundles[_i5];
            var dstBundle = mesh._struct.vertexBundles[_i5];
            srcOffset = bundle.view.offset;
            dstOffset = dstBundle.view.offset;
            vertStride = bundle.view.stride;
            vertCount = bundle.view.count + dstBundle.view.count;
            vb = new ArrayBuffer(vertCount * vertStride);
            vbView = new Uint8Array(vb);
            srcVBView = this._data.subarray(srcOffset, srcOffset + bundle.view.length);
            srcOffset += srcVBView.length;
            dstVBView = mesh._data.subarray(dstOffset, dstOffset + dstBundle.view.length);
            dstOffset += dstVBView.length;
            vbView.set(srcVBView);
            srcAttrOffset = 0;
            for (var _iterator3 = _createForOfIteratorHelperLoose(bundle.attributes), _step3; !(_step3 = _iterator3()).done;) {
              var attr = _step3.value;
              dstVBOffset = 0;
              hasAttr = false;
              for (var _iterator4 = _createForOfIteratorHelperLoose(dstBundle.attributes), _step4; !(_step4 = _iterator4()).done;) {
                var dstAttr = _step4.value;
                if (attr.name === dstAttr.name && attr.format === dstAttr.format) {
                  hasAttr = true;
                  break;
                }
                dstVBOffset += FormatInfos[dstAttr.format].size;
              }
              if (hasAttr) {
                attrSize = FormatInfos[attr.format].size;
                srcVBOffset = bundle.view.length + srcAttrOffset;
                for (var v = 0; v < dstBundle.view.count; ++v) {
                  dstAttrView = dstVBView.subarray(dstVBOffset, dstVBOffset + attrSize);
                  vbView.set(dstAttrView, srcVBOffset);
                  if ((attr.name === AttributeName.ATTR_POSITION || attr.name === AttributeName.ATTR_NORMAL) && worldMatrix) {
                    var f32_temp = new Float32Array(vbView.buffer, srcVBOffset, 3);
                    vec3_temp.set(f32_temp[0], f32_temp[1], f32_temp[2]);
                    switch (attr.name) {
                      case AttributeName.ATTR_POSITION:
                        vec3_temp.transformMat4(worldMatrix);
                        break;
                      case AttributeName.ATTR_NORMAL:
                        Vec3.transformQuat(vec3_temp, vec3_temp, rotate);
                        break;
                    }
                    f32_temp[0] = vec3_temp.x;
                    f32_temp[1] = vec3_temp.y;
                    f32_temp[2] = vec3_temp.z;
                  }
                  srcVBOffset += bundle.view.stride;
                  dstVBOffset += dstBundle.view.stride;
                }
              }
              srcAttrOffset += FormatInfos[attr.format].size;
            }
            vertexBundles[_i5] = {
              attributes: bundle.attributes,
              view: {
                offset: bufferBlob.getLength(),
                length: vb.byteLength,
                count: vertCount,
                stride: vertStride
              }
            };
            bufferBlob.addBuffer(vb);
          }
          var idxCount = 0;
          var idxStride = 2;
          var ibView;
          var srcIBView;
          var dstIBView;
          var primitives = new Array(this._struct.primitives.length);
          for (var _i6 = 0; _i6 < this._struct.primitives.length; ++_i6) {
            var prim = this._struct.primitives[_i6];
            var dstPrim = mesh._struct.primitives[_i6];
            primitives[_i6] = {
              primitiveMode: prim.primitiveMode,
              vertexBundelIndices: prim.vertexBundelIndices
            };
            var vertBatchCount = 0;
            for (var _iterator5 = _createForOfIteratorHelperLoose(prim.vertexBundelIndices), _step5; !(_step5 = _iterator5()).done;) {
              var bundleIdx = _step5.value;
              vertBatchCount = Math.max(vertBatchCount, this._struct.vertexBundles[bundleIdx].view.count);
            }
            if (prim.indexView && dstPrim.indexView) {
              idxCount = prim.indexView.count;
              idxCount += dstPrim.indexView.count;
              srcOffset = prim.indexView.offset;
              dstOffset = dstPrim.indexView.offset;
              if (idxCount < 256) {
                idxStride = 1;
              } else if (idxCount < 65536) {
                idxStride = 2;
              } else {
                idxStride = 4;
              }
              var ib = new ArrayBuffer(idxCount * idxStride);
              if (idxStride === 2) {
                ibView = new Uint16Array(ib);
              } else if (idxStride === 1) {
                ibView = new Uint8Array(ib);
              } else {
                ibView = new Uint32Array(ib);
              }
              if (prim.indexView.stride === 2) {
                srcIBView = new Uint16Array(this._data.buffer, srcOffset, prim.indexView.count);
              } else if (prim.indexView.stride === 1) {
                srcIBView = new Uint8Array(this._data.buffer, srcOffset, prim.indexView.count);
              } else {
                srcIBView = new Uint32Array(this._data.buffer, srcOffset, prim.indexView.count);
              }
              if (idxStride === prim.indexView.stride) {
                ibView.set(srcIBView);
              } else {
                for (var n = 0; n < prim.indexView.count; ++n) {
                  ibView[n] = srcIBView[n];
                }
              }
              srcOffset += prim.indexView.length;
              if (dstPrim.indexView.stride === 2) {
                dstIBView = new Uint16Array(mesh._data.buffer, dstOffset, dstPrim.indexView.count);
              } else if (dstPrim.indexView.stride === 1) {
                dstIBView = new Uint8Array(mesh._data.buffer, dstOffset, dstPrim.indexView.count);
              } else {
                dstIBView = new Uint32Array(mesh._data.buffer, dstOffset, dstPrim.indexView.count);
              }
              for (var _n = 0; _n < dstPrim.indexView.count; ++_n) {
                ibView[prim.indexView.count + _n] = vertBatchCount + dstIBView[_n];
              }
              dstOffset += dstPrim.indexView.length;
              primitives[_i6].indexView = {
                offset: bufferBlob.getLength(),
                length: ib.byteLength,
                count: idxCount,
                stride: idxStride
              };
              bufferBlob.setNextAlignment(idxStride);
              bufferBlob.addBuffer(ib);
            }
          }
          var meshStruct = {
            vertexBundles: vertexBundles,
            primitives: primitives,
            minPosition: this._struct.minPosition,
            maxPosition: this._struct.maxPosition
          };
          if (meshStruct.minPosition && mesh._struct.minPosition && meshStruct.maxPosition && mesh._struct.maxPosition) {
            if (worldMatrix) {
              Vec3.add(boundingBox.center, mesh._struct.maxPosition, mesh._struct.minPosition);
              Vec3.multiplyScalar(boundingBox.center, boundingBox.center, 0.5);
              Vec3.subtract(boundingBox.halfExtents, mesh._struct.maxPosition, mesh._struct.minPosition);
              Vec3.multiplyScalar(boundingBox.halfExtents, boundingBox.halfExtents, 0.5);
              AABB.transform(boundingBox, boundingBox, worldMatrix);
              Vec3.add(vec3_temp, boundingBox.center, boundingBox.halfExtents);
              Vec3.max(meshStruct.maxPosition, meshStruct.maxPosition, vec3_temp);
              Vec3.subtract(vec3_temp, boundingBox.center, boundingBox.halfExtents);
              Vec3.min(meshStruct.minPosition, meshStruct.minPosition, vec3_temp);
            } else {
              Vec3.min(meshStruct.minPosition, meshStruct.minPosition, mesh._struct.minPosition);
              Vec3.max(meshStruct.maxPosition, meshStruct.maxPosition, mesh._struct.maxPosition);
            }
          }
          this.reset({
            struct: meshStruct,
            data: new Uint8Array(bufferBlob.getCombined())
          });
          this.initialize();
          return true;
        };
        _proto.validateMergingMesh = function validateMergingMesh(mesh) {
          if (this._struct.dynamic || mesh._struct.dynamic) {
            return false;
          }
          if (this._struct.vertexBundles.length !== mesh._struct.vertexBundles.length) {
            return false;
          }
          for (var i = 0; i < this._struct.vertexBundles.length; ++i) {
            var bundle = this._struct.vertexBundles[i];
            var dstBundle = mesh._struct.vertexBundles[i];
            if (bundle.attributes.length !== dstBundle.attributes.length) {
              return false;
            }
            for (var j = 0; j < bundle.attributes.length; ++j) {
              if (bundle.attributes[j].format !== dstBundle.attributes[j].format) {
                return false;
              }
            }
          }
          if (this._struct.primitives.length !== mesh._struct.primitives.length) {
            return false;
          }
          for (var _i7 = 0; _i7 < this._struct.primitives.length; ++_i7) {
            var prim = this._struct.primitives[_i7];
            var dstPrim = mesh._struct.primitives[_i7];
            if (prim.vertexBundelIndices.length !== dstPrim.vertexBundelIndices.length) {
              return false;
            }
            for (var _j = 0; _j < prim.vertexBundelIndices.length; ++_j) {
              if (prim.vertexBundelIndices[_j] !== dstPrim.vertexBundelIndices[_j]) {
                return false;
              }
            }
            if (prim.primitiveMode !== dstPrim.primitiveMode) {
              return false;
            }
            if (prim.indexView) {
              if (dstPrim.indexView === undefined) {
                return false;
              }
            } else if (dstPrim.indexView) {
              return false;
            }
          }
          return true;
        };
        _proto.readAttribute = function readAttribute(primitiveIndex, attributeName) {
          var _this2 = this;
          var result = null;
          this._accessAttribute(primitiveIndex, attributeName, function (vertexBundle, iAttribute) {
            var vertexCount = vertexBundle.view.count;
            var format = vertexBundle.attributes[iAttribute].format;
            var StorageConstructor = getTypedArrayConstructor(FormatInfos[format]);
            if (vertexCount === 0) {
              return;
            }
            var inputView = new DataView(_this2._data.buffer, vertexBundle.view.offset + getOffset(vertexBundle.attributes, iAttribute));
            var formatInfo = FormatInfos[format];
            var reader = getReader(inputView, format);
            if (!StorageConstructor || !reader) {
              return;
            }
            var componentCount = formatInfo.count;
            var storage = new StorageConstructor(vertexCount * componentCount);
            var inputStride = vertexBundle.view.stride;
            for (var iVertex = 0; iVertex < vertexCount; ++iVertex) {
              for (var iComponent = 0; iComponent < componentCount; ++iComponent) {
                storage[componentCount * iVertex + iComponent] = reader(inputStride * iVertex + storage.BYTES_PER_ELEMENT * iComponent);
              }
            }
            result = storage;
          });
          return result;
        };
        _proto.copyAttribute = function copyAttribute(primitiveIndex, attributeName, buffer, stride, offset) {
          var _this3 = this;
          var written = false;
          this._accessAttribute(primitiveIndex, attributeName, function (vertexBundle, iAttribute) {
            var vertexCount = vertexBundle.view.count;
            if (vertexCount === 0) {
              written = true;
              return;
            }
            var format = vertexBundle.attributes[iAttribute].format;
            var inputView = new DataView(_this3._data.buffer, vertexBundle.view.offset + getOffset(vertexBundle.attributes, iAttribute));
            var outputView = new DataView(buffer, offset);
            var formatInfo = FormatInfos[format];
            var reader = getReader(inputView, format);
            var writer = getWriter(outputView, format);
            if (!reader || !writer) {
              return;
            }
            var componentCount = formatInfo.count;
            var inputStride = vertexBundle.view.stride;
            var inputComponentByteLength = getComponentByteLength(format);
            var outputStride = stride;
            var outputComponentByteLength = inputComponentByteLength;
            for (var iVertex = 0; iVertex < vertexCount; ++iVertex) {
              for (var iComponent = 0; iComponent < componentCount; ++iComponent) {
                var inputOffset = inputStride * iVertex + inputComponentByteLength * iComponent;
                var outputOffset = outputStride * iVertex + outputComponentByteLength * iComponent;
                writer(outputOffset, reader(inputOffset));
              }
            }
            written = true;
          });
          return written;
        };
        _proto.readIndices = function readIndices(primitiveIndex) {
          if (primitiveIndex >= this._struct.primitives.length) {
            return null;
          }
          var primitive = this._struct.primitives[primitiveIndex];
          if (!primitive.indexView) {
            return null;
          }
          var stride = primitive.indexView.stride;
          var Ctor = stride === 1 ? Uint8Array : stride === 2 ? Uint16Array : Uint32Array;
          return new Ctor(this._data.buffer, primitive.indexView.offset, primitive.indexView.count);
        };
        _proto.copyIndices = function copyIndices(primitiveIndex, outputArray) {
          if (primitiveIndex >= this._struct.primitives.length) {
            return false;
          }
          var primitive = this._struct.primitives[primitiveIndex];
          if (!primitive.indexView) {
            return false;
          }
          var indexCount = primitive.indexView.count;
          var indexFormat = primitive.indexView.stride === 1 ? Format.R8UI : primitive.indexView.stride === 2 ? Format.R16UI : Format.R32UI;
          var reader = getReader(new DataView(this._data.buffer), indexFormat);
          for (var i = 0; i < indexCount; ++i) {
            outputArray[i] = reader(primitive.indexView.offset + FormatInfos[indexFormat].size * i);
          }
          return true;
        };
        _proto.readAttributeFormat = function readAttributeFormat(primitiveIndex, attributeName) {
          var result = null;
          this._accessAttribute(primitiveIndex, attributeName, function (vertexBundle, iAttribute) {
            var format = vertexBundle.attributes[iAttribute].format;
            result = FormatInfos[format];
          });
          return result;
        };
        _proto._accessAttribute = function _accessAttribute(primitiveIndex, attributeName, accessor) {
          if (primitiveIndex >= this._struct.primitives.length) {
            return;
          }
          var primitive = this._struct.primitives[primitiveIndex];
          for (var _iterator6 = _createForOfIteratorHelperLoose(primitive.vertexBundelIndices), _step6; !(_step6 = _iterator6()).done;) {
            var vertexBundleIndex = _step6.value;
            var _vertexBundle4 = this._struct.vertexBundles[vertexBundleIndex];
            var _iAttribute = _vertexBundle4.attributes.findIndex(function (a) {
              return a.name === attributeName;
            });
            if (_iAttribute < 0) {
              continue;
            }
            accessor(_vertexBundle4, _iAttribute);
            break;
          }
        };
        _proto._createVertexBuffers = function _createVertexBuffers(gfxDevice, data) {
          return this._struct.vertexBundles.map(function (vertexBundle) {
            var vertexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.VERTEX, MemoryUsageBit.DEVICE, vertexBundle.view.length, vertexBundle.view.stride));
            var view = new Uint8Array(data, vertexBundle.view.offset, vertexBundle.view.length);
            vertexBuffer.update(view);
            return vertexBuffer;
          });
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          this.reset({
            struct: {
              vertexBundles: [],
              primitives: []
            },
            data: globalEmptyMeshBuffer
          });
        };
        _proto.releaseData = function releaseData() {
          this._data = globalEmptyMeshBuffer;
        };
        _createClass(Mesh, [{
          key: "_nativeAsset",
          get: function get() {
            return this._data.buffer;
          },
          set: function set(value) {
            this._data = new Uint8Array(value);
          }
        }, {
          key: "subMeshCount",
          get: function get() {
            var renderingMesh = this.renderingSubMeshes;
            return renderingMesh ? renderingMesh.length : 0;
          }
        }, {
          key: "minPosition",
          get: function get() {
            return this.struct.minPosition;
          }
        }, {
          key: "maxPosition",
          get: function get() {
            return this.struct.maxPosition;
          }
        }, {
          key: "struct",
          get: function get() {
            return this._struct;
          }
        }, {
          key: "data",
          get: function get() {
            return this._data;
          }
        }, {
          key: "hash",
          get: function get() {
            if (!this._hash) {
              this._hash = murmurhash2_32_gc(this._data, 666);
            }
            return this._hash;
          }
        }, {
          key: "jointBufferIndices",
          get: function get() {
            if (this._jointBufferIndices) {
              return this._jointBufferIndices;
            }
            return this._jointBufferIndices = this._struct.primitives.map(function (p) {
              return p.jointMapIndex || 0;
            });
          }
        }, {
          key: "renderingSubMeshes",
          get: function get() {
            this.initialize();
            return this._renderingSubMeshes;
          }
        }, {
          key: "allowDataAccess",
          get: function get() {
            return this._allowDataAccess;
          },
          set: function set(allowDataAccess) {
            this._allowDataAccess = allowDataAccess;
            if (this._isMeshDataUploaded && !this._allowDataAccess && !EDITOR) {
              this.releaseData();
            }
          }
        }]);
        return Mesh;
      }(Asset), (_initializer$2x = applyDecoratedInitializer(_class2$2H.prototype, "_struct", [serializable$p], function () {
        return {
          vertexBundles: [],
          primitives: []
        };
      }), _initializer2$25 = applyDecoratedInitializer(_class2$2H.prototype, "_hash", [serializable$p], function () {
        return 0;
      }), _initializer3$1y = applyDecoratedInitializer(_class2$2H.prototype, "_allowDataAccess", [serializable$p], function () {
        return true;
      })), _class2$2H)) || _class$2$));
      legacyCC.Mesh = Mesh;
      function getOffset(attributes, attributeIndex) {
        var result = 0;
        for (var i = 0; i < attributeIndex; ++i) {
          var attribute = attributes[i];
          result += FormatInfos[attribute.format].size;
        }
        return result;
      }
      var isLittleEndian = sys.isLittleEndian;
      function getComponentByteLength(format) {
        var info = FormatInfos[format];
        return info.size / info.count;
      }
      function getReader(dataView, format) {
        var info = FormatInfos[format];
        var stride = info.size / info.count;
        switch (info.type) {
          case FormatType.UNORM:
            {
              switch (stride) {
                case 1:
                  return function (offset) {
                    return dataView.getUint8(offset);
                  };
                case 2:
                  return function (offset) {
                    return dataView.getUint16(offset, isLittleEndian);
                  };
                case 4:
                  return function (offset) {
                    return dataView.getUint32(offset, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.SNORM:
            {
              switch (stride) {
                case 1:
                  return function (offset) {
                    return dataView.getInt8(offset);
                  };
                case 2:
                  return function (offset) {
                    return dataView.getInt16(offset, isLittleEndian);
                  };
                case 4:
                  return function (offset) {
                    return dataView.getInt32(offset, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.INT:
            {
              switch (stride) {
                case 1:
                  return function (offset) {
                    return dataView.getInt8(offset);
                  };
                case 2:
                  return function (offset) {
                    return dataView.getInt16(offset, isLittleEndian);
                  };
                case 4:
                  return function (offset) {
                    return dataView.getInt32(offset, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.UINT:
            {
              switch (stride) {
                case 1:
                  return function (offset) {
                    return dataView.getUint8(offset);
                  };
                case 2:
                  return function (offset) {
                    return dataView.getUint16(offset, isLittleEndian);
                  };
                case 4:
                  return function (offset) {
                    return dataView.getUint32(offset, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.FLOAT:
            {
              switch (stride) {
                case 2:
                  return function (offset) {
                    return dataView.getUint16(offset, isLittleEndian);
                  };
                case 4:
                  return function (offset) {
                    return dataView.getFloat32(offset, isLittleEndian);
                  };
              }
              break;
            }
        }
        return null;
      }
      function getWriter(dataView, format) {
        var info = FormatInfos[format];
        var stride = info.size / info.count;
        switch (info.type) {
          case FormatType.UNORM:
            {
              switch (stride) {
                case 1:
                  return function (offset, value) {
                    return dataView.setUint8(offset, value);
                  };
                case 2:
                  return function (offset, value) {
                    return dataView.setUint16(offset, value, isLittleEndian);
                  };
                case 4:
                  return function (offset, value) {
                    return dataView.setUint32(offset, value, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.SNORM:
            {
              switch (stride) {
                case 1:
                  return function (offset, value) {
                    return dataView.setInt8(offset, value);
                  };
                case 2:
                  return function (offset, value) {
                    return dataView.setInt16(offset, value, isLittleEndian);
                  };
                case 4:
                  return function (offset, value) {
                    return dataView.setInt32(offset, value, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.INT:
            {
              switch (stride) {
                case 1:
                  return function (offset, value) {
                    return dataView.setInt8(offset, value);
                  };
                case 2:
                  return function (offset, value) {
                    return dataView.setInt16(offset, value, isLittleEndian);
                  };
                case 4:
                  return function (offset, value) {
                    return dataView.setInt32(offset, value, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.UINT:
            {
              switch (stride) {
                case 1:
                  return function (offset, value) {
                    return dataView.setUint8(offset, value);
                  };
                case 2:
                  return function (offset, value) {
                    return dataView.setUint16(offset, value, isLittleEndian);
                  };
                case 4:
                  return function (offset, value) {
                    return dataView.setUint32(offset, value, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.FLOAT:
            {
              switch (stride) {
                case 2:
                  return function (offset, value) {
                    return dataView.setUint16(offset, value, isLittleEndian);
                  };
                case 4:
                  return function (offset, value) {
                    return dataView.setFloat32(offset, value, isLittleEndian);
                  };
              }
              break;
            }
        }
        return null;
      }
      function decodeMesh(mesh) {
        if (!mesh.struct.encoded) {
          return mesh;
        }
        var res_checker = function res_checker(res) {
          if (res < 0) {
            errorID(14204, res);
          }
        };
        var struct = JSON.parse(JSON.stringify(mesh.struct));
        var bufferBlob = new BufferBlob();
        bufferBlob.setNextAlignment(0);
        for (var _iterator7 = _createForOfIteratorHelperLoose(struct.vertexBundles), _step7; !(_step7 = _iterator7()).done;) {
          var bundle = _step7.value;
          var view = bundle.view;
          var bound = view.count * view.stride;
          var buffer = new Uint8Array(bound);
          var vertex = new Uint8Array(mesh.data.buffer, view.offset, view.length);
          var res = MeshoptDecoder.decodeVertexBuffer(buffer, view.count, view.stride, vertex);
          res_checker(res);
          bufferBlob.setNextAlignment(view.stride);
          var newView = {
            offset: bufferBlob.getLength(),
            length: buffer.byteLength,
            count: view.count,
            stride: view.stride
          };
          bundle.view = newView;
          bufferBlob.addBuffer(buffer);
        }
        for (var _iterator8 = _createForOfIteratorHelperLoose(struct.primitives), _step8; !(_step8 = _iterator8()).done;) {
          var primitive = _step8.value;
          if (primitive.indexView === undefined) {
            continue;
          }
          var _view = primitive.indexView;
          var _bound = _view.count * _view.stride;
          var _buffer = new Uint8Array(_bound);
          var index = new Uint8Array(mesh.data.buffer, _view.offset, _view.length);
          var _res = MeshoptDecoder.decodeIndexBuffer(_buffer, _view.count, _view.stride, index);
          res_checker(_res);
          bufferBlob.setNextAlignment(_view.stride);
          var _newView = {
            offset: bufferBlob.getLength(),
            length: _buffer.byteLength,
            count: _view.count,
            stride: _view.stride
          };
          primitive.indexView = _newView;
          bufferBlob.addBuffer(_buffer);
        }
        var data = new Uint8Array(bufferBlob.getCombined());
        return {
          struct: struct,
          data: data
        };
      }
      function inflateMesh(mesh) {
        var inflator = new _p.Inflate(mesh.data);
        var decompressed = inflator.decompress();
        mesh.data = decompressed;
        mesh.struct.compressed = false;
        return mesh;
      }
      function dequantizeMesh(mesh) {
        var struct = JSON.parse(JSON.stringify(mesh.struct));
        var bufferBlob = new BufferBlob();
        bufferBlob.setNextAlignment(0);
        function transformVertex(reader, writer, count, components, componentSize, readerStride, writerStride) {
          for (var i = 0; i < count; i++) {
            for (var j = 0; j < components; j++) {
              var inputOffset = readerStride * i + componentSize * j;
              var outputOffset = writerStride * i + componentSize * j;
              writer(outputOffset, reader(inputOffset));
            }
          }
        }
        function dequantizeHalf(reader, writer, count, components, readerStride, writerStride) {
          for (var i = 0; i < count; i++) {
            for (var j = 0; j < components; j++) {
              var inputOffset = readerStride * i + 2 * j;
              var outputOffset = writerStride * i + 4 * j;
              var _value = halfToFloat(reader(inputOffset));
              writer(outputOffset, _value);
            }
          }
        }
        for (var i = 0; i < struct.vertexBundles.length; ++i) {
          var bundle = struct.vertexBundles[i];
          var view = bundle.view;
          var attributes = bundle.attributes;
          var oldAttributes = mesh.struct.vertexBundles[i].attributes;
          var strides = [];
          var dequantizes = [];
          var readers = [];
          for (var j = 0; j < attributes.length; ++j) {
            var attr = attributes[j];
            var inputView = new DataView(mesh.data.buffer, view.offset + getOffset(oldAttributes, j));
            var reader = getReader(inputView, attr.format);
            var dequantize = true;
            switch (attr.format) {
              case Format.R16F:
                attr.format = Format.R32F;
                break;
              case Format.RG16F:
                attr.format = Format.RG32F;
                break;
              case Format.RGB16F:
                attr.format = Format.RGB32F;
                break;
              case Format.RGBA16F:
                attr.format = Format.RGBA32F;
                break;
              default:
                dequantize = false;
                break;
            }
            strides.push(FormatInfos[attr.format].size);
            dequantizes.push(dequantize);
            readers.push(reader);
          }
          var netStride = strides.reduce(function (acc, cur) {
            return acc + cur;
          }, 0);
          var newBuffer = new Uint8Array(netStride * view.count);
          for (var _j2 = 0; _j2 < attributes.length; ++_j2) {
            var attribute = attributes[_j2];
            var _reader = readers[_j2];
            var outputView = new DataView(newBuffer.buffer, getOffset(attributes, _j2));
            var writer = getWriter(outputView, attribute.format);
            var _dequantize = dequantizes[_j2];
            var formatInfo = FormatInfos[attribute.format];
            if (_dequantize) {
              dequantizeHalf(_reader, writer, view.count, formatInfo.count, view.stride, netStride);
            } else {
              transformVertex(_reader, writer, view.count, formatInfo.count, formatInfo.size / formatInfo.count, view.stride, netStride);
            }
          }
          bufferBlob.setNextAlignment(netStride);
          var newView = {
            offset: bufferBlob.getLength(),
            length: newBuffer.byteLength,
            count: view.count,
            stride: netStride
          };
          bundle.view = newView;
          bufferBlob.addBuffer(newBuffer);
        }
        for (var _iterator9 = _createForOfIteratorHelperLoose(struct.primitives), _step9; !(_step9 = _iterator9()).done;) {
          var primitive = _step9.value;
          if (primitive.indexView === undefined) {
            continue;
          }
          var _view2 = primitive.indexView;
          var buffer = new Uint8Array(mesh.data.buffer, _view2.offset, _view2.length);
          bufferBlob.setNextAlignment(_view2.stride);
          var _newView2 = {
            offset: bufferBlob.getLength(),
            length: buffer.byteLength,
            count: _view2.count,
            stride: _view2.stride
          };
          primitive.indexView = _newView2;
          bufferBlob.addBuffer(buffer);
        }
        var data = new Uint8Array(bufferBlob.getCombined());
        struct.quantized = false;
        return {
          struct: struct,
          data: data
        };
      }

      var _defAttrs = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_TANGENT, Format.RGBA32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F)];
      var v3_1$5 = new Vec3();
      function _createMesh(geometry, out, options) {
        options = options || {};
        var attributes = [];
        var stride = 0;
        var channels = [];
        var vertCount = 0;
        var attr;
        var positions = geometry.positions.slice();
        if (positions.length > 0) {
          attr = null;
          if (geometry.attributes) {
            for (var _iterator = _createForOfIteratorHelperLoose(geometry.attributes), _step; !(_step = _iterator()).done;) {
              var att = _step.value;
              if (att.name === AttributeName.ATTR_POSITION) {
                attr = att;
                break;
              }
            }
          }
          if (!attr) {
            attr = _defAttrs[0];
          }
          attributes.push(attr);
          var info = FormatInfos[attr.format];
          vertCount = Math.max(vertCount, Math.floor(positions.length / info.count));
          channels.push({
            offset: stride,
            data: positions,
            attribute: attr
          });
          stride += info.size;
        }
        if (geometry.normals && geometry.normals.length > 0) {
          attr = null;
          if (geometry.attributes) {
            for (var _iterator2 = _createForOfIteratorHelperLoose(geometry.attributes), _step2; !(_step2 = _iterator2()).done;) {
              var _att = _step2.value;
              if (_att.name === AttributeName.ATTR_NORMAL) {
                attr = _att;
                break;
              }
            }
          }
          if (!attr) {
            attr = _defAttrs[1];
          }
          var _info = FormatInfos[attr.format];
          attributes.push(attr);
          vertCount = Math.max(vertCount, Math.floor(geometry.normals.length / _info.count));
          channels.push({
            offset: stride,
            data: geometry.normals,
            attribute: attr
          });
          stride += _info.size;
        }
        if (geometry.uvs && geometry.uvs.length > 0) {
          attr = null;
          if (geometry.attributes) {
            for (var _iterator3 = _createForOfIteratorHelperLoose(geometry.attributes), _step3; !(_step3 = _iterator3()).done;) {
              var _att2 = _step3.value;
              if (_att2.name === AttributeName.ATTR_TEX_COORD) {
                attr = _att2;
                break;
              }
            }
          }
          if (!attr) {
            attr = _defAttrs[2];
          }
          var _info2 = FormatInfos[attr.format];
          attributes.push(attr);
          vertCount = Math.max(vertCount, Math.floor(geometry.uvs.length / _info2.count));
          channels.push({
            offset: stride,
            data: geometry.uvs,
            attribute: attr
          });
          stride += _info2.size;
        }
        if (geometry.tangents && geometry.tangents.length > 0) {
          attr = null;
          if (geometry.attributes) {
            for (var _iterator4 = _createForOfIteratorHelperLoose(geometry.attributes), _step4; !(_step4 = _iterator4()).done;) {
              var _att3 = _step4.value;
              if (_att3.name === AttributeName.ATTR_TANGENT) {
                attr = _att3;
                break;
              }
            }
          }
          if (!attr) {
            attr = _defAttrs[3];
          }
          var _info3 = FormatInfos[attr.format];
          attributes.push(attr);
          vertCount = Math.max(vertCount, Math.floor(geometry.tangents.length / _info3.count));
          channels.push({
            offset: stride,
            data: geometry.tangents,
            attribute: attr
          });
          stride += _info3.size;
        }
        if (geometry.colors && geometry.colors.length > 0) {
          attr = null;
          if (geometry.attributes) {
            for (var _iterator5 = _createForOfIteratorHelperLoose(geometry.attributes), _step5; !(_step5 = _iterator5()).done;) {
              var _att4 = _step5.value;
              if (_att4.name === AttributeName.ATTR_COLOR) {
                attr = _att4;
                break;
              }
            }
          }
          if (!attr) {
            attr = _defAttrs[4];
          }
          var _info4 = FormatInfos[attr.format];
          attributes.push(attr);
          vertCount = Math.max(vertCount, Math.floor(geometry.colors.length / _info4.count));
          channels.push({
            offset: stride,
            data: geometry.colors,
            attribute: attr
          });
          stride += _info4.size;
        }
        if (geometry.customAttributes) {
          for (var k = 0; k < geometry.customAttributes.length; k++) {
            var ca = geometry.customAttributes[k];
            var _info5 = FormatInfos[ca.attr.format];
            attributes.push(ca.attr);
            vertCount = Math.max(vertCount, Math.floor(ca.values.length / _info5.count));
            channels.push({
              offset: stride,
              data: ca.values,
              attribute: ca.attr
            });
            stride += _info5.size;
          }
        }
        var bufferBlob = new BufferBlob();
        var vertexBuffer = new ArrayBuffer(vertCount * stride);
        var vertexBufferView = new DataView(vertexBuffer);
        for (var _i = 0, _channels = channels; _i < _channels.length; _i++) {
          var channel = _channels[_i];
          writeBuffer(vertexBufferView, channel.data, channel.attribute.format, channel.offset, stride);
        }
        bufferBlob.setNextAlignment(0);
        var vertexBundle = {
          attributes: attributes,
          view: {
            offset: bufferBlob.getLength(),
            length: vertexBuffer.byteLength,
            count: vertCount,
            stride: stride
          }
        };
        bufferBlob.addBuffer(vertexBuffer);
        var indexBuffer = null;
        var idxCount = 0;
        var idxStride = 2;
        if (geometry.indices) {
          var indices = geometry.indices;
          idxCount = indices.length;
          indexBuffer = new ArrayBuffer(idxStride * idxCount);
          var indexBufferView = new DataView(indexBuffer);
          writeBuffer(indexBufferView, indices, Format.R16UI);
        }
        var primitive = {
          primitiveMode: geometry.primitiveMode || PrimitiveMode.TRIANGLE_LIST,
          vertexBundelIndices: [0]
        };
        if (indexBuffer) {
          bufferBlob.setNextAlignment(idxStride);
          primitive.indexView = {
            offset: bufferBlob.getLength(),
            length: indexBuffer.byteLength,
            count: idxCount,
            stride: idxStride
          };
          bufferBlob.addBuffer(indexBuffer);
        }
        var minPosition = geometry.minPos;
        if (!minPosition && options.calculateBounds) {
          minPosition = Vec3.set(new Vec3(), Infinity, Infinity, Infinity);
          for (var iVertex = 0; iVertex < vertCount; ++iVertex) {
            Vec3.set(v3_1$5, positions[iVertex * 3 + 0], positions[iVertex * 3 + 1], positions[iVertex * 3 + 2]);
            Vec3.min(minPosition, minPosition, v3_1$5);
          }
        }
        var maxPosition = geometry.maxPos;
        if (!maxPosition && options.calculateBounds) {
          maxPosition = Vec3.set(new Vec3(), -Infinity, -Infinity, -Infinity);
          for (var _iVertex = 0; _iVertex < vertCount; ++_iVertex) {
            Vec3.set(v3_1$5, positions[_iVertex * 3 + 0], positions[_iVertex * 3 + 1], positions[_iVertex * 3 + 2]);
            Vec3.max(maxPosition, maxPosition, v3_1$5);
          }
        }
        var meshStruct = {
          vertexBundles: [vertexBundle],
          primitives: [primitive]
        };
        if (minPosition) {
          meshStruct.minPosition = new Vec3(minPosition.x, minPosition.y, minPosition.z);
        }
        if (maxPosition) {
          meshStruct.maxPosition = new Vec3(maxPosition.x, maxPosition.y, maxPosition.z);
        }
        if (!out) {
          out = new Mesh();
        }
        out.reset({
          struct: meshStruct,
          data: new Uint8Array(bufferBlob.getCombined())
        });
        return out;
      }
      function getPadding(length, align) {
        if (align > 0) {
          var remainder = length % align;
          if (remainder !== 0) {
            var padding = align - remainder;
            return padding;
          }
        }
        return 0;
      }
      function _createDynamicMesh(primitiveIndex, geometry, out, options) {
        options = options || {
          maxSubMeshes: 1,
          maxSubMeshVertices: 1024,
          maxSubMeshIndices: 1024
        };
        var attributes = [];
        var stream = 0;
        if (geometry.positions.length > 0) {
          attributes.push(new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F, false, stream++, false, 0));
        }
        if (geometry.normals && geometry.normals.length > 0) {
          attributes.push(new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F, false, stream++, false, 0));
        }
        if (geometry.uvs && geometry.uvs.length > 0) {
          attributes.push(new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F, false, stream++, false, 0));
        }
        if (geometry.tangents && geometry.tangents.length > 0) {
          attributes.push(new Attribute(AttributeName.ATTR_TANGENT, Format.RGBA32F, false, stream++, false, 0));
        }
        if (geometry.colors && geometry.colors.length > 0) {
          attributes.push(new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F, false, stream++, false, 0));
        }
        if (geometry.customAttributes) {
          for (var k = 0; k < geometry.customAttributes.length; k++) {
            var ca = geometry.customAttributes[k];
            var attr = new Attribute();
            attr.copy(ca.attr);
            attr.stream = stream++;
            attributes.push(attr);
          }
        }
        var vertexBundles = [];
        var primitives = [];
        var dataSize = 0;
        for (var i = 0; i < options.maxSubMeshes; i++) {
          var primitive = {
            vertexBundelIndices: [],
            primitiveMode: geometry.primitiveMode || PrimitiveMode.TRIANGLE_LIST
          };
          for (var _iterator6 = _createForOfIteratorHelperLoose(attributes), _step6; !(_step6 = _iterator6()).done;) {
            var _attr = _step6.value;
            var formatInfo = FormatInfos[_attr.format];
            var vertexBufferSize = options.maxSubMeshVertices * formatInfo.size;
            var vertexView = {
              offset: dataSize,
              length: vertexBufferSize,
              count: 0,
              stride: formatInfo.size
            };
            var vertexBundle = {
              view: vertexView,
              attributes: [_attr]
            };
            var vertexBundleIndex = vertexBundles.length;
            primitive.vertexBundelIndices.push(vertexBundleIndex);
            vertexBundles.push(vertexBundle);
            dataSize += vertexBufferSize;
          }
          var stride = 0;
          if (geometry.indices16 && geometry.indices16.length > 0) {
            stride = 2;
          } else if (geometry.indices32 && geometry.indices32.length > 0) {
            stride = 4;
          }
          if (stride > 0) {
            dataSize += getPadding(dataSize, stride);
            var indexBufferSize = options.maxSubMeshIndices * stride;
            var indexView = {
              offset: dataSize,
              length: indexBufferSize,
              count: 0,
              stride: stride
            };
            primitive.indexView = indexView;
            dataSize += indexBufferSize;
          }
          primitives.push(primitive);
        }
        var dynamicInfo = {
          maxSubMeshes: options.maxSubMeshes,
          maxSubMeshVertices: options.maxSubMeshVertices,
          maxSubMeshIndices: options.maxSubMeshIndices
        };
        var dynamicStruct = {
          info: dynamicInfo,
          bounds: []
        };
        dynamicStruct.bounds.length = options.maxSubMeshes;
        var meshStruct = {
          vertexBundles: vertexBundles,
          primitives: primitives,
          dynamic: dynamicStruct
        };
        var createInfo = {
          struct: meshStruct,
          data: new Uint8Array(dataSize)
        };
        if (!out) {
          out = new Mesh();
        }
        out.reset(createInfo);
        out.initialize();
        out.updateSubMesh(primitiveIndex, geometry);
        return out;
      }
      var MeshUtils = function () {
        function MeshUtils() {}
        MeshUtils.createMesh = function createMesh(geometry, out, options) {
          return _createMesh(geometry, out, options);
        };
        MeshUtils.createDynamicMesh = function createDynamicMesh(primitiveIndex, geometry, out, options) {
          return _createDynamicMesh(primitiveIndex, geometry, out, options);
        };
        MeshUtils.decodeMesh = function decodeMesh$1(mesh) {
          return decodeMesh(mesh);
        };
        MeshUtils.inflateMesh = function inflateMesh$1(mesh) {
          return inflateMesh(mesh);
        };
        return MeshUtils;
      }();

      var utils = /*#__PURE__*/Object.freeze({
        __proto__: null,
        find: find,
        toPPM: toPPM,
        readMesh: readMesh,
        createMesh: _createMesh,
        MeshUtils: MeshUtils,
        readBuffer: readBuffer,
        writeBuffer: writeBuffer,
        mapBuffer: mapBuffer
      });
      exports('a7', utils);

      var _dec$31, _class$2_, _class2$2G;
      var INSET_LEFT = 0;
      var INSET_TOP = 1;
      var INSET_RIGHT = 2;
      var INSET_BOTTOM = 3;
      var temp_vec3 = new Vec3();
      var temp_matrix = new Mat4();
      var MeshType;
      (function (MeshType) {
        MeshType[MeshType["RECT"] = 0] = "RECT";
        MeshType[MeshType["POLYGON"] = 1] = "POLYGON";
      })(MeshType || (MeshType = {}));
      var temp_uvs = [{
        u: 0,
        v: 0
      }, {
        u: 0,
        v: 0
      }, {
        u: 0,
        v: 0
      }, {
        u: 0,
        v: 0
      }];
      var SpriteFrame = exports('b', (_dec$31 = ccclass$M('cc.SpriteFrame'), _dec$31(_class$2_ = (_class2$2G = function (_Asset) {
        _inheritsLoose(SpriteFrame, _Asset);
        SpriteFrame.createWithImage = function createWithImage(imageSourceOrImageAsset) {
          var img = imageSourceOrImageAsset instanceof ImageAsset ? imageSourceOrImageAsset : new ImageAsset(imageSourceOrImageAsset);
          var tex = new Texture2D();
          tex.image = img;
          var spf = new SpriteFrame();
          spf.texture = tex;
          return spf;
        };
        function SpriteFrame() {
          var _this;
          _this = _Asset.call(this) || this;
          _this.vertices = null;
          _this.uv = [];
          _this.unbiasUV = [];
          _this.uvSliced = [];
          _this._rect = new Rect$1();
          _this._trimmedBorder = new Vec4();
          _this._offset = new Vec2();
          _this._originalSize = new Size$1();
          _this._rotated = false;
          _this._capInsets = [0, 0, 0, 0];
          _this._atlasUuid = '';
          _this._texture = void 0;
          _this._isFlipUVY = false;
          _this._isFlipUVX = false;
          _this._original = null;
          _this._packable = true;
          _this._pixelsToUnit = 100;
          _this._pivot = new Vec2(0.5, 0.5);
          _this._meshType = MeshType.RECT;
          _this._extrude = 0;
          _this._customOutLine = [];
          _this._minPos = new Vec3();
          _this._maxPos = new Vec3();
          return _this;
        }
        var _proto = SpriteFrame.prototype;
        _proto.textureLoaded = function textureLoaded() {
          return !!this.texture;
        };
        _proto.isRotated = function isRotated() {
          return this._rotated;
        };
        _proto.setRotated = function setRotated(rotated) {
          this.rotated = rotated;
        };
        _proto.getRect = function getRect(out) {
          if (out) {
            out.set(this._rect);
            return out;
          }
          return this._rect.clone();
        };
        _proto.setRect = function setRect(rect) {
          this.rect = rect;
        };
        _proto.getOriginalSize = function getOriginalSize(out) {
          if (out) {
            out.set(this._originalSize);
            return out;
          }
          return this._originalSize.clone();
        };
        _proto.setOriginalSize = function setOriginalSize(size) {
          this.originalSize = size;
        };
        _proto.getOffset = function getOffset(out) {
          if (out) {
            out.set(this._offset);
            return out;
          }
          return this._offset.clone();
        };
        _proto.setOffset = function setOffset(offset) {
          this.offset = offset;
        };
        _proto.getGFXTexture = function getGFXTexture() {
          return this._texture.getGFXTexture();
        };
        _proto.getGFXSampler = function getGFXSampler() {
          return this._texture.getGFXSampler();
        };
        _proto.getHash = function getHash() {
          return this._texture.getHash();
        };
        _proto.getSamplerInfo = function getSamplerInfo() {
          return this._texture.getSamplerInfo();
        };
        _proto.reset = function reset(info, clearData) {
          if (clearData === void 0) {
            clearData = false;
          }
          var calUV = false;
          if (clearData) {
            this._originalSize.set(0, 0);
            this._rect.set(0, 0, 0, 0);
            this._offset.set(0, 0);
            this._capInsets = [0, 0, 0, 0];
            this._rotated = false;
            calUV = true;
          }
          if (info) {
            if (info.texture) {
              this._rect.x = this._rect.y = 0;
              this._rect.width = info.texture.width;
              this._rect.height = info.texture.height;
              this._refreshTexture(info.texture);
              this.checkRect(this._texture);
            }
            if (info.originalSize) {
              this._originalSize.set(info.originalSize);
            }
            if (info.rect) {
              this._rect.set(info.rect);
            }
            if (info.offset) {
              this._offset.set(info.offset);
            }
            if (info.borderTop !== undefined) {
              this._capInsets[INSET_TOP] = info.borderTop;
            }
            if (info.borderBottom !== undefined) {
              this._capInsets[INSET_BOTTOM] = info.borderBottom;
            }
            if (info.borderLeft !== undefined) {
              this._capInsets[INSET_LEFT] = info.borderLeft;
            }
            if (info.borderRight !== undefined) {
              this._capInsets[INSET_RIGHT] = info.borderRight;
            }
            if (info.isRotate !== undefined) {
              this._rotated = !!info.isRotate;
            }
            if (info.isFlipUv !== undefined) {
              this._isFlipUVY = !!info.isFlipUv;
            }
            calUV = true;
          }
          if (calUV && this.texture) {
            this._calculateUV();
          }
          this._calcTrimmedBorder();
        };
        _proto.checkRect = function checkRect(texture) {
          var rect = this._rect;
          var maxX = rect.x;
          var maxY = rect.y;
          if (this._rotated) {
            maxX += rect.height;
            maxY += rect.width;
          } else {
            maxX += rect.width;
            maxY += rect.height;
          }
          if (maxX > texture.width) {
            errorID(3300, this.name + "/" + texture.name, maxX, texture.width);
            return false;
          }
          if (maxY > texture.height) {
            errorID(3301, this.name + "/" + texture.name, maxY, texture.height);
            return false;
          }
          return true;
        };
        _proto._calcTrimmedBorder = function _calcTrimmedBorder() {
          var ow = this._originalSize.width;
          var oh = this._originalSize.height;
          var rw = this._rect.width;
          var rh = this._rect.height;
          var halfTrimmedWidth = (ow - rw) * 0.5;
          var halfTrimmedHeight = (oh - rh) * 0.5;
          this._trimmedBorder.x = this._offset.x + halfTrimmedWidth;
          this._trimmedBorder.y = this._offset.x - halfTrimmedWidth;
          this._trimmedBorder.z = this._offset.y + halfTrimmedHeight;
          this._trimmedBorder.w = this._offset.y - halfTrimmedHeight;
        };
        _proto.ensureMeshData = function ensureMeshData() {
          if (this._mesh) return;
          this._initVertices();
          this._createMesh();
        };
        _proto.destroy = function destroy() {
          if (this._packable && dynamicAtlasManager) {
            dynamicAtlasManager.deleteAtlasSpriteFrame(this);
          }
          return _Asset.prototype.destroy.call(this);
        };
        _proto._calculateSlicedUV = function _calculateSlicedUV() {
          var rect = this._rect;
          var tex = this.texture;
          var atlasWidth = tex.width;
          var atlasHeight = tex.height;
          var leftWidth = this._capInsets[INSET_LEFT];
          var rightWidth = this._capInsets[INSET_RIGHT];
          var centerWidth = rect.width - leftWidth - rightWidth;
          var topHeight = this._capInsets[INSET_TOP];
          var bottomHeight = this._capInsets[INSET_BOTTOM];
          var centerHeight = rect.height - topHeight - bottomHeight;
          var uvSliced = this.uvSliced;
          uvSliced.length = 0;
          if (this._rotated) {
            temp_uvs[0].u = rect.x / atlasWidth;
            temp_uvs[1].u = (rect.x + bottomHeight) / atlasWidth;
            temp_uvs[2].u = (rect.x + bottomHeight + centerHeight) / atlasWidth;
            temp_uvs[3].u = (rect.x + rect.height) / atlasWidth;
            temp_uvs[3].v = rect.y / atlasHeight;
            temp_uvs[2].v = (rect.y + leftWidth) / atlasHeight;
            temp_uvs[1].v = (rect.y + leftWidth + centerWidth) / atlasHeight;
            temp_uvs[0].v = (rect.y + rect.width) / atlasHeight;
            for (var row = 0; row < 4; ++row) {
              var rowD = temp_uvs[row];
              for (var col = 0; col < 4; ++col) {
                var colD = temp_uvs[3 - col];
                uvSliced.push({
                  u: rowD.u,
                  v: colD.v
                });
              }
            }
          } else {
            temp_uvs[0].u = rect.x / atlasWidth;
            temp_uvs[1].u = (rect.x + leftWidth) / atlasWidth;
            temp_uvs[2].u = (rect.x + leftWidth + centerWidth) / atlasWidth;
            temp_uvs[3].u = (rect.x + rect.width) / atlasWidth;
            temp_uvs[3].v = rect.y / atlasHeight;
            temp_uvs[2].v = (rect.y + topHeight) / atlasHeight;
            temp_uvs[1].v = (rect.y + topHeight + centerHeight) / atlasHeight;
            temp_uvs[0].v = (rect.y + rect.height) / atlasHeight;
            for (var _row = 0; _row < 4; ++_row) {
              var _rowD = temp_uvs[_row];
              for (var _col = 0; _col < 4; ++_col) {
                var _colD = temp_uvs[_col];
                uvSliced.push({
                  u: _colD.u,
                  v: _rowD.v
                });
              }
            }
          }
          this.emit(SpriteFrame.EVENT_UV_UPDATED, this);
        };
        _proto._calculateUV = function _calculateUV() {
          var rect = this._rect;
          var uv = this.uv;
          var unbiasUV = this.unbiasUV;
          var tex = this.texture;
          var texw = tex.width;
          var texh = tex.height;
          if (this._rotated) {
            var l = texw === 0 ? 0 : rect.x / texw;
            var r = texw === 0 ? 1 : (rect.x + rect.height) / texw;
            var t = texh === 0 ? 0 : rect.y / texh;
            var b = texh === 0 ? 1 : (rect.y + rect.width) / texh;
            if (this._isFlipUVX && this._isFlipUVY) {
              uv[0] = r;
              uv[1] = b;
              uv[2] = r;
              uv[3] = t;
              uv[4] = l;
              uv[5] = b;
              uv[6] = l;
              uv[7] = t;
            } else if (this._isFlipUVX) {
              uv[0] = r;
              uv[1] = t;
              uv[2] = r;
              uv[3] = b;
              uv[4] = l;
              uv[5] = t;
              uv[6] = l;
              uv[7] = b;
            } else if (this._isFlipUVY) {
              uv[0] = l;
              uv[1] = b;
              uv[2] = l;
              uv[3] = t;
              uv[4] = r;
              uv[5] = b;
              uv[6] = r;
              uv[7] = t;
            } else {
              uv[0] = l;
              uv[1] = t;
              uv[2] = l;
              uv[3] = b;
              uv[4] = r;
              uv[5] = t;
              uv[6] = r;
              uv[7] = b;
            }
            var ul = texw === 0 ? 0 : rect.x / texw;
            var ur = texw === 0 ? 1 : (rect.x + rect.height) / texw;
            var ut = texh === 0 ? 0 : rect.y / texh;
            var ub = texh === 0 ? 1 : (rect.y + rect.width) / texh;
            if (this._isFlipUVX && this._isFlipUVY) {
              unbiasUV[0] = ur;
              unbiasUV[1] = ub;
              unbiasUV[2] = ur;
              unbiasUV[3] = ut;
              unbiasUV[4] = ul;
              unbiasUV[5] = ub;
              unbiasUV[6] = ul;
              unbiasUV[7] = ut;
            } else if (this._isFlipUVX) {
              unbiasUV[0] = ur;
              unbiasUV[1] = ut;
              unbiasUV[2] = ur;
              unbiasUV[3] = ub;
              unbiasUV[4] = ul;
              unbiasUV[5] = ut;
              unbiasUV[6] = ul;
              unbiasUV[7] = ub;
            } else if (this._isFlipUVY) {
              unbiasUV[0] = ul;
              unbiasUV[1] = ub;
              unbiasUV[2] = ul;
              unbiasUV[3] = ut;
              unbiasUV[4] = ur;
              unbiasUV[5] = ub;
              unbiasUV[6] = ur;
              unbiasUV[7] = ut;
            } else {
              unbiasUV[0] = ul;
              unbiasUV[1] = ut;
              unbiasUV[2] = ul;
              unbiasUV[3] = ub;
              unbiasUV[4] = ur;
              unbiasUV[5] = ut;
              unbiasUV[6] = ur;
              unbiasUV[7] = ub;
            }
          } else {
            var _l = texw === 0 ? 0 : rect.x / texw;
            var _r = texw === 0 ? 1 : (rect.x + rect.width) / texw;
            var _b = texh === 0 ? 1 : (rect.y + rect.height) / texh;
            var _t = texh === 0 ? 0 : rect.y / texh;
            if (this._isFlipUVX && this._isFlipUVY) {
              uv[0] = _r;
              uv[1] = _t;
              uv[2] = _l;
              uv[3] = _t;
              uv[4] = _r;
              uv[5] = _b;
              uv[6] = _l;
              uv[7] = _b;
            } else if (this._isFlipUVX) {
              uv[0] = _r;
              uv[1] = _b;
              uv[2] = _l;
              uv[3] = _b;
              uv[4] = _r;
              uv[5] = _t;
              uv[6] = _l;
              uv[7] = _t;
            } else if (this._isFlipUVY) {
              uv[0] = _l;
              uv[1] = _t;
              uv[2] = _r;
              uv[3] = _t;
              uv[4] = _l;
              uv[5] = _b;
              uv[6] = _r;
              uv[7] = _b;
            } else {
              uv[0] = _l;
              uv[1] = _b;
              uv[2] = _r;
              uv[3] = _b;
              uv[4] = _l;
              uv[5] = _t;
              uv[6] = _r;
              uv[7] = _t;
            }
            var _ul = texw === 0 ? 0 : rect.x / texw;
            var _ur = texw === 0 ? 1 : (rect.x + rect.width) / texw;
            var _ub = texh === 0 ? 1 : (rect.y + rect.height) / texh;
            var _ut = texh === 0 ? 0 : rect.y / texh;
            if (this._isFlipUVX && this._isFlipUVY) {
              unbiasUV[0] = _ur;
              unbiasUV[1] = _ut;
              unbiasUV[2] = _ul;
              unbiasUV[3] = _ut;
              unbiasUV[4] = _ur;
              unbiasUV[5] = _ub;
              unbiasUV[6] = _ul;
              unbiasUV[7] = _ub;
            } else if (this._isFlipUVX) {
              unbiasUV[0] = _ur;
              unbiasUV[1] = _ub;
              unbiasUV[2] = _ul;
              unbiasUV[3] = _ub;
              unbiasUV[4] = _ur;
              unbiasUV[5] = _ut;
              unbiasUV[6] = _ul;
              unbiasUV[7] = _ut;
            } else if (this._isFlipUVY) {
              unbiasUV[0] = _ul;
              unbiasUV[1] = _ut;
              unbiasUV[2] = _ur;
              unbiasUV[3] = _ut;
              unbiasUV[4] = _ul;
              unbiasUV[5] = _ub;
              unbiasUV[6] = _ur;
              unbiasUV[7] = _ub;
            } else {
              unbiasUV[0] = _ul;
              unbiasUV[1] = _ub;
              unbiasUV[2] = _ur;
              unbiasUV[3] = _ub;
              unbiasUV[4] = _ul;
              unbiasUV[5] = _ut;
              unbiasUV[6] = _ur;
              unbiasUV[7] = _ut;
            }
          }
          this._calculateSlicedUV();
        };
        _proto._setDynamicAtlasFrame = function _setDynamicAtlasFrame(frame) {
          if (!frame) return;
          this._original = {
            _texture: this._texture,
            _x: this._rect.x,
            _y: this._rect.y
          };
          this._texture = frame.texture;
          this._rect.x = frame.x;
          this._rect.y = frame.y;
          this._calculateUV();
        };
        _proto._resetDynamicAtlasFrame = function _resetDynamicAtlasFrame() {
          if (!this._original) return;
          this._rect.x = this._original._x;
          this._rect.y = this._original._y;
          this._texture = this._original._texture;
          this._original = null;
          this._calculateUV();
        };
        _proto._checkPackable = function _checkPackable() {
          var dynamicAtlas = dynamicAtlasManager;
          if (!dynamicAtlas) return;
          var texture = this._texture;
          if (!(texture instanceof Texture2D) || texture.isCompressed) {
            this._packable = false;
            return;
          }
          var w = this.width;
          var h = this.height;
          if (!texture.image || w > dynamicAtlas.maxFrameSize || h > dynamicAtlas.maxFrameSize) {
            this._packable = false;
            return;
          }
          var CanvasElement = ccwindow.HTMLCanvasElement;
          if (texture.image && texture.image instanceof CanvasElement) {
            this._packable = true;
          }
        };
        _proto._serialize = function _serialize(ctxForExporting) {
          return null;
        };
        _proto._deserialize = function _deserialize(serializeData, handle) {
          var data = serializeData;
          var rect = data.rect;
          if (rect) {
            this._rect = new Rect$1(rect.x, rect.y, rect.width, rect.height);
          }
          var offset = data.offset;
          if (data.offset) {
            this._offset = new Vec2(offset.x, offset.y);
          }
          var originalSize = data.originalSize;
          if (data.originalSize) {
            this._originalSize = new Size$1(originalSize.width, originalSize.height);
          }
          this._rotated = !!data.rotated;
          this._name = data.name;
          this._packable = !!data.packable;
          this._pixelsToUnit = data.pixelsToUnit;
          var pivot = data.pivot;
          if (pivot) {
            this._pivot = new Vec2(pivot.x, pivot.y);
          }
          this._meshType = data.meshType;
          var capInsets = data.capInsets;
          if (capInsets) {
            this._capInsets[INSET_LEFT] = capInsets[INSET_LEFT];
            this._capInsets[INSET_TOP] = capInsets[INSET_TOP];
            this._capInsets[INSET_RIGHT] = capInsets[INSET_RIGHT];
            this._capInsets[INSET_BOTTOM] = capInsets[INSET_BOTTOM];
          }
          var vertices = data.vertices;
          if (vertices) {
            if (!this.vertices) {
              this.vertices = {
                rawPosition: [],
                positions: [],
                indexes: vertices.indexes,
                uv: vertices.uv,
                nuv: vertices.nuv,
                minPos: new Vec3(vertices.minPos.x, vertices.minPos.y, vertices.minPos.z),
                maxPos: new Vec3(vertices.maxPos.x, vertices.maxPos.y, vertices.maxPos.z)
              };
            }
            this.vertices.rawPosition.length = 0;
            var rawPosition = vertices.rawPosition;
            for (var i = 0; i < rawPosition.length; i += 3) {
              this.vertices.rawPosition.push(new Vec3(rawPosition[i], rawPosition[i + 1], rawPosition[i + 2]));
            }
            this._updateMeshVertices();
          }
        };
        _proto.clone = function clone() {
          var _sp$uv, _sp$unbiasUV, _sp$uvSliced, _sp$_capInsets, _sp$_customOutLine;
          var sp = new SpriteFrame();
          var v = this.vertices;
          sp.vertices = v ? {
            rawPosition: v.rawPosition.slice(0),
            positions: v.positions.slice(0),
            indexes: v.indexes.slice(0),
            uv: v.uv.slice(0),
            nuv: v.nuv.slice(0),
            minPos: v.minPos.clone(),
            maxPos: v.maxPos.clone()
          } : null;
          (_sp$uv = sp.uv).splice.apply(_sp$uv, [0, sp.uv.length].concat(this.uv));
          (_sp$unbiasUV = sp.unbiasUV).splice.apply(_sp$unbiasUV, [0, sp.unbiasUV.length].concat(this.unbiasUV));
          (_sp$uvSliced = sp.uvSliced).splice.apply(_sp$uvSliced, [0, sp.uvSliced.length].concat(this.uvSliced));
          sp._rect.set(this._rect);
          sp._trimmedBorder.set(this._trimmedBorder);
          sp._offset.set(this._offset);
          sp._originalSize.set(this._originalSize);
          sp._rotated = this._rotated;
          (_sp$_capInsets = sp._capInsets).splice.apply(_sp$_capInsets, [0, sp._capInsets.length].concat(this._capInsets));
          sp._atlasUuid = this._atlasUuid;
          sp._texture = this._texture;
          sp._isFlipUVX = this._isFlipUVX;
          sp._isFlipUVY = this._isFlipUVY;
          if (this._original) {
            sp._original = {
              _texture: this._original._texture,
              _x: this._original._x,
              _y: this._original._y
            };
          } else {
            sp._original = null;
          }
          sp._packable = this._packable;
          sp._pixelsToUnit = this._pixelsToUnit;
          sp._pivot.set(this._pivot);
          sp._meshType = this._meshType;
          sp._extrude = this._extrude;
          (_sp$_customOutLine = sp._customOutLine).splice.apply(_sp$_customOutLine, [0, sp._customOutLine.length].concat(this._customOutLine));
          sp._minPos = this._minPos;
          sp._maxPos = this._maxPos;
          if (this._mesh) {
            sp._createMesh();
          }
          return sp;
        };
        _proto._refreshTexture = function _refreshTexture(texture) {
          this._texture = texture;
          var tex = this._texture;
          var config = {};
          var isReset = false;
          if (this._rect.width === 0 || this._rect.height === 0 || !this.checkRect(tex)) {
            config.rect = new Rect$1(0, 0, tex.width, tex.height);
            isReset = true;
          }
          if (this._originalSize.width === 0 || this._originalSize.height === 0 || isReset) {
            config.originalSize = new Size$1(tex.width, tex.height);
            isReset = true;
          }
          if (isReset) {
            this.reset(config);
          }
          this._checkPackable();
          if (this._mesh) {
            this._updateMesh();
          }
        };
        _proto.onLoaded = function onLoaded() {
          this._calcTrimmedBorder();
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          var texture = new Texture2D();
          texture.initDefault();
          this._refreshTexture(texture);
          this._calculateUV();
        };
        _proto.validate = function validate() {
          return this._texture && this._rect && this._rect.width !== 0 && this._rect.height !== 0;
        };
        _proto._initVertices = function _initVertices() {
          if (!this.vertices) {
            this.vertices = {
              rawPosition: [],
              positions: [],
              indexes: [],
              uv: [],
              nuv: [],
              minPos: new Vec3(),
              maxPos: new Vec3()
            };
          } else {
            this.vertices.rawPosition.length = 0;
            this.vertices.positions.length = 0;
            this.vertices.indexes.length = 0;
            this.vertices.uv.length = 0;
            this.vertices.nuv.length = 0;
            this.vertices.minPos.set(0, 0, 0);
            this.vertices.maxPos.set(0, 0, 0);
          }
          if (this._meshType === MeshType.POLYGON) ; else {
            var tex = this.texture;
            var texw = tex.width;
            var texh = tex.height;
            var rect = this.rect;
            var width = rect.width;
            var height = rect.height;
            var rectX = rect.x;
            var rectY = texh - rect.y - height;
            var halfWidth = width / 2;
            var halfHeight = height / 2;
            var l = texw === 0 ? 0 : rectX / texw;
            var r = texw === 0 ? 1 : (rectX + width) / texw;
            var t = texh === 0 ? 1 : (rectY + height) / texh;
            var b = texh === 0 ? 0 : rect.y / texh;
            temp_vec3.set(-halfWidth, -halfHeight, 0);
            this.vertices.rawPosition.push(temp_vec3.clone());
            this.vertices.uv.push(rectX);
            this.vertices.uv.push(rectY + height);
            this.vertices.nuv.push(l);
            this.vertices.nuv.push(b);
            this.vertices.minPos.set(temp_vec3);
            temp_vec3.set(halfWidth, -halfHeight, 0);
            this.vertices.rawPosition.push(temp_vec3.clone());
            this.vertices.uv.push(rectX + width);
            this.vertices.uv.push(rectY + height);
            this.vertices.nuv.push(r);
            this.vertices.nuv.push(b);
            temp_vec3.set(-halfWidth, halfHeight, 0);
            this.vertices.rawPosition.push(temp_vec3.clone());
            this.vertices.uv.push(rectX);
            this.vertices.uv.push(rectY);
            this.vertices.nuv.push(l);
            this.vertices.nuv.push(t);
            temp_vec3.set(halfWidth, halfHeight, 0);
            this.vertices.rawPosition.push(temp_vec3.clone());
            this.vertices.uv.push(rectX + width);
            this.vertices.uv.push(rectY);
            this.vertices.nuv.push(r);
            this.vertices.nuv.push(t);
            this.vertices.maxPos.set(temp_vec3);
            this.vertices.indexes.push(0);
            this.vertices.indexes.push(1);
            this.vertices.indexes.push(2);
            this.vertices.indexes.push(2);
            this.vertices.indexes.push(1);
            this.vertices.indexes.push(3);
          }
          this._updateMeshVertices();
        };
        _proto._updateMeshVertices = function _updateMeshVertices() {
          temp_matrix.identity();
          var units = 1 / this._pixelsToUnit;
          var PosX = -(this._pivot.x - 0.5) * this.rect.width * units;
          var PosY = -(this._pivot.y - 0.5) * this.rect.height * units;
          var temp_vec3 = new Vec3(PosX, PosY, 0);
          temp_matrix.transform(temp_vec3);
          temp_vec3.set(units, units, 1);
          temp_matrix.scale(temp_vec3);
          var vertices = this.vertices;
          for (var i = 0; i < vertices.rawPosition.length; i++) {
            var pos = vertices.rawPosition[i];
            Vec3.transformMat4(temp_vec3, pos, temp_matrix);
            Vec3.toArray(vertices.positions, temp_vec3, 3 * i);
          }
          Vec3.transformMat4(this._minPos, vertices.minPos, temp_matrix);
          Vec3.transformMat4(this._maxPos, vertices.maxPos, temp_matrix);
        };
        _proto._createMesh = function _createMesh$1() {
          this._mesh = _createMesh({
            primitiveMode: PrimitiveMode.TRIANGLE_LIST,
            positions: this.vertices.positions,
            uvs: this.vertices.nuv,
            indices: this.vertices.indexes,
            minPos: this._minPos,
            maxPos: this._maxPos,
            attributes: [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F)]
          });
        };
        _proto._updateMesh = function _updateMesh() {
          if (this._mesh) {
            this._mesh.destroy();
          }
          this._initVertices();
          this._createMesh();
        };
        _createClass(SpriteFrame, [{
          key: "insetTop",
          get: function get() {
            return this._capInsets[INSET_TOP];
          },
          set: function set(value) {
            if (this._capInsets[INSET_TOP] === value) {
              return;
            }
            this._capInsets[INSET_TOP] = value;
            if (this._texture) {
              this._calculateSlicedUV();
            }
          }
        }, {
          key: "insetBottom",
          get: function get() {
            return this._capInsets[INSET_BOTTOM];
          },
          set: function set(value) {
            if (this._capInsets[INSET_BOTTOM] === value) {
              return;
            }
            this._capInsets[INSET_BOTTOM] = value;
            if (this._texture) {
              this._calculateSlicedUV();
            }
          }
        }, {
          key: "insetLeft",
          get: function get() {
            return this._capInsets[INSET_LEFT];
          },
          set: function set(value) {
            if (this._capInsets[INSET_LEFT] === value) {
              return;
            }
            this._capInsets[INSET_LEFT] = value;
            if (this._texture) {
              this._calculateSlicedUV();
            }
          }
        }, {
          key: "insetRight",
          get: function get() {
            return this._capInsets[INSET_RIGHT];
          },
          set: function set(value) {
            if (this._capInsets[INSET_RIGHT] === value) {
              return;
            }
            this._capInsets[INSET_RIGHT] = value;
            if (this._texture) {
              this._calculateSlicedUV();
            }
          }
        }, {
          key: "rect",
          get: function get() {
            return this._rect;
          },
          set: function set(value) {
            if (this._rect.equals(value)) {
              return;
            }
            this._rect.set(value);
            if (this._texture) {
              this._calculateUV();
            }
            this._calcTrimmedBorder();
          }
        }, {
          key: "originalSize",
          get: function get() {
            return this._originalSize;
          },
          set: function set(value) {
            if (this._originalSize.equals(value)) {
              return;
            }
            this._originalSize.set(value);
            if (this._texture) {
              this._calculateUV();
            }
            this._calcTrimmedBorder();
          }
        }, {
          key: "offset",
          get: function get() {
            return this._offset;
          },
          set: function set(value) {
            this._offset.set(value);
            this._calcTrimmedBorder();
          }
        }, {
          key: "rotated",
          get: function get() {
            return this._rotated;
          },
          set: function set(rotated) {
            if (this._rotated === rotated) {
              return;
            }
            this._rotated = rotated;
            if (this._texture) {
              this._calculateUV();
            }
          }
        }, {
          key: "texture",
          get: function get() {
            return this._texture;
          },
          set: function set(value) {
            if (!value) {
              warnID(3122, this.name);
              return;
            }
            if (value === this._texture) {
              return;
            }
            this.reset({
              texture: value
            }, true);
          }
        }, {
          key: "atlasUuid",
          get: function get() {
            return this._atlasUuid;
          },
          set: function set(value) {
            this._atlasUuid = value;
          }
        }, {
          key: "width",
          get: function get() {
            return this._texture.width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._texture.height;
          }
        }, {
          key: "_textureSource",
          set: function set(value) {
            if (globalThis.Build) {
              this._texture = value;
              return;
            }
            if (value) {
              this._refreshTexture(value);
              this._calculateUV();
            }
          }
        }, {
          key: "flipUVX",
          get: function get() {
            return this._isFlipUVX;
          },
          set: function set(value) {
            this._isFlipUVX = value;
            this._calculateUV();
          }
        }, {
          key: "flipUVY",
          get: function get() {
            return this._isFlipUVY;
          },
          set: function set(value) {
            this._isFlipUVY = value;
            this._calculateUV();
          }
        }, {
          key: "packable",
          get: function get() {
            return this._packable;
          },
          set: function set(value) {
            this._packable = value;
          }
        }, {
          key: "original",
          get: function get() {
            return this._original;
          }
        }, {
          key: "pixelsToUnit",
          get: function get() {
            return this._pixelsToUnit;
          }
        }, {
          key: "pivot",
          get: function get() {
            return this._pivot;
          }
        }, {
          key: "mesh",
          get: function get() {
            return this._mesh;
          }
        }, {
          key: "trimmedBorder",
          get: function get() {
            return this._trimmedBorder;
          }
        }]);
        return SpriteFrame;
      }(Asset), _class2$2G.EVENT_UV_UPDATED = 'uv_updated', _class2$2G.MeshType = MeshType, _class2$2G)) || _class$2_));
      legacyCC.SpriteFrame = SpriteFrame;

      var _dec$30, _class$2Z, _class2$2F, _initializer$2w;
      var SpriteAtlas = exports('a', (_dec$30 = ccclass$M('cc.SpriteAtlas'), _dec$30(_class$2Z = (_class2$2F = function (_Asset) {
        _inheritsLoose(SpriteAtlas, _Asset);
        function SpriteAtlas() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.spriteFrames = _initializer$2w && _initializer$2w();
          return _this;
        }
        var _proto = SpriteAtlas.prototype;
        _proto.getTexture = function getTexture() {
          var keys = Object.keys(this.spriteFrames);
          if (keys.length > 0) {
            var spriteFrame = this.spriteFrames[keys[0]];
            return spriteFrame && spriteFrame.texture;
          } else {
            return null;
          }
        };
        _proto.getSpriteFrame = function getSpriteFrame(key) {
          var sf = this.spriteFrames[key];
          if (!sf) {
            return null;
          }
          if (!sf.name) {
            sf.name = key;
          }
          return sf;
        };
        _proto.getSpriteFrames = function getSpriteFrames() {
          var frames = [];
          var spriteFrames = this.spriteFrames;
          for (var _i = 0, _Object$keys = Object.keys(spriteFrames); _i < _Object$keys.length; _i++) {
            var _key2 = _Object$keys[_i];
            frames.push(spriteFrames[_key2]);
          }
          return frames;
        };
        _proto._serialize = function _serialize(ctxForExporting) {
        };
        _proto._deserialize = function _deserialize(serializeData, handle) {
          var data = serializeData;
          this._name = data.name;
          var frames = data.spriteFrames;
          this.spriteFrames = createMap();
          for (var i = 0; i < frames.length; i += 2) {
            handle.result.push(this.spriteFrames, frames[i], frames[i + 1], getClassId(SpriteFrame));
          }
        };
        return SpriteAtlas;
      }(Asset), (_initializer$2w = applyDecoratedInitializer(_class2$2F.prototype, "spriteFrames", [serializable$p], function () {
        return createMap();
      })), _class2$2F)) || _class$2Z));
      legacyCC.SpriteAtlas = SpriteAtlas;

      var _dec$2$, _class$2Y;
      var Font = exports('F', (_dec$2$ = ccclass$M('cc.Font'), _dec$2$(_class$2Y = function (_Asset) {
        _inheritsLoose(Font, _Asset);
        function Font() {
          return _Asset.apply(this, arguments) || this;
        }
        return Font;
      }(Asset)) || _class$2Y));
      legacyCC.Font = Font;

      var _dec$2_, _class$2X, _class2$2E, _initializer$2v;
      var TTFFont = exports('T', (_dec$2_ = ccclass$M('cc.TTFFont'), _dec$2_(_class$2X = (_class2$2E = function (_Font) {
        _inheritsLoose(TTFFont, _Font);
        function TTFFont() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Font.call.apply(_Font, [this].concat(args)) || this;
          _this._fontFamily = _initializer$2v && _initializer$2v();
          return _this;
        }
        var _proto = TTFFont.prototype;
        _proto.initDefault = function initDefault(uuid) {
          this._fontFamily = 'Arial';
          _Font.prototype.initDefault.call(this, uuid);
        };
        _createClass(TTFFont, [{
          key: "_nativeAsset",
          get: function get() {
            return this._fontFamily;
          },
          set: function set(value) {
            this._fontFamily = value || 'Arial';
          }
        }, {
          key: "_nativeDep",
          get: function get() {
            return {
              uuid: this._uuid,
              __nativeName__: this._native,
              ext: extname(this._native),
              __isNative__: true
            };
          }
        }]);
        return TTFFont;
      }(Font), (_initializer$2v = applyDecoratedInitializer(_class2$2E.prototype, "_fontFamily", [serializable$p], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$2E.prototype, "_nativeAsset", [override$1, string], Object.getOwnPropertyDescriptor(_class2$2E.prototype, "_nativeAsset"), _class2$2E.prototype), _applyDecoratedDescriptor(_class2$2E.prototype, "_nativeDep", [override$1], Object.getOwnPropertyDescriptor(_class2$2E.prototype, "_nativeDep"), _class2$2E.prototype)), _class2$2E)) || _class$2X));
      legacyCC.TTFFont = TTFFont;

      var BASELINE_RATIO = exports('A', 0.26);
      var _BASELINE_OFFSET$1 = 0;
      var MIDDLE_RATIO = exports('D', (BASELINE_RATIO + 1) / 2 - BASELINE_RATIO);
      function getBaselineOffset() {
        return _BASELINE_OFFSET$1;
      }
      var MAX_CACHE_SIZE = 100;
      var pool$2 = new Pool$1(2);
      pool$2.get = function () {
        return this._get() || {
          key: '',
          value: 0,
          prev: null,
          next: null
        };
      };
      var LRUCache = exports('J', function () {
        function LRUCache(size) {
          this.count = 0;
          this.limit = 0;
          this.datas = {};
          this.limit = size;
        }
        var _proto = LRUCache.prototype;
        _proto.moveToHead = function moveToHead(node) {
          node.next = this.head;
          node.prev = null;
          if (this.head) this.head.prev = node;
          this.head = node;
          if (!this.tail) this.tail = node;
          this.count++;
          this.datas[node.key] = node;
        };
        _proto.put = function put(key, value) {
          var node = pool$2.get();
          node.key = key;
          node.value = value;
          if (this.count >= this.limit) {
            var discard = this.tail;
            delete this.datas[discard.key];
            this.count--;
            this.tail = discard.prev;
            this.tail.next = null;
            discard.prev = null;
            discard.next = null;
            pool$2.put(discard);
          }
          this.moveToHead(node);
        };
        _proto.remove = function remove(node) {
          if (node.prev) {
            node.prev.next = node.next;
          } else {
            this.head = node.next;
          }
          if (node.next) {
            node.next.prev = node.prev;
          } else {
            this.tail = node.prev;
          }
          delete this.datas[node.key];
          this.count--;
        };
        _proto.get = function get(key) {
          var node = this.datas[key];
          if (node) {
            this.remove(node);
            this.moveToHead(node);
            return node.value;
          }
          return null;
        };
        _proto.clear = function clear() {
          this.count = 0;
          this.datas = {};
          this.head = null;
          this.tail = null;
        };
        _proto.has = function has(key) {
          return !!this.datas[key];
        };
        _proto["delete"] = function _delete(key) {
          var node = this.datas[key];
          this.remove(node);
        };
        return LRUCache;
      }());
      var measureCache = new LRUCache(MAX_CACHE_SIZE);
      var WORD_REG = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûа-яА-ЯЁё]+|\S)/;
      var SYMBOL_REG = /^[!,.:;'}\]%\?>、‘“》？。，！]/;
      var LAST_WORD_REG = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁёáàảạãăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệiíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđÁÀẢẠÃĂẮẰẲẴẶÂẤẦẨẪẬÉÈẺẼẸÊẾỀỂỄỆIÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴĐ]+|\S)$/;
      var LAST_ENGLISH_REG = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁёáàảạãăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệiíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđÁÀẢẠÃĂẮẰẲẴẶÂẤẦẨẪẬÉÈẺẼẸÊẾỀỂỄỆIÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴĐ]+$/;
      var FIRST_ENGLISH_REG = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁёáàảạãăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệiíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđÁÀẢẠÃĂẮẰẲẴẶÂẤẦẨẪẬÉÈẺẼẸÊẾỀỂỄỆIÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴĐ]/;
      function isUnicodeCJK(ch) {
        var __CHINESE_REG = /^[\u4E00-\u9FFF\u3400-\u4DFF]+$/;
        var __JAPANESE_REG = /[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g;
        var __KOREAN_REG = /^[\u1100-\u11FF]|[\u3130-\u318F]|[\uA960-\uA97F]|[\uAC00-\uD7AF]|[\uD7B0-\uD7FF]+$/;
        return __CHINESE_REG.test(ch) || __JAPANESE_REG.test(ch) || __KOREAN_REG.test(ch);
      }
      function isUnicodeSpace(ch) {
        var chCode = ch.charCodeAt(0);
        return chCode >= 9 && chCode <= 13 || chCode === 32 || chCode === 133 || chCode === 160 || chCode === 5760 || chCode >= 8192 && chCode <= 8202 || chCode === 8232 || chCode === 8233 || chCode === 8239 || chCode === 8287 || chCode === 12288;
      }
      function safeMeasureText(ctx, string, desc) {
        var font = desc || ctx.font;
        var key = font + "\uD83C\uDFAE" + string;
        var cache = measureCache.get(key);
        if (cache !== null) {
          return cache;
        }
        var metric = ctx.measureText(string);
        var width = metric && metric.width || 0;
        measureCache.put(key, width);
        return width;
      }
      function getSymbolLength(str) {
        var length = str.length;
        var count = 0;
        var charCode = 0;
        for (var i = 0; i < length; i++) {
          charCode = str.charCodeAt(i);
          if (charCode === 0x200d) {
            continue;
          }
          if (charCode >= 0xd800 && charCode <= 0xdbff) {
            charCode = str.charCodeAt(i + 1);
            if (charCode >= 0xdc00 && charCode <= 0xdfff) {
              if (i + 2 >= length || str.charCodeAt(i + 2) !== 0x200d) {
                count++;
              }
              i++;
              continue;
            }
          }
          count++;
        }
        return count;
      }
      function getSymbolAt(str, index) {
        var length = str.length;
        var len = 0;
        var count = 0;
        var start = 0;
        var charCode = 0;
        for (var i = 0; i < length; i++) {
          charCode = str.charCodeAt(i);
          if (charCode === 0x200d) {
            len++;
            continue;
          }
          if (charCode >= 0xd800 && charCode <= 0xdbff) {
            len++;
            charCode = str.charCodeAt(i + 1);
            if (charCode >= 0xdc00 && charCode <= 0xdfff) {
              len++;
              if (i + 2 >= length || str.charCodeAt(i + 2) !== 0x200d) {
                if (index === count) {
                  return str.slice(start, start + len);
                }
                start += len;
                count++;
                len = 0;
              }
              i++;
              continue;
            }
          }
          if (index === count) {
            return str.charAt(i);
          }
          start = i + 1;
          count++;
          len = 0;
        }
        return '';
      }
      function getSymbolCodeAt(str, index) {
        var _char = getSymbolAt(str, index);
        if (_char.length === 1) {
          return "" + _char.charCodeAt(0);
        }
        var charCodes = '';
        for (var j = 0; j < _char.length; j++) {
          charCodes += "" + _char.charCodeAt(j);
        }
        return "" + charCodes;
      }
      function getSymbolStartIndex(targetString, index) {
        if (index >= targetString.length) {
          return targetString.length;
        }
        var startCheckIndex = index;
        var startChar = targetString[startCheckIndex];
        while (startCheckIndex >= 0) {
          if (startChar === "\u200D") {
            startCheckIndex--;
            startChar = targetString[startCheckIndex];
          }
          if (startChar >= "\uDC00" && startChar <= "\uDFFF") {
            if (startCheckIndex - 1 >= 0) {
              startCheckIndex--;
              startChar = targetString[startCheckIndex];
            }
          }
          if (startChar >= "\uD800" && startChar <= "\uDBFF") {
            if (startCheckIndex - 1 >= 0 && targetString[startCheckIndex - 1] === "\u200D") {
              startCheckIndex--;
              startChar = targetString[startCheckIndex];
            } else {
              break;
            }
          } else {
            break;
          }
        }
        return startCheckIndex;
      }
      function getSymbolEndIndex(targetString, index) {
        var newEndIndex = index;
        var endCheckIndex = index;
        var endChar = targetString[endCheckIndex];
        while (endCheckIndex < targetString.length) {
          if (endChar === "\u200D") {
            endCheckIndex++;
            newEndIndex++;
            endChar = targetString[endCheckIndex];
            if (endChar >= "\uD800" && endChar <= "\uDBFF") {
              endCheckIndex++;
              newEndIndex++;
              endChar = targetString[endCheckIndex];
            }
          }
          if (endChar >= "\uD800" && endChar <= "\uDBFF") {
            endCheckIndex++;
            newEndIndex++;
            endChar = targetString[endCheckIndex];
          } else if (endChar >= "\uDC00" && endChar <= "\uDFFF") {
            endCheckIndex++;
            endChar = targetString[endCheckIndex];
            if (endCheckIndex < targetString.length && targetString[endCheckIndex] === "\u200D") {
              newEndIndex++;
              endChar = targetString[endCheckIndex];
            } else {
              break;
            }
          } else {
            break;
          }
        }
        return newEndIndex;
      }
      function _safeSubstring(targetString, startIndex, endIndex) {
        var newStartIndex = getSymbolStartIndex(targetString, startIndex);
        if (newStartIndex < startIndex) {
          newStartIndex = getSymbolEndIndex(targetString, startIndex) + 1;
        }
        var newEndIndex = endIndex;
        if (endIndex !== undefined) {
          endIndex = Math.max(0, endIndex - 1);
          newEndIndex = getSymbolEndIndex(targetString, endIndex);
          var newStartEndIndex = getSymbolStartIndex(targetString, endIndex);
          if (newStartEndIndex < newStartIndex || newStartEndIndex === newStartIndex && startIndex > newStartIndex) {
            newEndIndex = newStartIndex;
          } else {
            newEndIndex += 1;
          }
        }
        return targetString.substring(newStartIndex, newEndIndex);
      }
      function isEnglishWordPartAtFirst(stringToken) {
        return FIRST_ENGLISH_REG.test(stringToken);
      }
      function isEnglishWordPartAtLast(stringToken) {
        return LAST_ENGLISH_REG.test(stringToken);
      }
      function getEnglishWordPartAtFirst(stringToken) {
        var result = FIRST_ENGLISH_REG.exec(stringToken);
        return result;
      }
      function getEnglishWordPartAtLast(stringToken) {
        var result = LAST_ENGLISH_REG.exec(stringToken);
        return result;
      }
      function fragmentText(stringToken, allWidth, maxWidth, measureText) {
        var wrappedWords = [];
        if (stringToken.length === 0 || maxWidth < 0) {
          wrappedWords.push('');
          return wrappedWords;
        }
        var text = stringToken;
        while (allWidth > maxWidth && text.length > 1) {
          var fuzzyLen = text.length * (maxWidth / allWidth) | 0;
          var tmpText = _safeSubstring(text, fuzzyLen);
          var width = allWidth - measureText(tmpText);
          var sLine = tmpText;
          var pushNum = 0;
          var checkWhile = 0;
          var checkCount = 100;
          while (width > maxWidth && checkWhile++ < checkCount) {
            fuzzyLen *= maxWidth / width;
            fuzzyLen |= 0;
            tmpText = _safeSubstring(text, fuzzyLen);
            width = allWidth - measureText(tmpText);
          }
          checkWhile = 0;
          while (tmpText && width <= maxWidth && checkWhile++ < checkCount) {
            var exec = WORD_REG.exec(tmpText);
            pushNum = exec ? exec[0].length : 1;
            sLine = tmpText;
            fuzzyLen += pushNum;
            tmpText = _safeSubstring(text, fuzzyLen);
            width = allWidth - measureText(tmpText);
          }
          fuzzyLen -= pushNum;
          if (fuzzyLen === 0) {
            fuzzyLen = 1;
            sLine = _safeSubstring(text, 1);
          } else if (fuzzyLen === 1 && text[0] >= "\uD800" && text[0] <= "\uDBFF") {
            fuzzyLen = 2;
            sLine = _safeSubstring(text, 2);
          }
          var sText = _safeSubstring(text, 0, fuzzyLen);
          var result = void 0;
          {
            if (SYMBOL_REG.test(sLine || tmpText)) {
              result = LAST_WORD_REG.exec(sText);
              fuzzyLen -= result ? result[0].length : 0;
              if (fuzzyLen === 0) {
                fuzzyLen = 1;
              }
              sLine = _safeSubstring(text, fuzzyLen);
              sText = _safeSubstring(text, 0, fuzzyLen);
            }
          }
          if (FIRST_ENGLISH_REG.test(sLine)) {
            result = LAST_ENGLISH_REG.exec(sText);
            if (result && sText !== result[0]) {
              fuzzyLen -= result[0].length;
              sLine = _safeSubstring(text, fuzzyLen);
              sText = _safeSubstring(text, 0, fuzzyLen);
            }
          }
          if (wrappedWords.length === 0) {
            wrappedWords.push(sText);
          } else {
            sText = sText.trim();
            if (sText.length > 0) {
              wrappedWords.push(sText);
            }
          }
          text = sLine || tmpText;
          allWidth = measureText(text);
        }
        if (wrappedWords.length === 0) {
          wrappedWords.push(text);
        } else {
          text = text.trim();
          if (text.length > 0) {
            wrappedWords.push(text);
          }
        }
        return wrappedWords;
      }

      var ccdocument$4 = ccwindow.document;
      var _canvasContext = null;
      var _intervalId = -1;
      var _testString = "BES bswy:->@123\u4E01\u3041\u1101";
      var _fontFaces = Object.create(null);
      var _loadingFonts = [];
      var _timeout = 3000;
      var useNativeCheck = function () {
        var nativeCheck;
        return function () {
          if (nativeCheck === undefined) {
            if ('FontFace' in ccwindow) {
              var match = /Gecko.*Firefox\/(\d+)/.exec(ccwindow.navigator.userAgent);
              var safari10Match = /OS X.*Version\/10\..*Safari/.exec(ccwindow.navigator.userAgent) && /Apple/.exec(ccwindow.navigator.vendor);
              if (match) {
                nativeCheck = parseInt(match[1], 10) > 42;
              } else if (safari10Match) {
                nativeCheck = false;
              } else {
                nativeCheck = true;
              }
            } else {
              nativeCheck = false;
            }
          }
          return nativeCheck;
        };
      }();
      function checkFontLoaded() {
        var allFontsLoaded = true;
        var now = Date.now();
        for (var i = _loadingFonts.length - 1; i >= 0; i--) {
          var fontLoadHandle = _loadingFonts[i];
          var fontFamily = fontLoadHandle.fontFamilyName;
          if (now - fontLoadHandle.startTime > _timeout) {
            warnID(4933, fontFamily);
            fontLoadHandle.onComplete(null, fontFamily);
            _loadingFonts.splice(i, 1);
            continue;
          }
          var oldWidth = fontLoadHandle.refWidth;
          var fontDesc = "40px " + fontFamily;
          _canvasContext.font = fontDesc;
          var newWidth = safeMeasureText(_canvasContext, _testString, fontDesc);
          if (oldWidth !== newWidth) {
            _loadingFonts.splice(i, 1);
            fontLoadHandle.onComplete(null, fontFamily);
          } else {
            allFontsLoaded = false;
          }
        }
        if (allFontsLoaded) {
          clearInterval(_intervalId);
          _intervalId = -1;
        }
      }
      function nativeCheckFontLoaded(start, font, callback) {
        var loader = new Promise(function (resolve, reject) {
          var check = function check() {
            var now = Date.now();
            if (now - start >= _timeout) {
              reject();
            } else {
              ccdocument$4.fonts.load("40px " + font).then(function (fonts) {
                if (fonts.length >= 1) {
                  resolve();
                } else {
                  setTimeout(check, 100);
                }
              }, function () {
                reject();
              });
            }
          };
          check();
        });
        var timeoutId = null;
        var timer = new Promise(function (resolve, reject) {
          timeoutId = setTimeout(reject, _timeout);
        });
        Promise.race([timer, loader]).then(function () {
          if (timeoutId) {
            clearTimeout(timeoutId);
            timeoutId = null;
          }
          callback(null, font);
        }, function () {
          warnID(4933, font);
          callback(null, font);
        });
      }
      function loadFont(url, options, onComplete) {
        var fontFamilyName = getFontFamily(url);
        if (_fontFaces[fontFamilyName]) {
          onComplete(null, fontFamilyName);
          return;
        }
        if (!_canvasContext) {
          var labelCanvas = ccdocument$4.createElement('canvas');
          labelCanvas.width = 100;
          labelCanvas.height = 100;
          _canvasContext = labelCanvas.getContext('2d');
        }
        var fontDesc = "40px " + fontFamilyName;
        var fontStyle = ccdocument$4.createElement('style');
        fontStyle.type = 'text/css';
        var fontStr = '';
        if (Number.isNaN(fontFamilyName)) {
          fontStr += "@font-face { font-family:" + fontFamilyName + "; src:";
        } else {
          fontStr += "@font-face { font-family:\"" + fontFamilyName + "\"; src:";
        }
        fontStr += "url(\"" + url + "\");";
        fontStyle.textContent = fontStr + "}";
        ccdocument$4.body.appendChild(fontStyle);
        var preloadDiv = ccdocument$4.createElement('div');
        var divStyle = preloadDiv.style;
        divStyle.fontFamily = fontFamilyName;
        preloadDiv.innerHTML = '.';
        divStyle.position = 'absolute';
        divStyle.left = '-100px';
        divStyle.top = '-100px';
        ccdocument$4.body.appendChild(preloadDiv);
        if (useNativeCheck()) {
          nativeCheckFontLoaded(Date.now(), fontFamilyName, onComplete);
        } else {
          var refWidth = safeMeasureText(_canvasContext, _testString, fontDesc);
          var fontLoadHandle = {
            fontFamilyName: fontFamilyName,
            refWidth: refWidth,
            onComplete: onComplete,
            startTime: Date.now()
          };
          _loadingFonts.push(fontLoadHandle);
          if (_intervalId === -1) {
            _intervalId = setInterval(checkFontLoaded, 100);
          }
        }
        _fontFaces[fontFamilyName] = fontStyle;
      }
      function getFontFamily(fontHandle) {
        var ttfIndex = fontHandle.lastIndexOf('.ttf');
        if (ttfIndex === -1) {
          return fontHandle;
        }
        var slashPos = fontHandle.lastIndexOf('/');
        var fontFamilyName;
        if (slashPos === -1) {
          fontFamilyName = fontHandle.substring(0, ttfIndex) + "_LABEL";
        } else {
          fontFamilyName = fontHandle.substring(slashPos + 1, ttfIndex) + "_LABEL";
        }
        if (fontFamilyName.indexOf(' ') !== -1) {
          fontFamilyName = "\"" + fontFamilyName + "\"";
        }
        return fontFamilyName;
      }
      function createFont(id, data, options, onComplete) {
        var out = new TTFFont();
        out._nativeUrl = id;
        out._nativeAsset = data;
        onComplete(null, out);
      }
      downloader$1.register({
        '.font': loadFont,
        '.eot': loadFont,
        '.ttf': loadFont,
        '.woff': loadFont,
        '.svg': loadFont,
        '.ttc': loadFont
      });
      factory.register({
        '.font': createFont,
        '.eot': createFont,
        '.ttf': createFont,
        '.woff': createFont,
        '.svg': createFont,
        '.ttc': createFont
      });

      var eventRegx = /^(click)(\s)*=|(param)(\s)*=/;
      var imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*align(\s)*=|(\s)*offset(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/;
      var HtmlTextParser = exports('z', function () {
        function HtmlTextParser() {
          this._specialSymbolArray = [];
          this._stack = [];
          this._resultObjectArray = [];
          this._specialSymbolArray.push([/&lt;/g, '<']);
          this._specialSymbolArray.push([/&gt;/g, '>']);
          this._specialSymbolArray.push([/&amp;/g, '&']);
          this._specialSymbolArray.push([/&quot;/g, '"']);
          this._specialSymbolArray.push([/&apos;/g, '\'']);
        }
        var _proto = HtmlTextParser.prototype;
        _proto.parse = function parse(htmlString) {
          this._resultObjectArray.length = 0;
          this._stack.length = 0;
          var startIndex = 0;
          var length = htmlString.length;
          while (startIndex < length) {
            var tagEndIndex = htmlString.indexOf('>', startIndex);
            var tagBeginIndex = -1;
            if (tagEndIndex >= 0) {
              tagBeginIndex = htmlString.lastIndexOf('<', tagEndIndex);
              var noTagBegin = tagBeginIndex < startIndex - 1;
              if (noTagBegin) {
                tagBeginIndex = htmlString.indexOf('<', tagEndIndex + 1);
                tagEndIndex = htmlString.indexOf('>', tagBeginIndex + 1);
              }
            }
            if (tagBeginIndex < 0) {
              this._stack.pop();
              this._processResult(htmlString.substring(startIndex));
              startIndex = length;
            } else {
              var newStr = htmlString.substring(startIndex, tagBeginIndex);
              var tagStr = htmlString.substring(tagBeginIndex + 1, tagEndIndex);
              if (tagStr === '') newStr = htmlString.substring(startIndex, tagEndIndex + 1);
              this._processResult(newStr);
              if (tagEndIndex === -1) {
                tagEndIndex = tagBeginIndex;
              } else if (htmlString.charAt(tagBeginIndex + 1) === '/') {
                this._stack.pop();
              } else {
                this._addToStack(tagStr);
              }
              startIndex = tagEndIndex + 1;
            }
          }
          return this._resultObjectArray;
        };
        _proto._attributeToObject = function _attributeToObject(attribute) {
          attribute = attribute.trim();
          var obj = {};
          var header = /^(color|size)(\s)*=/.exec(attribute);
          var tagName = '';
          var nextSpace = 0;
          var eventHandlerString = '';
          if (header) {
            tagName = header[0];
            attribute = attribute.substring(tagName.length).trim();
            if (attribute === '') {
              return obj;
            }
            nextSpace = attribute.indexOf(' ');
            switch (tagName[0]) {
              case 'c':
                if (nextSpace > -1) {
                  obj.color = attribute.substring(0, nextSpace).trim();
                } else {
                  obj.color = attribute;
                }
                break;
              case 's':
                obj.size = parseInt(attribute);
                break;
            }
            if (nextSpace > -1) {
              eventHandlerString = attribute.substring(nextSpace + 1).trim();
              obj.event = this._processEventHandler(eventHandlerString);
            }
            return obj;
          }
          header = /^(br(\s)*\/)/.exec(attribute);
          if (header && header[0].length > 0) {
            tagName = header[0].trim();
            if (tagName.startsWith('br') && tagName[tagName.length - 1] === '/') {
              obj.isNewLine = true;
              this._resultObjectArray.push({
                text: '',
                style: {
                  isNewLine: true
                }
              });
              return obj;
            }
          }
          header = /^(img(\s)*src(\s)*=[^>]+\/)/.exec(attribute);
          var remainingArgument = '';
          var rightQuot = -1;
          if (header && header[0].length > 0) {
            tagName = header[0].trim();
            if (tagName.startsWith('img') && tagName[tagName.length - 1] === '/') {
              header = imageAttrReg.exec(attribute);
              var tagValue;
              var isValidImageTag = false;
              while (header) {
                attribute = attribute.substring(attribute.indexOf(header[0]));
                tagName = attribute.substr(0, header[0].length);
                var originTagNameLength = tagName.length;
                tagName = tagName.replace(/[^a-zA-Z]/g, '').trim();
                tagName = tagName.toLowerCase();
                remainingArgument = attribute.substring(originTagNameLength).trim();
                if (tagName === 'src') {
                  rightQuot = this.getRightQuotationIndex(remainingArgument);
                } else {
                  rightQuot = -1;
                }
                nextSpace = remainingArgument.indexOf(' ', rightQuot + 1 >= remainingArgument.length ? -1 : rightQuot + 1);
                tagValue = nextSpace > -1 ? remainingArgument.substr(0, nextSpace) : remainingArgument;
                attribute = remainingArgument.substring(nextSpace).trim();
                if (tagValue.endsWith('/')) {
                  tagValue = tagValue.slice(0, -1);
                }
                if (tagName === 'src') {
                  switch (tagValue.charCodeAt(0)) {
                    case 34:
                    case 39:
                      isValidImageTag = true;
                      tagValue = tagValue.slice(1, -1);
                      break;
                  }
                  obj.isImage = true;
                  obj.src = tagValue;
                } else if (tagName === 'height') {
                  obj.imageHeight = parseInt(tagValue);
                } else if (tagName === 'width') {
                  obj.imageWidth = parseInt(tagValue);
                } else if (tagName === 'align') {
                  switch (tagValue.charCodeAt(0)) {
                    case 34:
                    case 39:
                      tagValue = tagValue.slice(1, -1);
                      break;
                  }
                  obj.imageAlign = tagValue.toLowerCase();
                } else if (tagName === 'offset') {
                  obj.imageOffset = tagValue;
                } else if (tagName === 'click') {
                  obj.event = this._processEventHandler(tagName + "=" + tagValue);
                }
                if (obj.event && tagName === 'param') {
                  obj.event[tagName] = tagValue.replace(/^"|"$/g, '');
                }
                header = imageAttrReg.exec(attribute);
              }
              if (isValidImageTag && obj.isImage) {
                this._resultObjectArray.push({
                  text: '',
                  style: obj
                });
              }
              return {};
            }
          }
          header = /^(outline(\s)*[^>]*)/.exec(attribute);
          if (header) {
            attribute = header[0].substring('outline'.length).trim();
            var defaultOutlineObject = {
              color: '#ffffff',
              width: 1
            };
            if (attribute) {
              var outlineAttrReg = /(\s)*color(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/;
              header = outlineAttrReg.exec(attribute);
              var _tagValue;
              while (header) {
                attribute = attribute.substring(attribute.indexOf(header[0]));
                tagName = attribute.substr(0, header[0].length);
                remainingArgument = attribute.substring(tagName.length).trim();
                nextSpace = remainingArgument.indexOf(' ');
                if (nextSpace > -1) {
                  _tagValue = remainingArgument.substr(0, nextSpace);
                } else {
                  _tagValue = remainingArgument;
                }
                tagName = tagName.replace(/[^a-zA-Z]/g, '').trim();
                tagName = tagName.toLowerCase();
                attribute = remainingArgument.substring(nextSpace).trim();
                if (tagName === 'click') {
                  obj.event = this._processEventHandler(tagName + "=" + _tagValue);
                } else if (tagName === 'color') {
                  defaultOutlineObject.color = _tagValue;
                } else if (tagName === 'width') {
                  defaultOutlineObject.width = parseInt(_tagValue);
                }
                if (obj.event && tagName === 'param') {
                  obj.event[tagName] = _tagValue.replace(/^"|"$/g, '');
                }
                header = outlineAttrReg.exec(attribute);
              }
            }
            obj.outline = defaultOutlineObject;
          }
          header = /^(on|u|b|i)(\s)*/.exec(attribute);
          if (header && header[0].length > 0) {
            tagName = header[0];
            attribute = attribute.substring(tagName.length).trim();
            switch (tagName[0]) {
              case 'u':
                obj.underline = true;
                break;
              case 'i':
                obj.italic = true;
                break;
              case 'b':
                obj.bold = true;
                break;
            }
            if (attribute === '') {
              return obj;
            }
            obj.event = this._processEventHandler(attribute);
          }
          return obj;
        };
        _proto.getRightQuotationIndex = function getRightQuotationIndex(remainingArgument) {
          var leftQuot = -1;
          var rightQuot = -1;
          var leftSingleQuot = remainingArgument.indexOf('\'');
          var leftDoubleQuot = remainingArgument.indexOf('"');
          var useSingleQuot = leftSingleQuot > -1 && (leftSingleQuot < leftDoubleQuot || leftDoubleQuot === -1);
          var useDoubleQuot = leftDoubleQuot > -1 && (leftDoubleQuot < leftSingleQuot || leftSingleQuot === -1);
          if (useSingleQuot) {
            leftQuot = leftSingleQuot;
            rightQuot = remainingArgument.indexOf('\'', leftQuot + 1 >= remainingArgument.length ? -1 : leftQuot + 1);
          } else if (useDoubleQuot) {
            leftQuot = leftDoubleQuot;
            rightQuot = remainingArgument.indexOf('"', leftQuot + 1 >= remainingArgument.length ? -1 : leftQuot + 1);
          }
          return rightQuot;
        };
        _proto._processEventHandler = function _processEventHandler(eventString) {
          var obj = {};
          var index = 0;
          var isValidTag = false;
          var eventNames = eventRegx.exec(eventString);
          while (eventNames) {
            var eventName = eventNames[0];
            var eventValue = '';
            isValidTag = false;
            eventString = eventString.substring(eventName.length).trim();
            if (eventString.charAt(0) === '"') {
              index = eventString.indexOf('"', 1);
              if (index > -1) {
                eventValue = eventString.substring(1, index).trim();
                isValidTag = true;
              }
              index++;
            } else if (eventString.charAt(0) === '\'') {
              index = eventString.indexOf('\'', 1);
              if (index > -1) {
                eventValue = eventString.substring(1, index).trim();
                isValidTag = true;
              }
              index++;
            } else {
              var match = /(\S)+/.exec(eventString);
              if (match) {
                eventValue = match[0];
              } else {
                eventValue = '';
              }
              index = eventValue.length;
            }
            if (isValidTag) {
              eventName = eventName.substring(0, eventName.length - 1).trim();
              obj[eventName] = eventValue;
            }
            eventString = eventString.substring(index).trim();
            eventNames = eventRegx.exec(eventString);
          }
          return obj;
        };
        _proto._addToStack = function _addToStack(attribute) {
          var obj = this._attributeToObject(attribute);
          if (this._stack.length === 0) {
            this._stack.push(obj);
          } else {
            if (obj.isNewLine || obj.isImage) {
              return;
            }
            var previousTagObj = this._stack[this._stack.length - 1];
            for (var key in previousTagObj) {
              if (!obj[key]) {
                obj[key] = previousTagObj[key];
              }
            }
            this._stack.push(obj);
          }
        };
        _proto._processResult = function _processResult(value) {
          if (value.length === 0) {
            return;
          }
          value = this._escapeSpecialSymbol(value);
          if (this._stack.length > 0) {
            this._resultObjectArray.push({
              text: value,
              style: this._stack[this._stack.length - 1]
            });
          } else {
            this._resultObjectArray.push({
              text: value
            });
          }
        };
        _proto._escapeSpecialSymbol = function _escapeSpecialSymbol(str) {
          for (var _iterator = _createForOfIteratorHelperLoose(this._specialSymbolArray), _step; !(_step = _iterator()).done;) {
            var symbolArr = _step.value;
            var key = symbolArr[0];
            var value = symbolArr[1];
            str = str.replace(key, value);
          }
          return str;
        };
        return HtmlTextParser;
      }());

      var _dec$2Z, _dec2$2j, _class2$2D, _class3$M, _initializer$2u, _initializer2$24, _initializer3$1x, _initializer4$1k;
      var FontLetterDefinition$1 = function FontLetterDefinition() {
        this.u = 0;
        this.v = 0;
        this.w = 0;
        this.h = 0;
        this.offsetX = 0;
        this.offsetY = 0;
        this.textureID = 0;
        this.valid = false;
        this.xAdvance = 0;
      };
      var FontAtlas = function () {
        function FontAtlas(texture) {
          this.letterDefinitions = {};
          this.texture = texture;
        }
        var _proto = FontAtlas.prototype;
        _proto.addLetterDefinitions = function addLetterDefinitions(letter, letterDefinition) {
          this.letterDefinitions[letter] = letterDefinition;
        };
        _proto.cloneLetterDefinition = function cloneLetterDefinition() {
          var copyLetterDefinitions = {};
          for (var _i = 0, _Object$keys = Object.keys(this.letterDefinitions); _i < _Object$keys.length; _i++) {
            var _key = _Object$keys[_i];
            var value = new FontLetterDefinition$1();
            mixin(value, this.letterDefinitions[_key]);
            copyLetterDefinitions[_key] = value;
          }
          return copyLetterDefinitions;
        };
        _proto.getTexture = function getTexture() {
          return this.texture;
        };
        _proto.getLetter = function getLetter(key) {
          return this.letterDefinitions[key];
        };
        _proto.getLetterDefinitionForChar = function getLetterDefinitionForChar(_char, labelInfo) {
          var key = getSymbolCodeAt(_char, 0);
          var hasKey = this.letterDefinitions.hasOwnProperty(key);
          var letter;
          if (hasKey) {
            letter = this.letterDefinitions[key];
          } else {
            letter = null;
          }
          return letter;
        };
        _proto.clear = function clear() {
          this.letterDefinitions = {};
        };
        return FontAtlas;
      }();
      var BitmapFont = exports('B', (_dec$2Z = ccclass$M('cc.BitmapFont'), _dec2$2j = type$d(SpriteFrame), _dec$2Z(_class2$2D = (_class3$M = function (_Font) {
        _inheritsLoose(BitmapFont, _Font);
        function BitmapFont() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this = _Font.call.apply(_Font, [this].concat(args)) || this;
          _this.fntDataStr = _initializer$2u && _initializer$2u();
          _this.spriteFrame = _initializer2$24 && _initializer2$24();
          _this.fontSize = _initializer3$1x && _initializer3$1x();
          _this.fntConfig = _initializer4$1k && _initializer4$1k();
          return _this;
        }
        var _proto2 = BitmapFont.prototype;
        _proto2.onLoaded = function onLoaded() {
          var spriteFrame = this.spriteFrame;
          if (!this.fontDefDictionary && spriteFrame) {
            this.fontDefDictionary = new FontAtlas(spriteFrame.texture);
          }
          var fntConfig = this.fntConfig;
          if (!fntConfig) {
            warn('The fnt config is not exists!');
            return;
          }
          var fontDict = fntConfig.fontDefDictionary;
          for (var fontDef in fontDict) {
            var letter = new FontLetterDefinition$1();
            var rect = fontDict[fontDef].rect;
            letter.offsetX = fontDict[fontDef].xOffset;
            letter.offsetY = fontDict[fontDef].yOffset;
            letter.w = rect.width;
            letter.h = rect.height;
            letter.u = rect.x;
            letter.v = rect.y;
            letter.textureID = 0;
            letter.valid = true;
            letter.xAdvance = fontDict[fontDef].xAdvance;
            this.fontDefDictionary.addLetterDefinitions(fontDef, letter);
          }
        };
        return BitmapFont;
      }(Font), (_initializer$2u = applyDecoratedInitializer(_class3$M.prototype, "fntDataStr", [serializable$p], function () {
        return '';
      }), _initializer2$24 = applyDecoratedInitializer(_class3$M.prototype, "spriteFrame", [_dec2$2j], function () {
        return null;
      }), _initializer3$1x = applyDecoratedInitializer(_class3$M.prototype, "fontSize", [serializable$p], function () {
        return -1;
      }), _initializer4$1k = applyDecoratedInitializer(_class3$M.prototype, "fntConfig", [serializable$p], function () {
        return null;
      })), _class3$M)) || _class2$2D));
      legacyCC.BitmapFont = BitmapFont;

      var _dec$2Y, _class$2W;
      var LabelAtlas = exports('L', (_dec$2Y = ccclass$M('cc.LabelAtlas'), _dec$2Y(_class$2W = function (_BitmapFont) {
        _inheritsLoose(LabelAtlas, _BitmapFont);
        function LabelAtlas() {
          return _BitmapFont.apply(this, arguments) || this;
        }
        return LabelAtlas;
      }(BitmapFont)) || _class$2W));
      legacyCC.LabelAtlas = LabelAtlas;

      var _canvasPool;
      var CanvasPool = function () {
        function CanvasPool() {
          this.pool = [];
        }
        CanvasPool.getInstance = function getInstance() {
          if (!_canvasPool) {
            _canvasPool = new CanvasPool();
          }
          return _canvasPool;
        };
        var _proto = CanvasPool.prototype;
        _proto.get = function get() {
          var data = this.pool.pop();
          if (!data) {
            var canvas = ccwindow.document.createElement('canvas');
            var context = canvas.getContext('2d');
            data = {
              canvas: canvas,
              context: context
            };
          }
          return data;
        };
        _proto.put = function put(canvas) {
          if (this.pool.length >= macro.MAX_LABEL_CANVAS_POOL_SIZE) {
            return;
          }
          this.pool.push(canvas);
        };
        return CanvasPool;
      }();
      var WHITE$1 = Color$1.WHITE.clone();
      var space = 0;
      var bleed = 2;
      var FontLetterDefinition = function FontLetterDefinition() {
        this.u = 0;
        this.v = 0;
        this.w = 0;
        this.h = 0;
        this.texture = null;
        this.offsetX = 0;
        this.offsetY = 0;
        this.valid = false;
        this.xAdvance = 0;
      };
      var _backgroundStyle = "rgba(255, 255, 255, " + (1 / 255).toFixed(3) + ")";
      var BASELINE_OFFSET = getBaselineOffset();
      var LetterTexture = function () {
        function LetterTexture(_char, labelInfo) {
          this.image = null;
          this.labelInfo = void 0;
          this["char"] = void 0;
          this.data = null;
          this.canvas = null;
          this.context = null;
          this.width = 0;
          this.height = 0;
          this.offsetY = 0;
          this.hash = void 0;
          this["char"] = _char;
          this.labelInfo = labelInfo;
          this.hash = "" + getSymbolCodeAt(_char, 0) + labelInfo.hash;
        }
        var _proto2 = LetterTexture.prototype;
        _proto2.updateRenderData = function updateRenderData() {
          this._updateProperties();
          this._updateTexture();
        };
        _proto2.destroy = function destroy() {
          this.image = null;
          CanvasPool.getInstance().put(this.data);
        };
        _proto2._updateProperties = function _updateProperties() {
          this.data = CanvasPool.getInstance().get();
          this.canvas = this.data.canvas;
          this.context = this.data.context;
          if (this.context) {
            var fontScale = this.labelInfo.fontScale;
            this.context.font = this.labelInfo.fontDesc;
            var width = safeMeasureText(this.context, this["char"], this.labelInfo.fontDesc);
            var blank = this.labelInfo.margin * 2 + bleed;
            this.width = parseFloat(width.toFixed(2)) * fontScale + blank;
            this.height = (1 + BASELINE_RATIO) * this.labelInfo.fontSize * fontScale + blank;
            this.offsetY = -(this.labelInfo.fontSize * BASELINE_RATIO) * fontScale / 2;
          }
          if (this.canvas.width !== this.width) {
            this.canvas.width = this.width;
          }
          if (this.canvas.height !== this.height) {
            this.canvas.height = this.height;
          }
          if (!this.image) {
            this.image = new ImageAsset();
          }
          this.image.reset(this.canvas);
        };
        _proto2._updateTexture = function _updateTexture() {
          if (!this.context || !this.canvas) {
            return;
          }
          var context = this.context;
          var labelInfo = this.labelInfo;
          var width = this.canvas.width;
          var height = this.canvas.height;
          var fontScale = labelInfo.fontScale;
          context.textAlign = 'center';
          context.textBaseline = 'alphabetic';
          context.clearRect(0, 0, width, height);
          context.fillStyle = _backgroundStyle;
          context.fillRect(0, 0, width, height);
          context.font = labelInfo.fontDesc.replace(/(\d+)(\.\d+)?(px|em|rem|pt)/g, function (w, m, n, u) {
            return (+m * fontScale + (+n || 0) * fontScale).toString() + u;
          });
          var fontSize = labelInfo.fontSize * fontScale;
          var startX = width / 2;
          var startY = height / 2 + fontSize * MIDDLE_RATIO + fontSize * BASELINE_OFFSET;
          var color = labelInfo.color;
          context.lineJoin = 'round';
          context.fillStyle = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", " + 1 + ")";
          if (labelInfo.isOutlined) {
            var strokeColor = labelInfo.out || WHITE$1;
            context.strokeStyle = "rgba(" + strokeColor.r + ", " + strokeColor.g + ", " + strokeColor.b + ", " + strokeColor.a / 255 + ")";
            context.lineWidth = labelInfo.margin * 2 * fontScale;
            context.strokeText(this["char"], startX, startY);
          }
          context.fillText(this["char"], startX, startY);
        };
        return LetterTexture;
      }();
      var LetterRenderTexture = function (_Texture2D) {
        _inheritsLoose(LetterRenderTexture, _Texture2D);
        function LetterRenderTexture() {
          return _Texture2D.apply(this, arguments) || this;
        }
        var _proto3 = LetterRenderTexture.prototype;
        _proto3.initWithSize = function initWithSize(width, height, format) {
          if (format === void 0) {
            format = PixelFormat.RGBA8888;
          }
          this.reset({
            width: width,
            height: height,
            format: format
          });
        };
        _proto3.drawTextureAt = function drawTextureAt(image, x, y) {
          var gfxTexture = this.getGFXTexture();
          if (!image || !gfxTexture) {
            return;
          }
          var gfxDevice = this._getGFXDevice();
          if (!gfxDevice) {
            log('Unable to get device');
            return;
          }
          var region = new BufferTextureCopy();
          region.texOffset.x = x;
          region.texOffset.y = y;
          region.texExtent.width = image.width;
          region.texExtent.height = image.height;
          gfxDevice.copyTexImagesToTexture([image.data], gfxTexture, [region]);
        };
        return LetterRenderTexture;
      }(Texture2D);
      var LetterAtlas = function () {
        function LetterAtlas(width, height) {
          this._x = space;
          this._y = space;
          this._nextY = space;
          this._width = 0;
          this._height = 0;
          this._halfBleed = 0;
          this._dirty = false;
          var texture = new LetterRenderTexture();
          texture.initWithSize(width, height);
          this.fontDefDictionary = new FontAtlas(texture);
          this._halfBleed = bleed / 2;
          this._width = width;
          this._height = height;
          director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this);
        }
        var _proto4 = LetterAtlas.prototype;
        _proto4.insertLetterTexture = function insertLetterTexture(letterTexture) {
          var texture = letterTexture.image;
          var device = director.root.device;
          if (!texture || !this.fontDefDictionary || !device) {
            return null;
          }
          var width = texture.width;
          var height = texture.height;
          if (this._x + width + space > this._width) {
            this._x = space;
            this._y = this._nextY;
          }
          if (this._y + height > this._nextY) {
            this._nextY = this._y + height + space;
          }
          if (this._nextY > this._height) {
            warnID(12100);
            return null;
          }
          this.fontDefDictionary.texture.drawTextureAt(texture, this._x, this._y);
          this._dirty = true;
          var letterDefinition = new FontLetterDefinition();
          letterDefinition.u = this._x + this._halfBleed;
          letterDefinition.v = this._y + this._halfBleed;
          letterDefinition.texture = this.fontDefDictionary.texture;
          letterDefinition.valid = true;
          letterDefinition.w = letterTexture.width - bleed;
          letterDefinition.h = letterTexture.height - bleed;
          letterDefinition.xAdvance = letterDefinition.w;
          letterDefinition.offsetY = letterTexture.offsetY;
          this._x += width + space;
          this.fontDefDictionary.addLetterDefinitions(letterTexture.hash, letterDefinition);
          return letterDefinition;
        };
        _proto4.update = function update() {
          if (!this._dirty) {
            return;
          }
          this._dirty = false;
        };
        _proto4.reset = function reset() {
          this._x = space;
          this._y = space;
          this._nextY = space;
          this.fontDefDictionary.clear();
        };
        _proto4.destroy = function destroy() {
          this.reset();
          if (this.fontDefDictionary) {
            this.fontDefDictionary.texture.destroy();
            this.fontDefDictionary.texture = null;
          }
        };
        _proto4.getTexture = function getTexture() {
          return this.fontDefDictionary.getTexture();
        };
        _proto4.beforeSceneLoad = function beforeSceneLoad() {
          this.clearAllCache();
        };
        _proto4.clearAllCache = function clearAllCache() {
          this.destroy();
          var texture = new LetterRenderTexture();
          texture.initWithSize(this._width, this._height);
          this.fontDefDictionary.texture = texture;
        };
        _proto4.getLetter = function getLetter(key) {
          return this.fontDefDictionary.letterDefinitions[key];
        };
        _proto4.getLetterDefinitionForChar = function getLetterDefinitionForChar(_char2, labelInfo) {
          var hash = getSymbolCodeAt(_char2, 0) + labelInfo.hash;
          var letter = this.fontDefDictionary.letterDefinitions[hash];
          if (!letter) {
            var temp = new LetterTexture(_char2, labelInfo);
            temp.updateRenderData();
            letter = this.insertLetterTexture(temp);
            temp.destroy();
          }
          return letter;
        };
        _createClass(LetterAtlas, [{
          key: "width",
          get: function get() {
            return this._width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          }
        }]);
        return LetterAtlas;
      }();
      var shareLabelInfo = {
        fontAtlas: null,
        fontSize: 0,
        lineHeight: 0,
        hAlign: 0,
        vAlign: 0,
        hash: '',
        fontFamily: '',
        fontDesc: 'Arial',
        color: Color$1.WHITE.clone(),
        isOutlined: false,
        out: Color$1.WHITE.clone(),
        margin: 0,
        fontScale: 1
      };
      function computeHash(labelInfo) {
        var hashData = '';
        var color = labelInfo.color.toHEX();
        var out = '';
        if (labelInfo.isOutlined && labelInfo.margin > 0) {
          out = out + labelInfo.margin + labelInfo.out.toHEX();
        }
        return hashData + labelInfo.fontSize + labelInfo.fontFamily + color + out;
      }

      var vfmt = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F)];
      var vfmtPosColor = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F)];
      var vfmtPosUvColor = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F)];
      var vfmtPosUvColor4B = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true)];
      var vfmtPosUvTwoColor = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F), new Attribute(AttributeName.ATTR_COLOR2, Format.RGBA32F)];
      var vfmtPosUvTwoColor4B = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true), new Attribute(AttributeName.ATTR_COLOR2, Format.RGBA8, true)];
      function getComponentPerVertex(attrs) {
        var count = 0;
        for (var i = 0; i < attrs.length; i++) {
          var attr = attrs[i];
          var info = FormatInfos[attr.format];
          count += info.count;
        }
        return count;
      }
      function getAttributeStride(attrs) {
        var count = 0;
        for (var i = 0; i < attrs.length; i++) {
          var attr = attrs[i];
          var info = FormatInfos[attr.format];
          count += info.size;
        }
        return count;
      }
      legacyCC.internal.vfmtPosUvColor = vfmtPosUvColor;
      legacyCC.internal.vfmtPosUvTwoColor = vfmtPosUvTwoColor;
      legacyCC.internal.vfmtPosUvColor4B = vfmtPosUvColor4B;
      legacyCC.internal.vfmtPosUvTwoColor4B = vfmtPosUvTwoColor4B;

      var vertexFormat = /*#__PURE__*/Object.freeze({
        __proto__: null,
        vfmt: vfmt,
        vfmtPosColor: vfmtPosColor,
        vfmtPosUvColor: vfmtPosUvColor,
        vfmtPosUvColor4B: vfmtPosUvColor4B,
        vfmtPosUvTwoColor: vfmtPosUvTwoColor,
        vfmtPosUvTwoColor4B: vfmtPosUvTwoColor4B,
        getComponentPerVertex: getComponentPerVertex,
        getAttributeStride: getAttributeStride
      });
      exports('w', vertexFormat);

      var MeshBufferSharedBufferView;
      (function (MeshBufferSharedBufferView) {
        MeshBufferSharedBufferView[MeshBufferSharedBufferView["byteOffset"] = 0] = "byteOffset";
        MeshBufferSharedBufferView[MeshBufferSharedBufferView["vertexOffset"] = 1] = "vertexOffset";
        MeshBufferSharedBufferView[MeshBufferSharedBufferView["indexOffset"] = 2] = "indexOffset";
        MeshBufferSharedBufferView[MeshBufferSharedBufferView["dirty"] = 3] = "dirty";
        MeshBufferSharedBufferView[MeshBufferSharedBufferView["count"] = 4] = "count";
      })(MeshBufferSharedBufferView || (MeshBufferSharedBufferView = {}));
      var IA_POOL_USED_SCALE = 1 / 2;
      var MeshBuffer = exports('M', function () {
        var _proto = MeshBuffer.prototype;
        _proto.initSharedBuffer = function initSharedBuffer() {
        };
        _proto.syncSharedBufferToNative = function syncSharedBufferToNative() {
        };
        function MeshBuffer() {
          this._byteOffset = 0;
          this._vertexOffset = 0;
          this._indexOffset = 0;
          this._dirty = false;
          this._floatsPerVertex = 0;
          this._vData = null;
          this._iData = null;
          this._vertexFormatBytes = 0;
          this._initVDataCount = 0;
          this._initIDataCount = 0;
          this._attributes = null;
          this._iaPool = [];
          this._iaInfo = null;
          this._nextFreeIAHandle = 0;
          this.initSharedBuffer();
          this.syncSharedBufferToNative();
        }
        _proto.initialize = function initialize(device, attrs, vFloatCount, iCount) {
          this._initVDataCount = vFloatCount;
          this._initIDataCount = iCount;
          this._attributes = attrs;
          this.floatsPerVertex = getAttributeStride(attrs) >> 2;
          assertIsTrue(this._initVDataCount / this._floatsPerVertex < 65536, getError(9005));
          if (!this.vData || !this.iData) {
            this.vData = new Float32Array(this._initVDataCount);
            this.iData = new Uint16Array(this._initIDataCount);
          }
          this._iaPool.push(this.createNewIA(device));
        };
        _proto.reset = function reset() {
          this._nextFreeIAHandle = 0;
          this.dirty = false;
        };
        _proto.destroy = function destroy() {
          this.reset();
          this._attributes = null;
          this._iaInfo = null;
          this.vData = null;
          this.iData = null;
          for (var i = 0; i < this._iaPool.length; ++i) {
            var iaRef = this._iaPool[i];
            if (iaRef.vertexBuffers[0]) {
              iaRef.vertexBuffers[0].destroy();
            }
            if (iaRef.indexBuffer) {
              iaRef.indexBuffer.destroy();
            }
            iaRef.ia.destroy();
          }
          this._iaPool.length = 0;
        };
        _proto.setDirty = function setDirty() {
          this.dirty = true;
        };
        _proto.request = function request(vertexCount, indexCount) {
          warnID(9002);
          return false;
        };
        _proto.requireFreeIA = function requireFreeIA(device) {
          if (this._iaPool.length <= this._nextFreeIAHandle) {
            this._iaPool.push(this.createNewIA(device));
          }
          var ia = this._iaPool[this._nextFreeIAHandle++].ia;
          return ia;
        };
        _proto.recycleIA = function recycleIA(ia) {
          var pool = this._iaPool;
          for (var i = 0; i < this._nextFreeIAHandle; ++i) {
            if (ia === pool[i].ia) {
              var iaRef = pool[i];
              pool[i] = pool[--this._nextFreeIAHandle];
              pool[this._nextFreeIAHandle] = iaRef;
              return;
            }
          }
        };
        _proto.checkCapacity = function checkCapacity(vertexCount, indexCount) {
          var maxVertex = (this.vertexOffset + vertexCount) * this._floatsPerVertex;
          var maxIndex = this.indexOffset + indexCount;
          if (maxVertex > this._initVDataCount || maxIndex > this._initIDataCount) {
            return false;
          }
          return true;
        };
        _proto.uploadBuffers = function uploadBuffers() {
          if (this.byteOffset === 0 || !this._dirty) {
            return;
          }
          var iOS14 = sys.__isWebIOS14OrIPadOS14Env;
          var submitCount = iOS14 ? this._nextFreeIAHandle : 1;
          if (iOS14 && submitCount / this._iaPool.length < IA_POOL_USED_SCALE) {
            var count = submitCount / IA_POOL_USED_SCALE;
            var length = this._iaPool.length;
            for (var i = length - 1; i >= count; i--) {
              var iaRef = this._iaPool[i];
              if (iaRef.vertexBuffers[0]) {
                iaRef.vertexBuffers[0].destroy();
              }
              if (iaRef.indexBuffer) {
                iaRef.indexBuffer.destroy();
              }
              iaRef.ia.destroy();
            }
            this._iaPool.length = count;
          }
          var byteCount = this.byteOffset;
          var indexCount = this.indexOffset;
          for (var _i = 0; _i < submitCount; ++_i) {
            var _iaRef = this._iaPool[_i];
            var verticesData = new Float32Array(this.vData.buffer, 0, byteCount >> 2);
            var indicesData = new Uint16Array(this.iData.buffer, 0, indexCount);
            var vertexBuffer = _iaRef.vertexBuffers[0];
            if (byteCount > vertexBuffer.size) {
              vertexBuffer.resize(byteCount);
            }
            vertexBuffer.update(verticesData);
            if (indexCount * 2 > _iaRef.indexBuffer.size) {
              _iaRef.indexBuffer.resize(indexCount * 2);
            }
            _iaRef.indexBuffer.update(indicesData);
          }
          this.dirty = false;
        };
        _proto.createNewIA = function createNewIA(device) {
          var ia;
          var vertexBuffers;
          var indexBuffer;
          if (sys.__isWebIOS14OrIPadOS14Env || !this._iaPool[0]) {
            var vbStride = this._vertexFormatBytes = this._floatsPerVertex * Float32Array.BYTES_PER_ELEMENT;
            var ibStride = Uint16Array.BYTES_PER_ELEMENT;
            var vertexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, vbStride, vbStride));
            indexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, ibStride, ibStride));
            vertexBuffers = [vertexBuffer];
            this._iaInfo = new InputAssemblerInfo(this._attributes, vertexBuffers, indexBuffer);
            ia = device.createInputAssembler(this._iaInfo);
          } else {
            ia = device.createInputAssembler(this._iaInfo);
            vertexBuffers = this._iaInfo.vertexBuffers;
            indexBuffer = this._iaInfo.indexBuffer;
          }
          return {
            ia: ia,
            vertexBuffers: vertexBuffers,
            indexBuffer: indexBuffer
          };
        };
        _createClass(MeshBuffer, [{
          key: "attributes",
          get: function get() {
            return this._attributes;
          }
        }, {
          key: "vertexFormatBytes",
          get: function get() {
            return this._vertexFormatBytes;
          }
        }, {
          key: "byteOffset",
          get: function get() {
            return this._byteOffset;
          },
          set: function set(val) {
            this._byteOffset = val;
          }
        }, {
          key: "vertexOffset",
          get: function get() {
            return this._vertexOffset;
          },
          set: function set(val) {
            this._vertexOffset = val;
          }
        }, {
          key: "indexOffset",
          get: function get() {
            return this._indexOffset;
          },
          set: function set(val) {
            this._indexOffset = val;
          }
        }, {
          key: "dirty",
          get: function get() {
            return this._dirty;
          },
          set: function set(val) {
            this._dirty = val;
          }
        }, {
          key: "floatsPerVertex",
          get: function get() {
            return this._floatsPerVertex;
          },
          set: function set(val) {
            this._floatsPerVertex = val;
          }
        }, {
          key: "vData",
          get: function get() {
            return this._vData;
          },
          set: function set(val) {
            this._vData = val;
          }
        }, {
          key: "iData",
          get: function get() {
            return this._iData;
          },
          set: function set(val) {
            this._iData = val;
          }
        }, {
          key: "nativeObj",
          get: function get() {
            return this._nativeObj;
          }
        }, {
          key: "sharedBuffer",
          get: function get() {
            return this._sharedBuffer;
          }
        }]);
        return MeshBuffer;
      }());

      var BufferAccessor = function () {
        function BufferAccessor(device, attributes) {
          this._device = null;
          this._attributes = null;
          this._vertexFormatBytes = void 0;
          this._floatsPerVertex = void 0;
          this._buffers = [];
          this._device = device;
          this._attributes = attributes;
          this._floatsPerVertex = getAttributeStride(attributes) >> 2;
          this._vertexFormatBytes = this._floatsPerVertex * Float32Array.BYTES_PER_ELEMENT;
        }
        var _proto = BufferAccessor.prototype;
        _proto.initialize = function initialize() {};
        _proto.reset = function reset() {};
        _proto.request = function request(vertexCount, indexCount) {
        };
        _proto.appendBuffers = function appendBuffers(vertices, indices) {};
        _proto.uploadBuffers = function uploadBuffers() {};
        _proto.destroy = function destroy() {
          this._attributes.length = 0;
        };
        _createClass(BufferAccessor, [{
          key: "attributes",
          get: function get() {
            return this._attributes;
          }
        }, {
          key: "vertexFormatBytes",
          get: function get() {
            return this._vertexFormatBytes;
          }
        }, {
          key: "floatsPerVertex",
          get: function get() {
            return this._floatsPerVertex;
          }
        }]);
        return BufferAccessor;
      }();

      var _entryPool = new Pool(function () {
        return {
          offset: 0,
          length: 0
        };
      }, 32);
      var StaticVBChunk = function () {
        function StaticVBChunk(vertexAccessor, bufferId, meshBuffer, vertexOffset, vb, indexCount) {
          this._ib = void 0;
          this.vertexAccessor = vertexAccessor;
          this.bufferId = bufferId;
          this.meshBuffer = meshBuffer;
          this.vertexOffset = vertexOffset;
          this.vb = vb;
          this.indexCount = indexCount;
          this._ib = new Uint16Array(indexCount);
          assertIsTrue(meshBuffer === vertexAccessor.getMeshBuffer(bufferId));
        }
        var _proto = StaticVBChunk.prototype;
        _proto.setIndexBuffer = function setIndexBuffer(indices) {
        };
        _createClass(StaticVBChunk, [{
          key: "ib",
          get: function get() {
            return this._ib;
          }
        }]);
        return StaticVBChunk;
      }();
      var StaticVBAccessor = function (_BufferAccessor) {
        _inheritsLoose(StaticVBAccessor, _BufferAccessor);
        function StaticVBAccessor(device, attributes, vCount, iCount) {
          var _this;
          _this = _BufferAccessor.call(this, device, attributes) || this;
          _this._freeLists = [];
          _this._vCount = 0;
          _this._iCount = 0;
          _this._id = 0;
          _this._vCount = vCount || Math.floor(macro.BATCHER2D_MEM_INCREMENT * 1024 / _this._vertexFormatBytes);
          _this._iCount = iCount || _this._vCount * StaticVBAccessor.IB_SCALE;
          _this._id = StaticVBAccessor.generateID();
          _this._allocateBuffer();
          return _this;
        }
        var _proto2 = StaticVBAccessor.prototype;
        _proto2.destroy = function destroy() {
          for (var i = 0; i < this._buffers.length; ++i) {
            this._buffers[i].destroy();
            var freeList = this._freeLists[i];
            for (var j = 0; j < freeList.length; ++j) {
              _entryPool.free(freeList[j]);
            }
          }
          this._buffers.length = 0;
          this._freeLists.length = 0;
          _BufferAccessor.prototype.destroy.call(this);
        };
        _proto2.reset = function reset() {
          for (var i = 0; i < this._buffers.length; ++i) {
            var buffer = this._buffers[i];
            buffer.indexOffset = 0;
            buffer.reset();
          }
        };
        _proto2.getVertexBuffer = function getVertexBuffer(bid) {
          return this._buffers[bid].vData;
        };
        _proto2.getIndexBuffer = function getIndexBuffer(bid) {
          return this._buffers[bid].iData;
        };
        _proto2.getMeshBuffer = function getMeshBuffer(bid) {
          return this._buffers[bid];
        };
        _proto2.uploadBuffers = function uploadBuffers() {
          for (var i = 0; i < this._buffers.length; ++i) {
            var firstEntry = this._freeLists[i][0];
            var buffer = this._buffers[i];
            if (!firstEntry || firstEntry.length < buffer.vData.byteLength) {
              buffer.uploadBuffers();
            }
          }
        };
        _proto2.appendIndices = function appendIndices(bufferId, indices) {
          var buf = this._buffers[bufferId];
          var iCount = indices.length;
          if (iCount) {
            var needLength = buf.indexOffset + indices.length;
            if (buf.iData.length < needLength) {
              var expansionLength = Math.floor(1.25 * needLength);
              var newIData = new Uint16Array(expansionLength);
              newIData.set(buf.iData);
              buf.iData = newIData;
            }
            buf.iData.set(indices, buf.indexOffset);
            buf.indexOffset += indices.length;
          }
        };
        _proto2.allocateChunk = function allocateChunk(vertexCount, indexCount) {
          var byteLength = vertexCount * this.vertexFormatBytes;
          if (vertexCount > this._vCount || indexCount > this._iCount) {
            errorID(9004, byteLength);
            return null;
          }
          var buf = null;
          var freeList;
          var bid = 0;
          var eid = -1;
          var entry = null;
          for (var i = 0; i < this._buffers.length; ++i) {
            buf = this._buffers[i];
            freeList = this._freeLists[i];
            for (var e = 0; e < freeList.length; ++e) {
              if (freeList[e].length >= byteLength) {
                entry = freeList[e];
                bid = i;
                eid = e;
                break;
              }
            }
            if (entry) break;
          }
          if (!entry) {
            bid = this._allocateBuffer();
            buf = this._buffers[bid];
            if (buf) {
              eid = 0;
              entry = this._freeLists[bid][eid];
            }
          }
          if (entry) {
            var _vertexOffset = entry.offset / this.vertexFormatBytes;
            assertIsTrue(Number.isInteger(_vertexOffset));
            var _vb = new Float32Array(buf.vData.buffer, entry.offset, byteLength >> 2).fill(0);
            this._allocateChunkFromEntry(bid, eid, entry, byteLength);
            return new StaticVBChunk(this, bid, buf, _vertexOffset, _vb, indexCount);
          } else {
            return null;
          }
        };
        _proto2.recycleChunk = function recycleChunk(chunk) {
          var freeList = this._freeLists[chunk.bufferId];
          var buf = this._buffers[chunk.bufferId];
          var offset = chunk.vertexOffset * this.vertexFormatBytes;
          var bytes = chunk.vb.byteLength;
          if (bytes === 0) return;
          var recycled = false;
          var i = 0;
          var prevEntry = null;
          var nextEntry = freeList[i];
          while (nextEntry && nextEntry.offset < offset) {
            prevEntry = nextEntry;
            nextEntry = freeList[++i];
          }
          if (prevEntry) {
            var distance = offset - (prevEntry.offset + prevEntry.length);
            assertIsTrue(distance >= 0);
            if (distance === 0) {
              prevEntry.length += bytes;
              offset = prevEntry.offset;
              bytes = prevEntry.length;
              if (nextEntry && nextEntry.offset - (offset + bytes) === 0) {
                prevEntry.length += nextEntry.length;
                freeList.splice(i, 1);
                _entryPool.free(nextEntry);
                nextEntry = null;
              }
              recycled = true;
            }
          }
          if (!recycled && nextEntry) {
            var _distance = nextEntry.offset - (offset + bytes);
            assertIsTrue(_distance >= 0);
            if (_distance === 0) {
              nextEntry.offset = offset;
              nextEntry.length += bytes;
            } else {
              var newEntry = _entryPool.alloc();
              newEntry.offset = offset;
              newEntry.length = bytes;
              freeList.splice(i, 0, newEntry);
            }
            recycled = true;
          }
          if (recycled) {
            if (offset + bytes === buf.byteOffset) {
              buf.byteOffset = offset;
            }
          } else {
            var _newEntry = _entryPool.alloc();
            _newEntry.offset = offset;
            _newEntry.length = bytes;
            freeList.push(_newEntry);
          }
        };
        _proto2._allocateChunkFromEntry = function _allocateChunkFromEntry(bid, eid, entry, bytes) {
          var remaining = entry.length - bytes;
          var offset = entry.offset + bytes;
          var buf = this._buffers[bid];
          if (buf.byteOffset < offset) {
            buf.byteOffset = offset;
          }
          assertID(remaining >= 0, 9004, bid, entry.offset, entry.length);
          if (remaining === 0) {
            this._freeLists[bid].splice(eid, 1);
            _entryPool.free(entry);
          } else {
            entry.offset += bytes;
            entry.length = remaining;
          }
        };
        _proto2._allocateBuffer = function _allocateBuffer() {
          assertID(this._buffers.length === this._freeLists.length, 9003);
          var buffer = new MeshBuffer();
          var vFloatCount = this._vCount * this._floatsPerVertex;
          buffer.initialize(this._device, this._attributes, vFloatCount, this._iCount);
          this._buffers.push(buffer);
          var entry = _entryPool.alloc();
          entry.offset = 0;
          entry.length = buffer.vData.byteLength;
          var freeList = [entry];
          this._freeLists.push(freeList);
          var batcher = director.root.batcher2D;
          batcher.syncMeshBuffersToNative(this.id, this._buffers);
          return this._buffers.length - 1;
        };
        StaticVBAccessor.generateID = function generateID() {
          return StaticVBAccessor.ID_COUNT++;
        };
        _createClass(StaticVBAccessor, [{
          key: "id",
          get: function get() {
            return this._id;
          }
        }]);
        return StaticVBAccessor;
      }(BufferAccessor);
      StaticVBAccessor.IB_SCALE = 4;
      StaticVBAccessor.ID_COUNT = 0;

      var AttrUInt8ArrayView;
      (function (AttrUInt8ArrayView) {
        AttrUInt8ArrayView[AttrUInt8ArrayView["DrawInfoType"] = 0] = "DrawInfoType";
        AttrUInt8ArrayView[AttrUInt8ArrayView["VertDirty"] = 1] = "VertDirty";
        AttrUInt8ArrayView[AttrUInt8ArrayView["IsMeshBuffer"] = 2] = "IsMeshBuffer";
        AttrUInt8ArrayView[AttrUInt8ArrayView["Stride"] = 3] = "Stride";
        AttrUInt8ArrayView[AttrUInt8ArrayView["Count"] = 4] = "Count";
      })(AttrUInt8ArrayView || (AttrUInt8ArrayView = {}));
      var AttrUInt16ArrayView;
      (function (AttrUInt16ArrayView) {
        AttrUInt16ArrayView[AttrUInt16ArrayView["BufferID"] = 0] = "BufferID";
        AttrUInt16ArrayView[AttrUInt16ArrayView["AccessorID"] = 1] = "AccessorID";
        AttrUInt16ArrayView[AttrUInt16ArrayView["Count"] = 2] = "Count";
      })(AttrUInt16ArrayView || (AttrUInt16ArrayView = {}));
      var AttrUInt32ArrayView;
      (function (AttrUInt32ArrayView) {
        AttrUInt32ArrayView[AttrUInt32ArrayView["VertexOffset"] = 0] = "VertexOffset";
        AttrUInt32ArrayView[AttrUInt32ArrayView["IndexOffset"] = 1] = "IndexOffset";
        AttrUInt32ArrayView[AttrUInt32ArrayView["VBCount"] = 2] = "VBCount";
        AttrUInt32ArrayView[AttrUInt32ArrayView["IBCount"] = 3] = "IBCount";
        AttrUInt32ArrayView[AttrUInt32ArrayView["DataHash"] = 4] = "DataHash";
        AttrUInt32ArrayView[AttrUInt32ArrayView["Count"] = 5] = "Count";
      })(AttrUInt32ArrayView || (AttrUInt32ArrayView = {}));
      var RenderDrawInfoType;
      (function (RenderDrawInfoType) {
        RenderDrawInfoType[RenderDrawInfoType["COMP"] = 0] = "COMP";
        RenderDrawInfoType[RenderDrawInfoType["MODEL"] = 1] = "MODEL";
        RenderDrawInfoType[RenderDrawInfoType["MIDDLEWARE"] = 2] = "MIDDLEWARE";
        RenderDrawInfoType[RenderDrawInfoType["SUB_NODE"] = 3] = "SUB_NODE";
      })(RenderDrawInfoType || (RenderDrawInfoType = {}));
      var RenderDrawInfo = function () {
        function RenderDrawInfo(nativeDrawInfo) {
          this._accId = -1;
          this._bufferId = -1;
          this._vertexOffset = 0;
          this._indexOffset = 0;
          this._vb = null;
          this._ib = null;
          this._vData = null;
          this._iData = null;
          this._vertDirty = false;
          this._vbCount = 0;
          this._ibCount = 0;
          this._dataHash = 0;
          this._isMeshBuffer = false;
          this._material = null;
          this._texture = null;
          this._sampler = null;
          this._stride = 0;
          this._useLocal = false;
          this._model = null;
          this._drawInfoType = RenderDrawInfoType.COMP;
          this._subNode = null;
          this._uint8SharedBuffer = void 0;
          this._uint16SharedBuffer = void 0;
          this._uint32SharedBuffer = void 0;
          this.init(nativeDrawInfo);
          var attrSharedBuffer = this._nativeObj.getAttrSharedBufferForJS();
          var offset = 0;
          this._uint8SharedBuffer = new Uint8Array(attrSharedBuffer, offset, AttrUInt8ArrayView.Count);
          offset += AttrUInt8ArrayView.Count * Uint8Array.BYTES_PER_ELEMENT;
          this._uint16SharedBuffer = new Uint16Array(attrSharedBuffer, offset, AttrUInt16ArrayView.Count);
          offset += AttrUInt16ArrayView.Count * Uint16Array.BYTES_PER_ELEMENT;
          this._uint32SharedBuffer = new Uint32Array(attrSharedBuffer, offset, AttrUInt32ArrayView.Count);
        }
        var _proto = RenderDrawInfo.prototype;
        _proto.init = function init(nativeDrawInfo) {
        };
        _proto.clear = function clear() {
          this._bufferId = 0;
          this._vertexOffset = 0;
          this._indexOffset = 0;
          this._vertDirty = false;
        };
        _proto.setAccId = function setAccId(accId) {
          this._accId = accId;
        };
        _proto.setBufferId = function setBufferId(bufferId) {
          this._bufferId = bufferId;
        };
        _proto.setAccAndBuffer = function setAccAndBuffer(accId, bufferId) {
          this._bufferId = bufferId;
          this._accId = accId;
        };
        _proto.setVertexOffset = function setVertexOffset(vertexOffset) {
          this._vertexOffset = vertexOffset;
        };
        _proto.setIndexOffset = function setIndexOffset(indexOffset) {
          this._indexOffset = indexOffset;
        };
        _proto.setVB = function setVB(vbBuffer) {
        };
        _proto.setIB = function setIB(ibBuffer) {
        };
        _proto.setVData = function setVData(vDataBuffer) {
        };
        _proto.setIData = function setIData(iDataBuffer) {
        };
        _proto.setVBCount = function setVBCount(vbCount) {
          this._vbCount = vbCount;
        };
        _proto.setIBCount = function setIBCount(ibCount) {
        };
        _proto.setVertDirty = function setVertDirty(val) {
          this._vertDirty = val;
        };
        _proto.setDataHash = function setDataHash(dataHash) {
          this._dataHash = dataHash;
        };
        _proto.setIsMeshBuffer = function setIsMeshBuffer(isMeshBuffer) {
          this._isMeshBuffer = isMeshBuffer;
        };
        _proto.setMaterial = function setMaterial(material) {
          this._material = material;
        };
        _proto.setTexture = function setTexture(texture) {
          this._texture = texture;
        };
        _proto.setSampler = function setSampler(sampler) {
          this._sampler = sampler;
        };
        _proto.setModel = function setModel(model) {
        };
        _proto.setDrawInfoType = function setDrawInfoType(drawInfoType) {
          this._drawInfoType = drawInfoType;
        };
        _proto.setSubNode = function setSubNode(node) {
          this._subNode = node;
        };
        _proto.setStride = function setStride(stride) {
          this._stride = stride;
        };
        _proto.initRender2dBuffer = function initRender2dBuffer() {
        };
        _proto.fillRender2dBuffer = function fillRender2dBuffer(vertexDataArr) {
        };
        _createClass(RenderDrawInfo, [{
          key: "nativeObj",
          get: function get() {
            return this._nativeObj;
          }
        }, {
          key: "render2dBuffer",
          get: function get() {
            return this._render2dBuffer;
          }
        }]);
        return RenderDrawInfo;
      }();

      var Stage;
      (function (Stage) {
        Stage[Stage["DISABLED"] = 0] = "DISABLED";
        Stage[Stage["CLEAR"] = 1] = "CLEAR";
        Stage[Stage["ENTER_LEVEL"] = 2] = "ENTER_LEVEL";
        Stage[Stage["ENABLED"] = 3] = "ENABLED";
        Stage[Stage["EXIT_LEVEL"] = 4] = "EXIT_LEVEL";
        Stage[Stage["CLEAR_INVERTED"] = 5] = "CLEAR_INVERTED";
        Stage[Stage["ENTER_LEVEL_INVERTED"] = 6] = "ENTER_LEVEL_INVERTED";
      })(Stage || (Stage = {}));
      var StencilSharedBufferView;
      (function (StencilSharedBufferView) {
        StencilSharedBufferView[StencilSharedBufferView["stencilTest"] = 0] = "stencilTest";
        StencilSharedBufferView[StencilSharedBufferView["func"] = 1] = "func";
        StencilSharedBufferView[StencilSharedBufferView["stencilMask"] = 2] = "stencilMask";
        StencilSharedBufferView[StencilSharedBufferView["writeMask"] = 3] = "writeMask";
        StencilSharedBufferView[StencilSharedBufferView["failOp"] = 4] = "failOp";
        StencilSharedBufferView[StencilSharedBufferView["zFailOp"] = 5] = "zFailOp";
        StencilSharedBufferView[StencilSharedBufferView["passOp"] = 6] = "passOp";
        StencilSharedBufferView[StencilSharedBufferView["ref"] = 7] = "ref";
        StencilSharedBufferView[StencilSharedBufferView["count"] = 8] = "count";
      })(StencilSharedBufferView || (StencilSharedBufferView = {}));
      var StencilManager = exports('S', function () {
        function StencilManager() {
          this._maskStack = [];
          this._stencilPattern = {
            stencilTest: true,
            func: ComparisonFunc.ALWAYS,
            stencilMask: 0xffff,
            writeMask: 0xffff,
            failOp: StencilOp.KEEP,
            zFailOp: StencilOp.KEEP,
            passOp: StencilOp.KEEP,
            ref: 1
          };
          this._stage = Stage.DISABLED;
          this.stencilStateMap = new Map();
          this.stencilStateMapWithDepth = new Map();
        }
        var _proto = StencilManager.prototype;
        _proto.pushMask = function pushMask(mask) {
          this._maskStack.push(mask);
        };
        _proto.clear = function clear(comp) {
          var isInverted = comp.stencilStage !== Stage.ENTER_LEVEL;
          return isInverted ? Stage.CLEAR_INVERTED : Stage.CLEAR;
        };
        _proto.enableMask = function enableMask() {
          this.stage = Stage.ENABLED;
        };
        _proto.exitMask = function exitMask() {
          if (this._maskStack.length === 0) {
            return;
          }
          this._maskStack.pop();
          if (this._maskStack.length === 0) {
            this.stage = Stage.DISABLED;
          } else {
            this.stage = Stage.ENABLED;
          }
        };
        _proto.getWriteMask = function getWriteMask() {
          return 1 << this._maskStack.length - 1;
        };
        _proto.getExitWriteMask = function getExitWriteMask() {
          return 1 << this._maskStack.length;
        };
        _proto.getStencilRef = function getStencilRef() {
          var result = 0;
          for (var i = 0; i < this._maskStack.length; ++i) {
            result += 0x00000001 << i;
          }
          return result;
        };
        _proto.getMaskStackSize = function getMaskStackSize() {
          return this._maskStack.length;
        };
        _proto.reset = function reset() {
          this._maskStack.length = 0;
          this.stage = Stage.DISABLED;
        };
        _proto.destroy = function destroy() {
          this.stencilStateMap.forEach(function (value, key) {
            value.destroy();
          });
          this.stencilStateMap.clear();
        };
        _proto.getStencilStage = function getStencilStage(stage, mat) {
          var key = 0;
          var depthTest = false;
          var depthWrite = false;
          var depthFunc = ComparisonFunc.LESS;
          var cacheMap = this.stencilStateMap;
          if (mat && mat.passes[0]) {
            var pass = mat.passes[0];
            var dss = pass.depthStencilState;
            var depthTestValue = 0;
            var depthWriteValue = 0;
            if (dss.depthTest) depthTestValue = 1;
            if (dss.depthWrite) depthWriteValue = 1;
            key = depthTestValue | depthWriteValue << 1 | dss.depthFunc << 2 | stage << 6 | this._maskStack.length << 9;
            depthTest = dss.depthTest;
            depthWrite = dss.depthWrite;
            depthFunc = dss.depthFunc;
            cacheMap = this.stencilStateMapWithDepth;
          } else {
            key = stage << 16 | this._maskStack.length;
          }
          if (cacheMap && cacheMap.has(key)) {
            return cacheMap.get(key);
          }
          this.setStateFromStage(stage);
          var depthStencilState = new DepthStencilState(depthTest, depthWrite, depthFunc, this._stencilPattern.stencilTest, this._stencilPattern.func, this._stencilPattern.stencilMask, this._stencilPattern.writeMask, this._stencilPattern.failOp, this._stencilPattern.zFailOp, this._stencilPattern.passOp, this._stencilPattern.ref, this._stencilPattern.stencilTest, this._stencilPattern.func, this._stencilPattern.stencilMask, this._stencilPattern.writeMask, this._stencilPattern.failOp, this._stencilPattern.zFailOp, this._stencilPattern.passOp, this._stencilPattern.ref);
          cacheMap.set(key, depthStencilState);
          return depthStencilState;
        };
        _proto.getStencilHash = function getStencilHash(stage) {
          return stage << 8 | this._maskStack.length;
        };
        _proto.setStateFromStage = function setStateFromStage(stage) {
          var pattern = this._stencilPattern;
          if (stage === Stage.DISABLED) {
            pattern.stencilTest = false;
            pattern.func = ComparisonFunc.ALWAYS;
            pattern.failOp = StencilOp.KEEP;
            pattern.stencilMask = pattern.writeMask = 0xffff;
            pattern.ref = 1;
          } else {
            pattern.stencilTest = true;
            if (stage === Stage.ENABLED) {
              pattern.func = ComparisonFunc.EQUAL;
              pattern.failOp = StencilOp.KEEP;
              pattern.stencilMask = pattern.ref = this.getStencilRef();
              pattern.writeMask = this.getWriteMask();
            } else if (stage === Stage.CLEAR) {
              pattern.func = ComparisonFunc.NEVER;
              pattern.failOp = StencilOp.ZERO;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            } else if (stage === Stage.CLEAR_INVERTED) {
              pattern.func = ComparisonFunc.NEVER;
              pattern.failOp = StencilOp.REPLACE;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            } else if (stage === Stage.ENTER_LEVEL) {
              pattern.func = ComparisonFunc.NEVER;
              pattern.failOp = StencilOp.REPLACE;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            } else if (stage === Stage.ENTER_LEVEL_INVERTED) {
              pattern.func = ComparisonFunc.NEVER;
              pattern.failOp = StencilOp.ZERO;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            }
          }
        };
        _createClass(StencilManager, [{
          key: "stage",
          get: function get() {
            return this._stage;
          },
          set: function set(val) {
            this._stage = val;
          }
        }, {
          key: "pattern",
          get: function get() {
            return this._stencilPattern;
          }
        }]);
        return StencilManager;
      }());
      StencilManager.sharedManager = null;
      StencilManager.sharedManager = new StencilManager();

      var RenderEntityType;
      (function (RenderEntityType) {
        RenderEntityType[RenderEntityType["STATIC"] = 0] = "STATIC";
        RenderEntityType[RenderEntityType["DYNAMIC"] = 1] = "DYNAMIC";
        RenderEntityType[RenderEntityType["CROSSED"] = 2] = "CROSSED";
      })(RenderEntityType || (RenderEntityType = {}));
      var RenderEntityFloatSharedBufferView;
      (function (RenderEntityFloatSharedBufferView) {
        RenderEntityFloatSharedBufferView[RenderEntityFloatSharedBufferView["localOpacity"] = 0] = "localOpacity";
        RenderEntityFloatSharedBufferView[RenderEntityFloatSharedBufferView["count"] = 1] = "count";
      })(RenderEntityFloatSharedBufferView || (RenderEntityFloatSharedBufferView = {}));
      var RenderEntityUInt8SharedBufferView;
      (function (RenderEntityUInt8SharedBufferView) {
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["colorR"] = 0] = "colorR";
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["colorG"] = 1] = "colorG";
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["colorB"] = 2] = "colorB";
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["colorA"] = 3] = "colorA";
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["maskMode"] = 4] = "maskMode";
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["count"] = 5] = "count";
      })(RenderEntityUInt8SharedBufferView || (RenderEntityUInt8SharedBufferView = {}));
      var RenderEntityBoolSharedBufferView;
      (function (RenderEntityBoolSharedBufferView) {
        RenderEntityBoolSharedBufferView[RenderEntityBoolSharedBufferView["colorDirty"] = 0] = "colorDirty";
        RenderEntityBoolSharedBufferView[RenderEntityBoolSharedBufferView["enabled"] = 1] = "enabled";
        RenderEntityBoolSharedBufferView[RenderEntityBoolSharedBufferView["useLocal"] = 2] = "useLocal";
        RenderEntityBoolSharedBufferView[RenderEntityBoolSharedBufferView["count"] = 3] = "count";
      })(RenderEntityBoolSharedBufferView || (RenderEntityBoolSharedBufferView = {}));
      var MaskMode;
      (function (MaskMode) {
        MaskMode[MaskMode["NONE"] = 0] = "NONE";
        MaskMode[MaskMode["MASK"] = 1] = "MASK";
        MaskMode[MaskMode["MASK_INVERTED"] = 2] = "MASK_INVERTED";
        MaskMode[MaskMode["MASK_NODE"] = 3] = "MASK_NODE";
        MaskMode[MaskMode["MASK_NODE_INVERTED"] = 4] = "MASK_NODE_INVERTED";
      })(MaskMode || (MaskMode = {}));
      var RenderEntity = function () {
        function RenderEntity(entityType) {
          this._renderEntityType = RenderEntityType.STATIC;
          this._dynamicDrawInfoArr = [];
          this._node = null;
          this._renderTransform = null;
          this._stencilStage = Stage.DISABLED;
          this._useLocal = false;
          this._maskMode = MaskMode.NONE;
          this._color = Color$1.WHITE;
          this._localOpacity = 255;
          this._colorDirty = true;
          this._enabled = false;
        }
        var _proto = RenderEntity.prototype;
        _proto.addDynamicRenderDrawInfo = function addDynamicRenderDrawInfo(renderDrawInfo) {
        };
        _proto.removeDynamicRenderDrawInfo = function removeDynamicRenderDrawInfo() {
        };
        _proto.clearDynamicRenderDrawInfos = function clearDynamicRenderDrawInfos() {
        };
        _proto.clearStaticRenderDrawInfos = function clearStaticRenderDrawInfos() {
        };
        _proto.setDynamicRenderDrawInfo = function setDynamicRenderDrawInfo(renderDrawInfo, index) {
        };
        _proto.setMaskMode = function setMaskMode(mode) {
          this._maskMode = mode;
        };
        _proto.getStaticRenderDrawInfo = function getStaticRenderDrawInfo() {
          return null;
        };
        _proto.setNode = function setNode(node) {
          this._node = node;
        };
        _proto.setRenderTransform = function setRenderTransform(renderTransform) {
          this._renderTransform = renderTransform;
        };
        _proto.setStencilStage = function setStencilStage(stage) {
          this._stencilStage = stage;
        };
        _proto.setUseLocal = function setUseLocal(useLocal) {
          this._useLocal = useLocal;
        };
        _proto.initSharedBuffer = function initSharedBuffer() {
        };
        _createClass(RenderEntity, [{
          key: "nativeObj",
          get: function get() {
            return this._nativeObj;
          }
        }, {
          key: "renderDrawInfoArr",
          get: function get() {
            return this._dynamicDrawInfoArr;
          }
        }, {
          key: "renderEntityType",
          get: function get() {
            return this._renderEntityType;
          }
        }, {
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(val) {
            this._color = val;
          }
        }, {
          key: "localOpacity",
          get: function get() {
            return this._localOpacity;
          },
          set: function set(val) {
            this._localOpacity = val;
          }
        }, {
          key: "colorDirty",
          get: function get() {
            return this._colorDirty;
          },
          set: function set(val) {
            this._colorDirty = val;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }]);
        return RenderEntity;
      }();

      var DEFAULT_STRIDE = getAttributeStride(vfmtPosUvColor) >> 2;
      var BaseRenderData = exports('t', function () {
        function BaseRenderData(vertexFormat) {
          if (vertexFormat === void 0) {
            vertexFormat = vfmtPosUvColor;
          }
          this.chunk = null;
          this._renderDrawInfo = null;
          this._material = null;
          this._dataHash = 0;
          this._isMeshBuffer = false;
          this._vc = 0;
          this._ic = 0;
          this._floatStride = 0;
          this._vertexFormat = vfmtPosUvColor;
          this._drawInfoType = RenderDrawInfoType.COMP;
          this._multiOwner = false;
          this._batcher = null;
          this._floatStride = vertexFormat === vfmtPosUvColor ? DEFAULT_STRIDE : getAttributeStride(vertexFormat) >> 2;
          this._vertexFormat = vertexFormat;
        }
        var _proto = BaseRenderData.prototype;
        _proto.isValid = function isValid() {
          return this._ic > 0 && this.chunk.vertexAccessor;
        };
        _proto.initRenderDrawInfo = function initRenderDrawInfo(comp, drawInfoType) {
          if (drawInfoType === void 0) {
            drawInfoType = RenderDrawInfoType.COMP;
          }
        };
        _proto.removeRenderDrawInfo = function removeRenderDrawInfo(comp) {
        };
        _proto.setRenderDrawInfoAttributes = function setRenderDrawInfoAttributes() {
        };
        _createClass(BaseRenderData, [{
          key: "vertexCount",
          get: function get() {
            return this._vc;
          }
        }, {
          key: "indexCount",
          get: function get() {
            return this._ic;
          }
        }, {
          key: "stride",
          get: function get() {
            return this._floatStride << 2;
          }
        }, {
          key: "floatStride",
          get: function get() {
            return this._floatStride;
          }
        }, {
          key: "vertexFormat",
          get: function get() {
            return this._vertexFormat;
          }
        }, {
          key: "drawInfoType",
          get: function get() {
            return this._drawInfoType;
          },
          set: function set(type) {
            this._drawInfoType = type;
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setDrawInfoType(type);
            }
          }
        }, {
          key: "renderDrawInfo",
          get: function get() {
            return this._renderDrawInfo;
          }
        }, {
          key: "material",
          get: function get() {
            return this._material;
          },
          set: function set(val) {
            this._material = val;
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setMaterial(val);
            }
          }
        }, {
          key: "dataHash",
          get: function get() {
            return this._dataHash;
          },
          set: function set(val) {
            this._dataHash = val;
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setDataHash(val);
            }
          }
        }, {
          key: "multiOwner",
          get: function get() {
            return this._multiOwner;
          },
          set: function set(val) {
            this._multiOwner = val;
          }
        }, {
          key: "batcher",
          get: function get() {
            if (!this._batcher) {
              this._batcher = director.root.batcher2D;
            }
            return this._batcher;
          }
        }]);
        return BaseRenderData;
      }());
      var RenderData = exports('u', function (_BaseRenderData) {
        _inheritsLoose(RenderData, _BaseRenderData);
        RenderData.add = function add(vertexFormat, accessor) {
          if (vertexFormat === void 0) {
            vertexFormat = vfmtPosUvColor;
          }
          var rd = new RenderData(vertexFormat, accessor);
          if (!accessor) {
            var batcher = director.root.batcher2D;
            accessor = batcher.switchBufferAccessor(rd._vertexFormat);
          }
          rd._accessor = accessor;
          return rd;
        };
        RenderData.remove = function remove(data) {
          data.clear();
          data._accessor = null;
        };
        function RenderData(vertexFormat, accessor) {
          var _this;
          if (vertexFormat === void 0) {
            vertexFormat = vfmtPosUvColor;
          }
          _this = _BaseRenderData.call(this, vertexFormat) || this;
          _this._vertDirty = true;
          _this._textureHash = 0;
          _this.indices = null;
          _this.layer = 0;
          _this.nodeDirty = true;
          _this.passDirty = true;
          _this.textureDirty = true;
          _this.hashDirty = true;
          _this._data = [];
          _this._frame = null;
          _this._accessor = null;
          _this.vertexRow = 1;
          _this.vertexCol = 1;
          if (!accessor) {
            accessor = _this.batcher.switchBufferAccessor(_this._vertexFormat);
          }
          _this._accessor = accessor;
          return _this;
        }
        var _proto2 = RenderData.prototype;
        _proto2.resize = function resize(vertexCount, indexCount) {
          if (vertexCount === this._vc && indexCount === this._ic && this.chunk) return;
          this._vc = vertexCount;
          this._ic = indexCount;
          if (this.chunk) {
            this._accessor.recycleChunk(this.chunk);
            this.chunk = null;
          }
          this.chunk = this._accessor.allocateChunk(vertexCount, indexCount);
          this.updateHash();
        };
        _proto2.setRenderDrawInfoAttributes = function setRenderDrawInfoAttributes() {
        };
        _proto2.fillDrawInfoAttributes = function fillDrawInfoAttributes(drawInfo) {
        };
        _proto2.syncRender2dBuffer = function syncRender2dBuffer() {
        };
        _proto2.resizeAndCopy = function resizeAndCopy(vertexCount, indexCount) {
          if (vertexCount === this._vc && indexCount === this._ic && this.chunk) return;
          this._vc = vertexCount;
          this._ic = indexCount;
          var oldChunk = this.chunk;
          this.chunk = this._accessor.allocateChunk(vertexCount, indexCount);
          if (oldChunk) {
            this.chunk.vb.set(oldChunk.vb);
            this._accessor.recycleChunk(oldChunk);
          }
          this.updateHash();
        };
        _proto2.getMeshBuffer = function getMeshBuffer() {
          if (this.chunk && this._accessor) {
            return this._accessor.getMeshBuffer(this.chunk.bufferId);
          } else {
            return null;
          }
        };
        _proto2.updateNode = function updateNode(comp) {
          this.layer = comp.node.layer;
          this.nodeDirty = false;
          this.hashDirty = true;
        };
        _proto2.updatePass = function updatePass(comp) {
          this.material = comp.getRenderMaterial(0);
          this.passDirty = false;
          this.hashDirty = true;
        };
        _proto2.updateTexture = function updateTexture(frame) {
          this.frame = frame;
          this.textureHash = frame.getHash();
          this.textureDirty = false;
          this.hashDirty = true;
        };
        _proto2.updateHash = function updateHash() {
          var bid = this.chunk ? this.chunk.bufferId : -1;
          var hashString = "" + bid + this.layer + " " + this.textureHash;
          this.dataHash = murmurhash2_32_gc(hashString, 666);
          this.hashDirty = false;
        };
        _proto2.updateRenderData = function updateRenderData(comp, frame) {
          if (this.passDirty) {
            this.material = comp.getRenderMaterial(0);
            this.passDirty = false;
            this.hashDirty = true;
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setMaterial(this.material);
            }
          }
          if (this.nodeDirty) {
            var renderScene = comp.node.scene ? comp._getRenderScene() : null;
            this.layer = comp.node.layer;
            if (renderScene !== null) {
              this.nodeDirty = false;
            }
            this.hashDirty = true;
          }
          if (this.textureDirty) {
            this.frame = frame;
            this.textureHash = frame.getHash();
            this.textureDirty = false;
            this.hashDirty = true;
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setTexture(this.frame ? this.frame.getGFXTexture() : null);
              this._renderDrawInfo.setSampler(this.frame ? this.frame.getGFXSampler() : null);
            }
          }
          if (this.hashDirty) {
            this.updateHash();
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setDataHash(this.dataHash);
            }
          }
        };
        _proto2.clear = function clear() {
          this.resize(0, 0);
          this._data.length = 0;
          this.indices = null;
          this.vertDirty = true;
          this.material = null;
          this.nodeDirty = true;
          this.passDirty = true;
          this.textureDirty = true;
          this.hashDirty = true;
          this.layer = 0;
          this.frame = null;
          this.textureHash = 0;
          this.dataHash = 0;
        };
        RenderData.createStaticVBAccessor = function createStaticVBAccessor(attributes, vCount, iCount) {
          var device = director.root.device;
          var accessor = new StaticVBAccessor(device, attributes, vCount, iCount);
          return accessor;
        };
        _createClass(RenderData, [{
          key: "dataLength",
          get: function get() {
            return this._data.length;
          },
          set: function set(length) {
            var data = this._data;
            if (data.length !== length) {
              for (var i = data.length; i < length; i++) {
                data.push({
                  x: 0,
                  y: 0,
                  z: 0,
                  u: 0,
                  v: 0,
                  color: Color$1.WHITE.clone()
                });
              }
              data.length = length;
            }
            this.syncRender2dBuffer();
          }
        }, {
          key: "data",
          get: function get() {
            return this._data;
          }
        }, {
          key: "vertDirty",
          get: function get() {
            return this._vertDirty;
          },
          set: function set(val) {
            this._vertDirty = val;
            if (this._renderDrawInfo && val) {
              this._renderDrawInfo.setVertDirty(val);
            }
          }
        }, {
          key: "textureHash",
          get: function get() {
            return this._textureHash;
          },
          set: function set(val) {
            this._textureHash = val;
          }
        }, {
          key: "frame",
          get: function get() {
            return this._frame;
          },
          set: function set(val) {
            this._frame = val;
            if (this._renderDrawInfo) {
              if (this._frame) {
                this._renderDrawInfo.setTexture(this._frame.getGFXTexture());
                this._renderDrawInfo.setSampler(this._frame.getGFXSampler());
              } else {
                this._renderDrawInfo.setTexture(null);
                this._renderDrawInfo.setSampler(null);
              }
            }
          }
        }, {
          key: "accessor",
          get: function get() {
            return this._accessor;
          }
        }]);
        return RenderData;
      }(BaseRenderData));
      var MeshRenderData = exports('v', function (_BaseRenderData2) {
        _inheritsLoose(MeshRenderData, _BaseRenderData2);
        MeshRenderData.add = function add(vertexFormat) {
          if (vertexFormat === void 0) {
            vertexFormat = vfmtPosUvColor;
          }
          var rd = new MeshRenderData();
          rd._floatStride = vertexFormat === vfmtPosUvColor ? DEFAULT_STRIDE : getAttributeStride(vertexFormat) >> 2;
          rd._vertexFormat = vertexFormat;
          return rd;
        };
        MeshRenderData.remove = function remove(data) {
          data.clear();
        };
        function MeshRenderData(vertexFormat) {
          var _this2;
          if (vertexFormat === void 0) {
            vertexFormat = vfmtPosUvColor;
          }
          _this2 = _BaseRenderData2.call(this, vertexFormat) || this;
          _this2._isMeshBuffer = true;
          _this2.vData = void 0;
          _this2.iData = void 0;
          _this2.vertexStart = 0;
          _this2.vertexRange = 0;
          _this2.indexStart = 0;
          _this2.indexRange = 0;
          _this2.lastFilledIndex = 0;
          _this2.lastFilledVertex = 0;
          _this2.frame = void 0;
          _this2._byteLength = 0;
          _this2._vertexBuffers = [];
          _this2._indexBuffer = null;
          _this2._iaPool = null;
          _this2._iaInfo = null;
          _this2.vData = new Float32Array(256 * _this2.stride);
          _this2.iData = new Uint16Array(256 * 6);
          return _this2;
        }
        var _proto3 = MeshRenderData.prototype;
        _proto3.request = function request(vertexCount, indexCount) {
          var byteOffset = this._byteLength + vertexCount * this.stride;
          var succeed = this.reserve(vertexCount, indexCount);
          if (!succeed) return false;
          this._vc += vertexCount;
          this._ic += indexCount;
          this._byteLength = byteOffset;
          this.vertexRange = this._vc;
          this.indexRange = this._ic;
          return true;
        };
        _proto3.reserve = function reserve(vertexCount, indexCount) {
          var newVBytes = this._byteLength + vertexCount * this.stride;
          var newICount = this.indexCount + indexCount;
          if (vertexCount + this.vertexCount > 65535) {
            return false;
          }
          var byteLength = this.vData.byteLength;
          var indicesLength = this.iData.length;
          var vCount = this.vData.length;
          var iCount = this.iData.length;
          if (newVBytes > byteLength || newICount > indicesLength) {
            while (byteLength < newVBytes || indicesLength < newICount) {
              vCount *= 2;
              iCount *= 2;
              byteLength = vCount * 4;
              indicesLength = iCount;
            }
            this._reallocBuffer(vCount, iCount);
          }
          return true;
        };
        _proto3.resize = function resize(vertexCount, indexCount) {
          var byteLength = vertexCount * this.stride;
          assertIsTrue(vertexCount >= 0 && indexCount >= 0 && byteLength <= this.vData.byteLength && indexCount <= this.iData.length);
          this._vc = vertexCount;
          this._ic = indexCount;
          this._byteLength = byteLength;
          this.updateRange(0, vertexCount, 0, indexCount);
        };
        _proto3.updateRange = function updateRange(vertOffset, vertexCount, indexOffset, indexCount) {
          assertIsTrue(vertexCount >= 0 && indexCount >= 0 && vertexCount <= this._vc && indexCount <= this._ic);
          this.vertexStart = vertOffset;
          this.indexStart = indexOffset;
          this.vertexRange = vertexCount;
          this.indexRange = indexCount;
        };
        _proto3.requestIA = function requestIA(device) {
          this._initIAInfo(device);
          var ia = this._iaPool.add();
          ia.firstIndex = this.indexStart;
          ia.indexCount = this.indexRange;
          return ia;
        };
        _proto3.uploadBuffers = function uploadBuffers() {
          if (this._byteLength === 0 || !this._vertexBuffers[0] || !this._indexBuffer) {
            return;
          }
          var indexCount = this._ic;
          var verticesData = new Float32Array(this.vData.buffer, 0, this._byteLength >> 2);
          var indicesData = new Uint16Array(this.iData.buffer, 0, indexCount);
          var vertexBuffer = this._vertexBuffers[0];
          if (this._byteLength > vertexBuffer.size) {
            vertexBuffer.resize(this._byteLength);
          }
          vertexBuffer.update(verticesData);
          var indexBytes = indexCount << 1;
          if (indexBytes > this._indexBuffer.size) {
            this._indexBuffer.resize(indexBytes);
          }
          this._indexBuffer.update(indicesData);
        };
        _proto3.freeIAPool = function freeIAPool() {
          if (this._iaPool) {
            this._iaPool.reset();
          }
        };
        _proto3.reset = function reset() {
          this._vc = 0;
          this._ic = 0;
          this._byteLength = 0;
          this.vertexStart = 0;
          this.vertexRange = 0;
          this.indexStart = 0;
          this.indexRange = 0;
          this.lastFilledIndex = 0;
          this.lastFilledVertex = 0;
          this.material = null;
          this.freeIAPool();
        };
        _proto3.clear = function clear() {
          this.reset();
          if (this._iaPool) {
            this._iaPool.destroy();
          }
          if (this._vertexBuffers[0]) {
            this._vertexBuffers[0].destroy();
            this._vertexBuffers = [];
          }
          this._iaInfo = null;
          this.vData = new Float32Array(256 * this.stride);
          this.iData = new Uint16Array(256 * 6);
        };
        _proto3._initIAInfo = function _initIAInfo(device) {
          var _this3 = this;
          if (!this._iaInfo) {
            var vbStride = this.stride;
            var vbs = this._vertexBuffers;
            if (!vbs.length) {
              vbs.push(device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, vbStride, vbStride)));
            }
            var ibStride = Uint16Array.BYTES_PER_ELEMENT;
            if (!this._indexBuffer) {
              this._indexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibStride, ibStride));
            }
            this._iaInfo = new InputAssemblerInfo(this._vertexFormat, vbs, this._indexBuffer);
            this._iaPool = new RecyclePool(function () {
              return device.createInputAssembler(_this3._iaInfo);
            }, 1, function (ia) {
              ia.destroy();
            });
          }
        };
        _proto3._reallocBuffer = function _reallocBuffer(vCount, iCount) {
          var oldVData = this.vData;
          this.vData = new Float32Array(vCount);
          if (oldVData) {
            this.vData.set(oldVData, 0);
          }
          var oldIData = this.iData;
          this.iData = new Uint16Array(iCount);
          if (oldIData) {
            this.iData.set(oldIData, 0);
          }
        };
        _proto3.setRenderDrawInfoAttributes = function setRenderDrawInfoAttributes() {
        };
        _proto3.particleInitRenderDrawInfo = function particleInitRenderDrawInfo(entity) {
        };
        _createClass(MeshRenderData, [{
          key: "formatByte",
          get: function get() {
            return this.stride;
          },
          set: function set(value) {}
        }, {
          key: "floatStride",
          get: function get() {
            return this._floatStride;
          }
        }, {
          key: "vDataOffset",
          get: function get() {
            return this._byteLength >>> 2;
          }
        }]);
        return MeshRenderData;
      }(BaseRenderData));

      var _dec$2X, _dec2$2i, _class$2V, _class2$2C, _initializer$2t, _initializer2$23, _class3$L;
      var _vec2a = new Vec2();
      var _vec2b = new Vec2();
      var _vec3a = new Vec3();
      var _mat4_temp$5 = new Mat4();
      var _matrix$1 = new Mat4();
      var _worldMatrix$1 = new Mat4();
      var _zeroMatrix = new Mat4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
      var _rect = new Rect$1();
      var UITransform = exports('e', (_dec$2X = ccclass$M('cc.UITransform'), _dec2$2i = executionOrder$1(110), _dec$2X(_class$2V = _dec2$2i(_class$2V = disallowMultiple$1(_class$2V = (_class2$2C = (_class3$L = function (_Component) {
        _inheritsLoose(UITransform, _Component);
        function UITransform() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._priority = 0;
          _this._contentSize = _initializer$2t && _initializer$2t();
          _this._anchorPoint = _initializer2$23 && _initializer2$23();
          return _this;
        }
        var _proto = UITransform.prototype;
        _proto.__preload = function __preload() {
          this.node._uiProps.uiTransformComp = this;
        };
        _proto.onLoad = function onLoad() {
          if (this.node.parent) {
            UITransform.insertChangeMap(this.node.parent);
          }
        };
        _proto.onEnable = function onEnable() {
          this.node.on(NodeEventType.PARENT_CHANGED, this._parentChanged, this);
          this._markRenderDataDirty();
        };
        _proto.onDisable = function onDisable() {
          this.node.off(NodeEventType.PARENT_CHANGED, this._parentChanged, this);
        };
        _proto.onDestroy = function onDestroy() {
          this.node._uiProps.uiTransformComp = null;
        };
        _proto.setContentSize = function setContentSize(size, height) {
          var locContentSize = this._contentSize;
          var locWidth;
          var locHeight;
          if (height === undefined) {
            size = size;
            if (approx(size.width, locContentSize.width, EPSILON$3) && approx(size.height, locContentSize.height, EPSILON$3)) {
              return;
            }
            locWidth = size.width;
            locHeight = size.height;
          } else {
            size = size;
            if (approx(size, locContentSize.width, EPSILON$3) && approx(height, locContentSize.height, EPSILON$3)) {
              return;
            }
            locWidth = size;
            locHeight = height;
          }
          {
            locContentSize.width = locWidth;
            locContentSize.height = locHeight;
            this.node.emit(NodeEventType.SIZE_CHANGED);
          }
          this._markRenderDataDirty();
        };
        _proto.setAnchorPoint = function setAnchorPoint(point, y) {
          var locAnchorPoint = this._anchorPoint;
          if (y === undefined) {
            point = point;
            if (point.x === locAnchorPoint.x && point.y === locAnchorPoint.y) {
              return;
            }
            locAnchorPoint.x = point.x;
            locAnchorPoint.y = point.y;
          } else {
            if (point === locAnchorPoint.x && y === locAnchorPoint.y) {
              return;
            }
            locAnchorPoint.x = point;
            locAnchorPoint.y = y;
          }
          this.node.emit(NodeEventType.ANCHOR_CHANGED, this._anchorPoint);
          this._markRenderDataDirty();
        };
        _proto.isHit = function isHit(uiPoint) {
          var w = this._contentSize.width;
          var h = this._contentSize.height;
          var v2WorldPt = _vec2a;
          var testPt = _vec2b;
          var cameras = this._getRenderScene().cameras;
          for (var i = 0; i < cameras.length; i++) {
            var camera = cameras[i];
            if (!(camera.visibility & this.node.layer)) continue;
            camera.node.getWorldRT(_mat4_temp$5);
            var m12 = _mat4_temp$5.m12;
            var m13 = _mat4_temp$5.m13;
            var center = visibleRect.center;
            _mat4_temp$5.m12 = center.x - (_mat4_temp$5.m00 * m12 + _mat4_temp$5.m04 * m13);
            _mat4_temp$5.m13 = center.y - (_mat4_temp$5.m01 * m12 + _mat4_temp$5.m05 * m13);
            Mat4.invert(_mat4_temp$5, _mat4_temp$5);
            Vec2.transformMat4(v2WorldPt, uiPoint, _mat4_temp$5);
            this.node.getWorldMatrix(_worldMatrix$1);
            Mat4.invert(_mat4_temp$5, _worldMatrix$1);
            if (Mat4.strictEquals(_mat4_temp$5, _zeroMatrix)) {
              continue;
            }
            Vec2.transformMat4(testPt, v2WorldPt, _mat4_temp$5);
            testPt.x += this._anchorPoint.x * w;
            testPt.y += this._anchorPoint.y * h;
            var hit = false;
            if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) {
              hit = this._maskTest(v2WorldPt);
            }
            if (hit) {
              return true;
            }
          }
          return false;
        };
        _proto.hitTest = function hitTest(screenPoint, windowId) {
          if (windowId === void 0) {
            windowId = 0;
          }
          var w = this._contentSize.width;
          var h = this._contentSize.height;
          var v3WorldPt = _vec3a;
          var v2WorldPt = _vec2a;
          var testPt = _vec2b;
          var cameras = this._getRenderScene().cameras;
          for (var i = 0; i < cameras.length; i++) {
            var camera = cameras[i];
            if (!(camera.visibility & this.node.layer) || camera.window && !camera.window.swapchain) {
              continue;
            }
            if (camera.systemWindowId !== windowId) {
              continue;
            }
            Vec3.set(v3WorldPt, screenPoint.x, screenPoint.y, 0);
            camera.screenToWorld(v3WorldPt, v3WorldPt);
            Vec2.set(v2WorldPt, v3WorldPt.x, v3WorldPt.y);
            this.node.getWorldMatrix(_worldMatrix$1);
            Mat4.invert(_mat4_temp$5, _worldMatrix$1);
            if (Mat4.strictEquals(_mat4_temp$5, _zeroMatrix)) {
              continue;
            }
            Vec2.transformMat4(testPt, v2WorldPt, _mat4_temp$5);
            testPt.x += this._anchorPoint.x * w;
            testPt.y += this._anchorPoint.y * h;
            var hit = false;
            if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) {
              hit = this._maskTest(v2WorldPt);
            }
            if (hit) {
              return true;
            }
          }
          return false;
        };
        _proto._maskTest = function _maskTest(pointInWorldSpace) {
          var _this$node, _this$node$eventProce;
          var maskList = (_this$node = this.node) === null || _this$node === void 0 ? void 0 : (_this$node$eventProce = _this$node.eventProcessor) === null || _this$node$eventProce === void 0 ? void 0 : _this$node$eventProce.maskList;
          if (maskList) {
            var parent = this.node;
            var length = maskList.length;
            for (var i = 0, j = 0; parent && j < length; ++i, parent = parent.parent) {
              var temp = maskList[j];
              if (i === temp.index) {
                if (parent === temp.comp.node) {
                  var comp = temp.comp;
                  if (comp && comp._enabled && !comp.isHit(pointInWorldSpace)) {
                    return false;
                  }
                  j++;
                } else {
                  maskList.length = j;
                  break;
                }
              } else if (i > temp.index) {
                maskList.length = j;
                break;
              }
            }
          }
          return true;
        };
        _proto.convertToNodeSpaceAR = function convertToNodeSpaceAR(worldPoint, out) {
          this.node.getWorldMatrix(_worldMatrix$1);
          Mat4.invert(_mat4_temp$5, _worldMatrix$1);
          if (!out) {
            out = new Vec3();
          }
          return Vec3.transformMat4(out, worldPoint, _mat4_temp$5);
        };
        _proto.convertToWorldSpaceAR = function convertToWorldSpaceAR(nodePoint, out) {
          this.node.getWorldMatrix(_worldMatrix$1);
          if (!out) {
            out = new Vec3();
          }
          return Vec3.transformMat4(out, nodePoint, _worldMatrix$1);
        };
        _proto.getBoundingBox = function getBoundingBox() {
          var rect = new Rect$1();
          this._selfBoundingBox(rect);
          Mat4.fromSRT(_matrix$1, this.node.rotation, this.node.position, this.node.scale);
          rect.transformMat4(_matrix$1);
          return rect;
        };
        _proto.getBoundingBoxToWorld = function getBoundingBoxToWorld() {
          var rect = new Rect$1();
          var locChildren = this.node.children;
          for (var i = 0; i < locChildren.length; ++i) {
            var child = locChildren[i];
            if (child && child.active) {
              var uiTransform = child.getComponent(UITransform);
              if (uiTransform && uiTransform.contentSize.width && uiTransform.contentSize.height) {
                uiTransform._selfBoundingBox(_rect);
                _rect.transformMat4(child.worldMatrix);
                if (rect.width === 0) {
                  rect.set(_rect);
                } else {
                  Rect$1.union(rect, rect, _rect);
                }
              }
            }
          }
          if (this._contentSize.width && this._contentSize.height) {
            this._selfBoundingBox(_rect);
            _rect.transformMat4(this.node.worldMatrix);
            if (rect.width === 0) {
              rect.set(_rect);
            } else {
              Rect$1.union(rect, rect, _rect);
            }
          }
          return rect;
        };
        _proto.getBoundingBoxTo = function getBoundingBoxTo(targetMat) {
          var rect = new Rect$1();
          var locChildren = this.node.children;
          Mat4.invert(_mat4_temp$5, targetMat);
          for (var i = 0; i < locChildren.length; ++i) {
            var child = locChildren[i];
            if (child && child.active) {
              var uiTransform = child.getComponent(UITransform);
              if (uiTransform && uiTransform.contentSize.width && uiTransform.contentSize.height) {
                uiTransform._selfBoundingBox(_rect);
                Mat4.multiply(_matrix$1, child.worldMatrix, _mat4_temp$5);
                _rect.transformMat4(_matrix$1);
                if (rect.width === 0) {
                  rect.set(_rect);
                } else {
                  Rect$1.union(rect, rect, _rect);
                }
              }
            }
          }
          if (this._contentSize.width && this._contentSize.height) {
            this._selfBoundingBox(_rect);
            Mat4.multiply(_matrix$1, this.node.worldMatrix, _mat4_temp$5);
            _rect.transformMat4(_matrix$1);
            if (rect.width === 0) {
              rect.set(_rect);
            } else {
              Rect$1.union(rect, rect, _rect);
            }
          }
          return rect;
        };
        _proto.getComputeAABB = function getComputeAABB(out) {
          var width = this._contentSize.width;
          var height = this._contentSize.height;
          _rect.set(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height);
          _rect.transformMat4(this.node.worldMatrix);
          var px = _rect.x + _rect.width * 0.5;
          var py = _rect.y + _rect.height * 0.5;
          var pz = this.node.worldPosition.z;
          var w = _rect.width / 2;
          var h = _rect.height / 2;
          var l = 0.001;
          if (out != null) {
            AABB.set(out, px, py, pz, w, h, l);
            return out;
          } else {
            return new AABB(px, py, pz, w, h, l);
          }
        };
        _proto._selfBoundingBox = function _selfBoundingBox(out) {
          var width = this._contentSize.width;
          var height = this._contentSize.height;
          out.set(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height);
          return out;
        };
        _proto._parentChanged = function _parentChanged(node) {
          if (this.node.getComponent('cc.RenderRoot2D')) {
            return;
          }
          if (this.node.parent) {
            UITransform.insertChangeMap(this.node.parent);
          }
        };
        _proto._markRenderDataDirty = function _markRenderDataDirty() {
          var uiComp = this.node._uiProps.uiComp;
          if (uiComp) {
            uiComp.markForUpdateRenderData();
          }
        };
        UITransform.insertChangeMap = function insertChangeMap(node) {
          var key = node.uuid;
          if (!UITransform.priorityChangeNodeMap.has(key)) {
            UITransform.priorityChangeNodeMap.set(key, node);
          }
        };
        UITransform._sortChildrenSibling = function _sortChildrenSibling(node) {
          var siblings = node.children;
          if (siblings) {
            siblings.sort(function (a, b) {
              var aComp = a._uiProps.uiTransformComp;
              var bComp = b._uiProps.uiTransformComp;
              var ca = aComp ? aComp._priority : 0;
              var cb = bComp ? bComp._priority : 0;
              var diff = ca - cb;
              if (diff === 0) return a.getSiblingIndex() - b.getSiblingIndex();
              return diff;
            });
          }
        };
        UITransform._sortSiblings = function _sortSiblings() {
          UITransform.priorityChangeNodeMap.forEach(function (node, ID) {
            UITransform._sortChildrenSibling(node);
            node._updateSiblingIndex();
            node.emit('childrenSiblingOrderChanged');
          });
          UITransform.priorityChangeNodeMap.clear();
        };
        UITransform._cleanChangeMap = function _cleanChangeMap() {
          UITransform.priorityChangeNodeMap.clear();
        };
        _createClass(UITransform, [{
          key: "contentSize",
          get: function get() {
            return this._contentSize;
          },
          set: function set(value) {
            if (this._contentSize.equals(value)) {
              return;
            }
            {
              this._contentSize.set(value);
              this.node.emit(NodeEventType.SIZE_CHANGED);
            }
            this._markRenderDataDirty();
          }
        }, {
          key: "width",
          get: function get() {
            return this._contentSize.width;
          },
          set: function set(value) {
            if (this._contentSize.width === value) {
              return;
            }
            {
              this._contentSize.width = value;
              this.node.emit(NodeEventType.SIZE_CHANGED);
            }
            this._markRenderDataDirty();
          }
        }, {
          key: "height",
          get: function get() {
            return this._contentSize.height;
          },
          set: function set(value) {
            if (this.contentSize.height === value) {
              return;
            }
            {
              this._contentSize.height = value;
              this.node.emit(NodeEventType.SIZE_CHANGED);
            }
            this._markRenderDataDirty();
          }
        }, {
          key: "anchorPoint",
          get: function get() {
            return this._anchorPoint;
          },
          set: function set(value) {
            if (this._anchorPoint.equals(value)) {
              return;
            }
            this._anchorPoint.set(value);
            this.node.emit(NodeEventType.ANCHOR_CHANGED, this._anchorPoint);
            this._markRenderDataDirty();
          }
        }, {
          key: "anchorX",
          get: function get() {
            return this._anchorPoint.x;
          },
          set: function set(value) {
            if (this._anchorPoint.x === value) {
              return;
            }
            this._anchorPoint.x = value;
            this.node.emit(NodeEventType.ANCHOR_CHANGED, this._anchorPoint);
            this._markRenderDataDirty();
          }
        }, {
          key: "anchorY",
          get: function get() {
            return this._anchorPoint.y;
          },
          set: function set(value) {
            if (this._anchorPoint.y === value) {
              return;
            }
            this._anchorPoint.y = value;
            this.node.emit(NodeEventType.ANCHOR_CHANGED, this._anchorPoint);
            this._markRenderDataDirty();
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(value) {
            if (this._priority === value) {
              return;
            }
            if (this.node.getComponent('cc.RenderRoot2D')) {
              warnID(6706);
              return;
            }
            this._priority = value;
            if (this.node.parent) {
              UITransform.insertChangeMap(this.node.parent);
            }
          }
        }, {
          key: "visibility",
          get: function get() {
            var camera = director.root.batcher2D.getFirstRenderCamera(this.node);
            return camera ? camera.visibility : 0;
          }
        }, {
          key: "cameraPriority",
          get: function get() {
            var camera = director.root.batcher2D.getFirstRenderCamera(this.node);
            return camera ? camera.priority : 0;
          }
        }]);
        return UITransform;
      }(Component), _class3$L.EventType = NodeEventType, _class3$L.priorityChangeNodeMap = new Map(), _class3$L), (_initializer$2t = applyDecoratedInitializer(_class2$2C.prototype, "_contentSize", [serializable$p], function () {
        return new Size$1(100, 100);
      }), _initializer2$23 = applyDecoratedInitializer(_class2$2C.prototype, "_anchorPoint", [serializable$p], function () {
        return new Vec2(0.5, 0.5);
      })), _class2$2C)) || _class$2V) || _class$2V) || _class$2V));
      director.on(Director.EVENT_AFTER_UPDATE, UITransform._sortSiblings);
      director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, UITransform._cleanChangeMap);

      var _dec$2W, _dec2$2h, _dec3$1G, _class$2U, _class2$2B, _initializer$2s;
      var _matInsInfo$2 = {
        parent: null,
        owner: null,
        subModelIdx: 0
      };
      var ccclass$K = ccclass$M,
        disallowMultiple = disallowMultiple$1,
        type$c = type$d;
      var Renderer = exports('e1', (_dec$2W = ccclass$K('cc.Renderer'), _dec2$2h = type$c(Material), _dec3$1G = type$c([Material]), _dec$2W(_class$2U = disallowMultiple(_class$2U = (_class2$2B = function (_Component) {
        _inheritsLoose(Renderer, _Component);
        function Renderer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._materials = _initializer$2s && _initializer$2s();
          _this._materialInstances = [];
          return _this;
        }
        var _proto = Renderer.prototype;
        _proto.getMaterial = function getMaterial(idx) {
          return this.getSharedMaterial(idx);
        };
        _proto.setMaterial = function setMaterial(material, index) {
          this.setSharedMaterial(material, index);
        };
        _proto.getSharedMaterial = function getSharedMaterial(idx) {
          if (idx < 0 || idx >= this._materials.length) {
            return null;
          }
          return this._materials[idx];
        };
        _proto.setSharedMaterial = function setSharedMaterial(material, index) {
          if (material && material instanceof MaterialInstance) {
            errorID(12012);
          }
          this._materials[index] = material;
          var inst = this._materialInstances[index];
          if (inst) {
            inst.destroy();
            this._materialInstances[index] = null;
          }
          this._onMaterialModified(index, this._materials[index]);
        };
        _proto.getMaterialInstance = function getMaterialInstance(idx) {
          var mat = this._materials[idx];
          if (!mat) {
            return null;
          }
          if (!this._materialInstances[idx]) {
            _matInsInfo$2.parent = this._materials[idx];
            _matInsInfo$2.owner = this;
            _matInsInfo$2.subModelIdx = idx;
            var instantiated = new MaterialInstance(_matInsInfo$2);
            _matInsInfo$2.parent = null;
            _matInsInfo$2.owner = null;
            _matInsInfo$2.subModelIdx = 0;
            this.setMaterialInstance(instantiated, idx);
          }
          return this._materialInstances[idx];
        };
        _proto.setMaterialInstance = function setMaterialInstance(matInst, index) {
          if (typeof matInst === 'number') {
            warnID(12007);
            var temp = matInst;
            matInst = index;
            index = temp;
          }
          var curInst = this._materialInstances[index];
          if (matInst && matInst.parent) {
            if (matInst !== curInst) {
              this._materialInstances[index] = matInst;
              this._onMaterialModified(index, matInst);
            }
            return;
          }
          if (matInst !== this._materials[index] || curInst) {
            this.setSharedMaterial(matInst, index);
          }
        };
        _proto.getRenderMaterial = function getRenderMaterial(index) {
          return this._materialInstances[index] || this._materials[index];
        };
        _proto._onMaterialModified = function _onMaterialModified(index, material) {};
        _proto._onRebuildPSO = function _onRebuildPSO(index, material) {};
        _proto._clearMaterials = function _clearMaterials() {};
        _createClass(Renderer, [{
          key: "sharedMaterial",
          get: function get() {
            return this.getSharedMaterial(0);
          }
        }, {
          key: "sharedMaterials",
          get: function get() {
            return this._materials;
          },
          set: function set(val) {
            for (var i = 0; i < val.length; i++) {
              if (val[i] !== this._materials[i]) {
                this.setSharedMaterial(val[i], i);
              }
            }
            if (val.length < this._materials.length) {
              for (var _i = val.length; _i < this._materials.length; _i++) {
                this.setSharedMaterial(null, _i);
              }
              this._materials.splice(val.length);
            }
          }
        }, {
          key: "material",
          get: function get() {
            return this.getMaterialInstance(0);
          },
          set: function set(val) {
            if (this._materials.length === 1 && !this._materialInstances[0] && this._materials[0] === val) {
              return;
            }
            this.setMaterialInstance(val, 0);
          }
        }, {
          key: "materials",
          get: function get() {
            for (var i = 0; i < this._materials.length; i++) {
              this._materialInstances[i] = this.getMaterialInstance(i);
            }
            return this._materialInstances;
          },
          set: function set(val) {
            var newLength = val.length;
            var oldLength = this._materials.length;
            for (var i = newLength; i < oldLength; i++) {
              this.setMaterialInstance(null, i);
            }
            this._materials.length = newLength;
            this._materialInstances.length = newLength;
            for (var _i2 = 0; _i2 < newLength; _i2++) {
              if (this._materialInstances[_i2] != val[_i2]) {
                this.setMaterialInstance(val[_i2], _i2);
              }
            }
          }
        }]);
        return Renderer;
      }(Component), (_applyDecoratedDescriptor(_class2$2B.prototype, "sharedMaterials", [_dec2$2h], Object.getOwnPropertyDescriptor(_class2$2B.prototype, "sharedMaterials"), _class2$2B.prototype), _initializer$2s = applyDecoratedInitializer(_class2$2B.prototype, "_materials", [_dec3$1G], function () {
        return [];
      })), _class2$2B)) || _class$2U) || _class$2U));

      var _dec$2V, _dec2$2g, _dec3$1F, _dec4$1b, _class$2T, _class2$2A, _initializer$2r, _initializer2$22, _initializer3$1w, _initializer4$1j, _initializer5$12, _class3$K;
      ccenum(BlendFactor);
      ccenum(BlendOp);
      ccenum(ColorMask);
      var InstanceMaterialType; exports('I', InstanceMaterialType);
      (function (InstanceMaterialType) {
        InstanceMaterialType[InstanceMaterialType["ADD_COLOR"] = 0] = "ADD_COLOR";
        InstanceMaterialType[InstanceMaterialType["ADD_COLOR_AND_TEXTURE"] = 1] = "ADD_COLOR_AND_TEXTURE";
        InstanceMaterialType[InstanceMaterialType["GRAYSCALE"] = 2] = "GRAYSCALE";
        InstanceMaterialType[InstanceMaterialType["USE_ALPHA_SEPARATED"] = 3] = "USE_ALPHA_SEPARATED";
        InstanceMaterialType[InstanceMaterialType["USE_ALPHA_SEPARATED_AND_GRAY"] = 4] = "USE_ALPHA_SEPARATED_AND_GRAY";
      })(InstanceMaterialType || (exports('I', InstanceMaterialType = {})));
      var UIRenderer = exports('d', (_dec$2V = ccclass$M('cc.UIRenderer'), _dec2$2g = requireComponent(UITransform), _dec3$1F = type$d(Material), _dec4$1b = type$d(Material), _dec$2V(_class$2T = _dec2$2g(_class$2T = (_class2$2A = (_class3$K = function (_Renderer) {
        _inheritsLoose(UIRenderer, _Renderer);
        function UIRenderer() {
          var _this;
          _this = _Renderer.call(this) || this;
          _this._renderData = null;
          _this._materials = _initializer$2r && _initializer$2r();
          _this._customMaterial = _initializer2$22 && _initializer2$22();
          _this._srcBlendFactor = _initializer3$1w && _initializer3$1w();
          _this._dstBlendFactor = _initializer4$1j && _initializer4$1j();
          _this._color = _initializer5$12 && _initializer5$12();
          _this._stencilStage = Stage.DISABLED;
          _this._assembler = null;
          _this._postAssembler = null;
          _this._renderDataFlag = true;
          _this._renderFlag = true;
          _this._renderEntity = void 0;
          _this._instanceMaterialType = -1;
          _this._srcBlendFactorCache = BlendFactor.SRC_ALPHA;
          _this._dstBlendFactorCache = BlendFactor.ONE_MINUS_SRC_ALPHA;
          _this._dirtyVersion = -1;
          _this._internalId = -1;
          _this._flagChangedVersion = -1;
          _this._useVertexOpacity = false;
          _this._lastParent = null;
          _this._renderEntity = _this.createRenderEntity();
          return _this;
        }
        var _proto = UIRenderer.prototype;
        _proto.setRenderData = function setRenderData(renderData) {
          this._renderData = renderData;
        };
        _proto.onLoad = function onLoad() {
          this._renderEntity.setNode(this.node);
        };
        _proto.__preload = function __preload() {
          this.node._uiProps.uiComp = this;
          if (this._flushAssembler) {
            this._flushAssembler();
          }
        };
        _proto.onEnable = function onEnable() {
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
          this.node.on(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
          this.node.on(NodeEventType.PARENT_CHANGED, this._colorDirty, this);
          this.updateMaterial();
          this._colorDirty();
          uiRendererManager.addRenderer(this);
          this.markForUpdateRenderData();
        };
        _proto.onRestore = function onRestore() {
          this.updateMaterial();
          this.markForUpdateRenderData();
        };
        _proto.onDisable = function onDisable() {
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
          this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
          this.node.off(NodeEventType.PARENT_CHANGED, this._colorDirty, this);
          uiRendererManager.removeRenderer(this);
          this._renderFlag = false;
          this._renderEntity.enabled = false;
        };
        _proto.onDestroy = function onDestroy() {
          this._renderEntity.setNode(null);
          if (this.node._uiProps.uiComp === this) {
            this.node._uiProps.uiComp = null;
          }
          this.destroyRenderData();
          if (this._materialInstances) {
            for (var i = 0; i < this._materialInstances.length; i++) {
              var instance = this._materialInstances[i];
              if (instance) {
                instance.destroy();
              }
            }
          }
        };
        _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
          if (enable === void 0) {
            enable = true;
          }
          if (enable) {
            var renderData = this._renderData;
            if (renderData) {
              renderData.vertDirty = true;
            }
            uiRendererManager.markDirtyRenderer(this);
          }
        };
        _proto.requestRenderData = function requestRenderData(drawInfoType) {
          if (drawInfoType === void 0) {
            drawInfoType = RenderDrawInfoType.COMP;
          }
          var data = RenderData.add();
          data.initRenderDrawInfo(this, drawInfoType);
          this._renderData = data;
          return data;
        };
        _proto.destroyRenderData = function destroyRenderData() {
          if (!this._renderData) {
            return;
          }
          this._renderData.removeRenderDrawInfo(this);
          RenderData.remove(this._renderData);
          this._renderData = null;
        };
        _proto.updateRenderer = function updateRenderer() {
          if (this._assembler) {
            this._assembler.updateRenderData(this);
          }
          this._renderFlag = this._canRender();
          this._renderEntity.enabled = this._renderFlag;
        };
        _proto.fillBuffers = function fillBuffers(render) {
          if (this._renderFlag) {
            this._render(render);
          }
        };
        _proto.postUpdateAssembler = function postUpdateAssembler(render) {
          if (this._postAssembler && this._renderFlag) {
            this._postRender(render);
          }
        };
        _proto._render = function _render(render) {};
        _proto._postRender = function _postRender(render) {};
        _proto._canRender = function _canRender() {
          {
            assert(this.isValid, 'this component should not be invalid!');
          }
          return this.getSharedMaterial(0) !== null && this._enabled && this._color.a > 0;
        };
        _proto._postCanRender = function _postCanRender() {};
        _proto.updateMaterial = function updateMaterial() {
          if (this._customMaterial) {
            if (this.getSharedMaterial(0) !== this._customMaterial) {
              this.setSharedMaterial(this._customMaterial, 0);
            }
            return;
          }
          var mat = this._updateBuiltinMaterial();
          this.setSharedMaterial(mat, 0);
          if (this.stencilStage === Stage.ENTER_LEVEL || this.stencilStage === Stage.ENTER_LEVEL_INVERTED) {
            this.getMaterialInstance(0).recompileShaders({
              USE_ALPHA_TEST: true
            });
          }
          this._updateBlendFunc();
        };
        _proto._updateColor = function _updateColor() {
          this.node._uiProps.colorDirty = true;
          this.setEntityColorDirty(true);
          this.setEntityColor(this._color);
          this.setEntityOpacity(this.node._uiProps.localOpacity);
          if (this._assembler) {
            this._assembler.updateColor(this);
            var renderFlag = this._renderFlag;
            this._renderFlag = this._canRender();
            this.setEntityEnabled(this._renderFlag);
            if (renderFlag !== this._renderFlag) {
              var renderData = this.renderData;
              if (renderData) {
                renderData.vertDirty = true;
              }
            }
          }
        };
        UIRenderer.setEntityColorDirtyRecursively = function setEntityColorDirtyRecursively(node, dirty) {
          var render = node._uiProps.uiComp;
          if (render && render.color) {
            render._renderEntity.colorDirty = dirty;
          }
          for (var i = 0; i < node.children.length; i++) {
            UIRenderer.setEntityColorDirtyRecursively(node.children[i], dirty);
          }
        };
        _proto.setEntityColorDirty = function setEntityColorDirty(dirty) {
        };
        _proto.setEntityColor = function setEntityColor(color) {
        };
        _proto.setEntityOpacity = function setEntityOpacity(opacity) {
        };
        _proto.setEntityEnabled = function setEntityEnabled(enabled) {
        };
        _proto._updateBlendFunc = function _updateBlendFunc() {
          var target = this.getRenderMaterial(0).passes[0].blendState.targets[0];
          this._dstBlendFactorCache = target.blendDst;
          this._srcBlendFactorCache = target.blendSrc;
          if (this._dstBlendFactorCache !== this._dstBlendFactor || this._srcBlendFactorCache !== this._srcBlendFactor) {
            target = this.getMaterialInstance(0).passes[0].blendState.targets[0];
            target.blend = true;
            target.blendDstAlpha = BlendFactor.ONE_MINUS_SRC_ALPHA;
            target.blendDst = this._dstBlendFactor;
            target.blendSrc = this._srcBlendFactor;
            var targetPass = this.getMaterialInstance(0).passes[0];
            targetPass.blendState.setTarget(0, target);
            targetPass._updatePassHash();
            this._dstBlendFactorCache = this._dstBlendFactor;
            this._srcBlendFactorCache = this._srcBlendFactor;
          }
        };
        _proto._nodeStateChange = function _nodeStateChange(transformType) {
          if (this._renderData) {
            this.markForUpdateRenderData();
          }
          for (var i = 0; i < this.node.children.length; ++i) {
            var child = this.node.children[i];
            var renderComp = child.getComponent(UIRenderer);
            if (renderComp) {
              renderComp.markForUpdateRenderData();
            }
          }
        };
        _proto._colorDirty = function _colorDirty() {
          this.node._uiProps.colorDirty = true;
          this.setEntityColorDirty(true);
        };
        _proto._onMaterialModified = function _onMaterialModified(idx, material) {
          if (this._renderData) {
            this.markForUpdateRenderData();
            this._renderData.passDirty = true;
          }
          _Renderer.prototype._onMaterialModified.call(this, idx, material);
        };
        _proto._updateBuiltinMaterial = function _updateBuiltinMaterial() {
          var mat;
          switch (this._instanceMaterialType) {
            case InstanceMaterialType.ADD_COLOR:
              mat = builtinResMgr.get("ui-base-material");
              break;
            case InstanceMaterialType.GRAYSCALE:
              mat = builtinResMgr.get("ui-sprite-gray-material");
              break;
            case InstanceMaterialType.USE_ALPHA_SEPARATED:
              mat = builtinResMgr.get("ui-sprite-alpha-sep-material");
              break;
            case InstanceMaterialType.USE_ALPHA_SEPARATED_AND_GRAY:
              mat = builtinResMgr.get("ui-sprite-gray-alpha-sep-material");
              break;
            default:
              mat = builtinResMgr.get("ui-sprite-material");
              break;
          }
          return mat;
        };
        _proto.setNodeDirty = function setNodeDirty() {
          if (this._renderData) {
            this._renderData.nodeDirty = true;
          }
        };
        _proto.setTextureDirty = function setTextureDirty() {
          if (this._renderData) {
            this._renderData.textureDirty = true;
          }
        };
        _proto.createRenderEntity = function createRenderEntity() {
          return new RenderEntity(RenderEntityType.STATIC);
        };
        _createClass(UIRenderer, [{
          key: "sharedMaterials",
          get: function get() {
            return this._materials;
          },
          set: function set(val) {
            for (var i = 0; i < val.length; i++) {
              if (val[i] !== this._materials[i]) {
                this.setSharedMaterial(val[i], i);
              }
            }
            if (val.length < this._materials.length) {
              for (var _i = val.length; _i < this._materials.length; _i++) {
                this.setSharedMaterial(null, _i);
              }
              this._materials.splice(val.length);
            }
          }
        }, {
          key: "customMaterial",
          get: function get() {
            return this._customMaterial;
          },
          set: function set(val) {
            this._customMaterial = val;
            this.updateMaterial();
          }
        }, {
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(value) {
            if (this._color.equals(value)) {
              return;
            }
            this._color.set(value);
            this._updateColor();
          }
        }, {
          key: "renderData",
          get: function get() {
            return this._renderData;
          }
        }, {
          key: "useVertexOpacity",
          get: function get() {
            return this._useVertexOpacity;
          }
        }, {
          key: "stencilStage",
          get: function get() {
            return this._stencilStage;
          },
          set: function set(val) {
            this._stencilStage = val;
            this._renderEntity.setStencilStage(val);
          }
        }, {
          key: "srcBlendFactor",
          get: function get() {
            return this._srcBlendFactor;
          },
          set: function set(srcBlendFactor) {
            this._srcBlendFactor = srcBlendFactor;
          }
        }, {
          key: "batcher",
          get: function get() {
            return director.root.batcher2D;
          }
        }, {
          key: "renderEntity",
          get: function get() {
            {
              assert(Boolean(this._renderEntity), 'this._renderEntity should not be invalid');
            }
            return this._renderEntity;
          }
        }]);
        return UIRenderer;
      }(Renderer), _class3$K.BlendState = BlendFactor, _class3$K.Assembler = null, _class3$K.PostAssembler = null, _class3$K), (_applyDecoratedDescriptor(_class2$2A.prototype, "sharedMaterials", [override$1], Object.getOwnPropertyDescriptor(_class2$2A.prototype, "sharedMaterials"), _class2$2A.prototype), _applyDecoratedDescriptor(_class2$2A.prototype, "customMaterial", [_dec3$1F], Object.getOwnPropertyDescriptor(_class2$2A.prototype, "customMaterial"), _class2$2A.prototype), _initializer$2r = applyDecoratedInitializer(_class2$2A.prototype, "_materials", [override$1], function () {
        return [];
      }), _initializer2$22 = applyDecoratedInitializer(_class2$2A.prototype, "_customMaterial", [_dec4$1b], function () {
        return null;
      }), _initializer3$1w = applyDecoratedInitializer(_class2$2A.prototype, "_srcBlendFactor", [serializable$p], function () {
        return BlendFactor.SRC_ALPHA;
      }), _initializer4$1j = applyDecoratedInitializer(_class2$2A.prototype, "_dstBlendFactor", [serializable$p], function () {
        return BlendFactor.ONE_MINUS_SRC_ALPHA;
      }), _initializer5$12 = applyDecoratedInitializer(_class2$2A.prototype, "_color", [serializable$p], function () {
        return Color$1.WHITE.clone();
      })), _class2$2A)) || _class$2T) || _class$2T));
      legacyCC.internal.UIRenderer = UIRenderer;

      var TextStyle = function () {
        function TextStyle() {
          this.isBold = false;
          this.isItalic = false;
          this.isUnderline = false;
          this.underlineHeight = 1;
          this.isOutlined = false;
          this.outlineColor = Color$1.WHITE.clone();
          this.outlineWidth = 1;
          this.hasShadow = false;
          this.shadowColor = Color$1.BLACK.clone();
          this.shadowBlur = 2;
          this.shadowOffsetX = 0;
          this.shadowOffsetY = 0;
          this.color = Color$1.WHITE.clone();
          this.fontSize = 40;
          this.actualFontSize = 0;
          this.isSystemFontUsed = false;
          this.originFontSize = 0;
          this.bmfontScale = 1.0;
          this.fontFamily = 'Arial';
          this.fontDesc = '';
          this.fntConfig = null;
          this.spriteFrame = null;
          this.fontScale = 1;
        }
        var _proto = TextStyle.prototype;
        _proto.reset = function reset() {
          this.isBold = false;
          this.isItalic = false;
          this.isUnderline = false;
          this.underlineHeight = 1;
          this.isOutlined = false;
          this.outlineColor.set();
          this.outlineWidth = 1;
          this.hasShadow = false;
          this.shadowColor.set();
          this.shadowBlur = 2;
          this.shadowOffsetX = 0;
          this.shadowOffsetY = 0;
        };
        return TextStyle;
      }();

      var TextLayout = function () {
        function TextLayout() {
          this.horizontalAlign = 0;
          this.verticalAlign = 0;
          this.wrapping = true;
          this.overFlow = 0;
          this.lineHeight = 10;
          this.maxLineWidth = 0;
          this.spacingX = 0;
          this.textWidthTemp = 0;
          this.textHeightTemp = 0;
          this.textDimensions = new Size$1();
          this.horizontalKerning = [];
          this.numberOfLines = 1;
          this.linesOffsetX = [];
          this.letterOffsetY = 0;
          this.tailoredTopY = 0;
          this.tailoredBottomY = 0;
          this.textDesiredHeight = 0;
          this.linesWidth = [];
        }
        var _proto = TextLayout.prototype;
        _proto.reset = function reset() {
          this.horizontalAlign = 0;
          this.verticalAlign = 0;
          this.wrapping = true;
          this.overFlow = 0;
          this.lineHeight = 10;
          this.maxLineWidth = 0;
          this.spacingX = 0;
          this.textWidthTemp = 0;
          this.textHeightTemp = 0;
          this.textDimensions.set();
          this.horizontalKerning.length = 0;
          this.numberOfLines = 1;
          this.linesOffsetX.length = 0;
          this.letterOffsetY = 0;
          this.tailoredTopY = 0;
          this.tailoredBottomY = 0;
          this.textDesiredHeight = 0;
          this.linesWidth.length = 0;
        };
        return TextLayout;
      }();

      var TextOutputLayoutData = function () {
        function TextOutputLayoutData() {
          this.parsedString = [];
          this.nodeContentSize = Size$1.ZERO.clone();
          this.canvasSize = new Size$1();
          this.canvasPadding = new Rect$1();
          this.contentSizeExtend = Size$1.ZERO.clone();
          this.startPosition = Vec2.ZERO.clone();
        }
        var _proto = TextOutputLayoutData.prototype;
        _proto.reset = function reset() {
          this.parsedString.length = 0;
          this.nodeContentSize.set(0, 0);
          this.canvasSize.set();
          this.canvasPadding.set();
          this.contentSizeExtend.set();
          this.startPosition.set();
        };
        return TextOutputLayoutData;
      }();
      var TextOutputRenderData = function () {
        function TextOutputRenderData() {
          this.quadCount = 0;
          this.vertexBuffer = [];
          this.texture = null;
          this.uiTransAnchorX = 0.5;
          this.uiTransAnchorY = 0.5;
        }
        var _proto2 = TextOutputRenderData.prototype;
        _proto2.reset = function reset() {
          this.quadCount = 0;
          this.vertexBuffer.length = 0;
          this.texture = null;
          this.uiTransAnchorX = 0.5;
          this.uiTransAnchorY = 0.5;
        };
        return TextOutputRenderData;
      }();

      var _dec$2U, _dec2$2f, _dec3$1E, _dec4$1a, _dec5$12, _dec6$O, _dec7$D, _class$2S, _class2$2z, _initializer$2q, _initializer2$21, _initializer3$1v, _initializer4$1i, _initializer5$11, _initializer6$S, _initializer7$G, _initializer8$C, _initializer9$x, _initializer10$u, _initializer11$s, _initializer12$p, _initializer13$m, _initializer14$i, _initializer15$e, _initializer16$e, _initializer17$b, _initializer18$b, _initializer19$a, _initializer20$8, _initializer21$8, _initializer22$7, _initializer23$5, _initializer24$5, _class3$J;
      Color$1.WHITE.clone();
      var HorizontalTextAlignment; exports('H', HorizontalTextAlignment);
      (function (HorizontalTextAlignment) {
        HorizontalTextAlignment[HorizontalTextAlignment["LEFT"] = 0] = "LEFT";
        HorizontalTextAlignment[HorizontalTextAlignment["CENTER"] = 1] = "CENTER";
        HorizontalTextAlignment[HorizontalTextAlignment["RIGHT"] = 2] = "RIGHT";
      })(HorizontalTextAlignment || (exports('H', HorizontalTextAlignment = {})));
      ccenum(HorizontalTextAlignment);
      var VerticalTextAlignment; exports('V', VerticalTextAlignment);
      (function (VerticalTextAlignment) {
        VerticalTextAlignment[VerticalTextAlignment["TOP"] = 0] = "TOP";
        VerticalTextAlignment[VerticalTextAlignment["CENTER"] = 1] = "CENTER";
        VerticalTextAlignment[VerticalTextAlignment["BOTTOM"] = 2] = "BOTTOM";
      })(VerticalTextAlignment || (exports('V', VerticalTextAlignment = {})));
      ccenum(VerticalTextAlignment);
      var Overflow$1; exports('O', Overflow$1);
      (function (Overflow) {
        Overflow[Overflow["NONE"] = 0] = "NONE";
        Overflow[Overflow["CLAMP"] = 1] = "CLAMP";
        Overflow[Overflow["SHRINK"] = 2] = "SHRINK";
        Overflow[Overflow["RESIZE_HEIGHT"] = 3] = "RESIZE_HEIGHT";
      })(Overflow$1 || (exports('O', Overflow$1 = {})));
      ccenum(Overflow$1);
      var CacheMode; exports('q', CacheMode);
      (function (CacheMode) {
        CacheMode[CacheMode["NONE"] = 0] = "NONE";
        CacheMode[CacheMode["BITMAP"] = 1] = "BITMAP";
        CacheMode[CacheMode["CHAR"] = 2] = "CHAR";
      })(CacheMode || (exports('q', CacheMode = {})));
      ccenum(CacheMode);
      var Label = exports('r', (_dec$2U = ccclass$M('cc.Label'), _dec2$2f = executionOrder$1(110), _dec3$1E = type$d(HorizontalTextAlignment), _dec4$1a = type$d(VerticalTextAlignment), _dec5$12 = type$d(Overflow$1), _dec6$O = type$d(Font), _dec7$D = type$d(CacheMode), _dec$2U(_class$2S = _dec2$2f(_class$2S = (_class2$2z = (_class3$J = function (_UIRenderer) {
        _inheritsLoose(Label, _UIRenderer);
        function Label() {
          var _this;
          _this = _UIRenderer.call(this) || this;
          _this._string = _initializer$2q && _initializer$2q();
          _this._horizontalAlign = _initializer2$21 && _initializer2$21();
          _this._verticalAlign = _initializer3$1v && _initializer3$1v();
          _this._actualFontSize = _initializer4$1i && _initializer4$1i();
          _this._fontSize = _initializer5$11 && _initializer5$11();
          _this._fontFamily = _initializer6$S && _initializer6$S();
          _this._lineHeight = _initializer7$G && _initializer7$G();
          _this._overflow = _initializer8$C && _initializer8$C();
          _this._enableWrapText = _initializer9$x && _initializer9$x();
          _this._font = _initializer10$u && _initializer10$u();
          _this._isSystemFontUsed = _initializer11$s && _initializer11$s();
          _this._spacingX = _initializer12$p && _initializer12$p();
          _this._isItalic = _initializer13$m && _initializer13$m();
          _this._isBold = _initializer14$i && _initializer14$i();
          _this._isUnderline = _initializer15$e && _initializer15$e();
          _this._underlineHeight = _initializer16$e && _initializer16$e();
          _this._cacheMode = _initializer17$b && _initializer17$b();
          _this._enableOutline = _initializer18$b && _initializer18$b();
          _this._outlineColor = _initializer19$a && _initializer19$a();
          _this._outlineWidth = _initializer20$8 && _initializer20$8();
          _this._enableShadow = _initializer21$8 && _initializer21$8();
          _this._shadowColor = _initializer22$7 && _initializer22$7();
          _this._shadowOffset = _initializer23$5 && _initializer23$5();
          _this._shadowBlur = _initializer24$5 && _initializer24$5();
          _this._N$file = null;
          _this._texture = null;
          _this._ttfSpriteFrame = null;
          _this._userDefinedFont = null;
          _this._assemblerData = null;
          _this._fontAtlas = null;
          _this._letterTexture = null;
          _this._contentWidth = 0;
          _this._textStyle = null;
          _this._textLayout = null;
          _this._textRenderData = null;
          _this._textLayoutData = null;
          _this._ttfSpriteFrame = null;
          _this._textStyle = new TextStyle();
          _this._textLayout = new TextLayout();
          _this._textLayoutData = new TextOutputLayoutData();
          _this._textRenderData = new TextOutputRenderData();
          return _this;
        }
        var _proto = Label.prototype;
        _proto.onEnable = function onEnable() {
          _UIRenderer.prototype.onEnable.call(this);
          if (!this._font && !this._isSystemFontUsed) {
            this.useSystemFont = true;
          }
          if (this._isSystemFontUsed && !this._fontFamily) {
            this.fontFamily = 'Arial';
          }
          this._applyFontTexture();
        };
        _proto.destroyTtfSpriteFrame = function destroyTtfSpriteFrame() {
          if (!this._ttfSpriteFrame) {
            return;
          }
          this._ttfSpriteFrame._resetDynamicAtlasFrame();
          var tex = this._ttfSpriteFrame.texture;
          this._ttfSpriteFrame.destroy();
          if (tex) {
            var tex2d = tex;
            if (tex2d.image) {
              tex2d.image.destroy();
            }
            tex.destroy();
          }
          this._ttfSpriteFrame = null;
        };
        _proto._onPreDestroy = function _onPreDestroy() {
          _UIRenderer.prototype._onPreDestroy.call(this);
          if (!this._isOnLoadCalled) {
            this.destroyTtfSpriteFrame();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._assembler && this._assembler.resetAssemblerData) {
            this._assembler.resetAssemblerData(this._assemblerData);
          }
          this._assemblerData = null;
          this.destroyTtfSpriteFrame();
          this._letterTexture = null;
          _UIRenderer.prototype.onDestroy.call(this);
        };
        _proto.updateRenderData = function updateRenderData(force) {
          if (force === void 0) {
            force = false;
          }
          if (force) {
            this._flushAssembler();
            if (this.renderData) this.renderData.vertDirty = true;
            this._applyFontTexture();
          }
          if (this._assembler) {
            this._assembler.updateRenderData(this);
          }
        };
        _proto._render = function _render(render) {
          render.commitComp(this, this.renderData, this._texture, this._assembler, null);
        };
        _proto._updateColor = function _updateColor() {
          _UIRenderer.prototype._updateColor.call(this);
          this.markForUpdateRenderData();
        };
        _proto.setEntityColor = function setEntityColor(color) {
        };
        _proto._canRender = function _canRender() {
          if (!_UIRenderer.prototype._canRender.call(this) || !this._string) {
            return false;
          }
          var font = this._font;
          if (font && font instanceof BitmapFont) {
            var spriteFrame = font.spriteFrame;
            if (!spriteFrame || !spriteFrame.texture) {
              return false;
            }
          }
          return true;
        };
        _proto._flushAssembler = function _flushAssembler() {
          var assembler = Label.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this.destroyRenderData();
            this._assembler = assembler;
            this.textStyle.reset();
            this.textLayout.reset();
            this.textLayoutData.reset();
            this.textRenderData.reset();
          }
          if (!this.renderData) {
            if (this._assembler && this._assembler.createData) {
              this._renderData = this._assembler.createData(this);
              this.renderData.material = this.material;
              this._updateColor();
            }
          }
        };
        _proto._applyFontTexture = function _applyFontTexture() {
          this.markForUpdateRenderData();
          var font = this._font;
          if (font instanceof BitmapFont) {
            var spriteFrame = font.spriteFrame;
            if (spriteFrame && spriteFrame.texture) {
              this._texture = spriteFrame;
              if (this.renderData) {
                this.renderData.textureDirty = true;
              }
              this.changeMaterialForDefine();
              if (this._assembler) {
                this._assembler.updateRenderData(this);
              }
            }
          } else {
            if (this.cacheMode === CacheMode.CHAR) {
              this._letterTexture = this._assembler.getAssemblerData();
              this._texture = this._letterTexture;
            } else if (!this._ttfSpriteFrame) {
              this._ttfSpriteFrame = new SpriteFrame();
              this._assemblerData = this._assembler.getAssemblerData();
              var image = new ImageAsset(this._assemblerData.canvas);
              var texture = new Texture2D();
              texture.image = image;
              this._ttfSpriteFrame.texture = texture;
            }
            if (this.cacheMode !== CacheMode.CHAR) {
              this._texture = this._ttfSpriteFrame;
            }
            this.changeMaterialForDefine();
          }
        };
        _proto.changeMaterialForDefine = function changeMaterialForDefine() {
          if (!this._texture) {
            return;
          }
          var value = false;
          if (this.cacheMode !== CacheMode.CHAR) {
            var spriteFrame = this._texture;
            var texture = spriteFrame.texture;
            if (texture instanceof TextureBase) {
              var format = texture.getPixelFormat();
              value = format === PixelFormat.RGBA_ETC1 || format === PixelFormat.RGB_A_PVRTC_4BPPV1 || format === PixelFormat.RGB_A_PVRTC_2BPPV1;
            }
          }
          if (value) {
            this._instanceMaterialType = InstanceMaterialType.USE_ALPHA_SEPARATED;
          } else {
            this._instanceMaterialType = InstanceMaterialType.ADD_COLOR_AND_TEXTURE;
          }
          this.updateMaterial();
        };
        _proto._updateBlendFunc = function _updateBlendFunc() {
          _UIRenderer.prototype._updateBlendFunc.call(this);
        };
        _createClass(Label, [{
          key: "string",
          get: function get() {
            return this._string;
          },
          set: function set(value) {
            if (value === null || value === undefined) {
              value = '';
            } else {
              value = value.toString();
            }
            if (this._string === value) {
              return;
            }
            this._string = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "horizontalAlign",
          get: function get() {
            return this._horizontalAlign;
          },
          set: function set(value) {
            if (this._horizontalAlign === value) {
              return;
            }
            this._horizontalAlign = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "verticalAlign",
          get: function get() {
            return this._verticalAlign;
          },
          set: function set(value) {
            if (this._verticalAlign === value) {
              return;
            }
            this._verticalAlign = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "actualFontSize",
          get: function get() {
            return this._actualFontSize;
          },
          set: function set(value) {
            this._actualFontSize = value;
          }
        }, {
          key: "fontSize",
          get: function get() {
            return this._fontSize;
          },
          set: function set(value) {
            if (this._fontSize === value) {
              return;
            }
            this._fontSize = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "lineHeight",
          get: function get() {
            return this._lineHeight;
          },
          set: function set(value) {
            if (this._lineHeight === value) {
              return;
            }
            this._lineHeight = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "spacingX",
          get: function get() {
            return this._spacingX;
          },
          set: function set(value) {
            if (this._spacingX === value) {
              return;
            }
            this._spacingX = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "overflow",
          get: function get() {
            return this._overflow;
          },
          set: function set(value) {
            if (this._overflow === value) {
              return;
            }
            this._overflow = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "enableWrapText",
          get: function get() {
            return this._enableWrapText;
          },
          set: function set(value) {
            if (this._enableWrapText === value) {
              return;
            }
            this._enableWrapText = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "useSystemFont",
          get: function get() {
            return this._isSystemFontUsed;
          },
          set: function set(value) {
            if (this._isSystemFontUsed === value) {
              return;
            }
            this.destroyRenderData();
            this._isSystemFontUsed = !!value;
            if (value) {
              this.font = null;
            }
            this._flushAssembler();
            this.markForUpdateRenderData();
          }
        }, {
          key: "fontFamily",
          get: function get() {
            return this._fontFamily;
          },
          set: function set(value) {
            if (this._fontFamily === value) {
              return;
            }
            this._fontFamily = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "font",
          get: function get() {
            return this._font;
          },
          set: function set(value) {
            if (this._font === value) {
              return;
            }
            this._isSystemFontUsed = !value;
            this._font = value;
            this.destroyRenderData();
            this._fontAtlas = null;
            this.updateRenderData(true);
          }
        }, {
          key: "cacheMode",
          get: function get() {
            return this._cacheMode;
          },
          set: function set(value) {
            if (this._cacheMode === value) {
              return;
            }
            if (this._cacheMode === CacheMode.BITMAP && !(this._font instanceof BitmapFont) && this._ttfSpriteFrame) {
              this._ttfSpriteFrame._resetDynamicAtlasFrame();
            }
            if (this._cacheMode === CacheMode.CHAR) {
              this._ttfSpriteFrame = null;
            }
            this._cacheMode = value;
            this.updateRenderData(true);
          }
        }, {
          key: "isBold",
          get: function get() {
            return this._isBold;
          },
          set: function set(value) {
            if (this._isBold === value) {
              return;
            }
            this._isBold = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "isItalic",
          get: function get() {
            return this._isItalic;
          },
          set: function set(value) {
            if (this._isItalic === value) {
              return;
            }
            this._isItalic = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "isUnderline",
          get: function get() {
            return this._isUnderline;
          },
          set: function set(value) {
            if (this._isUnderline === value) {
              return;
            }
            this._isUnderline = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "underlineHeight",
          get: function get() {
            return this._underlineHeight;
          },
          set: function set(value) {
            if (this._underlineHeight === value) return;
            this._underlineHeight = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "enableOutline",
          get: function get() {
            return this._enableOutline;
          },
          set: function set(value) {
            if (this._enableOutline === value) return;
            this._enableOutline = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "outlineColor",
          get: function get() {
            return this._outlineColor;
          },
          set: function set(value) {
            if (this._outlineColor === value) return;
            this._outlineColor.set(value);
            this.markForUpdateRenderData();
          }
        }, {
          key: "outlineWidth",
          get: function get() {
            return this._outlineWidth;
          },
          set: function set(value) {
            if (this._outlineWidth === value) return;
            this._outlineWidth = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "enableShadow",
          get: function get() {
            return this._enableShadow;
          },
          set: function set(value) {
            if (this._enableShadow === value) return;
            this._enableShadow = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "shadowColor",
          get: function get() {
            return this._shadowColor;
          },
          set: function set(value) {
            if (this._shadowColor === value) return;
            this._shadowColor.set(value);
            this.markForUpdateRenderData();
          }
        }, {
          key: "shadowOffset",
          get: function get() {
            return this._shadowOffset;
          },
          set: function set(value) {
            if (this._shadowOffset === value) return;
            this._shadowOffset.set(value);
            this.markForUpdateRenderData();
          }
        }, {
          key: "shadowBlur",
          get: function get() {
            return this._shadowBlur;
          },
          set: function set(value) {
            if (this._shadowBlur === value) return;
            this._shadowBlur = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "spriteFrame",
          get: function get() {
            return this._texture;
          }
        }, {
          key: "ttfSpriteFrame",
          get: function get() {
            return this._ttfSpriteFrame;
          }
        }, {
          key: "assemblerData",
          get: function get() {
            return this._assemblerData;
          }
        }, {
          key: "fontAtlas",
          get: function get() {
            return this._fontAtlas;
          },
          set: function set(value) {
            this._fontAtlas = value;
          }
        }, {
          key: "_bmFontOriginalSize",
          get: function get() {
            if (this._font instanceof BitmapFont) {
              return this._font.fontSize;
            } else {
              return -1;
            }
          }
        }, {
          key: "textStyle",
          get: function get() {
            return this._textStyle;
          }
        }, {
          key: "textLayout",
          get: function get() {
            return this._textLayout;
          }
        }, {
          key: "textRenderData",
          get: function get() {
            return this._textRenderData;
          }
        }, {
          key: "textLayoutData",
          get: function get() {
            return this._textLayoutData;
          }
        }, {
          key: "contentWidth",
          get: function get() {
            return this._contentWidth;
          },
          set: function set(val) {
            this._contentWidth = val;
          }
        }]);
        return Label;
      }(UIRenderer), _class3$J.HorizontalAlign = HorizontalTextAlignment, _class3$J.VerticalAlign = VerticalTextAlignment, _class3$J.Overflow = Overflow$1, _class3$J.CacheMode = CacheMode, _class3$J._canvasPool = CanvasPool.getInstance(), _class3$J), (_applyDecoratedDescriptor(_class2$2z.prototype, "horizontalAlign", [_dec3$1E], Object.getOwnPropertyDescriptor(_class2$2z.prototype, "horizontalAlign"), _class2$2z.prototype), _applyDecoratedDescriptor(_class2$2z.prototype, "verticalAlign", [_dec4$1a], Object.getOwnPropertyDescriptor(_class2$2z.prototype, "verticalAlign"), _class2$2z.prototype), _applyDecoratedDescriptor(_class2$2z.prototype, "overflow", [_dec5$12], Object.getOwnPropertyDescriptor(_class2$2z.prototype, "overflow"), _class2$2z.prototype), _applyDecoratedDescriptor(_class2$2z.prototype, "font", [_dec6$O], Object.getOwnPropertyDescriptor(_class2$2z.prototype, "font"), _class2$2z.prototype), _applyDecoratedDescriptor(_class2$2z.prototype, "cacheMode", [_dec7$D], Object.getOwnPropertyDescriptor(_class2$2z.prototype, "cacheMode"), _class2$2z.prototype), _initializer$2q = applyDecoratedInitializer(_class2$2z.prototype, "_string", [serializable$p], function () {
        return 'label';
      }), _initializer2$21 = applyDecoratedInitializer(_class2$2z.prototype, "_horizontalAlign", [serializable$p], function () {
        return HorizontalTextAlignment.CENTER;
      }), _initializer3$1v = applyDecoratedInitializer(_class2$2z.prototype, "_verticalAlign", [serializable$p], function () {
        return VerticalTextAlignment.CENTER;
      }), _initializer4$1i = applyDecoratedInitializer(_class2$2z.prototype, "_actualFontSize", [serializable$p], function () {
        return 0;
      }), _initializer5$11 = applyDecoratedInitializer(_class2$2z.prototype, "_fontSize", [serializable$p], function () {
        return 40;
      }), _initializer6$S = applyDecoratedInitializer(_class2$2z.prototype, "_fontFamily", [serializable$p], function () {
        return 'Arial';
      }), _initializer7$G = applyDecoratedInitializer(_class2$2z.prototype, "_lineHeight", [serializable$p], function () {
        return 40;
      }), _initializer8$C = applyDecoratedInitializer(_class2$2z.prototype, "_overflow", [serializable$p], function () {
        return Overflow$1.NONE;
      }), _initializer9$x = applyDecoratedInitializer(_class2$2z.prototype, "_enableWrapText", [serializable$p], function () {
        return true;
      }), _initializer10$u = applyDecoratedInitializer(_class2$2z.prototype, "_font", [serializable$p], function () {
        return null;
      }), _initializer11$s = applyDecoratedInitializer(_class2$2z.prototype, "_isSystemFontUsed", [serializable$p], function () {
        return true;
      }), _initializer12$p = applyDecoratedInitializer(_class2$2z.prototype, "_spacingX", [serializable$p], function () {
        return 0;
      }), _initializer13$m = applyDecoratedInitializer(_class2$2z.prototype, "_isItalic", [serializable$p], function () {
        return false;
      }), _initializer14$i = applyDecoratedInitializer(_class2$2z.prototype, "_isBold", [serializable$p], function () {
        return false;
      }), _initializer15$e = applyDecoratedInitializer(_class2$2z.prototype, "_isUnderline", [serializable$p], function () {
        return false;
      }), _initializer16$e = applyDecoratedInitializer(_class2$2z.prototype, "_underlineHeight", [serializable$p], function () {
        return 2;
      }), _initializer17$b = applyDecoratedInitializer(_class2$2z.prototype, "_cacheMode", [serializable$p], function () {
        return CacheMode.NONE;
      }), _initializer18$b = applyDecoratedInitializer(_class2$2z.prototype, "_enableOutline", [serializable$p], function () {
        return false;
      }), _initializer19$a = applyDecoratedInitializer(_class2$2z.prototype, "_outlineColor", [serializable$p], function () {
        return new Color$1(0, 0, 0, 255);
      }), _initializer20$8 = applyDecoratedInitializer(_class2$2z.prototype, "_outlineWidth", [serializable$p], function () {
        return 2;
      }), _initializer21$8 = applyDecoratedInitializer(_class2$2z.prototype, "_enableShadow", [serializable$p], function () {
        return false;
      }), _initializer22$7 = applyDecoratedInitializer(_class2$2z.prototype, "_shadowColor", [serializable$p], function () {
        return new Color$1(0, 0, 0, 255);
      }), _initializer23$5 = applyDecoratedInitializer(_class2$2z.prototype, "_shadowOffset", [serializable$p], function () {
        return new Vec2(2, 2);
      }), _initializer24$5 = applyDecoratedInitializer(_class2$2z.prototype, "_shadowBlur", [serializable$p], function () {
        return 2;
      })), _class2$2z)) || _class$2S) || _class$2S));
      legacyCC.Label = Label;

      var _stageOffset = 0;
      var _name2stageID = {};
      var config = {
        addStage: function addStage(name) {
          if (_name2stageID[name] !== undefined) {
            return;
          }
          var stageID = 1 << _stageOffset;
          _name2stageID[name] = stageID;
          _stageOffset += 1;
        },
        stageID: function stageID(name) {
          var id = _name2stageID[name];
          if (id === undefined) {
            return -1;
          }
          return id;
        },
        stageIDs: function stageIDs(nameList) {
          var key = 0;
          for (var _iterator = _createForOfIteratorHelperLoose(nameList), _step; !(_step = _iterator()).done;) {
            var name = _step.value;
            var id = _name2stageID[name];
            if (id !== undefined) {
              key |= id;
            }
          }
          return key;
        }
      };

      function createIA(device, data) {
        if (!data.positions) {
          console.error('The data must have positions field');
          return null;
        }
        var verts = [];
        var vcount = data.positions.length / 3;
        for (var i = 0; i < vcount; ++i) {
          verts.push(data.positions[3 * i], data.positions[3 * i + 1], data.positions[3 * i + 2]);
          if (data.normals) {
            verts.push(data.normals[3 * i], data.normals[3 * i + 1], data.normals[3 * i + 2]);
          }
          if (data.uvs) {
            verts.push(data.uvs[2 * i], data.uvs[2 * i + 1]);
          }
          if (data.colors) {
            verts.push(data.colors[3 * i], data.colors[3 * i + 1], data.colors[3 * i + 2]);
          }
        }
        var vfmt = [];
        vfmt.push(new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F));
        if (data.normals) {
          vfmt.push(new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F));
        }
        if (data.uvs) {
          vfmt.push(new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F));
        }
        if (data.colors) {
          vfmt.push(new Attribute(AttributeName.ATTR_COLOR, Format.RGB32F));
        }
        var vb = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, verts.length * 4, verts.length * 4 / vcount));
        vb.update(new Float32Array(verts));
        var ib = null;
        if (data.indices) {
          ib = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, data.indices.length * 2, 2));
          ib.update(new Uint16Array(data.indices));
        }
        return device.createInputAssembler(new InputAssemblerInfo(vfmt, [vb], ib));
      }

      var RenderQueue;
      (function (RenderQueue) {
        RenderQueue[RenderQueue["OPAQUE"] = 0] = "OPAQUE";
        RenderQueue[RenderQueue["TRANSPARENT"] = 1] = "TRANSPARENT";
        RenderQueue[RenderQueue["OVERLAY"] = 2] = "OVERLAY";
      })(RenderQueue || (RenderQueue = {}));
      var PassStage;
      (function (PassStage) {
        PassStage[PassStage["DEFAULT"] = 1] = "DEFAULT";
        PassStage[PassStage["FORWARD"] = 2] = "FORWARD";
        PassStage[PassStage["SHADOWCAST"] = 4] = "SHADOWCAST";
      })(PassStage || (PassStage = {}));

      function nearestPOT(num) {
        --num;
        num |= num >> 16;
        num |= num >> 8;
        num |= num >> 4;
        num |= num >> 2;
        num |= num >> 1;
        ++num;
        return num;
      }
      function roundUp(n, alignment) {
        return Math.ceil(n / alignment) * alignment;
      }
      var TextureBufferPool = function () {
        function TextureBufferPool(device) {
          this._device = void 0;
          this._format = Format.UNKNOWN;
          this._formatSize = 0;
          this._chunks = [];
          this._chunkCount = 0;
          this._handles = [];
          this._region0 = new BufferTextureCopy();
          this._region1 = new BufferTextureCopy();
          this._region2 = new BufferTextureCopy();
          this._roundUpFn = null;
          this._bufferViewCtor = Uint8Array;
          this._channels = 4;
          this._alignment = 1;
          this._device = device;
        }
        var _proto = TextureBufferPool.prototype;
        _proto.initialize = function initialize(info) {
          var formatInfo = FormatInfos[info.format];
          this._format = info.format;
          this._formatSize = formatInfo.size;
          this._channels = formatInfo.count;
          this._bufferViewCtor = getTypedArrayConstructor(formatInfo);
          this._roundUpFn = info.roundUpFn || null;
          this._alignment = info.alignment || 1;
          if (info.inOrderFree) {
            this.alloc = this._McDonaldAlloc;
          }
        };
        _proto.destroy = function destroy() {
          for (var i = 0; i < this._chunkCount; ++i) {
            var chunk = this._chunks[i];
            chunk.texture.destroy();
          }
          this._chunks.length = 0;
          this._handles.length = 0;
        };
        _proto.alloc = function alloc(size, chunkIdx) {
          size = roundUp(size, this._alignment);
          var index = -1;
          var start = -1;
          if (chunkIdx !== undefined) {
            index = chunkIdx;
            start = this._findAvailableSpace(size, index);
          }
          if (start < 0) {
            for (var i = 0; i < this._chunkCount; ++i) {
              index = i;
              start = this._findAvailableSpace(size, index);
              if (start >= 0) {
                break;
              }
            }
          }
          if (start >= 0) {
            var chunk = this._chunks[index];
            chunk.start += size;
            var handle = {
              chunkIdx: index,
              start: start,
              end: start + size,
              texture: chunk.texture
            };
            this._handles.push(handle);
            return handle;
          }
          var targetSize = Math.sqrt(size / this._formatSize);
          var texLength = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize));
          var newChunk = this._chunks[this.createChunk(texLength)];
          newChunk.start += size;
          var texHandle = {
            chunkIdx: this._chunkCount - 1,
            start: 0,
            end: size,
            texture: newChunk.texture
          };
          this._handles.push(texHandle);
          return texHandle;
        };
        _proto.free = function free(handle) {
          for (var i = 0; i < this._handles.length; ++i) {
            if (this._handles[i] === handle) {
              this._chunks[handle.chunkIdx].end = handle.end;
              this._handles.splice(i, 1);
              return;
            }
          }
        };
        _proto.createChunk = function createChunk(length) {
          var texSize = length * length * this._formatSize;
          debug("TextureBufferPool: Allocate chunk " + this._chunkCount + ", size: " + texSize + ", format: " + this._format);
          var texture = this._device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, this._format, length, length));
          var chunk = {
            texture: texture,
            size: texSize,
            start: 0,
            end: texSize
          };
          this._chunks[this._chunkCount] = chunk;
          return this._chunkCount++;
        };
        _proto.update = function update(handle, buffer) {
          var buffers = [];
          var regions = [];
          var start = handle.start / this._formatSize;
          var remainSize = buffer.byteLength / this._formatSize;
          var offsetX = start % handle.texture.width;
          var offsetY = Math.floor(start / handle.texture.width);
          var copySize = Math.min(handle.texture.width - offsetX, remainSize);
          var begin = 0;
          if (offsetX > 0) {
            this._region0.texOffset.x = offsetX;
            this._region0.texOffset.y = offsetY;
            this._region0.texExtent.width = copySize;
            this._region0.texExtent.height = 1;
            buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, copySize * this._channels));
            regions.push(this._region0);
            offsetX = 0;
            offsetY += 1;
            remainSize -= copySize;
            begin += copySize;
          }
          if (remainSize > 0) {
            this._region1.texOffset.x = offsetX;
            this._region1.texOffset.y = offsetY;
            if (remainSize > handle.texture.width) {
              this._region1.texExtent.width = handle.texture.width;
              this._region1.texExtent.height = Math.floor(remainSize / handle.texture.width);
              copySize = this._region1.texExtent.width * this._region1.texExtent.height;
            } else {
              copySize = remainSize;
              this._region1.texExtent.width = copySize;
              this._region1.texExtent.height = 1;
            }
            buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, copySize * this._channels));
            regions.push(this._region1);
            offsetX = 0;
            offsetY += this._region1.texExtent.height;
            remainSize -= copySize;
            begin += copySize;
          }
          if (remainSize > 0) {
            this._region2.texOffset.x = offsetX;
            this._region2.texOffset.y = offsetY;
            this._region2.texExtent.width = remainSize;
            this._region2.texExtent.height = 1;
            buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, remainSize * this._channels));
            regions.push(this._region2);
          }
          this._device.copyBuffersToTexture(buffers, handle.texture, regions);
        };
        _proto._findAvailableSpace = function _findAvailableSpace(size, chunkIdx) {
          var chunk = this._chunks[chunkIdx];
          var isFound = false;
          var start = chunk.start;
          if (start + size <= chunk.size) {
            isFound = true;
          } else {
            start = 0;
            var handles = this._handles.filter(function (h) {
              return h.chunkIdx === chunkIdx;
            }).sort(function (a, b) {
              return a.start - b.start;
            });
            for (var i = 0; i < handles.length; i++) {
              var handle = handles[i];
              if (start + size <= handle.start) {
                isFound = true;
                break;
              }
              start = handle.end;
            }
            if (!isFound && start + size <= chunk.size) {
              isFound = true;
            }
          }
          return isFound ? start : -1;
        };
        _proto._McDonaldAlloc = function _McDonaldAlloc(size) {
          size = roundUp(size, this._alignment);
          for (var i = 0; i < this._chunkCount; ++i) {
            var chunk = this._chunks[i];
            var isFound = false;
            var start = chunk.start;
            if (start + size <= chunk.end) {
              isFound = true;
            } else if (start > chunk.end) {
              if (start + size <= chunk.size) {
                isFound = true;
              } else if (size <= chunk.end) {
                chunk.start = start = 0;
                isFound = true;
              }
            } else if (start === chunk.end) {
              chunk.start = start = 0;
              chunk.end = chunk.size;
              if (size <= chunk.end) {
                isFound = true;
              }
            }
            if (isFound) {
              chunk.start += size;
              var handle = {
                chunkIdx: i,
                start: start,
                end: start + size,
                texture: chunk.texture
              };
              this._handles.push(handle);
              return handle;
            }
          }
          var targetSize = Math.sqrt(size / this._formatSize);
          var texLength = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize));
          var newChunk = this._chunks[this.createChunk(texLength)];
          newChunk.start += size;
          var texHandle = {
            chunkIdx: this._chunkCount,
            start: 0,
            end: size,
            texture: newChunk.texture
          };
          this._handles.push(texHandle);
          return texHandle;
        };
        return TextureBufferPool;
      }();

      var NativeBufferPool = function () {
        function NativeBufferPool(dataType, entryBits, stride) {
          this._arrayBuffers = [];
          this._chunkSize = void 0;
          this._chunkSize = stride * (1 << entryBits);
        }
        var _proto = NativeBufferPool.prototype;
        _proto.allocateNewChunk = function allocateNewChunk() {
          return new ArrayBuffer(this._chunkSize);
        };
        return NativeBufferPool;
      }();

      var _Render2dViewDataType, _Render2dViewDataMemb, _NodeViewDataType, _NodeViewDataMembers, _PassViewDataType, _PassViewDataMembers, _AABBViewDataType, _AABBViewDataMembers;
      var contains = function contains(a, t) {
        for (var i = 0; i < a.length; ++i) {
          if (a[i] === t) return true;
        }
        return false;
      };
      var BufferDataType;
      (function (BufferDataType) {
        BufferDataType[BufferDataType["UINT32"] = 0] = "UINT32";
        BufferDataType[BufferDataType["FLOAT32"] = 1] = "FLOAT32";
        BufferDataType[BufferDataType["NEVER"] = 2] = "NEVER";
      })(BufferDataType || (BufferDataType = {}));
      var BufferPool = function () {
        function BufferPool(poolType, dataType, dataMembers, enumType, entryBits) {
          if (entryBits === void 0) {
            entryBits = 8;
          }
          this._dataType = void 0;
          this._dataMembers = void 0;
          this._elementCount = void 0;
          this._entryBits = void 0;
          this._stride = void 0;
          this._entriesPerChunk = void 0;
          this._entryMask = void 0;
          this._chunkMask = void 0;
          this._poolFlag = void 0;
          this._arrayBuffers = [];
          this._freeLists = [];
          this._uint32BufferViews = [];
          this._float32BufferViews = [];
          this._hasUint32 = false;
          this._hasFloat32 = false;
          this._nativePool = void 0;
          this._elementCount = enumType.COUNT;
          this._entryBits = entryBits;
          this._dataType = dataType;
          this._dataMembers = dataMembers;
          var bytesPerElement = 4;
          this._stride = bytesPerElement * this._elementCount;
          this._entriesPerChunk = 1 << entryBits;
          this._entryMask = this._entriesPerChunk - 1;
          this._poolFlag = 1 << 30;
          this._chunkMask = ~(this._entryMask | this._poolFlag);
          this._nativePool = new NativeBufferPool(poolType, entryBits, this._stride);
          var type = BufferDataType.NEVER;
          var hasFloat32 = false;
          var hasUint32 = false;
          for (var e in dataType) {
            hasFloat32 = this._hasFloat32;
            hasUint32 = this._hasUint32;
            if (hasUint32 && hasFloat32) {
              break;
            }
            type = dataType[e];
            if (!hasFloat32 && type === BufferDataType.FLOAT32) {
              this._hasFloat32 = true;
            } else if (!hasUint32 && type === BufferDataType.UINT32) {
              this._hasUint32 = true;
            }
          }
        }
        var _proto = BufferPool.prototype;
        _proto.alloc = function alloc() {
          var i = 0;
          for (; i < this._freeLists.length; i++) {
            var list = this._freeLists[i];
            if (list.length) {
              var j = list[list.length - 1];
              list.length--;
              return (i << this._entryBits) + j + this._poolFlag;
            }
          }
          var buffer = this._nativePool.allocateNewChunk();
          var float32BufferViews = [];
          var uint32BufferViews = [];
          var freeList = [];
          var hasFloat32 = this._hasFloat32;
          var hasUint32 = this._hasUint32;
          for (var _j = 0; _j < this._entriesPerChunk; _j++) {
            if (hasFloat32) {
              float32BufferViews.push(new Float32Array(buffer, this._stride * _j, this._elementCount));
            }
            if (hasUint32) {
              uint32BufferViews.push(new Uint32Array(buffer, this._stride * _j, this._elementCount));
            }
            if (_j) {
              freeList.push(_j);
            }
          }
          if (hasUint32) {
            this._uint32BufferViews.push(uint32BufferViews);
          }
          if (hasFloat32) {
            this._float32BufferViews.push(float32BufferViews);
          }
          this._freeLists.push(freeList);
          this._arrayBuffers.push(buffer);
          var handle = (i << this._entryBits) + this._poolFlag;
          return handle;
        };
        _proto.getBuffer = function getBuffer(handle) {
          var chunk = (this._chunkMask & handle) >> this._entryBits;
          var entry = this._entryMask & handle;
          var bufferViews = this._hasFloat32 ? this._float32BufferViews : this._uint32BufferViews;
          if ((!handle || chunk < 0 || chunk >= bufferViews.length || entry < 0 || entry >= this._entriesPerChunk || contains(this._freeLists[chunk], entry))) {
            console.warn('invalid buffer pool handle');
            return [];
          }
          return bufferViews[chunk][entry];
        };
        _proto.getTypedArray = function getTypedArray(handle, element) {
          var chunk = (this._chunkMask & handle) >> this._entryBits;
          var entry = this._entryMask & handle;
          var bufferViews = this._dataType[element] === BufferDataType.UINT32 ? this._uint32BufferViews : this._float32BufferViews;
          if ((!handle || chunk < 0 || chunk >= bufferViews.length || entry < 0 || entry >= this._entriesPerChunk || contains(this._freeLists[chunk], entry))) {
            console.warn('invalid buffer pool handle');
            return [];
          }
          var index = element;
          var view = bufferViews[chunk][entry];
          var count = this._dataMembers[element];
          return view.subarray(index, index + count);
        };
        _proto.free = function free(handle) {
          var chunk = (this._chunkMask & handle) >> this._entryBits;
          var entry = this._entryMask & handle;
          if ((!handle || chunk < 0 || chunk >= this._freeLists.length || entry < 0 || entry >= this._entriesPerChunk || contains(this._freeLists[chunk], entry))) {
            console.warn('invalid buffer pool handle');
            return;
          }
          var bufferViews = this._hasUint32 ? this._uint32BufferViews : this._float32BufferViews;
          bufferViews[chunk][entry].fill(0);
          this._freeLists[chunk].push(entry);
        };
        return BufferPool;
      }();
      var PoolType;
      (function (PoolType) {
        PoolType[PoolType["NODE"] = 0] = "NODE";
        PoolType[PoolType["PASS"] = 1] = "PASS";
        PoolType[PoolType["AABB"] = 2] = "AABB";
        PoolType[PoolType["RENDER2D"] = 3] = "RENDER2D";
      })(PoolType || (PoolType = {}));
      var NULL_HANDLE = 0;
      var Render2dView;
      (function (Render2dView) {
        Render2dView[Render2dView["POSITION"] = 0] = "POSITION";
        Render2dView[Render2dView["UV"] = 3] = "UV";
        Render2dView[Render2dView["COLOR"] = 5] = "COLOR";
        Render2dView[Render2dView["COUNT"] = 9] = "COUNT";
      })(Render2dView || (Render2dView = {}));
      var Render2dViewDataType = (_Render2dViewDataType = {}, _Render2dViewDataType[Render2dView.POSITION] = BufferDataType.FLOAT32, _Render2dViewDataType[Render2dView.UV] = BufferDataType.FLOAT32, _Render2dViewDataType[Render2dView.COLOR] = BufferDataType.UINT32, _Render2dViewDataType[Render2dView.COUNT] = BufferDataType.NEVER, _Render2dViewDataType);
      var Render2dViewDataMembers = (_Render2dViewDataMemb = {}, _Render2dViewDataMemb[Render2dView.POSITION] = Render2dView.UV - Render2dView.POSITION, _Render2dViewDataMemb[Render2dView.UV] = Render2dView.COLOR - Render2dView.UV, _Render2dViewDataMemb[Render2dView.COLOR] = Render2dView.COUNT - Render2dView.COLOR, _Render2dViewDataMemb[Render2dView.COUNT] = 1, _Render2dViewDataMemb);
      var Render2dPool = new BufferPool(PoolType.RENDER2D, Render2dViewDataType, Render2dViewDataMembers, Render2dView);
      var NodeView;
      (function (NodeView) {
        NodeView[NodeView["DIRTY_FLAG"] = 0] = "DIRTY_FLAG";
        NodeView[NodeView["LAYER"] = 1] = "LAYER";
        NodeView[NodeView["WORLD_SCALE"] = 2] = "WORLD_SCALE";
        NodeView[NodeView["WORLD_POSITION"] = 5] = "WORLD_POSITION";
        NodeView[NodeView["WORLD_ROTATION"] = 8] = "WORLD_ROTATION";
        NodeView[NodeView["WORLD_MATRIX"] = 12] = "WORLD_MATRIX";
        NodeView[NodeView["LOCAL_SCALE"] = 28] = "LOCAL_SCALE";
        NodeView[NodeView["LOCAL_POSITION"] = 31] = "LOCAL_POSITION";
        NodeView[NodeView["LOCAL_ROTATION"] = 34] = "LOCAL_ROTATION";
        NodeView[NodeView["COUNT"] = 38] = "COUNT";
      })(NodeView || (NodeView = {}));
      var NodeViewDataType = (_NodeViewDataType = {}, _NodeViewDataType[NodeView.DIRTY_FLAG] = BufferDataType.UINT32, _NodeViewDataType[NodeView.LAYER] = BufferDataType.UINT32, _NodeViewDataType[NodeView.WORLD_SCALE] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.WORLD_POSITION] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.WORLD_ROTATION] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.WORLD_MATRIX] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.LOCAL_SCALE] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.LOCAL_POSITION] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.LOCAL_ROTATION] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.COUNT] = BufferDataType.NEVER, _NodeViewDataType);
      var NodeViewDataMembers = (_NodeViewDataMembers = {}, _NodeViewDataMembers[NodeView.DIRTY_FLAG] = NodeView.LAYER - NodeView.DIRTY_FLAG, _NodeViewDataMembers[NodeView.LAYER] = NodeView.WORLD_SCALE - NodeView.LAYER, _NodeViewDataMembers[NodeView.WORLD_SCALE] = NodeView.WORLD_POSITION - NodeView.WORLD_SCALE, _NodeViewDataMembers[NodeView.WORLD_POSITION] = NodeView.WORLD_ROTATION - NodeView.WORLD_POSITION, _NodeViewDataMembers[NodeView.WORLD_ROTATION] = NodeView.WORLD_MATRIX - NodeView.WORLD_ROTATION, _NodeViewDataMembers[NodeView.WORLD_MATRIX] = NodeView.LOCAL_SCALE - NodeView.WORLD_MATRIX, _NodeViewDataMembers[NodeView.LOCAL_SCALE] = NodeView.LOCAL_POSITION - NodeView.LOCAL_SCALE, _NodeViewDataMembers[NodeView.LOCAL_POSITION] = NodeView.LOCAL_ROTATION - NodeView.LOCAL_POSITION, _NodeViewDataMembers[NodeView.LOCAL_ROTATION] = NodeView.COUNT - NodeView.LOCAL_ROTATION, _NodeViewDataMembers[NodeView.COUNT] = 1, _NodeViewDataMembers);
      var NodePool$1 = new BufferPool(PoolType.NODE, NodeViewDataType, NodeViewDataMembers, NodeView);
      var PassView;
      (function (PassView) {
        PassView[PassView["PRIORITY"] = 0] = "PRIORITY";
        PassView[PassView["STAGE"] = 1] = "STAGE";
        PassView[PassView["PHASE"] = 2] = "PHASE";
        PassView[PassView["PRIMITIVE"] = 3] = "PRIMITIVE";
        PassView[PassView["BATCHING_SCHEME"] = 4] = "BATCHING_SCHEME";
        PassView[PassView["DYNAMIC_STATE"] = 5] = "DYNAMIC_STATE";
        PassView[PassView["HASH"] = 6] = "HASH";
        PassView[PassView["COUNT"] = 7] = "COUNT";
      })(PassView || (PassView = {}));
      var PassViewDataType = (_PassViewDataType = {}, _PassViewDataType[PassView.PRIORITY] = BufferDataType.UINT32, _PassViewDataType[PassView.STAGE] = BufferDataType.UINT32, _PassViewDataType[PassView.PHASE] = BufferDataType.UINT32, _PassViewDataType[PassView.PRIMITIVE] = BufferDataType.UINT32, _PassViewDataType[PassView.BATCHING_SCHEME] = BufferDataType.UINT32, _PassViewDataType[PassView.DYNAMIC_STATE] = BufferDataType.UINT32, _PassViewDataType[PassView.HASH] = BufferDataType.UINT32, _PassViewDataType[PassView.COUNT] = BufferDataType.NEVER, _PassViewDataType);
      var PassViewDataMembers = (_PassViewDataMembers = {}, _PassViewDataMembers[PassView.PRIORITY] = PassView.STAGE - PassView.PRIORITY, _PassViewDataMembers[PassView.STAGE] = PassView.PHASE - PassView.STAGE, _PassViewDataMembers[PassView.PHASE] = PassView.PRIMITIVE - PassView.PHASE, _PassViewDataMembers[PassView.PRIMITIVE] = PassView.BATCHING_SCHEME - PassView.PRIMITIVE, _PassViewDataMembers[PassView.BATCHING_SCHEME] = PassView.DYNAMIC_STATE - PassView.BATCHING_SCHEME, _PassViewDataMembers[PassView.DYNAMIC_STATE] = PassView.HASH - PassView.DYNAMIC_STATE, _PassViewDataMembers[PassView.HASH] = PassView.COUNT - PassView.HASH, _PassViewDataMembers[PassView.COUNT] = 1, _PassViewDataMembers);
      var PassPool = new BufferPool(PoolType.PASS, PassViewDataType, PassViewDataMembers, PassView);
      var AABBView;
      (function (AABBView) {
        AABBView[AABBView["CENTER"] = 0] = "CENTER";
        AABBView[AABBView["HALFEXTENTS"] = 3] = "HALFEXTENTS";
        AABBView[AABBView["COUNT"] = 6] = "COUNT";
      })(AABBView || (AABBView = {}));
      var AABBViewDataType = (_AABBViewDataType = {}, _AABBViewDataType[AABBView.CENTER] = BufferDataType.FLOAT32, _AABBViewDataType[AABBView.HALFEXTENTS] = BufferDataType.FLOAT32, _AABBViewDataType[AABBView.COUNT] = BufferDataType.NEVER, _AABBViewDataType);
      var AABBViewDataMembers = (_AABBViewDataMembers = {}, _AABBViewDataMembers[AABBView.CENTER] = AABBView.HALFEXTENTS - AABBView.CENTER, _AABBViewDataMembers[AABBView.HALFEXTENTS] = AABBView.COUNT - AABBView.HALFEXTENTS, _AABBViewDataMembers[AABBView.COUNT] = 1, _AABBViewDataMembers);
      var AABBPool = new BufferPool(PoolType.AABB, AABBViewDataType, AABBViewDataMembers, AABBView);

      removeProperty(RenderScene.prototype, 'RenderScene.prototype', [{
        name: 'raycastUI2DNode'
      }, {
        name: 'raycastUINode'
      }]);
      removeProperty(RenderScene.prototype, 'RenderScene.prototype', [{
        name: 'raycastAll',
        suggest: 'using intersect.rayModel in geometry'
      }, {
        name: 'raycastAllModels',
        suggest: 'using intersect.rayModel in geometry'
      }, {
        name: 'raycastSingleModel',
        suggest: 'using intersect.rayModel in geometry'
      }, {
        name: 'raycastAllCanvas',
        suggest: 'using intersect.rayAABB in geometry'
      }, {
        name: 'rayResultCanvas'
      }, {
        name: 'rayResultModels'
      }, {
        name: 'rayResultAll'
      }, {
        name: 'rayResultSingleModel'
      }]);
      removeProperty(Model.prototype, 'Model.prototype', [{
        name: 'isInstancingEnabled'
      }, {
        name: 'instancedAttributes'
      }]);
      var CameraVisFlags = {};
      removeProperty(CameraVisFlags, 'CameraVisFlags', [{
        name: 'GENERAL'
      }]);
      replaceProperty(CameraVisFlags, 'CameraVisFlags', [{
        name: 'PROFILER',
        newName: 'PROFILER',
        target: Layers.BitMask,
        targetName: 'PROFILER'
      }, {
        name: 'GIZMOS',
        newName: 'GIZMOS',
        target: Layers.BitMask,
        targetName: 'GIZMOS'
      }, {
        name: 'EDITOR',
        newName: 'EDITOR',
        target: Layers.BitMask,
        targetName: 'EDITOR'
      }, {
        name: 'UI',
        newName: 'UI',
        target: Layers.BitMask,
        targetName: 'UI_3D'
      }, {
        name: 'UI2D',
        newName: 'UI2D',
        target: Layers.BitMask,
        targetName: 'UI_2D'
      }]);
      legacyCC.CameraVisFlags = CameraVisFlags;
      var VisibilityFlags = {};
      removeProperty(VisibilityFlags, 'VisibilityFlags', [{
        name: 'GENERAL'
      }]);
      replaceProperty(VisibilityFlags, 'VisibilityFlags', [{
        name: 'ALWALS',
        newName: 'ALWALS',
        target: Layers.Enum,
        targetName: 'ALWALS'
      }, {
        name: 'PROFILER',
        newName: 'PROFILER',
        target: Layers.Enum,
        targetName: 'PROFILER'
      }, {
        name: 'GIZMOS',
        newName: 'GIZMOS',
        target: Layers.Enum,
        targetName: 'GIZMOS'
      }, {
        name: 'EDITOR',
        newName: 'EDITOR',
        target: Layers.Enum,
        targetName: 'EDITOR'
      }, {
        name: 'UI',
        newName: 'UI',
        target: Layers.Enum,
        targetName: 'UI_3D'
      }, {
        name: 'UI2D',
        newName: 'UI2D',
        target: Layers.Enum,
        targetName: 'UI_2D'
      }]);
      legacyCC.VisibilityFlags = VisibilityFlags;
      replaceProperty(Pass.prototype, 'Pass.prototype', [{
        name: 'getBindingTypeFromHandle',
        newName: 'getDescriptorTypeFromHandle'
      }]);
      removeProperty(Camera$1.prototype, 'Camera.prototype', [{
        name: 'getSplitFrustum'
      }, {
        name: 'setMatView'
      }, {
        name: 'setMatViewInv'
      }, {
        name: 'setMatProjInv'
      }, {
        name: 'setMatViewProjInv'
      }, {
        name: 'setMatProj'
      }, {
        name: 'setMatViewProj'
      }, {
        name: 'getMatViewInv'
      }]);
      removeProperty(Shadows.prototype, 'Shadows.prototype', [{
        name: 'aspect'
      }, {
        name: 'selfShadow'
      }, {
        name: 'linear'
      }, {
        name: 'packing'
      }, {
        name: 'autoAdapt'
      }, {
        name: 'fixedArea'
      }, {
        name: 'pcf'
      }, {
        name: 'bias'
      }, {
        name: 'normalBias'
      }, {
        name: 'near'
      }, {
        name: 'far'
      }, {
        name: 'shadowDistance'
      }, {
        name: 'invisibleOcclusionRange'
      }, {
        name: 'orthoSize'
      }, {
        name: 'saturation'
      }]);
      removeProperty(SpotLight$1.prototype, 'SpotLight.prototype', [{
        name: 'aspect'
      }]);
      replaceProperty(SubModel.prototype, 'SubModel.prototype', [{
        name: 'subMeshData',
        newName: 'subMesh'
      }]);
      removeProperty(SubModel.prototype, 'SubModel.prototype', [{
        name: 'getSubModel',
        suggest: 'Use `subModels[i]` instead'
      }, {
        name: 'subModelNum',
        suggest: 'Use `subModels.length` instead'
      }]);

      var addStage = config.addStage;

      var renderer = /*#__PURE__*/Object.freeze({
        __proto__: null,
        addStage: addStage,
        scene: index$2,
        createIA: createIA,
        programLib: programLib,
        getDeviceShaderVersion: getDeviceShaderVersion,
        get RenderQueue () { return RenderQueue; },
        get PassStage () { return PassStage; },
        genHandle: genHandle,
        getTypeFromHandle: getTypeFromHandle,
        getBindingFromHandle: getBindingFromHandle,
        getCountFromHandle: getCountFromHandle,
        getOffsetFromHandle: getOffsetFromHandle,
        customizeType: customizeType,
        type2reader: type2reader,
        type2writer: type2writer,
        type2validator: type2validator,
        getDefaultFromType: getDefaultFromType,
        getStringFromType: getStringFromType,
        overrideMacros: overrideMacros,
        get BatchingSchemes () { return BatchingSchemes; },
        Pass: Pass,
        nearestPOT: nearestPOT,
        TextureBufferPool: TextureBufferPool,
        MaterialInstance: MaterialInstance,
        PassInstance: PassInstance,
        get PoolType () { return PoolType; },
        NULL_HANDLE: NULL_HANDLE,
        get Render2dView () { return Render2dView; },
        Render2dPool: Render2dPool,
        get NodeView () { return NodeView; },
        NodePool: NodePool$1,
        get PassView () { return PassView; },
        PassPool: PassPool,
        get AABBView () { return AABBView; },
        AABBPool: AABBPool,
        RenderScene: RenderScene,
        CameraVisFlags: CameraVisFlags,
        VisibilityFlags: VisibilityFlags
      });
      exports('aG', renderer);

      var LineCap;
      (function (LineCap) {
        LineCap[LineCap["BUTT"] = 0] = "BUTT";
        LineCap[LineCap["ROUND"] = 1] = "ROUND";
        LineCap[LineCap["SQUARE"] = 2] = "SQUARE";
      })(LineCap || (LineCap = {}));
      ccenum(LineCap);
      var LineJoin;
      (function (LineJoin) {
        LineJoin[LineJoin["BEVEL"] = 0] = "BEVEL";
        LineJoin[LineJoin["ROUND"] = 1] = "ROUND";
        LineJoin[LineJoin["MITER"] = 2] = "MITER";
      })(LineJoin || (LineJoin = {}));
      ccenum(LineJoin);
      var PointFlags;
      (function (PointFlags) {
        PointFlags[PointFlags["PT_CORNER"] = 1] = "PT_CORNER";
        PointFlags[PointFlags["PT_LEFT"] = 2] = "PT_LEFT";
        PointFlags[PointFlags["PT_BEVEL"] = 4] = "PT_BEVEL";
        PointFlags[PointFlags["PT_INNERBEVEL"] = 8] = "PT_INNERBEVEL";
      })(PointFlags || (PointFlags = {}));
      ccenum(PointFlags);

      var PI$1 = Math.PI;
      var min$1 = Math.min;
      var max$1 = Math.max;
      var cos$1 = Math.cos;
      var sin$1 = Math.sin;
      var abs = Math.abs;
      var sign = Math.sign;
      var KAPPA90 = 0.5522847493;
      function arc(ctx, cx, cy, r, startAngle, endAngle, counterclockwise) {
        counterclockwise = counterclockwise || false;
        var a = 0;
        var da = 0;
        var hda = 0;
        var kappa = 0;
        var dx = 0;
        var dy = 0;
        var x = 0;
        var y = 0;
        var tanx = 0;
        var tany = 0;
        var px = 0;
        var py = 0;
        var ptanx = 0;
        var ptany = 0;
        var i = 0;
        var ndivs = 0;
        da = endAngle - startAngle;
        if (counterclockwise) {
          if (abs(da) >= PI$1 * 2) {
            da = PI$1 * 2;
          } else {
            while (da < 0) {
              da += PI$1 * 2;
            }
          }
        } else if (abs(da) >= PI$1 * 2) {
          da = -PI$1 * 2;
        } else {
          while (da > 0) {
            da -= PI$1 * 2;
          }
        }
        ndivs = max$1(1, min$1(abs(da) / (PI$1 * 0.5) + 0.5, 5)) | 0;
        hda = da / ndivs / 2.0;
        kappa = abs(4.0 / 3.0 * (1 - cos$1(hda)) / sin$1(hda));
        if (!counterclockwise) {
          kappa = -kappa;
        }
        for (i = 0; i <= ndivs; i++) {
          a = startAngle + da * (i / ndivs);
          dx = cos$1(a);
          dy = sin$1(a);
          x = cx + dx * r;
          y = cy + dy * r;
          tanx = -dy * r * kappa;
          tany = dx * r * kappa;
          if (i === 0) {
            ctx.moveTo(x, y);
          } else {
            ctx.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y);
          }
          px = x;
          py = y;
          ptanx = tanx;
          ptany = tany;
        }
      }
      function ellipse(ctx, cx, cy, rx, ry) {
        ctx.moveTo(cx - rx, cy);
        ctx.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry);
        ctx.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy);
        ctx.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry);
        ctx.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy);
        ctx.close();
      }
      function roundRect(ctx, x, y, w, h, r) {
        if (r < 0.1) {
          ctx.rect(x, y, w, h);
        } else {
          var rx = min$1(r, abs(w) * 0.5) * sign(w);
          var ry = min$1(r, abs(h) * 0.5) * sign(h);
          ctx.moveTo(x, y + ry);
          ctx.lineTo(x, y + h - ry);
          ctx.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h);
          ctx.lineTo(x + w - rx, y + h);
          ctx.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry);
          ctx.lineTo(x + w, y + ry);
          ctx.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y);
          ctx.lineTo(x + rx, y);
          ctx.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry);
          ctx.close();
        }
      }
      function tesselateBezier(ctx, x1, y1, x2, y2, x3, y3, x4, y4, level, type) {
        var x12 = 0;
        var y12 = 0;
        var x23 = 0;
        var y23 = 0;
        var x34 = 0;
        var y34 = 0;
        var x123 = 0;
        var y123 = 0;
        var x234 = 0;
        var y234 = 0;
        var x1234 = 0;
        var y1234 = 0;
        var dx = 0;
        var dy = 0;
        var d2 = 0;
        var d3 = 0;
        if (level > 10) {
          return;
        }
        x12 = (x1 + x2) * 0.5;
        y12 = (y1 + y2) * 0.5;
        x23 = (x2 + x3) * 0.5;
        y23 = (y2 + y3) * 0.5;
        x34 = (x3 + x4) * 0.5;
        y34 = (y3 + y4) * 0.5;
        x123 = (x12 + x23) * 0.5;
        y123 = (y12 + y23) * 0.5;
        dx = x4 - x1;
        dy = y4 - y1;
        d2 = abs((x2 - x4) * dy - (y2 - y4) * dx);
        d3 = abs((x3 - x4) * dy - (y3 - y4) * dx);
        if ((d2 + d3) * (d2 + d3) < ctx.tessTol * (dx * dx + dy * dy)) {
          ctx.addPoint(x4, y4, type === 0 ? type | PointFlags.PT_BEVEL : type);
          return;
        }
        x234 = (x23 + x34) * 0.5;
        y234 = (y23 + y34) * 0.5;
        x1234 = (x123 + x234) * 0.5;
        y1234 = (y123 + y234) * 0.5;
        tesselateBezier(ctx, x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1, 0);
        tesselateBezier(ctx, x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1, type);
      }

      var Point$2 = function (_Vec) {
        _inheritsLoose(Point, _Vec);
        function Point() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Vec.call.apply(_Vec, [this].concat(args)) || this;
          _this.dx = 0;
          _this.dy = 0;
          _this.dmx = 0;
          _this.dmy = 0;
          _this.flags = 0;
          _this.len = 0;
          return _this;
        }
        var _proto = Point.prototype;
        _proto.reset = function reset() {
          this.dx = 0;
          this.dy = 0;
          this.dmx = 0;
          this.dmy = 0;
          this.flags = 0;
          this.len = 0;
        };
        return Point;
      }(Vec2);
      var Path = function () {
        function Path() {
          this.closed = false;
          this.bevel = 0;
          this.complex = true;
          this.points = [];
        }
        var _proto2 = Path.prototype;
        _proto2.reset = function reset() {
          this.closed = false;
          this.bevel = 0;
          this.complex = true;
          this.points.length = 0;
        };
        return Path;
      }();
      var Impl = function () {
        function Impl(comp) {
          this.dataOffset = 0;
          this.updatePathOffset = false;
          this.pathLength = 0;
          this.pathOffset = 0;
          this.paths = [];
          this.tessTol = 0.25;
          this.distTol = 0.01;
          this.fillColor = Color$1.WHITE.clone();
          this.lineCap = LineCap.BUTT;
          this.strokeColor = Color$1.BLACK.clone();
          this.lineJoin = LineJoin.MITER;
          this.lineWidth = 0;
          this.pointsOffset = 0;
          this._commandX = 0;
          this._commandY = 0;
          this._points = [];
          this._renderDataList = [];
          this._curPath = null;
          this._comp = void 0;
          this._comp = comp;
        }
        var _proto3 = Impl.prototype;
        _proto3.moveTo = function moveTo(x, y) {
          if (this.updatePathOffset) {
            this.pathOffset = this.pathLength;
            this.updatePathOffset = false;
          }
          this._addPath();
          this.addPoint(x, y, PointFlags.PT_CORNER);
          this._commandX = x;
          this._commandY = y;
        };
        _proto3.lineTo = function lineTo(x, y) {
          this.addPoint(x, y, PointFlags.PT_CORNER);
          this._commandX = x;
          this._commandY = y;
        };
        _proto3.bezierCurveTo = function bezierCurveTo(c1x, c1y, c2x, c2y, x, y) {
          var path = this._curPath;
          var last = path.points[path.points.length - 1];
          if (!last) {
            return;
          }
          if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) {
            this.lineTo(x, y);
            return;
          }
          tesselateBezier(this, last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER);
          this._commandX = x;
          this._commandY = y;
        };
        _proto3.quadraticCurveTo = function quadraticCurveTo(cx, cy, x, y) {
          var x0 = this._commandX;
          var y0 = this._commandY;
          this.bezierCurveTo(x0 + 2.0 / 3.0 * (cx - x0), y0 + 2.0 / 3.0 * (cy - y0), x + 2.0 / 3.0 * (cx - x), y + 2.0 / 3.0 * (cy - y), x, y);
        };
        _proto3.arc = function arc$1(cx, cy, r, startAngle, endAngle, counterclockwise) {
          arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
        };
        _proto3.ellipse = function ellipse$1(cx, cy, rx, ry) {
          ellipse(this, cx, cy, rx, ry);
          this._curPath.complex = false;
        };
        _proto3.circle = function circle(cx, cy, r) {
          ellipse(this, cx, cy, r, r);
          this._curPath.complex = false;
        };
        _proto3.rect = function rect(x, y, w, h) {
          this.moveTo(x, y);
          this.lineTo(x + w, y);
          this.lineTo(x + w, y + h);
          this.lineTo(x, y + h);
          this.close();
          this._curPath.complex = false;
        };
        _proto3.roundRect = function roundRect$1(x, y, w, h, r) {
          roundRect(this, x, y, w, h, r);
          this._curPath.complex = false;
        };
        _proto3.clear = function clear() {
          this.pathLength = 0;
          this.pathOffset = 0;
          this.pointsOffset = 0;
          this.dataOffset = 0;
          this._curPath = null;
          this.paths.length = 0;
          this._points.length = 0;
          var dataList = this._renderDataList;
          for (var i = 0, l = dataList.length; i < l; i++) {
            var data = dataList[i];
            if (!data) {
              continue;
            }
            MeshRenderData.remove(data);
            data.removeRenderDrawInfo(this._comp);
          }
          this._renderDataList.length = 0;
        };
        _proto3.close = function close() {
          this._curPath.closed = true;
        };
        _proto3.requestRenderData = function requestRenderData() {
          var renderData = MeshRenderData.add();
          this._renderDataList.push(renderData);
          return renderData;
        };
        _proto3.getRenderDataList = function getRenderDataList() {
          if (this._renderDataList.length === 0) {
            this.requestRenderData();
          }
          return this._renderDataList;
        };
        _proto3.addPoint = function addPoint(x, y, flags) {
          var path = this._curPath;
          if (!path) {
            return;
          }
          var points = this._points;
          var pathPoints = path.points;
          var offset = this.pointsOffset++;
          var pt = points[offset];
          if (!pt) {
            pt = new Point$2(x, y);
            points.push(pt);
          } else {
            pt.x = x;
            pt.y = y;
          }
          pt.flags = flags;
          pathPoints.push(pt);
        };
        _proto3._addPath = function _addPath() {
          var offset = this.pathLength;
          var path = this.paths[offset];
          if (!path) {
            path = new Path();
            this.paths.push(path);
          } else {
            path.reset();
          }
          this.pathLength++;
          this._curPath = path;
          return path;
        };
        return Impl;
      }();

      var _dec$2T, _dec2$2e, _dec3$1D, _dec4$19, _class$2R, _class2$2y, _initializer$2p, _initializer2$20, _initializer3$1u, _initializer4$1h, _initializer5$10, _initializer6$R, _class3$I;
      var attributes = vfmtPosColor.concat([new Attribute('a_dist', Format.R32F)]);
      var componentPerVertex = getComponentPerVertex(attributes);
      var stride = getAttributeStride(attributes);
      var Graphics = exports('G', (_dec$2T = ccclass$M('cc.Graphics'), _dec2$2e = executionOrder$1(110), _dec3$1D = type$d(LineJoin), _dec4$19 = type$d(LineCap), _dec$2T(_class$2R = _dec2$2e(_class$2R = (_class2$2y = (_class3$I = function (_UIRenderer) {
        _inheritsLoose(Graphics, _UIRenderer);
        function Graphics() {
          var _this;
          _this = _UIRenderer.call(this) || this;
          _this.impl = null;
          _this.model = null;
          _this._lineWidth = _initializer$2p && _initializer$2p();
          _this._strokeColor = _initializer2$20 && _initializer2$20();
          _this._lineJoin = _initializer3$1u && _initializer3$1u();
          _this._lineCap = _initializer4$1h && _initializer4$1h();
          _this._fillColor = _initializer5$10 && _initializer5$10();
          _this._miterLimit = _initializer6$R && _initializer6$R();
          _this._isDrawing = false;
          _this._isNeedUploadData = true;
          _this._graphicsUseSubMeshes = [];
          _this._instanceMaterialType = InstanceMaterialType.ADD_COLOR;
          _this.impl = new Impl(_assertThisInitialized(_this));
          return _this;
        }
        var _proto = Graphics.prototype;
        _proto.onRestore = function onRestore() {
          if (!this.impl) {
            this._flushAssembler();
          }
        };
        _proto.onLoad = function onLoad() {
          _UIRenderer.prototype.onLoad.call(this);
          {
            this.model = director.root.createModel(Model);
            this.model.node = this.model.transform = this.node;
          }
          this._flushAssembler();
        };
        _proto.onEnable = function onEnable() {
          _UIRenderer.prototype.onEnable.call(this);
          this._updateMtlForGraphics();
        };
        _proto.onDestroy = function onDestroy() {
          this._sceneGetter = null;
          {
            if (this.model) {
              director.root.destroyModel(this.model);
              this.model = null;
            }
            var subMeshLength = this._graphicsUseSubMeshes.length;
            if (subMeshLength > 0) {
              for (var i = 0; i < subMeshLength; ++i) {
                this._graphicsUseSubMeshes[i].destroy();
              }
              this._graphicsUseSubMeshes.length = 0;
            }
          }
          if (this.impl) {
            this._isDrawing = false;
            this.impl.clear();
            this.impl = null;
          }
          _UIRenderer.prototype.onDestroy.call(this);
        };
        _proto.moveTo = function moveTo(x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.moveTo(x, y);
        };
        _proto.lineTo = function lineTo(x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.lineTo(x, y);
        };
        _proto.bezierCurveTo = function bezierCurveTo(c1x, c1y, c2x, c2y, x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
        };
        _proto.quadraticCurveTo = function quadraticCurveTo(cx, cy, x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.quadraticCurveTo(cx, cy, x, y);
        };
        _proto.arc = function arc(cx, cy, r, startAngle, endAngle, counterclockwise) {
          if (!this.impl) {
            return;
          }
          this.impl.arc(cx, cy, r, startAngle, endAngle, counterclockwise);
        };
        _proto.ellipse = function ellipse(cx, cy, rx, ry) {
          if (!this.impl) {
            return;
          }
          this.impl.ellipse(cx, cy, rx, ry);
        };
        _proto.circle = function circle(cx, cy, r) {
          if (!this.impl) {
            return;
          }
          this.impl.circle(cx, cy, r);
        };
        _proto.rect = function rect(x, y, w, h) {
          if (!this.impl) {
            return;
          }
          this.impl.rect(x, y, w, h);
        };
        _proto.roundRect = function roundRect(x, y, w, h, r) {
          if (!this.impl) {
            return;
          }
          this.impl.roundRect(x, y, w, h, r);
        };
        _proto.fillRect = function fillRect(x, y, w, h) {
          this.rect(x, y, w, h);
          this.fill();
        };
        _proto.clear = function clear() {
          if (!this.impl) {
            return;
          }
          this.impl.clear();
          this._isDrawing = false;
          if (this.model) {
            for (var i = 0; i < this.model.subModels.length; i++) {
              var subModel = this.model.subModels[i];
              subModel.inputAssembler.indexCount = 0;
            }
          }
          this.markForUpdateRenderData();
        };
        _proto.close = function close() {
          if (!this.impl) {
            return;
          }
          this.impl.close();
        };
        _proto.stroke = function stroke() {
          if (!this._assembler) {
            this._flushAssembler();
          }
          this._isDrawing = true;
          this._isNeedUploadData = true;
          this._assembler.stroke(this);
        };
        _proto.fill = function fill() {
          if (!this._assembler) {
            this._flushAssembler();
          }
          this._isDrawing = true;
          this._isNeedUploadData = true;
          this._assembler.fill(this);
        };
        _proto._updateMtlForGraphics = function _updateMtlForGraphics() {
          var mat;
          if (this._customMaterial) {
            mat = this.getMaterialInstance(0);
          } else {
            mat = builtinResMgr.get('ui-graphics-material');
            this.setSharedMaterial(mat, 0);
            mat = this.getMaterialInstance(0);
            mat.recompileShaders({
              USE_LOCAL: true
            });
          }
        };
        _proto.activeSubModel = function activeSubModel(idx) {
          if (!this.model) {
            warnID(4500, this.node.name);
            return;
          }
          if (this.model.subModels.length <= idx) {
            var gfxDevice = deviceManager.gfxDevice;
            var vertexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 65535 * stride, stride));
            var indexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 65535 * Uint16Array.BYTES_PER_ELEMENT * 2, Uint16Array.BYTES_PER_ELEMENT));
            var renderMesh = new RenderingSubMesh([vertexBuffer], attributes, PrimitiveMode.TRIANGLE_LIST, indexBuffer);
            renderMesh.subMeshIdx = 0;
            this.model.initSubModel(idx, renderMesh, this.getMaterialInstance(0));
            this._graphicsUseSubMeshes.push(renderMesh);
          }
        };
        _proto._uploadData = function _uploadData() {
          var impl = this.impl;
          if (!impl) {
            return;
          }
          var renderDataList = impl && impl.getRenderDataList();
          if (renderDataList.length <= 0 || !this.model) {
            return;
          }
          var subModelList = this.model.subModels;
          for (var i = 0; i < renderDataList.length; i++) {
            var renderData = renderDataList[i];
            var ia = subModelList[i].inputAssembler;
            if (renderData.lastFilledVertex === renderData.vertexStart) {
              continue;
            }
            var vb = new Float32Array(renderData.vData.buffer, 0, renderData.vertexStart * componentPerVertex);
            ia.vertexBuffers[0].update(vb);
            ia.vertexCount = renderData.vertexStart;
            var ib = new Uint16Array(renderData.iData.buffer, 0, renderData.indexStart);
            ia.indexBuffer.update(ib);
            ia.indexCount = renderData.indexStart;
            renderData.lastFilledVertex = renderData.vertexStart;
            renderData.lastFilledIndex = renderData.indexStart;
          }
          this._isNeedUploadData = false;
        };
        _proto._render = function _render(render) {
          if (this._isNeedUploadData) {
            if (this.impl) {
              var renderDataList = this.impl.getRenderDataList();
              var len = this.model.subModels.length;
              if (renderDataList.length > len) {
                for (var i = len; i < renderDataList.length; i++) {
                  this.activeSubModel(i);
                }
              }
            }
            this._uploadData();
          }
          render.commitModel(this, this.model, this.getMaterialInstance(0));
        };
        _proto._flushAssembler = function _flushAssembler() {
          var assembler = Graphics.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
          }
        };
        _proto._canRender = function _canRender() {
          if (!_UIRenderer.prototype._canRender.call(this)) {
            return false;
          }
          {
            return !!this.model && this._isDrawing;
          }
        };
        _proto.updateRenderer = function updateRenderer() {
          _UIRenderer.prototype.updateRenderer.call(this);
        };
        _proto.createRenderEntity = function createRenderEntity() {
          return new RenderEntity(RenderEntityType.DYNAMIC);
        };
        _createClass(Graphics, [{
          key: "lineWidth",
          get: function get() {
            return this._lineWidth;
          },
          set: function set(value) {
            this._lineWidth = value;
            if (!this.impl) {
              return;
            }
            this.impl.lineWidth = value;
          }
        }, {
          key: "lineJoin",
          get: function get() {
            return this._lineJoin;
          },
          set: function set(value) {
            this._lineJoin = value;
            if (!this.impl) {
              return;
            }
            this.impl.lineJoin = value;
          }
        }, {
          key: "lineCap",
          get: function get() {
            return this._lineCap;
          },
          set: function set(value) {
            this._lineCap = value;
            if (!this.impl) {
              return;
            }
            this.impl.lineCap = value;
          }
        }, {
          key: "strokeColor",
          get: function get() {
            return this._strokeColor;
          },
          set: function set(value) {
            if (!this.impl) {
              return;
            }
            this._strokeColor.set(value);
            this.impl.strokeColor = this._strokeColor;
          }
        }, {
          key: "fillColor",
          get: function get() {
            return this._fillColor;
          },
          set: function set(value) {
            if (!this.impl) {
              return;
            }
            this._fillColor.set(value);
            this.impl.fillColor = this._fillColor;
          }
        }, {
          key: "miterLimit",
          get: function get() {
            return this._miterLimit;
          },
          set: function set(value) {
            this._miterLimit = value;
          }
        }, {
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(value) {
            if (this._color === value) {
              return;
            }
            this._color.set(value);
          }
        }, {
          key: "graphicsNativeProxy",
          get: function get() {
            return this._graphicsNativeProxy;
          }
        }]);
        return Graphics;
      }(UIRenderer), _class3$I.LineJoin = LineJoin, _class3$I.LineCap = LineCap, _class3$I), (_applyDecoratedDescriptor(_class2$2y.prototype, "lineJoin", [_dec3$1D], Object.getOwnPropertyDescriptor(_class2$2y.prototype, "lineJoin"), _class2$2y.prototype), _applyDecoratedDescriptor(_class2$2y.prototype, "lineCap", [_dec4$19], Object.getOwnPropertyDescriptor(_class2$2y.prototype, "lineCap"), _class2$2y.prototype), _applyDecoratedDescriptor(_class2$2y.prototype, "color", [override$1], Object.getOwnPropertyDescriptor(_class2$2y.prototype, "color"), _class2$2y.prototype), _initializer$2p = applyDecoratedInitializer(_class2$2y.prototype, "_lineWidth", [serializable$p], function () {
        return 1;
      }), _initializer2$20 = applyDecoratedInitializer(_class2$2y.prototype, "_strokeColor", [serializable$p], function () {
        return Color$1.BLACK.clone();
      }), _initializer3$1u = applyDecoratedInitializer(_class2$2y.prototype, "_lineJoin", [serializable$p], function () {
        return LineJoin.MITER;
      }), _initializer4$1h = applyDecoratedInitializer(_class2$2y.prototype, "_lineCap", [serializable$p], function () {
        return LineCap.BUTT;
      }), _initializer5$10 = applyDecoratedInitializer(_class2$2y.prototype, "_fillColor", [serializable$p], function () {
        return Color$1.WHITE.clone();
      }), _initializer6$R = applyDecoratedInitializer(_class2$2y.prototype, "_miterLimit", [serializable$p], function () {
        return 10;
      })), _class2$2y)) || _class$2R) || _class$2R));
      legacyCC.Graphics = Graphics;

      var _dec$2S, _dec2$2d, _dec3$1C, _dec4$18, _dec5$11, _dec6$N, _dec7$C, _class$2Q, _class2$2x, _initializer$2o, _initializer2$1$, _initializer3$1t, _initializer4$1g, _initializer5$$, _initializer6$Q, _initializer7$F, _initializer8$B, _initializer9$w, _initializer10$t, _class3$H;
      var SpriteType$1;
      (function (SpriteType) {
        SpriteType[SpriteType["SIMPLE"] = 0] = "SIMPLE";
        SpriteType[SpriteType["SLICED"] = 1] = "SLICED";
        SpriteType[SpriteType["TILED"] = 2] = "TILED";
        SpriteType[SpriteType["FILLED"] = 3] = "FILLED";
      })(SpriteType$1 || (SpriteType$1 = {}));
      ccenum(SpriteType$1);
      var FillType$2;
      (function (FillType) {
        FillType[FillType["HORIZONTAL"] = 0] = "HORIZONTAL";
        FillType[FillType["VERTICAL"] = 1] = "VERTICAL";
        FillType[FillType["RADIAL"] = 2] = "RADIAL";
      })(FillType$2 || (FillType$2 = {}));
      ccenum(FillType$2);
      var SizeMode$1;
      (function (SizeMode) {
        SizeMode[SizeMode["CUSTOM"] = 0] = "CUSTOM";
        SizeMode[SizeMode["TRIMMED"] = 1] = "TRIMMED";
        SizeMode[SizeMode["RAW"] = 2] = "RAW";
      })(SizeMode$1 || (SizeMode$1 = {}));
      ccenum(SizeMode$1);
      var EventType$9;
      (function (EventType) {
        EventType["SPRITE_FRAME_CHANGED"] = "spriteframe-changed";
      })(EventType$9 || (EventType$9 = {}));
      var Sprite = exports('j', (_dec$2S = ccclass$M('cc.Sprite'), _dec2$2d = executionOrder$1(110), _dec3$1C = type$d(SpriteAtlas), _dec4$18 = type$d(SpriteFrame), _dec5$11 = type$d(SpriteType$1), _dec6$N = type$d(FillType$2), _dec7$C = type$d(SizeMode$1), _dec$2S(_class$2Q = _dec2$2d(_class$2Q = (_class2$2x = (_class3$H = function (_UIRenderer) {
        _inheritsLoose(Sprite, _UIRenderer);
        function Sprite() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _UIRenderer.call.apply(_UIRenderer, [this].concat(args)) || this;
          _this._spriteFrame = _initializer$2o && _initializer$2o();
          _this._type = _initializer2$1$ && _initializer2$1$();
          _this._fillType = _initializer3$1t && _initializer3$1t();
          _this._sizeMode = _initializer4$1g && _initializer4$1g();
          _this._fillCenter = _initializer5$$ && _initializer5$$();
          _this._fillStart = _initializer6$Q && _initializer6$Q();
          _this._fillRange = _initializer7$F && _initializer7$F();
          _this._isTrimmedMode = _initializer8$B && _initializer8$B();
          _this._useGrayscale = _initializer9$w && _initializer9$w();
          _this._atlas = _initializer10$t && _initializer10$t();
          return _this;
        }
        var _proto = Sprite.prototype;
        _proto.__preload = function __preload() {
          this.changeMaterialForDefine();
          _UIRenderer.prototype.__preload.call(this);
        };
        _proto.onEnable = function onEnable() {
          _UIRenderer.prototype.onEnable.call(this);
          this._activateMaterial();
          var spriteFrame = this._spriteFrame;
          if (spriteFrame) {
            this._updateUVs();
            if (this._type === SpriteType$1.SLICED) {
              spriteFrame.on(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
            }
          }
        };
        _proto.onDisable = function onDisable() {
          _UIRenderer.prototype.onDisable.call(this);
          if (this._spriteFrame && this._type === SpriteType$1.SLICED) {
            this._spriteFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
          }
        };
        _proto.onDestroy = function onDestroy() {
          _UIRenderer.prototype.onDestroy.call(this);
        };
        _proto.changeSpriteFrameFromAtlas = function changeSpriteFrameFromAtlas(name) {
          if (!this._atlas) {
            console.warn('SpriteAtlas is null.');
            return;
          }
          var sprite = this._atlas.getSpriteFrame(name);
          this.spriteFrame = sprite;
        };
        _proto.changeMaterialForDefine = function changeMaterialForDefine() {
          var texture;
          var lastInstanceMaterialType = this._instanceMaterialType;
          if (this._spriteFrame) {
            texture = this._spriteFrame.texture;
          }
          var value = false;
          if (texture instanceof TextureBase) {
            var format = texture.getPixelFormat();
            value = format === PixelFormat.RGBA_ETC1 || format === PixelFormat.RGB_A_PVRTC_4BPPV1 || format === PixelFormat.RGB_A_PVRTC_2BPPV1;
          }
          if (value && this.grayscale) {
            this._instanceMaterialType = InstanceMaterialType.USE_ALPHA_SEPARATED_AND_GRAY;
          } else if (value) {
            this._instanceMaterialType = InstanceMaterialType.USE_ALPHA_SEPARATED;
          } else if (this.grayscale) {
            this._instanceMaterialType = InstanceMaterialType.GRAYSCALE;
          } else {
            this._instanceMaterialType = InstanceMaterialType.ADD_COLOR_AND_TEXTURE;
          }
          if (lastInstanceMaterialType !== this._instanceMaterialType) {
            this.updateMaterial();
          }
        };
        _proto._updateBuiltinMaterial = function _updateBuiltinMaterial() {
          var mat = _UIRenderer.prototype._updateBuiltinMaterial.call(this);
          if (this.spriteFrame && this.spriteFrame.texture instanceof RenderTexture) {
            var defines = _extends({
              SAMPLE_FROM_RT: true
            }, mat.passes[0].defines);
            var renderMat = new Material();
            renderMat.initialize({
              effectAsset: mat.effectAsset,
              defines: defines
            });
            mat = renderMat;
          }
          return mat;
        };
        _proto._render = function _render(render) {
          render.commitComp(this, this.renderData, this._spriteFrame, this._assembler, null);
        };
        _proto._canRender = function _canRender() {
          if (!_UIRenderer.prototype._canRender.call(this)) {
            return false;
          }
          var spriteFrame = this._spriteFrame;
          if (!spriteFrame || !spriteFrame.texture) {
            return false;
          }
          return true;
        };
        _proto._flushAssembler = function _flushAssembler() {
          var assembler = Sprite.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this.destroyRenderData();
            this._assembler = assembler;
          }
          if (!this._renderData) {
            if (this._assembler && this._assembler.createData) {
              this._renderData = this._assembler.createData(this);
              this._renderData.material = this.getRenderMaterial(0);
              this.markForUpdateRenderData();
              if (this.spriteFrame) {
                this._assembler.updateUVs(this);
              }
              this._updateColor();
            }
          }
          if (this._spriteFrame) {
            if (this._type === SpriteType$1.SLICED) {
              this._spriteFrame.on(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
            } else {
              this._spriteFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
            }
          }
        };
        _proto._applySpriteSize = function _applySpriteSize() {
          if (this._spriteFrame) {
            {
              if (SizeMode$1.RAW === this._sizeMode) {
                var size = this._spriteFrame.originalSize;
                this.node._uiProps.uiTransformComp.setContentSize(size);
              } else if (SizeMode$1.TRIMMED === this._sizeMode) {
                var rect = this._spriteFrame.rect;
                this.node._uiProps.uiTransformComp.setContentSize(rect.width, rect.height);
              }
            }
          }
        };
        _proto._resized = function _resized() {
          {
            return;
          }
        };
        _proto._activateMaterial = function _activateMaterial() {
          var spriteFrame = this._spriteFrame;
          var material = this.getRenderMaterial(0);
          if (spriteFrame) {
            if (material) {
              this.markForUpdateRenderData();
            }
          }
          if (this.renderData) {
            this.renderData.material = material;
          }
        };
        _proto._updateUVs = function _updateUVs() {
          if (this._assembler) {
            this._assembler.updateUVs(this);
          }
        };
        _proto._applySpriteFrame = function _applySpriteFrame(oldFrame) {
          var spriteFrame = this._spriteFrame;
          if (oldFrame && this._type === SpriteType$1.SLICED) {
            oldFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
          }
          var textureChanged = false;
          if (spriteFrame) {
            if (!oldFrame || oldFrame.texture !== spriteFrame.texture) {
              textureChanged = true;
            }
            if (textureChanged) {
              if (this.renderData) this.renderData.textureDirty = true;
              this.changeMaterialForDefine();
            }
            this._applySpriteSize();
            if (this._type === SpriteType$1.SLICED) {
              spriteFrame.on(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
            }
          }
        };
        _createClass(Sprite, [{
          key: "spriteAtlas",
          get: function get() {
            return this._atlas;
          },
          set: function set(value) {
            if (this._atlas === value) {
              return;
            }
            this._atlas = value;
          }
        }, {
          key: "spriteFrame",
          get: function get() {
            return this._spriteFrame;
          },
          set: function set(value) {
            if (this._spriteFrame === value) {
              return;
            }
            var lastSprite = this._spriteFrame;
            this._spriteFrame = value;
            this.markForUpdateRenderData();
            this._applySpriteFrame(lastSprite);
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(value) {
            if (this._type !== value) {
              this._type = value;
              this._flushAssembler();
            }
          }
        }, {
          key: "fillType",
          get: function get() {
            return this._fillType;
          },
          set: function set(value) {
            if (this._fillType !== value) {
              if (value === FillType$2.RADIAL || this._fillType === FillType$2.RADIAL) {
                this.destroyRenderData();
              } else if (this.renderData) {
                this.markForUpdateRenderData(true);
              }
            }
            this._fillType = value;
            this._flushAssembler();
          }
        }, {
          key: "fillCenter",
          get: function get() {
            return this._fillCenter;
          },
          set: function set(value) {
            this._fillCenter.x = value.x;
            this._fillCenter.y = value.y;
            if (this._type === SpriteType$1.FILLED && this.renderData) {
              this.markForUpdateRenderData();
            }
          }
        }, {
          key: "fillStart",
          get: function get() {
            return this._fillStart;
          },
          set: function set(value) {
            this._fillStart = clamp$1(value, 0, 1);
            if (this._type === SpriteType$1.FILLED && this.renderData) {
              this.markForUpdateRenderData();
              this._updateUVs();
            }
          }
        }, {
          key: "fillRange",
          get: function get() {
            return this._fillRange;
          },
          set: function set(value) {
            this._fillRange = clamp$1(value, -1, 1);
            if (this._type === SpriteType$1.FILLED && this.renderData) {
              this.markForUpdateRenderData();
              this._updateUVs();
            }
          }
        }, {
          key: "trim",
          get: function get() {
            return this._isTrimmedMode;
          },
          set: function set(value) {
            if (this._isTrimmedMode === value) {
              return;
            }
            this._isTrimmedMode = value;
            if (this._type === SpriteType$1.SIMPLE && this.renderData) {
              this.markForUpdateRenderData(true);
            }
          }
        }, {
          key: "grayscale",
          get: function get() {
            return this._useGrayscale;
          },
          set: function set(value) {
            if (this._useGrayscale === value) {
              return;
            }
            this._useGrayscale = value;
            this.changeMaterialForDefine();
            this.updateMaterial();
          }
        }, {
          key: "sizeMode",
          get: function get() {
            return this._sizeMode;
          },
          set: function set(value) {
            if (this._sizeMode === value) {
              return;
            }
            this._sizeMode = value;
            if (value !== SizeMode$1.CUSTOM) {
              this._applySpriteSize();
            }
          }
        }]);
        return Sprite;
      }(UIRenderer), _class3$H.FillType = FillType$2, _class3$H.Type = SpriteType$1, _class3$H.SizeMode = SizeMode$1, _class3$H.EventType = EventType$9, _class3$H), (_applyDecoratedDescriptor(_class2$2x.prototype, "spriteAtlas", [_dec3$1C], Object.getOwnPropertyDescriptor(_class2$2x.prototype, "spriteAtlas"), _class2$2x.prototype), _applyDecoratedDescriptor(_class2$2x.prototype, "spriteFrame", [_dec4$18], Object.getOwnPropertyDescriptor(_class2$2x.prototype, "spriteFrame"), _class2$2x.prototype), _applyDecoratedDescriptor(_class2$2x.prototype, "type", [_dec5$11], Object.getOwnPropertyDescriptor(_class2$2x.prototype, "type"), _class2$2x.prototype), _applyDecoratedDescriptor(_class2$2x.prototype, "fillType", [_dec6$N], Object.getOwnPropertyDescriptor(_class2$2x.prototype, "fillType"), _class2$2x.prototype), _applyDecoratedDescriptor(_class2$2x.prototype, "sizeMode", [_dec7$C], Object.getOwnPropertyDescriptor(_class2$2x.prototype, "sizeMode"), _class2$2x.prototype), _initializer$2o = applyDecoratedInitializer(_class2$2x.prototype, "_spriteFrame", [serializable$p], function () {
        return null;
      }), _initializer2$1$ = applyDecoratedInitializer(_class2$2x.prototype, "_type", [serializable$p], function () {
        return SpriteType$1.SIMPLE;
      }), _initializer3$1t = applyDecoratedInitializer(_class2$2x.prototype, "_fillType", [serializable$p], function () {
        return FillType$2.HORIZONTAL;
      }), _initializer4$1g = applyDecoratedInitializer(_class2$2x.prototype, "_sizeMode", [serializable$p], function () {
        return SizeMode$1.TRIMMED;
      }), _initializer5$$ = applyDecoratedInitializer(_class2$2x.prototype, "_fillCenter", [serializable$p], function () {
        return new Vec2(0, 0);
      }), _initializer6$Q = applyDecoratedInitializer(_class2$2x.prototype, "_fillStart", [serializable$p], function () {
        return 0;
      }), _initializer7$F = applyDecoratedInitializer(_class2$2x.prototype, "_fillRange", [serializable$p], function () {
        return 0;
      }), _initializer8$B = applyDecoratedInitializer(_class2$2x.prototype, "_isTrimmedMode", [serializable$p], function () {
        return true;
      }), _initializer9$w = applyDecoratedInitializer(_class2$2x.prototype, "_useGrayscale", [serializable$p], function () {
        return false;
      }), _initializer10$t = applyDecoratedInitializer(_class2$2x.prototype, "_atlas", [serializable$p], function () {
        return null;
      })), _class2$2x)) || _class$2Q) || _class$2Q));
      legacyCC.Sprite = Sprite;

      var _dec$2R, _dec2$2c, _dec3$1B, _class$2P, _class2$2w, _initializer$2n, _initializer2$1_, _initializer3$1s, _initializer4$1f, _class3$G;
      var _worldMatrix = new Mat4();
      var _vec2_temp$1 = new Vec2();
      var _mat4_temp$4 = new Mat4();
      var _circlePoints = [];
      function _calculateCircle(center, radius, segments) {
        _circlePoints.length = 0;
        var anglePerStep = Math.PI * 2 / segments;
        for (var step = 0; step < segments; ++step) {
          _circlePoints.push(new Vec3(radius.x * Math.cos(anglePerStep * step) + center.x, radius.y * Math.sin(anglePerStep * step) + center.y, 0));
        }
        return _circlePoints;
      }
      var MaskType;
      (function (MaskType) {
        MaskType[MaskType["GRAPHICS_RECT"] = 0] = "GRAPHICS_RECT";
        MaskType[MaskType["GRAPHICS_ELLIPSE"] = 1] = "GRAPHICS_ELLIPSE";
        MaskType[MaskType["GRAPHICS_STENCIL"] = 2] = "GRAPHICS_STENCIL";
        MaskType[MaskType["SPRITE_STENCIL"] = 3] = "SPRITE_STENCIL";
      })(MaskType || (MaskType = {}));
      ccenum(MaskType);
      var SEGMENTS_MIN = 3;
      var SEGMENTS_MAX = 10000;
      var Mask = exports('h', (_dec$2R = ccclass$M('cc.Mask'), _dec2$2c = executionOrder$1(110), _dec3$1B = type$d(MaskType), _dec$2R(_class$2P = _dec2$2c(_class$2P = (_class2$2w = (_class3$G = function (_Component) {
        _inheritsLoose(Mask, _Component);
        function Mask() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._type = _initializer$2n && _initializer$2n();
          _this._inverted = _initializer2$1_ && _initializer2$1_();
          _this._segments = _initializer3$1s && _initializer3$1s();
          _this._alphaThreshold = _initializer4$1f && _initializer4$1f();
          _this._sprite = null;
          _this._graphics = null;
          _this._stencilStage = Stage.DISABLED;
          return _this;
        }
        var _proto = Mask.prototype;
        _proto.onLoad = function onLoad() {
          this._changeRenderType();
        };
        _proto.onEnable = function onEnable() {
          this._changeRenderType();
          this._updateGraphics();
          this._enableRender();
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
          this.node.on(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
        };
        _proto.onRestore = function onRestore() {
          this._changeRenderType();
          this._updateGraphics();
        };
        _proto.onDisable = function onDisable() {
          this._disableRender();
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
          this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
        };
        _proto.onDestroy = function onDestroy() {
          this._removeMaskNode();
        };
        _proto.isHit = function isHit(worldPt) {
          var uiTrans = this.node._uiProps.uiTransformComp;
          var size = uiTrans.contentSize;
          var w = size.width;
          var h = size.height;
          var testPt = _vec2_temp$1;
          this.node.getWorldMatrix(_worldMatrix);
          Mat4.invert(_mat4_temp$4, _worldMatrix);
          Vec2.transformMat4(testPt, worldPt, _mat4_temp$4);
          var ap = uiTrans.anchorPoint;
          testPt.x += ap.x * w;
          testPt.y += ap.y * h;
          var result = false;
          if (this.type === MaskType.GRAPHICS_RECT || this.type === MaskType.GRAPHICS_STENCIL || this.type === MaskType.SPRITE_STENCIL) {
            result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
          } else if (this.type === MaskType.GRAPHICS_ELLIPSE) {
            var rx = w / 2;
            var ry = h / 2;
            var px = testPt.x - 0.5 * w;
            var py = testPt.y - 0.5 * h;
            result = px * px / (rx * rx) + py * py / (ry * ry) < 1;
          }
          if (this._inverted) {
            result = !result;
          }
          return result;
        };
        _proto._nodeStateChange = function _nodeStateChange(type) {
          this._updateGraphics();
        };
        _proto._changeRenderType = function _changeRenderType() {
          var isGraphics = this._type !== MaskType.SPRITE_STENCIL;
          if (isGraphics) {
            this._createGraphics();
          } else {
            this._createSprite();
          }
        };
        _proto._createSprite = function _createSprite() {
          if (!this._sprite) {
            var sprite = this._sprite = this.node.getComponent(Sprite);
            if (!sprite) {
              var node = this.node;
              sprite = this._sprite = node.addComponent(Sprite);
            }
          }
          this._sprite.stencilStage = this.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL;
          this._sprite.updateMaterial();
        };
        _proto._createGraphics = function _createGraphics() {
          if (!this._graphics) {
            var graphics = this._graphics = this.node.getComponent(Graphics);
            if (!graphics) {
              var node = this.node;
              graphics = this._graphics = node.addComponent(Graphics);
            }
            graphics.lineWidth = 1;
            var color = Color$1.WHITE.clone();
            color.a = 0;
            graphics.fillColor = color;
          }
          this._graphics.stencilStage = this.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL;
        };
        _proto._updateGraphics = function _updateGraphics() {
          if (!this._graphics || this._type !== MaskType.GRAPHICS_RECT && this._type !== MaskType.GRAPHICS_ELLIPSE) {
            return;
          }
          var uiTrans = this.node._uiProps.uiTransformComp;
          var graphics = this._graphics;
          graphics.clear();
          var size = uiTrans.contentSize;
          var width = size.width;
          var height = size.height;
          var ap = uiTrans.anchorPoint;
          var x = -width * ap.x;
          var y = -height * ap.y;
          if (this._type === MaskType.GRAPHICS_RECT) {
            graphics.rect(x, y, width, height);
          } else if (this._type === MaskType.GRAPHICS_ELLIPSE) {
            var center = new Vec3(x + width / 2, y + height / 2, 0);
            var radius = new Vec3(width / 2, height / 2, 0);
            var points = _calculateCircle(center, radius, this._segments);
            for (var i = 0; i < points.length; ++i) {
              var point = points[i];
              if (i === 0) {
                graphics.moveTo(point.x, point.y);
              } else {
                graphics.lineTo(point.x, point.y);
              }
            }
            graphics.close();
          }
          graphics.fill();
        };
        _proto._enableRender = function _enableRender() {
          if (this.subComp) {
            this.subComp.enabled = true;
          }
        };
        _proto._disableRender = function _disableRender() {
          if (this.subComp) {
            this.subComp.stencilStage = Stage.DISABLED;
            this.subComp.updateMaterial();
            if (this.node.activeInHierarchy) {
              this.subComp.enabled = false;
            }
          }
        };
        _proto._removeMaskNode = function _removeMaskNode() {
          if (this._sprite) {
            this._sprite = null;
          }
          if (this._graphics) {
            this._graphics = null;
          }
        };
        _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
          if (enable === void 0) {
            enable = true;
          }
          warnID(9007);
          if (this.subComp) {
            this.subComp.markForUpdateRenderData(enable);
          }
        };
        _proto.requestRenderData = function requestRenderData(any) {
          warnID(9007);
        };
        _proto.destroyRenderData = function destroyRenderData() {
          warnID(9007);
        };
        _proto.updateRenderer = function updateRenderer() {
          warnID(9007);
          if (this.subComp) {
            this.subComp.updateRenderer();
          }
        };
        _proto.fillBuffers = function fillBuffers(render) {
          warnID(9007);
        };
        _proto.postUpdateAssembler = function postUpdateAssembler(render) {
          warnID(9007);
        };
        _proto.setNodeDirty = function setNodeDirty() {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setNodeDirty();
          }
        };
        _proto.setTextureDirty = function setTextureDirty() {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setTextureDirty();
          }
        };
        _proto.getMaterial = function getMaterial(idx) {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.getSharedMaterial(idx);
          }
          return null;
        };
        _proto.setMaterial = function setMaterial(material, index) {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setMaterial(material, index);
          }
        };
        _proto.getMaterialInstance = function getMaterialInstance(idx) {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.getMaterialInstance(idx);
          }
          return null;
        };
        _proto.setMaterialInstance = function setMaterialInstance(matInst, index) {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setMaterialInstance(matInst, index);
          }
        };
        _proto.getRenderMaterial = function getRenderMaterial(index) {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.getRenderMaterial(index);
          }
          return null;
        };
        _createClass(Mask, [{
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(value) {
            if (this._type === value) {
              return;
            }
            this._type = value;
            if (this._type !== MaskType.SPRITE_STENCIL) {
              if (this._sprite) {
                this.node.removeComponent(Sprite);
                this._sprite._destroyImmediate();
                this._sprite = null;
              }
              this._changeRenderType();
              this._updateGraphics();
            } else {
              if (this._graphics) {
                this._graphics.clear();
                this.node.removeComponent(Graphics);
                this._graphics._destroyImmediate();
                this._graphics = null;
              }
              this._changeRenderType();
            }
          }
        }, {
          key: "inverted",
          get: function get() {
            return this._inverted;
          },
          set: function set(value) {
            this._inverted = value;
            this.subComp.stencilStage = this.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL;
          }
        }, {
          key: "segments",
          get: function get() {
            return this._segments;
          },
          set: function set(value) {
            if (this._segments === value) {
              return;
            }
            this._segments = clamp$1(value, SEGMENTS_MIN, SEGMENTS_MAX);
            this._updateGraphics();
          }
        }, {
          key: "spriteFrame",
          get: function get() {
            if (this._sprite) {
              return this._sprite.spriteFrame;
            }
            return null;
          },
          set: function set(value) {
            if (this._sprite) {
              this._sprite.spriteFrame = value;
            } else {
              error('please change type to sprite_stencil first');
            }
          }
        }, {
          key: "alphaThreshold",
          get: function get() {
            return this._alphaThreshold;
          },
          set: function set(value) {
            if (this._alphaThreshold === value) {
              return;
            }
            this._alphaThreshold = value;
            if (this.type === MaskType.SPRITE_STENCIL && this._sprite) {
              var mat = this._sprite.getMaterialInstance(0);
              mat.setProperty('alphaThreshold', this._alphaThreshold);
            }
          }
        }, {
          key: "subComp",
          get: function get() {
            return this._graphics || this._sprite;
          }
        }, {
          key: "customMaterial",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.customMaterial;
            }
            return null;
          },
          set: function set(val) {
            warnID(9007);
            if (this.subComp) {
              this.subComp.customMaterial = val;
            }
          }
        }, {
          key: "color",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.color;
            }
            return null;
          },
          set: function set(value) {
            warnID(9007);
            if (this.subComp && value) {
              this.subComp.color = value;
            }
          }
        }, {
          key: "sharedMaterial",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.sharedMaterial;
            }
            return null;
          }
        }, {
          key: "sharedMaterials",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.sharedMaterials;
            }
            return null;
          },
          set: function set(val) {
            warnID(9007);
            if (this.subComp && val) {
              this.subComp.sharedMaterials = val;
            }
          }
        }, {
          key: "material",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.material;
            }
            return null;
          },
          set: function set(val) {
            warnID(9007);
            if (this.subComp) {
              this.subComp.material = val;
            }
          }
        }, {
          key: "materials",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.materials;
            }
            return [null];
          },
          set: function set(val) {
            warnID(9007);
            if (this.subComp) {
              this.subComp.materials = val;
            }
          }
        }]);
        return Mask;
      }(Component), _class3$G.Type = MaskType, _class3$G), (_applyDecoratedDescriptor(_class2$2w.prototype, "type", [_dec3$1B], Object.getOwnPropertyDescriptor(_class2$2w.prototype, "type"), _class2$2w.prototype), _initializer$2n = applyDecoratedInitializer(_class2$2w.prototype, "_type", [serializable$p], function () {
        return MaskType.GRAPHICS_RECT;
      }), _initializer2$1_ = applyDecoratedInitializer(_class2$2w.prototype, "_inverted", [serializable$p], function () {
        return false;
      }), _initializer3$1s = applyDecoratedInitializer(_class2$2w.prototype, "_segments", [serializable$p], function () {
        return 64;
      }), _initializer4$1f = applyDecoratedInitializer(_class2$2w.prototype, "_alphaThreshold", [serializable$p], function () {
        return 0.1;
      })), _class2$2w)) || _class$2P) || _class$2P));
      NodeEventProcessor._maskComp = Mask;
      legacyCC.Mask = Mask;

      var _dec$2Q, _dec2$2b, _dec3$1A, _class$2O;
      var LabelOutline = exports('m', (_dec$2Q = ccclass$M('cc.LabelOutline'), _dec2$2b = executionOrder$1(110), _dec3$1A = requireComponent(Label), _dec$2Q(_class$2O = _dec2$2b(_class$2O = _dec3$1A(_class$2O = function (_Component) {
        _inheritsLoose(LabelOutline, _Component);
        function LabelOutline() {
          return _Component.apply(this, arguments) || this;
        }
        var _proto = LabelOutline.prototype;
        _proto.onEnable = function onEnable() {
          var label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.enableOutline = true;
        };
        _proto.onDisable = function onDisable() {
          var label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.enableOutline = false;
        };
        _createClass(LabelOutline, [{
          key: "color",
          get: function get() {
            var label = this.node.getComponent(Label);
            assertIsTrue(label);
            return label.outlineColor;
          },
          set: function set(value) {
            var label = this.node.getComponent(Label);
            assertIsTrue(label);
            label.outlineColor = value;
          }
        }, {
          key: "width",
          get: function get() {
            var label = this.node.getComponent(Label);
            assertIsTrue(label);
            return label.outlineWidth;
          },
          set: function set(value) {
            var label = this.node.getComponent(Label);
            assertIsTrue(label);
            label.outlineWidth = value;
          }
        }]);
        return LabelOutline;
      }(Component)) || _class$2O) || _class$2O) || _class$2O));
      legacyCC.LabelOutline = LabelOutline;

      deprecateModuleExportedName({
        RenderComponent: {
          newName: 'UIRenderer',
          since: '1.2.0',
          removed: true
        },
        UITransformComponent: {
          newName: 'UITransform',
          since: '1.2.0',
          removed: false
        },
        CanvasComponent: {
          newName: 'Canvas',
          since: '1.2.0',
          removed: false
        }
      });

      deprecateModuleExportedName({
        UIRenderable: {
          newName: 'UIRenderer',
          since: '3.0.0',
          removed: true
        }
      });

      deprecateModuleExportedName({
        Renderable2D: {
          newName: 'UIRenderer',
          since: '3.6.0',
          removed: false
        }
      });

      var _dec$2P, _class$2N, _class2$2v, _initializer$2m, _initializer2$1Z, _initializer3$1r, _class3$F;
      var PostProcess = (_dec$2P = ccclass$M('cc.PostProcess'), _dec$2P(_class$2N = disallowMultiple$1(_class$2N = (_class2$2v = (_class3$F = function (_Component) {
        _inheritsLoose(PostProcess, _Component);
        function PostProcess() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.global = _initializer$2m && _initializer$2m();
          _this._shadingScale = _initializer2$1Z && _initializer2$1Z();
          _this.enableShadingScaleInEditor = _initializer3$1r && _initializer3$1r();
          _this.settings = new Map();
          return _this;
        }
        var _proto = PostProcess.prototype;
        _proto.addSetting = function addSetting(setting) {
          this.settings.set(setting.constructor, setting);
        };
        _proto.removeSetting = function removeSetting(setting) {
          this.settings["delete"](setting.constructor);
        };
        _proto.getSetting = function getSetting(ctor) {
          return this.settings.get(ctor);
        };
        _proto.onEnable = function onEnable() {
          PostProcess.all.push(this);
        };
        _proto.onDisable = function onDisable() {
          var idx = PostProcess.all.indexOf(this);
          if (idx !== -1) {
            PostProcess.all.splice(idx, 1);
          }
        };
        _createClass(PostProcess, [{
          key: "shadingScale",
          get: function get() {
            return this._shadingScale;
          },
          set: function set(v) {
            this._shadingScale = v;
          }
        }]);
        return PostProcess;
      }(Component), _class3$F.all = [], _class3$F), (_initializer$2m = applyDecoratedInitializer(_class2$2v.prototype, "global", [property$3, serializable$p], function () {
        return true;
      }), _initializer2$1Z = applyDecoratedInitializer(_class2$2v.prototype, "_shadingScale", [serializable$p], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$2v.prototype, "shadingScale", [property$3], Object.getOwnPropertyDescriptor(_class2$2v.prototype, "shadingScale"), _class2$2v.prototype), _initializer3$1r = applyDecoratedInitializer(_class2$2v.prototype, "enableShadingScaleInEditor", [property$3, serializable$p], function () {
        return false;
      })), _class2$2v)) || _class$2N) || _class$2N);

      var _dec$2O, _dec2$2a, _dec3$1z, _dec4$17, _dec5$10, _dec6$M, _dec7$B, _dec8$r, _dec9$m, _dec10$e, _class$2M, _class2$2u, _initializer$2l, _initializer2$1Y, _initializer3$1q, _initializer4$1e, _initializer5$_, _initializer6$P, _initializer7$E, _initializer8$A, _initializer9$v, _initializer10$s, _initializer11$r, _initializer12$o, _initializer13$l, _initializer14$h, _initializer15$d, _initializer16$d, _initializer17$a, _initializer18$a, _initializer19$9, _initializer20$7, _initializer21$7, _initializer22$6, _class3$E;
      var _temp_vec3_1$1 = new Vec3();
      var ProjectionType = Enum(CameraProjection);
      var FOVAxis = Enum(CameraFOVAxis);
      var Aperture = Enum(CameraAperture);
      var Shutter = Enum(CameraShutter);
      var ISO = Enum(CameraISO);
      var ClearFlag = Enum({
        SKYBOX: SKYBOX_FLAG | ClearFlagBit.DEPTH_STENCIL,
        SOLID_COLOR: ClearFlagBit.ALL,
        DEPTH_ONLY: ClearFlagBit.DEPTH_STENCIL,
        DONT_CLEAR: ClearFlagBit.NONE
      });
      var Camera = exports('d$', (_dec$2O = ccclass$M('cc.Camera'), _dec2$2a = type$d(Layers.BitMask), _dec3$1z = type$d(ClearFlag), _dec4$17 = type$d(ProjectionType), _dec5$10 = type$d(FOVAxis), _dec6$M = type$d(Aperture), _dec7$B = type$d(Shutter), _dec8$r = type$d(ISO), _dec9$m = type$d(RenderTexture), _dec10$e = type$d(PostProcess), _dec$2O(_class$2M = (_class2$2u = (_class3$E = function (_Component) {
        _inheritsLoose(Camera, _Component);
        function Camera() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._projection = _initializer$2l && _initializer$2l();
          _this._priority = _initializer2$1Y && _initializer2$1Y();
          _this._fov = _initializer3$1q && _initializer3$1q();
          _this._fovAxis = _initializer4$1e && _initializer4$1e();
          _this._orthoHeight = _initializer5$_ && _initializer5$_();
          _this._near = _initializer6$P && _initializer6$P();
          _this._far = _initializer7$E && _initializer7$E();
          _this._color = _initializer8$A && _initializer8$A();
          _this._depth = _initializer9$v && _initializer9$v();
          _this._stencil = _initializer10$s && _initializer10$s();
          _this._clearFlags = _initializer11$r && _initializer11$r();
          _this._rect = _initializer12$o && _initializer12$o();
          _this._aperture = _initializer13$l && _initializer13$l();
          _this._shutter = _initializer14$h && _initializer14$h();
          _this._iso = _initializer15$d && _initializer15$d();
          _this._screenScale = _initializer16$d && _initializer16$d();
          _this._visibility = _initializer17$a && _initializer17$a();
          _this._targetTexture = _initializer18$a && _initializer18$a();
          _this._postProcess = _initializer19$9 && _initializer19$9();
          _this._usePostProcess = _initializer20$7 && _initializer20$7();
          _this._camera = null;
          _this._inEditorMode = false;
          _this._flows = undefined;
          _this._cameraType = _initializer21$7 && _initializer21$7();
          _this._trackingType = _initializer22$6 && _initializer22$6();
          return _this;
        }
        var _proto = Camera.prototype;
        _proto.onLoad = function onLoad() {
          this._createCamera();
        };
        _proto.onEnable = function onEnable() {
          this.node.hasChangedFlags |= TransformBit.POSITION;
          if (this._camera) {
            this._attachToScene();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._camera) {
            this._detachFromScene();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._camera) {
            this._camera.destroy();
            this._camera = null;
          }
          if (this._targetTexture) {
            this._targetTexture.off('resize');
          }
        };
        _proto.screenPointToRay = function screenPointToRay(x, y, out) {
          if (!out) {
            out = Ray.create();
          }
          if (this._camera) {
            this._camera.screenPointToRay(out, x, y);
          }
          return out;
        };
        _proto.worldToScreen = function worldToScreen(worldPos, out) {
          if (!out) {
            out = new Vec3();
          }
          if (this._camera) {
            this._camera.worldToScreen(out, worldPos);
          }
          return out;
        };
        _proto.screenToWorld = function screenToWorld(screenPos, out) {
          if (!out) {
            out = this.node.getWorldPosition();
          }
          if (this._camera) {
            this._camera.screenToWorld(out, screenPos);
          }
          return out;
        };
        _proto.convertToUINode = function convertToUINode(wpos, uiNode, out) {
          if (!out) {
            out = new Vec3();
          }
          if (!this._camera) {
            return out;
          }
          this.worldToScreen(wpos, _temp_vec3_1$1);
          var cmp = uiNode.getComponent('cc.UITransform');
          var designSize = legacyCC.view.getVisibleSize();
          var xoffset = _temp_vec3_1$1.x - this._camera.width * 0.5;
          var yoffset = _temp_vec3_1$1.y - this._camera.height * 0.5;
          _temp_vec3_1$1.x = xoffset / legacyCC.view.getScaleX() + designSize.width * 0.5;
          _temp_vec3_1$1.y = yoffset / legacyCC.view.getScaleY() + designSize.height * 0.5;
          if (cmp) {
            cmp.convertToNodeSpaceAR(_temp_vec3_1$1, out);
          }
          return out;
        };
        _proto._createCamera = function _createCamera() {
          if (!this._camera) {
            this._camera = legacyCC.director.root.createCamera();
            this._camera.initialize({
              name: this.node.name,
              node: this.node,
              projection: this._projection,
              window: this._inEditorMode ? legacyCC.director.root && legacyCC.director.root.mainWindow : legacyCC.director.root && legacyCC.director.root.tempWindow,
              priority: this._priority,
              cameraType: this.cameraType,
              trackingType: this.trackingType
            });
            this._camera.setViewportInOrientedSpace(this._rect);
            this._camera.fovAxis = this._fovAxis;
            this._camera.fov = toRadian(this._fov);
            this._camera.orthoHeight = this._orthoHeight;
            this._camera.nearClip = this._near;
            this._camera.farClip = this._far;
            this._camera.clearColor = this._color;
            this._camera.clearDepth = this._depth;
            this._camera.clearStencil = this._stencil;
            this._camera.clearFlag = this._clearFlags;
            this._camera.visibility = this._visibility;
            this._camera.aperture = this._aperture;
            this._camera.shutter = this._shutter;
            this._camera.iso = this._iso;
            this._camera.postProcess = this._postProcess;
            this._camera.usePostProcess = this._usePostProcess;
          }
          this._updateTargetTexture();
        };
        _proto._attachToScene = function _attachToScene() {
          if (!this.node.scene || !this._camera) {
            return;
          }
          if (this._camera && this._camera.scene) {
            this._camera.scene.removeCamera(this._camera);
          }
          var rs = this._getRenderScene();
          rs.addCamera(this._camera);
        };
        _proto._detachFromScene = function _detachFromScene() {
          if (this._camera && this._camera.scene) {
            this._camera.scene.removeCamera(this._camera);
          }
        };
        _proto._checkTargetTextureEvent = function _checkTargetTextureEvent(old) {
          var _this2 = this;
          if (old) {
            old.off('resize');
          }
          if (this._targetTexture) {
            this._targetTexture.on('resize', function (window) {
              if (_this2._camera) {
                _this2._camera.setFixedSize(window.width, window.height);
              }
            }, this);
          }
        };
        _proto._updateTargetTexture = function _updateTargetTexture() {
          if (!this._camera) {
            return;
          }
          if (this._targetTexture) {
            var window = this._targetTexture.window;
            this._camera.changeTargetWindow(window);
            this._camera.setFixedSize(window.width, window.height);
          }
        };
        _createClass(Camera, [{
          key: "camera",
          get: function get() {
            return this._camera;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(val) {
            this._priority = val;
            if (this._camera) {
              this._camera.priority = val;
            }
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(val) {
            this._visibility = val;
            if (this._camera) {
              this._camera.visibility = val;
            }
          }
        }, {
          key: "clearFlags",
          get: function get() {
            return this._clearFlags;
          },
          set: function set(val) {
            this._clearFlags = val;
            if (this._camera) {
              this._camera.clearFlag = val;
            }
          }
        }, {
          key: "clearColor",
          get: function get() {
            return this._color;
          },
          set: function set(val) {
            this._color.set(val);
            if (this._camera) {
              this._camera.clearColor = this._color;
            }
          }
        }, {
          key: "clearDepth",
          get: function get() {
            return this._depth;
          },
          set: function set(val) {
            this._depth = val;
            if (this._camera) {
              this._camera.clearDepth = val;
            }
          }
        }, {
          key: "clearStencil",
          get: function get() {
            return this._stencil;
          },
          set: function set(val) {
            this._stencil = val;
            if (this._camera) {
              this._camera.clearStencil = val;
            }
          }
        }, {
          key: "projection",
          get: function get() {
            return this._projection;
          },
          set: function set(val) {
            this._projection = val;
            if (this._camera) {
              this._camera.projectionType = val;
            }
          }
        }, {
          key: "fovAxis",
          get: function get() {
            return this._fovAxis;
          },
          set: function set(val) {
            if (val === this._fovAxis) {
              return;
            }
            this._fovAxis = val;
            if (this._camera) {
              this._camera.fovAxis = val;
              if (val === CameraFOVAxis.VERTICAL) {
                this.fov = this._fov * this._camera.aspect;
              } else {
                this.fov = this._fov / this._camera.aspect;
              }
            }
          }
        }, {
          key: "fov",
          get: function get() {
            return this._fov;
          },
          set: function set(val) {
            this._fov = val;
            if (this._camera) {
              this._camera.fov = toRadian(val);
            }
          }
        }, {
          key: "orthoHeight",
          get: function get() {
            return this._orthoHeight;
          },
          set: function set(val) {
            this._orthoHeight = val;
            if (this._camera) {
              this._camera.orthoHeight = val;
            }
          }
        }, {
          key: "near",
          get: function get() {
            return this._near;
          },
          set: function set(val) {
            this._near = val;
            if (this._camera) {
              this._camera.nearClip = val;
            }
          }
        }, {
          key: "far",
          get: function get() {
            return this._far;
          },
          set: function set(val) {
            this._far = val;
            if (this._camera) {
              this._camera.farClip = val;
            }
          }
        }, {
          key: "aperture",
          get: function get() {
            return this._aperture;
          },
          set: function set(val) {
            this._aperture = val;
            if (this._camera) {
              this._camera.aperture = val;
            }
          }
        }, {
          key: "shutter",
          get: function get() {
            return this._shutter;
          },
          set: function set(val) {
            this._shutter = val;
            if (this._camera) {
              this._camera.shutter = val;
            }
          }
        }, {
          key: "iso",
          get: function get() {
            return this._iso;
          },
          set: function set(val) {
            this._iso = val;
            if (this._camera) {
              this._camera.iso = val;
            }
          }
        }, {
          key: "rect",
          get: function get() {
            return this._rect;
          },
          set: function set(val) {
            this._rect = val;
            if (this._camera) {
              this._camera.setViewportInOrientedSpace(val);
            }
          }
        }, {
          key: "targetTexture",
          get: function get() {
            return this._targetTexture;
          },
          set: function set(value) {
            if (this._targetTexture === value) {
              return;
            }
            var old = this._targetTexture;
            this._targetTexture = value;
            this._checkTargetTextureEvent(old);
            this._updateTargetTexture();
            if (!value && this._camera) {
              this._camera.changeTargetWindow(null);
              this._camera.isWindowSize = true;
            }
            this.node.emit(Camera.TARGET_TEXTURE_CHANGE, this);
          }
        }, {
          key: "usePostProcess",
          get: function get() {
            return this._usePostProcess;
          },
          set: function set(v) {
            this._usePostProcess = v;
            if (this._camera) {
              this._camera.usePostProcess = v;
            }
          }
        }, {
          key: "postProcess",
          get: function get() {
            return this._postProcess;
          },
          set: function set(v) {
            this._postProcess = v;
            if (this._camera) {
              this._camera.postProcess = v;
            }
          }
        }, {
          key: "screenScale",
          get: function get() {
            return this._screenScale;
          },
          set: function set(val) {
            this._screenScale = val;
            if (this._camera) {
              this._camera.screenScale = val;
            }
          }
        }, {
          key: "inEditorMode",
          get: function get() {
            return this._inEditorMode;
          },
          set: function set(value) {
            this._inEditorMode = value;
            if (this._camera) {
              this._camera.changeTargetWindow(value ? legacyCC.director.root && legacyCC.director.root.mainWindow : legacyCC.director.root && legacyCC.director.root.tempWindow);
            }
          }
        }, {
          key: "cameraType",
          get: function get() {
            return this._cameraType;
          },
          set: function set(val) {
            if (this._cameraType === val) {
              return;
            }
            this._cameraType = val;
            if (this.camera) {
              this.camera.cameraType = val;
            }
          }
        }, {
          key: "trackingType",
          get: function get() {
            return this._trackingType;
          },
          set: function set(val) {
            if (this._trackingType === val) {
              return;
            }
            this._trackingType = val;
            if (this.camera) {
              this.camera.trackingType = val;
            }
          }
        }]);
        return Camera;
      }(Component), _class3$E.ProjectionType = ProjectionType, _class3$E.FOVAxis = FOVAxis, _class3$E.ClearFlag = ClearFlag, _class3$E.Aperture = Aperture, _class3$E.Shutter = Shutter, _class3$E.ISO = ISO, _class3$E.TARGET_TEXTURE_CHANGE = 'tex-change', _class3$E), (_initializer$2l = applyDecoratedInitializer(_class2$2u.prototype, "_projection", [serializable$p], function () {
        return ProjectionType.PERSPECTIVE;
      }), _initializer2$1Y = applyDecoratedInitializer(_class2$2u.prototype, "_priority", [serializable$p], function () {
        return 0;
      }), _initializer3$1q = applyDecoratedInitializer(_class2$2u.prototype, "_fov", [serializable$p], function () {
        return 45;
      }), _initializer4$1e = applyDecoratedInitializer(_class2$2u.prototype, "_fovAxis", [serializable$p], function () {
        return FOVAxis.VERTICAL;
      }), _initializer5$_ = applyDecoratedInitializer(_class2$2u.prototype, "_orthoHeight", [serializable$p], function () {
        return 10;
      }), _initializer6$P = applyDecoratedInitializer(_class2$2u.prototype, "_near", [serializable$p], function () {
        return 1;
      }), _initializer7$E = applyDecoratedInitializer(_class2$2u.prototype, "_far", [serializable$p], function () {
        return 1000;
      }), _initializer8$A = applyDecoratedInitializer(_class2$2u.prototype, "_color", [serializable$p], function () {
        return new Color$1('#333333');
      }), _initializer9$v = applyDecoratedInitializer(_class2$2u.prototype, "_depth", [serializable$p], function () {
        return 1;
      }), _initializer10$s = applyDecoratedInitializer(_class2$2u.prototype, "_stencil", [serializable$p], function () {
        return 0;
      }), _initializer11$r = applyDecoratedInitializer(_class2$2u.prototype, "_clearFlags", [serializable$p], function () {
        return ClearFlag.SOLID_COLOR;
      }), _initializer12$o = applyDecoratedInitializer(_class2$2u.prototype, "_rect", [serializable$p], function () {
        return new Rect$1(0, 0, 1, 1);
      }), _initializer13$l = applyDecoratedInitializer(_class2$2u.prototype, "_aperture", [serializable$p], function () {
        return Aperture.F16_0;
      }), _initializer14$h = applyDecoratedInitializer(_class2$2u.prototype, "_shutter", [serializable$p], function () {
        return Shutter.D125;
      }), _initializer15$d = applyDecoratedInitializer(_class2$2u.prototype, "_iso", [serializable$p], function () {
        return ISO.ISO100;
      }), _initializer16$d = applyDecoratedInitializer(_class2$2u.prototype, "_screenScale", [serializable$p], function () {
        return 1;
      }), _initializer17$a = applyDecoratedInitializer(_class2$2u.prototype, "_visibility", [serializable$p], function () {
        return CAMERA_DEFAULT_MASK;
      }), _initializer18$a = applyDecoratedInitializer(_class2$2u.prototype, "_targetTexture", [serializable$p], function () {
        return null;
      }), _initializer19$9 = applyDecoratedInitializer(_class2$2u.prototype, "_postProcess", [serializable$p], function () {
        return null;
      }), _initializer20$7 = applyDecoratedInitializer(_class2$2u.prototype, "_usePostProcess", [serializable$p], function () {
        return false;
      }), _initializer21$7 = applyDecoratedInitializer(_class2$2u.prototype, "_cameraType", [serializable$p], function () {
        return CameraType.DEFAULT;
      }), _initializer22$6 = applyDecoratedInitializer(_class2$2u.prototype, "_trackingType", [serializable$p], function () {
        return TrackingType.NO_TRACKING;
      }), _applyDecoratedDescriptor(_class2$2u.prototype, "visibility", [_dec2$2a], Object.getOwnPropertyDescriptor(_class2$2u.prototype, "visibility"), _class2$2u.prototype), _applyDecoratedDescriptor(_class2$2u.prototype, "clearFlags", [_dec3$1z], Object.getOwnPropertyDescriptor(_class2$2u.prototype, "clearFlags"), _class2$2u.prototype), _applyDecoratedDescriptor(_class2$2u.prototype, "projection", [_dec4$17], Object.getOwnPropertyDescriptor(_class2$2u.prototype, "projection"), _class2$2u.prototype), _applyDecoratedDescriptor(_class2$2u.prototype, "fovAxis", [_dec5$10], Object.getOwnPropertyDescriptor(_class2$2u.prototype, "fovAxis"), _class2$2u.prototype), _applyDecoratedDescriptor(_class2$2u.prototype, "aperture", [_dec6$M], Object.getOwnPropertyDescriptor(_class2$2u.prototype, "aperture"), _class2$2u.prototype), _applyDecoratedDescriptor(_class2$2u.prototype, "shutter", [_dec7$B], Object.getOwnPropertyDescriptor(_class2$2u.prototype, "shutter"), _class2$2u.prototype), _applyDecoratedDescriptor(_class2$2u.prototype, "iso", [_dec8$r], Object.getOwnPropertyDescriptor(_class2$2u.prototype, "iso"), _class2$2u.prototype), _applyDecoratedDescriptor(_class2$2u.prototype, "targetTexture", [_dec9$m], Object.getOwnPropertyDescriptor(_class2$2u.prototype, "targetTexture"), _class2$2u.prototype), _applyDecoratedDescriptor(_class2$2u.prototype, "usePostProcess", [property$3], Object.getOwnPropertyDescriptor(_class2$2u.prototype, "usePostProcess"), _class2$2u.prototype), _applyDecoratedDescriptor(_class2$2u.prototype, "postProcess", [_dec10$e], Object.getOwnPropertyDescriptor(_class2$2u.prototype, "postProcess"), _class2$2u.prototype)), _class2$2u)) || _class$2M));
      legacyCC.Camera = Camera;

      var _orientationMap;
      var localWinSize = new Size$1();
      var orientationMap = (_orientationMap = {}, _orientationMap[macro.ORIENTATION_AUTO] = Orientation$1.AUTO, _orientationMap[macro.ORIENTATION_LANDSCAPE] = Orientation$1.LANDSCAPE, _orientationMap[macro.ORIENTATION_PORTRAIT] = Orientation$1.PORTRAIT, _orientationMap);
      var View = exports('hf', function (_Eventify) {
        _inheritsLoose(View, _Eventify);
        function View() {
          var _this;
          _this = _Eventify.call(this) || this;
          _this._designResolutionSize = void 0;
          _this._scaleX = void 0;
          _this._scaleY = void 0;
          _this._viewportRect = void 0;
          _this._visibleRect = void 0;
          _this._autoFullScreen = void 0;
          _this._retinaEnabled = void 0;
          _this._resizeCallback = void 0;
          _this._resolutionPolicy = void 0;
          _this._rpExactFit = void 0;
          _this._rpShowAll = void 0;
          _this._rpNoBorder = void 0;
          _this._rpFixedHeight = void 0;
          _this._rpFixedWidth = void 0;
          var _strategyer = ContainerStrategy;
          var _strategy = ContentStrategy;
          _this._designResolutionSize = new Size$1(0, 0);
          _this._scaleX = 1;
          _this._scaleY = 1;
          _this._viewportRect = new Rect$1(0, 0, 0, 0);
          _this._visibleRect = new Rect$1(0, 0, 0, 0);
          _this._autoFullScreen = false;
          _this._retinaEnabled = false;
          _this._resizeCallback = null;
          _this._rpExactFit = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.EXACT_FIT);
          _this._rpShowAll = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.SHOW_ALL);
          _this._rpNoBorder = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.NO_BORDER);
          _this._rpFixedHeight = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT);
          _this._rpFixedWidth = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH);
          _this._resolutionPolicy = _this._rpShowAll;
          return _this;
        }
        var _proto = View.prototype;
        _proto.init = function init() {
          var windowSize = screen$1.windowSize;
          var w = windowSize.width;
          var h = windowSize.height;
          this._designResolutionSize.width = w;
          this._designResolutionSize.height = h;
          this._viewportRect.width = w;
          this._viewportRect.height = h;
          this._visibleRect.width = w;
          this._visibleRect.height = h;
          localWinSize.width = this._visibleRect.width;
          localWinSize.height = this._visibleRect.height;
          if (visibleRect) {
            visibleRect.init(this._visibleRect);
          }
          {
            this.resizeWithBrowserSize(true);
            var designResolution = settings.querySettings(Settings.Category.SCREEN, 'designResolution');
            if (designResolution) {
              this.setDesignResolutionSize(Number(designResolution.width), Number(designResolution.height), designResolution.policy || ResolutionPolicy.FIXED_HEIGHT);
            }
          }
          screen$1.on('window-resize', this._updateAdaptResult, this);
          screen$1.on('fullscreen-change', this._updateAdaptResult, this);
        };
        _proto.resizeWithBrowserSize = function resizeWithBrowserSize(enabled) {
          screenAdapter.handleResizeEvent = enabled;
        };
        _proto.setResizeCallback = function setResizeCallback(callback) {
          if (typeof callback === 'function' || callback == null) {
            this._resizeCallback = callback;
          }
        };
        _proto.setOrientation = function setOrientation(orientation) {
          screenAdapter.orientation = orientationMap[orientation];
        };
        _proto.adjustViewportMeta = function adjustViewportMeta(enabled) {};
        _proto.enableRetina = function enableRetina(enabled) {
          this._retinaEnabled = !!enabled;
        };
        _proto.isRetinaEnabled = function isRetinaEnabled() {
          return this._retinaEnabled;
        };
        _proto.enableAutoFullScreen = function enableAutoFullScreen(enabled) {
          if (enabled === this._autoFullScreen) {
            return;
          }
          this._autoFullScreen = enabled;
          if (enabled) {
            screen$1.requestFullScreen()["catch"](function (e) {});
          }
        };
        _proto.isAutoFullScreenEnabled = function isAutoFullScreenEnabled() {
          return this._autoFullScreen;
        };
        _proto.setCanvasSize = function setCanvasSize(width, height) {
          screenAdapter.resolutionScale = 1;
          var dpr = screenAdapter.devicePixelRatio;
          var windowSize = new Size$1(width * dpr, height * dpr);
          screen$1.windowSize = windowSize;
        };
        _proto.getCanvasSize = function getCanvasSize() {
          return screen$1.windowSize;
        };
        _proto.getFrameSize = function getFrameSize() {
          var dpr = screenAdapter.devicePixelRatio;
          var sizeInCssPixels = screen$1.windowSize;
          sizeInCssPixels.width /= dpr;
          sizeInCssPixels.height /= dpr;
          return sizeInCssPixels;
        };
        _proto.setFrameSize = function setFrameSize(width, height) {
          var dpr = screenAdapter.devicePixelRatio;
          screen$1.windowSize = new Size$1(width * dpr, height * dpr);
        };
        _proto.getVisibleSize = function getVisibleSize() {
          return new Size$1(this._visibleRect.width, this._visibleRect.height);
        };
        _proto.getVisibleSizeInPixel = function getVisibleSizeInPixel() {
          return new Size$1(this._visibleRect.width * this._scaleX, this._visibleRect.height * this._scaleY);
        };
        _proto.getVisibleOrigin = function getVisibleOrigin() {
          return new Vec2(this._visibleRect.x, this._visibleRect.y);
        };
        _proto.getVisibleOriginInPixel = function getVisibleOriginInPixel() {
          return new Vec2(this._visibleRect.x * this._scaleX, this._visibleRect.y * this._scaleY);
        };
        _proto.getResolutionPolicy = function getResolutionPolicy() {
          return this._resolutionPolicy;
        };
        _proto._updateResolutionPolicy = function _updateResolutionPolicy(resolutionPolicy) {
          if (resolutionPolicy instanceof ResolutionPolicy) {
            this._resolutionPolicy = resolutionPolicy;
          } else {
            var _locPolicy = ResolutionPolicy;
            if (resolutionPolicy === _locPolicy.EXACT_FIT) {
              this._resolutionPolicy = this._rpExactFit;
            }
            if (resolutionPolicy === _locPolicy.SHOW_ALL) {
              this._resolutionPolicy = this._rpShowAll;
            }
            if (resolutionPolicy === _locPolicy.NO_BORDER) {
              this._resolutionPolicy = this._rpNoBorder;
            }
            if (resolutionPolicy === _locPolicy.FIXED_HEIGHT) {
              this._resolutionPolicy = this._rpFixedHeight;
            }
            if (resolutionPolicy === _locPolicy.FIXED_WIDTH) {
              this._resolutionPolicy = this._rpFixedWidth;
            }
          }
        };
        _proto.setResolutionPolicy = function setResolutionPolicy(resolutionPolicy) {
          this._updateResolutionPolicy(resolutionPolicy);
          var designedResolution = view.getDesignResolutionSize();
          view.setDesignResolutionSize(designedResolution.width, designedResolution.height, resolutionPolicy);
        };
        _proto.setDesignResolutionSize = function setDesignResolutionSize(width, height, resolutionPolicy) {
          if (!(width > 0 && height > 0)) {
            errorID(2200);
            return;
          }
          this._updateResolutionPolicy(resolutionPolicy);
          var policy = this._resolutionPolicy;
          if (policy) {
            policy.preApply(this);
          }
          this._designResolutionSize.width = width;
          this._designResolutionSize.height = height;
          var result = policy.apply(this, this._designResolutionSize);
          if (result.scale && result.scale.length === 2) {
            this._scaleX = result.scale[0];
            this._scaleY = result.scale[1];
          }
          if (result.viewport) {
            var vp = this._viewportRect;
            var vb = this._visibleRect;
            var rv = result.viewport;
            vp.x = rv.x;
            vp.y = rv.y;
            vp.width = rv.width;
            vp.height = rv.height;
            vb.x = 0;
            vb.y = 0;
            vb.width = rv.width / this._scaleX;
            vb.height = rv.height / this._scaleY;
          }
          policy.postApply(this);
          localWinSize.width = this._visibleRect.width;
          localWinSize.height = this._visibleRect.height;
          if (visibleRect) {
            visibleRect.init(this._visibleRect);
          }
          this.emit('design-resolution-changed');
        };
        _proto.getDesignResolutionSize = function getDesignResolutionSize() {
          return new Size$1(this._designResolutionSize.width, this._designResolutionSize.height);
        };
        _proto.setRealPixelResolution = function setRealPixelResolution(width, height, resolutionPolicy) {
          {
            document.documentElement.style.width = width + "px";
            document.body.style.width = width + "px";
            document.body.style.left = '0px';
            document.body.style.top = '0px';
          }
          this.setDesignResolutionSize(width, height, resolutionPolicy);
        };
        _proto.getViewportRect = function getViewportRect() {
          return this._viewportRect;
        };
        _proto.getScaleX = function getScaleX() {
          return this._scaleX;
        };
        _proto.getScaleY = function getScaleY() {
          return this._scaleY;
        };
        _proto.getDevicePixelRatio = function getDevicePixelRatio() {
          return screenAdapter.devicePixelRatio;
        };
        _proto.convertToLocationInView = function convertToLocationInView(tx, ty, relatedPos, out) {
          if (out === void 0) {
            out = new Vec2();
          }
          var x = screenAdapter.devicePixelRatio * (tx - relatedPos.left);
          var y = screenAdapter.devicePixelRatio * (relatedPos.top + relatedPos.height - ty);
          if (screenAdapter.isFrameRotated) {
            out.x = screen$1.windowSize.width - y;
            out.y = x;
          } else {
            out.x = x;
            out.y = y;
          }
          return out;
        };
        _proto._convertToUISpace = function _convertToUISpace(point) {
          var viewport = this._viewportRect;
          point.x = (point.x - viewport.x) / this._scaleX;
          point.y = (point.y - viewport.y) / this._scaleY;
        };
        _proto._updateAdaptResult = function _updateAdaptResult(width, height, windowId) {
          var _this$_resizeCallback;
          legacyCC.director.root.resize(width, height, windowId === undefined || windowId === 0 ? 1 : windowId);
          var w = this._designResolutionSize.width;
          var h = this._designResolutionSize.height;
          if (width > 0 && height > 0) {
            this.setDesignResolutionSize(w, h, this._resolutionPolicy);
          } else {
            assert(false, '_updateAdaptResult Invalid size.');
          }
          this.emit('canvas-resize');
          (_this$_resizeCallback = this._resizeCallback) === null || _this$_resizeCallback === void 0 ? void 0 : _this$_resizeCallback.call(this);
        };
        return View;
      }(Eventify(System)));
      View.instance = void 0;
      var ContainerStrategy = function () {
        function ContainerStrategy() {
          this.name = 'ContainerStrategy';
        }
        var _proto2 = ContainerStrategy.prototype;
        _proto2.preApply = function preApply(_view) {};
        _proto2.apply = function apply(_view, designedResolution) {};
        _proto2.postApply = function postApply(_view) {};
        _proto2._setupCanvas = function _setupCanvas() {
          var locCanvas = legacyCC.game.canvas;
          if (locCanvas) {
            var windowSize = screen$1.windowSize;
            if (locCanvas.width !== windowSize.width) {
              locCanvas.width = windowSize.width;
            }
            if (locCanvas.height !== windowSize.height) {
              locCanvas.height = windowSize.height;
            }
          }
        };
        return ContainerStrategy;
      }();
      ContainerStrategy.EQUAL_TO_FRAME = void 0;
      ContainerStrategy.PROPORTION_TO_FRAME = void 0;
      var ContentStrategy = function () {
        function ContentStrategy() {
          this.name = 'ContentStrategy';
          this._result = void 0;
          this._result = {
            scale: [1, 1],
            viewport: null
          };
        }
        var _proto3 = ContentStrategy.prototype;
        _proto3.preApply = function preApply(_view) {};
        _proto3.apply = function apply(_view, designedResolution) {
          return {
            scale: [1, 1]
          };
        };
        _proto3.postApply = function postApply(_view) {};
        _proto3._buildResult = function _buildResult(containerW, containerH, contentW, contentH, scaleX, scaleY) {
          if (Math.abs(containerW - contentW) < 2) {
            contentW = containerW;
          }
          if (Math.abs(containerH - contentH) < 2) {
            contentH = containerH;
          }
          var viewport = new Rect$1(Math.round((containerW - contentW) / 2), Math.round((containerH - contentH) / 2), contentW, contentH);
          this._result.scale = [scaleX, scaleY];
          this._result.viewport = viewport;
          return this._result;
        };
        return ContentStrategy;
      }();
      ContentStrategy.EXACT_FIT = void 0;
      ContentStrategy.SHOW_ALL = void 0;
      ContentStrategy.NO_BORDER = void 0;
      ContentStrategy.FIXED_HEIGHT = void 0;
      ContentStrategy.FIXED_WIDTH = void 0;
      (function () {
        var EqualToFrame = function (_ContainerStrategy) {
          _inheritsLoose(EqualToFrame, _ContainerStrategy);
          function EqualToFrame() {
            var _this2;
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = arguments[_key];
            }
            _this2 = _ContainerStrategy.call.apply(_ContainerStrategy, [this].concat(args)) || this;
            _this2.name = 'EqualToFrame';
            return _this2;
          }
          var _proto4 = EqualToFrame.prototype;
          _proto4.apply = function apply(_view, designedResolution) {
            screenAdapter.isProportionalToFrame = false;
            this._setupCanvas();
          };
          return EqualToFrame;
        }(ContainerStrategy);
        var ProportionalToFrame = function (_ContainerStrategy2) {
          _inheritsLoose(ProportionalToFrame, _ContainerStrategy2);
          function ProportionalToFrame() {
            var _this3;
            for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
              args[_key2] = arguments[_key2];
            }
            _this3 = _ContainerStrategy2.call.apply(_ContainerStrategy2, [this].concat(args)) || this;
            _this3.name = 'ProportionalToFrame';
            return _this3;
          }
          var _proto5 = ProportionalToFrame.prototype;
          _proto5.apply = function apply(_view, designedResolution) {
            screenAdapter.isProportionalToFrame = true;
            this._setupCanvas();
          };
          return ProportionalToFrame;
        }(ContainerStrategy);
        ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame();
        ContainerStrategy.PROPORTION_TO_FRAME = new ProportionalToFrame();
        var ExactFit = function (_ContentStrategy) {
          _inheritsLoose(ExactFit, _ContentStrategy);
          function ExactFit() {
            var _this4;
            for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
              args[_key3] = arguments[_key3];
            }
            _this4 = _ContentStrategy.call.apply(_ContentStrategy, [this].concat(args)) || this;
            _this4.name = 'ExactFit';
            return _this4;
          }
          var _proto6 = ExactFit.prototype;
          _proto6.apply = function apply(_view, designedResolution) {
            var windowSize = screen$1.windowSize;
            var containerW = windowSize.width;
            var containerH = windowSize.height;
            var scaleX = containerW / designedResolution.width;
            var scaleY = containerH / designedResolution.height;
            return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY);
          };
          return ExactFit;
        }(ContentStrategy);
        var ShowAll = function (_ContentStrategy2) {
          _inheritsLoose(ShowAll, _ContentStrategy2);
          function ShowAll() {
            var _this5;
            for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
              args[_key4] = arguments[_key4];
            }
            _this5 = _ContentStrategy2.call.apply(_ContentStrategy2, [this].concat(args)) || this;
            _this5.name = 'ShowAll';
            return _this5;
          }
          var _proto7 = ShowAll.prototype;
          _proto7.apply = function apply(_view, designedResolution) {
            var windowSize = screen$1.windowSize;
            var containerW = windowSize.width;
            var containerH = windowSize.height;
            var designW = designedResolution.width;
            var designH = designedResolution.height;
            var scaleX = containerW / designW;
            var scaleY = containerH / designH;
            var scale = 0;
            var contentW;
            var contentH;
            if (scaleX < scaleY) {
              scale = scaleX;
              contentW = containerW;
              contentH = designH * scale;
            } else {
              scale = scaleY;
              contentW = designW * scale;
              contentH = containerH;
            }
            return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
          };
          return ShowAll;
        }(ContentStrategy);
        var NoBorder = function (_ContentStrategy3) {
          _inheritsLoose(NoBorder, _ContentStrategy3);
          function NoBorder() {
            var _this6;
            for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
              args[_key5] = arguments[_key5];
            }
            _this6 = _ContentStrategy3.call.apply(_ContentStrategy3, [this].concat(args)) || this;
            _this6.name = 'NoBorder';
            return _this6;
          }
          var _proto8 = NoBorder.prototype;
          _proto8.apply = function apply(_view, designedResolution) {
            var windowSize = screen$1.windowSize;
            var containerW = windowSize.width;
            var containerH = windowSize.height;
            var designW = designedResolution.width;
            var designH = designedResolution.height;
            var scaleX = containerW / designW;
            var scaleY = containerH / designH;
            var scale;
            var contentW;
            var contentH;
            if (scaleX < scaleY) {
              scale = scaleY;
              contentW = designW * scale;
              contentH = containerH;
            } else {
              scale = scaleX;
              contentW = containerW;
              contentH = designH * scale;
            }
            return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
          };
          return NoBorder;
        }(ContentStrategy);
        var FixedHeight = function (_ContentStrategy4) {
          _inheritsLoose(FixedHeight, _ContentStrategy4);
          function FixedHeight() {
            var _this7;
            for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
              args[_key6] = arguments[_key6];
            }
            _this7 = _ContentStrategy4.call.apply(_ContentStrategy4, [this].concat(args)) || this;
            _this7.name = 'FixedHeight';
            return _this7;
          }
          var _proto9 = FixedHeight.prototype;
          _proto9.apply = function apply(_view, designedResolution) {
            var windowSize = screen$1.windowSize;
            var containerW = windowSize.width;
            var containerH = windowSize.height;
            var designH = designedResolution.height;
            var scale = containerH / designH;
            var contentW = containerW;
            var contentH = containerH;
            return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
          };
          return FixedHeight;
        }(ContentStrategy);
        var FixedWidth = function (_ContentStrategy5) {
          _inheritsLoose(FixedWidth, _ContentStrategy5);
          function FixedWidth() {
            var _this8;
            for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
              args[_key7] = arguments[_key7];
            }
            _this8 = _ContentStrategy5.call.apply(_ContentStrategy5, [this].concat(args)) || this;
            _this8.name = 'FixedWidth';
            return _this8;
          }
          var _proto10 = FixedWidth.prototype;
          _proto10.apply = function apply(_view, designedResolution) {
            var windowSize = screen$1.windowSize;
            var containerW = windowSize.width;
            var containerH = windowSize.height;
            var designW = designedResolution.width;
            var scale = containerW / designW;
            var contentW = containerW;
            var contentH = containerH;
            return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
          };
          return FixedWidth;
        }(ContentStrategy);
        ContentStrategy.EXACT_FIT = new ExactFit();
        ContentStrategy.SHOW_ALL = new ShowAll();
        ContentStrategy.NO_BORDER = new NoBorder();
        ContentStrategy.FIXED_HEIGHT = new FixedHeight();
        ContentStrategy.FIXED_WIDTH = new FixedWidth();
      })();
      var ResolutionPolicy = exports('hg', function () {
        function ResolutionPolicy(containerStg, contentStg) {
          this.name = 'ResolutionPolicy';
          this._containerStrategy = void 0;
          this._contentStrategy = void 0;
          this._containerStrategy = null;
          this._contentStrategy = null;
          this.setContainerStrategy(containerStg);
          this.setContentStrategy(contentStg);
        }
        var _proto11 = ResolutionPolicy.prototype;
        _proto11.preApply = function preApply(_view) {
          this._contentStrategy.preApply(_view);
        };
        _proto11.apply = function apply(_view, designedResolution) {
          this._containerStrategy.apply(_view, designedResolution);
          return this._contentStrategy.apply(_view, designedResolution);
        };
        _proto11.postApply = function postApply(_view) {
          this._contentStrategy.postApply(_view);
        };
        _proto11.setContainerStrategy = function setContainerStrategy(containerStg) {
          if (containerStg instanceof ContainerStrategy) {
            this._containerStrategy = containerStg;
          }
        };
        _proto11.setContentStrategy = function setContentStrategy(contentStg) {
          if (contentStg instanceof ContentStrategy) {
            this._contentStrategy = contentStg;
          }
        };
        _createClass(ResolutionPolicy, [{
          key: "canvasSize",
          get: function get() {
            return screen$1.windowSize;
          }
        }]);
        return ResolutionPolicy;
      }());
      ResolutionPolicy.EXACT_FIT = 0;
      ResolutionPolicy.NO_BORDER = 1;
      ResolutionPolicy.SHOW_ALL = 2;
      ResolutionPolicy.FIXED_HEIGHT = 3;
      ResolutionPolicy.FIXED_WIDTH = 4;
      ResolutionPolicy.UNKNOWN = 5;
      ResolutionPolicy.ContainerStrategy = ContainerStrategy;
      ResolutionPolicy.ContentStrategy = ContentStrategy;
      legacyCC.ResolutionPolicy = ResolutionPolicy;
      var view = exports('hh', View.instance = legacyCC.view = new View());
      director.registerSystem('view', view, 0);
      legacyCC.winSize = localWinSize;

      var _dec$2N, _dec2$29, _dec3$1y, _class$2L;
      var RenderRoot2D = exports('R', (_dec$2N = ccclass$M('cc.RenderRoot2D'), _dec2$29 = executionOrder$1(100), _dec3$1y = requireComponent(UITransform), _dec$2N(_class$2L = _dec2$29(_class$2L = _dec3$1y(_class$2L = disallowMultiple$1(_class$2L = function (_Component) {
        _inheritsLoose(RenderRoot2D, _Component);
        function RenderRoot2D() {
          return _Component.apply(this, arguments) || this;
        }
        var _proto = RenderRoot2D.prototype;
        _proto.onEnable = function onEnable() {
          legacyCC.director.root.batcher2D.addScreen(this);
        };
        _proto.onDisable = function onDisable() {
          legacyCC.director.root.batcher2D.removeScreen(this);
        };
        _proto.onDestroy = function onDestroy() {
          legacyCC.director.root.batcher2D.removeScreen(this);
        };
        return RenderRoot2D;
      }(Component)) || _class$2L) || _class$2L) || _class$2L) || _class$2L));

      var _dec$2M, _dec2$28, _dec3$1x, _dec4$16, _class$2K, _class2$2t, _initializer$2k, _initializer2$1X;
      var _worldPos = new Vec3();
      var RenderMode$1 = Enum({
        OVERLAY: 0,
        INTERSPERSE: 1
      });
      var Canvas = exports('C', (_dec$2M = ccclass$M('cc.Canvas'), _dec2$28 = executionOrder$1(100), _dec3$1x = type$d(Camera), _dec4$16 = type$d(Camera), _dec$2M(_class$2K = _dec2$28(_class$2K = disallowMultiple$1(_class$2K = (_class2$2t = function (_RenderRoot2D) {
        _inheritsLoose(Canvas, _RenderRoot2D);
        function Canvas() {
          var _this;
          _this = _RenderRoot2D.call(this) || this;
          _this._cameraComponent = _initializer$2k && _initializer$2k();
          _this._alignCanvasWithScreen = _initializer2$1X && _initializer2$1X();
          _this._thisOnCameraResized = void 0;
          _this.fitDesignResolution_EDITOR = void 0;
          _this._pos = new Vec3();
          _this._renderMode = RenderMode$1.OVERLAY;
          _this._thisOnCameraResized = _this._onResizeCamera.bind(_assertThisInitialized(_this));
          return _this;
        }
        var _proto = Canvas.prototype;
        _proto.__preload = function __preload() {
          var widget = this.getComponent('cc.Widget');
          if (widget) {
            widget.updateAlignment();
          }
          {
            if (this._cameraComponent) {
              this._cameraComponent._createCamera();
              this._cameraComponent.node.on(Camera.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized);
            }
          }
          this._onResizeCamera();
          {
            this.node.on(NodeEventType.TRANSFORM_CHANGED, this._thisOnCameraResized);
          }
        };
        _proto.onEnable = function onEnable() {
          _RenderRoot2D.prototype.onEnable.call(this);
          if (this._cameraComponent) {
            this._cameraComponent.node.on(Camera.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized);
          }
        };
        _proto.onDisable = function onDisable() {
          _RenderRoot2D.prototype.onDisable.call(this);
          if (this._cameraComponent) {
            this._cameraComponent.node.off(Camera.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized);
          }
        };
        _proto.onDestroy = function onDestroy() {
          _RenderRoot2D.prototype.onDestroy.call(this);
          this.node.off(NodeEventType.TRANSFORM_CHANGED, this._thisOnCameraResized);
        };
        _proto._onResizeCamera = function _onResizeCamera() {
          if (this._cameraComponent && this._alignCanvasWithScreen) {
            if (this._cameraComponent.targetTexture) {
              this._cameraComponent.orthoHeight = visibleRect.height / 2;
            } else {
              var size = screen$1.windowSize;
              this._cameraComponent.orthoHeight = size.height / view.getScaleY() / 2;
            }
            this.node.getWorldPosition(_worldPos);
            this._cameraComponent.node.setWorldPosition(_worldPos.x, _worldPos.y, 1000);
          }
        };
        _proto._getViewPriority = function _getViewPriority() {
          if (this._cameraComponent) {
            var _this$cameraComponent;
            var priority = (_this$cameraComponent = this.cameraComponent) === null || _this$cameraComponent === void 0 ? void 0 : _this$cameraComponent.priority;
            priority = this._renderMode === RenderMode$1.OVERLAY ? priority | 1 << 30 : priority & ~(1 << 30);
            return priority;
          }
          return 0;
        };
        _createClass(Canvas, [{
          key: "renderMode",
          get: function get() {
            return this._renderMode;
          },
          set: function set(val) {
            this._renderMode = val;
            if (this._cameraComponent) {
              this._cameraComponent.priority = this._getViewPriority();
            }
          }
        }, {
          key: "cameraComponent",
          get: function get() {
            return this._cameraComponent;
          },
          set: function set(value) {
            if (this._cameraComponent === value) {
              return;
            }
            this._cameraComponent = value;
            this._onResizeCamera();
          }
        }, {
          key: "alignCanvasWithScreen",
          get: function get() {
            return this._alignCanvasWithScreen;
          },
          set: function set(value) {
            this._alignCanvasWithScreen = value;
            this._onResizeCamera();
          }
        }]);
        return Canvas;
      }(RenderRoot2D), (_applyDecoratedDescriptor(_class2$2t.prototype, "cameraComponent", [_dec3$1x], Object.getOwnPropertyDescriptor(_class2$2t.prototype, "cameraComponent"), _class2$2t.prototype), _initializer$2k = applyDecoratedInitializer(_class2$2t.prototype, "_cameraComponent", [_dec4$16], function () {
        return null;
      }), _initializer2$1X = applyDecoratedInitializer(_class2$2t.prototype, "_alignCanvasWithScreen", [serializable$p], function () {
        return true;
      })), _class2$2t)) || _class$2K) || _class$2K) || _class$2K));
      legacyCC.Canvas = Canvas;

      var _dec$2L, _dec2$27, _dec3$1w, _class$2J;
      var UIComponent = exports('U', (_dec$2L = ccclass$M('cc.UIComponent'), _dec2$27 = requireComponent(UITransform), _dec3$1w = executionOrder$1(110), _dec$2L(_class$2J = _dec2$27(_class$2J = _dec3$1w(_class$2J = disallowMultiple$1(_class$2J = function (_Component) {
        _inheritsLoose(UIComponent, _Component);
        function UIComponent() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._lastParent = null;
          _this.stencilStage = Stage.DISABLED;
          return _this;
        }
        var _proto = UIComponent.prototype;
        _proto.__preload = function __preload() {
          this.node._uiProps.uiComp = this;
        };
        _proto.onEnable = function onEnable() {};
        _proto.onDisable = function onDisable() {};
        _proto.onDestroy = function onDestroy() {
          if (this.node._uiProps.uiComp === this) {
            this.node._uiProps.uiComp = null;
          }
        };
        _proto.postUpdateAssembler = function postUpdateAssembler(render) {};
        _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
        };
        _proto.setNodeDirty = function setNodeDirty() {};
        _proto.setTextureDirty = function setTextureDirty() {};
        return UIComponent;
      }(Component)) || _class$2J) || _class$2J) || _class$2J) || _class$2J));

      removeProperty(UIComponent.prototype, 'UIComponent', [{
        name: '_visibility'
      }, {
        name: 'setVisibility'
      }]);
      replaceProperty(Canvas.prototype, 'Canvas.prototype', [{
        name: 'camera',
        newName: 'cameraComponent.camera',
        customGetter: function customGetter() {
          var _this$_cameraComponen;
          return (_this$_cameraComponen = this._cameraComponent) === null || _this$_cameraComponen === void 0 ? void 0 : _this$_cameraComponen.camera;
        }
      }, {
        name: 'clearFlag',
        newName: 'cameraComponent.clearFlags',
        customGetter: function customGetter() {
          return this._cameraComponent ? this._cameraComponent.clearFlags : 0;
        },
        customSetter: function customSetter(val) {
          if (this._cameraComponent) this._cameraComponent.clearFlags = val;
        }
      }, {
        name: 'color',
        newName: 'cameraComponent.clearColor',
        customGetter: function customGetter() {
          return this._cameraComponent ? this._cameraComponent.clearColor : Color$1.BLACK;
        },
        customSetter: function customSetter(val) {
          if (this._cameraComponent) this._cameraComponent.clearColor = val;
        }
      }, {
        name: 'priority',
        newName: 'cameraComponent.priority',
        customGetter: function customGetter() {
          return this._cameraComponent ? this._cameraComponent.priority : 0;
        },
        customSetter: function customSetter(val) {
          if (this._cameraComponent) this._cameraComponent.priority = val;
        }
      }, {
        name: 'targetTexture',
        newName: 'cameraComponent.targetTexture',
        customGetter: function customGetter() {
          return this._cameraComponent ? this._cameraComponent.targetTexture : null;
        },
        customSetter: function customSetter(value) {
          if (this._cameraComponent) this._cameraComponent.targetTexture = value;
        }
      }, {
        name: 'visibility',
        newName: 'cameraComponent.visibility',
        customGetter: function customGetter() {
          return this._cameraComponent ? this._cameraComponent.visibility : 0;
        }
      }]);
      markAsWarning(UITransform.prototype, 'UITransform.prototype', [{
        name: 'priority',
        suggest: "Please use setSiblingIndex to change index of the current node in its parent's children array."
      }]);
      legacyCC.UITransformComponent = UITransform;
      setClassAlias(UITransform, 'cc.UITransformComponent');
      setClassAlias(UIRenderer, 'cc.RenderComponent');
      legacyCC.CanvasComponent = Canvas;
      setClassAlias(Canvas, 'cc.CanvasComponent');
      legacyCC.internal.Renderable2D = UIRenderer;
      setClassAlias(UIRenderer, 'cc.Renderable2D');

      function rayAABB2(ray, min, max) {
        var o = ray.o;
        var d = ray.d;
        var ix = 1 / d.x;
        var iy = 1 / d.y;
        var iz = 1 / d.z;
        var t1 = (min.x - o.x) * ix;
        var t2 = (max.x - o.x) * ix;
        var t3 = (min.y - o.y) * iy;
        var t4 = (max.y - o.y) * iy;
        var t5 = (min.z - o.z) * iz;
        var t6 = (max.z - o.z) * iz;
        var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
        var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6));
        if (tmax < 0 || tmin > tmax) {
          return 0;
        }
        return tmin > 0 ? tmin : tmax;
      }
      var raySubMesh = function () {
        var tri = Triangle$1.create();
        var deOpt = {
          distance: Infinity,
          doubleSided: false,
          mode: ERaycastMode.ANY
        };
        var minDis = 0;
        var fillResult = function fillResult(m, d, i0, i1, i2, r) {
          if (m === ERaycastMode.CLOSEST) {
            if (minDis > d || minDis === 0) {
              minDis = d;
              if (r) {
                if (r.length === 0) {
                  r.push({
                    distance: d,
                    vertexIndex0: i0 / 3,
                    vertexIndex1: i1 / 3,
                    vertexIndex2: i2 / 3
                  });
                } else {
                  r[0].distance = d;
                  r[0].vertexIndex0 = i0 / 3;
                  r[0].vertexIndex1 = i1 / 3;
                  r[0].vertexIndex2 = i2 / 3;
                }
              }
            }
          } else {
            minDis = d;
            if (r) r.push({
              distance: d,
              vertexIndex0: i0 / 3,
              vertexIndex1: i1 / 3,
              vertexIndex2: i2 / 3
            });
          }
        };
        var narrowphase = function narrowphase(vb, ib, pm, ray, opt) {
          if (pm === PrimitiveMode.TRIANGLE_LIST) {
            var cnt = ib.length;
            for (var j = 0; j < cnt; j += 3) {
              var i0 = ib[j] * 3;
              var i1 = ib[j + 1] * 3;
              var i2 = ib[j + 2] * 3;
              Vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]);
              Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]);
              Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]);
              var dist = intersect.rayTriangle(ray, tri, opt.doubleSided);
              if (dist === 0 || dist > opt.distance) continue;
              fillResult(opt.mode, dist, i0, i1, i2, opt.result);
              if (opt.mode === ERaycastMode.ANY) return dist;
            }
          } else if (pm === PrimitiveMode.TRIANGLE_STRIP) {
            var _cnt = ib.length - 2;
            var rev = 0;
            for (var _j = 0; _j < _cnt; _j += 1) {
              var _i = ib[_j - rev] * 3;
              var _i2 = ib[_j + rev + 1] * 3;
              var _i3 = ib[_j + 2] * 3;
              Vec3.set(tri.a, vb[_i], vb[_i + 1], vb[_i + 2]);
              Vec3.set(tri.b, vb[_i2], vb[_i2 + 1], vb[_i2 + 2]);
              Vec3.set(tri.c, vb[_i3], vb[_i3 + 1], vb[_i3 + 2]);
              rev = ~rev;
              var _dist = intersect.rayTriangle(ray, tri, opt.doubleSided);
              if (_dist === 0 || _dist > opt.distance) continue;
              fillResult(opt.mode, _dist, _i, _i2, _i3, opt.result);
              if (opt.mode === ERaycastMode.ANY) return _dist;
            }
          } else if (pm === PrimitiveMode.TRIANGLE_FAN) {
            var _cnt2 = ib.length - 1;
            var _i4 = ib[0] * 3;
            Vec3.set(tri.a, vb[_i4], vb[_i4 + 1], vb[_i4 + 2]);
            for (var _j2 = 1; _j2 < _cnt2; _j2 += 1) {
              var _i5 = ib[_j2] * 3;
              var _i6 = ib[_j2 + 1] * 3;
              Vec3.set(tri.b, vb[_i5], vb[_i5 + 1], vb[_i5 + 2]);
              Vec3.set(tri.c, vb[_i6], vb[_i6 + 1], vb[_i6 + 2]);
              var _dist2 = intersect.rayTriangle(ray, tri, opt.doubleSided);
              if (_dist2 === 0 || _dist2 > opt.distance) continue;
              fillResult(opt.mode, _dist2, _i4, _i5, _i6, opt.result);
              if (opt.mode === ERaycastMode.ANY) return _dist2;
            }
          }
          return minDis;
        };
        return function (ray, submesh, options) {
          minDis = 0;
          if (submesh.geometricInfo.positions.length === 0) return minDis;
          var opt = options === undefined ? deOpt : options;
          var min = submesh.geometricInfo.boundingBox.min;
          var max = submesh.geometricInfo.boundingBox.max;
          if (rayAABB2(ray, min, max)) {
            var pm = submesh.primitiveMode;
            var _submesh$geometricInf = submesh.geometricInfo,
              vb = _submesh$geometricInf.positions,
              ib = _submesh$geometricInf.indices;
            narrowphase(vb, ib, pm, ray, opt);
          }
          return minDis;
        };
      }();
      var rayMesh = function () {
        var minDis = 0;
        var deOpt = {
          distance: Infinity,
          doubleSided: false,
          mode: ERaycastMode.ANY
        };
        return function (ray, mesh, options) {
          minDis = 0;
          var opt = options === undefined ? deOpt : options;
          var length = mesh.renderingSubMeshes.length;
          var min = mesh.struct.minPosition;
          var max = mesh.struct.maxPosition;
          if (min && max && !rayAABB2(ray, min, max)) return minDis;
          for (var i = 0; i < length; i++) {
            var sm = mesh.renderingSubMeshes[i];
            var dis = raySubMesh(ray, sm, opt);
            if (dis) {
              if (opt.mode === ERaycastMode.CLOSEST) {
                if (minDis === 0 || minDis > dis) {
                  minDis = dis;
                  if (opt.subIndices) opt.subIndices[0] = i;
                }
              } else {
                minDis = dis;
                if (opt.subIndices) opt.subIndices.push(i);
                if (opt.mode === ERaycastMode.ANY) {
                  return dis;
                }
              }
            }
          }
          if (minDis && opt.mode === ERaycastMode.CLOSEST) {
            if (opt.result) {
              opt.result[0].distance = minDis;
              opt.result.length = 1;
            }
            if (opt.subIndices) opt.subIndices.length = 1;
          }
          return minDis;
        };
      }();
      var rayModel = function () {
        var minDis = 0;
        var deOpt = {
          distance: Infinity,
          doubleSided: false,
          mode: ERaycastMode.ANY
        };
        var modelRay = new Ray();
        var m4 = new Mat4();
        return function (r, model, options) {
          minDis = 0;
          var opt = options === undefined ? deOpt : options;
          var wb = model.worldBounds;
          if (wb && !intersect.rayAABB(r, wb)) return minDis;
          Ray.copy(modelRay, r);
          if (model.node) {
            Mat4.invert(m4, model.node.getWorldMatrix(m4));
            Vec3.transformMat4(modelRay.o, r.o, m4);
            Vec3.transformMat4Normal(modelRay.d, r.d, m4);
          }
          var subModels = model.subModels;
          for (var i = 0; i < subModels.length; i++) {
            var subMesh = subModels[i].subMesh;
            var dis = raySubMesh(modelRay, subMesh, opt);
            if (dis) {
              if (opt.mode === ERaycastMode.CLOSEST) {
                if (minDis === 0 || minDis > dis) {
                  minDis = dis;
                  if (opt.subIndices) opt.subIndices[0] = i;
                }
              } else {
                minDis = dis;
                if (opt.subIndices) opt.subIndices.push(i);
                if (opt.mode === ERaycastMode.ANY) {
                  return dis;
                }
              }
            }
          }
          if (minDis && opt.mode === ERaycastMode.CLOSEST) {
            if (opt.result) {
              opt.result[0].distance = minDis;
              opt.result.length = 1;
            }
            if (opt.subIndices) opt.subIndices.length = 1;
          }
          return minDis;
        };
      }();
      intersect.rayModel = rayModel;
      intersect.raySubMesh = raySubMesh;
      intersect.rayMesh = rayMesh;

      var _dec$2K, _class$2I, _class2$2s, _initializer$2j;
      getPhaseID('specular-pass');
      var ModelRenderer = exports('e0', (_dec$2K = ccclass$M('cc.ModelRenderer'), _dec$2K(_class$2I = (_class2$2s = function (_Renderer) {
        _inheritsLoose(ModelRenderer, _Renderer);
        function ModelRenderer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Renderer.call.apply(_Renderer, [this].concat(args)) || this;
          _this._visFlags = _initializer$2j && _initializer$2j();
          _this._models = [];
          _this._priority = 0;
          return _this;
        }
        var _proto = ModelRenderer.prototype;
        _proto._collectModels = function _collectModels() {
          return this._models;
        };
        _proto.onEnable = function onEnable() {
          this._updatePriority();
        };
        _proto._attachToScene = function _attachToScene() {};
        _proto._detachFromScene = function _detachFromScene() {};
        _proto._onVisibilityChange = function _onVisibilityChange(val) {};
        _proto._updatePriority = function _updatePriority() {
          if (this._models.length > 0) {
            for (var i = 0; i < this._models.length; i++) {
              this._models[i].priority = this._priority;
            }
          }
        };
        _createClass(ModelRenderer, [{
          key: "visibility",
          get: function get() {
            return this._visFlags;
          },
          set: function set(val) {
            this._visFlags = val;
            this._onVisibilityChange(val);
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(val) {
            if (val === this._priority) return;
            this._priority = val;
            this._updatePriority();
          }
        }]);
        return ModelRenderer;
      }(Renderer), (_initializer$2j = applyDecoratedInitializer(_class2$2s.prototype, "_visFlags", [serializable$p], function () {
        return Layers.Enum.NONE;
      })), _class2$2s)) || _class$2I));

      var _dec$2J, _dec2$26, _class$2H, _class2$2r, _initializer$2i;
      var ccclass$J = ccclass$M,
        serializable$n = serializable$p,
        type$b = type$d;
      var PrefabLink = exports('e3', (_dec$2J = ccclass$J('cc.PrefabLink'), _dec2$26 = type$b(Prefab), _dec$2J(_class$2H = (_class2$2r = function (_Component) {
        _inheritsLoose(PrefabLink, _Component);
        function PrefabLink() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.prefab = _initializer$2i && _initializer$2i();
          return _this;
        }
        return PrefabLink;
      }(Component), (_initializer$2i = applyDecoratedInitializer(_class2$2r.prototype, "prefab", [_dec2$26, serializable$n], function () {
        return null;
      })), _class2$2r)) || _class$2H));

      replaceProperty(Camera, 'Camera', [{
        name: 'CameraClearFlag',
        newName: 'ClearFlag'
      }]);
      replaceProperty(Camera.prototype, 'Camera.prototype', [{
        name: 'color',
        newName: 'clearColor'
      }, {
        name: 'depth',
        newName: 'clearDepth'
      }, {
        name: 'stencil',
        newName: 'clearStencil'
      }]);
      markAsWarning(Renderer.prototype, 'Renderer.prototype', [{
        name: 'getMaterial',
        suggest: 'please use renderer.getSharedMaterial instead.'
      }]);
      legacyCC.CameraComponent = Camera;
      setClassAlias(Camera, 'cc.CameraComponent');
      legacyCC.RenderableComponent = ModelRenderer;
      setClassAlias(ModelRenderer, 'cc.RenderableComponent');

      var _dec$2I, _dec2$25, _dec3$1v, _class$2G, _class2$2q, _initializer$2h, _initializer2$1W, _initializer3$1p, _initializer4$1d, _initializer5$Z, _initializer6$O;
      var SpriteMode;
      (function (SpriteMode) {
        SpriteMode[SpriteMode["SIMPLE"] = 0] = "SIMPLE";
        SpriteMode[SpriteMode["SLICED"] = 1] = "SLICED";
        SpriteMode[SpriteMode["TILED"] = 2] = "TILED";
      })(SpriteMode || (SpriteMode = {}));
      var SpriteRenderer = exports('f', (_dec$2I = ccclass$M('cc.SpriteRenderer'), _dec2$25 = executionOrder$1(100), _dec3$1v = type$d(SpriteFrame), _dec$2I(_class$2G = _dec2$25(_class$2G = (_class2$2q = function (_ModelRenderer) {
        _inheritsLoose(SpriteRenderer, _ModelRenderer);
        function SpriteRenderer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ModelRenderer.call.apply(_ModelRenderer, [this].concat(args)) || this;
          _this._spriteFrame = _initializer$2h && _initializer$2h();
          _this._mode = _initializer2$1W && _initializer2$1W();
          _this._color = _initializer3$1p && _initializer3$1p();
          _this._flipX = _initializer4$1d && _initializer4$1d();
          _this._flipY = _initializer5$Z && _initializer5$Z();
          _this._size = _initializer6$O && _initializer6$O();
          _this._model = null;
          return _this;
        }
        var _proto = SpriteRenderer.prototype;
        _proto.onLoad = function onLoad() {
          if (this._spriteFrame) {
            if (!this._spriteFrame.mesh) {
              this._spriteFrame.ensureMeshData();
            }
            this._spriteFrame.mesh.initialize();
          }
          this._updateModels();
        };
        _proto.onRestore = function onRestore() {
          this._updateModels();
          if (this.enabledInHierarchy) {
            this._attachToScene();
          }
        };
        _proto.onEnable = function onEnable() {
          _ModelRenderer.prototype.onEnable.call(this);
          if (!this._model) {
            this._updateModels();
          }
          this._attachToScene();
        };
        _proto.onDisable = function onDisable() {
          if (this._model) {
            this._detachFromScene();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._model) {
            legacyCC.director.root.destroyModel(this._model);
            this._model = null;
            this._models.length = 0;
          }
        };
        _proto._updateModels = function _updateModels() {
          if (!this._spriteFrame) {
            return;
          }
          var model = this._model;
          if (model) {
            model.destroy();
            model.initialize();
            model.node = model.transform = this.node;
          } else {
            this._createModel();
          }
          if (this._model) {
            var mesh = this._spriteFrame.mesh;
            this._model.createBoundingShape(mesh.struct.minPosition, mesh.struct.maxPosition);
            this._updateModelParams();
            this._onUpdateLocalDescriptorSet();
          }
        };
        _proto._createModel = function _createModel() {
          var model = this._model = legacyCC.director.root.createModel(Model);
          model.visFlags = this.visibility;
          model.node = model.transform = this.node;
          this._models.length = 0;
          this._models.push(this._model);
        };
        _proto._updateModelParams = function _updateModelParams() {
          if (!this._spriteFrame || !this._model) {
            return;
          }
          this._spriteFrame.ensureMeshData();
          var mesh = this._spriteFrame.mesh;
          this.node.hasChangedFlags |= TransformBit.POSITION;
          this._model.transform.hasChangedFlags |= TransformBit.POSITION;
          var renderingMesh = mesh ? mesh.renderingSubMeshes : null;
          if (renderingMesh) {
            var meshCount = renderingMesh.length;
            for (var i = 0; i < meshCount; ++i) {
              var material = this.getRenderMaterial(i);
              if (material && !material.isValid) {
                material = null;
              }
              var subMeshData = renderingMesh[i];
              if (subMeshData) {
                this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial());
              }
            }
          }
          this._model.enabled = true;
        };
        _proto._getBuiltinMaterial = function _getBuiltinMaterial() {
          return builtinResMgr.get('missing-material');
        };
        _proto._onMaterialModified = function _onMaterialModified(idx, material) {
          _ModelRenderer.prototype._onMaterialModified.call(this, idx, material);
          if (!this._spriteFrame || !this._model || !this._model.inited) {
            return;
          }
          this._onRebuildPSO(idx, material || this._getBuiltinMaterial());
        };
        _proto._onRebuildPSO = function _onRebuildPSO(idx, material) {
          if (!this._model || !this._model.inited) {
            return;
          }
          this._model.setSubModelMaterial(idx, material);
          this._onUpdateLocalDescriptorSet();
        };
        _proto._onUpdateLocalDescriptorSet = function _onUpdateLocalDescriptorSet() {
          if (!this._spriteFrame || !this._model || !this._model.inited) {
            return;
          }
          var texture = this._spriteFrame.getGFXTexture();
          var sampler = this._spriteFrame.getGFXSampler();
          var subModels = this._model.subModels;
          var binding = ModelLocalBindings.SAMPLER_SPRITE;
          for (var i = 0; i < subModels.length; i++) {
            var descriptorSet = subModels[i].descriptorSet;
            descriptorSet.bindTexture(binding, texture);
            descriptorSet.bindSampler(binding, sampler);
            descriptorSet.update();
          }
        };
        _proto._attachToScene = function _attachToScene() {
          if (!this.node.scene || !this._model) {
            return;
          }
          var renderScene = this._getRenderScene();
          if (this._model.scene !== null) {
            this._detachFromScene();
          }
          renderScene.addModel(this._model);
        };
        _proto._detachFromScene = function _detachFromScene() {
          if (this._model && this._model.scene) {
            this._model.scene.removeModel(this._model);
          }
        };
        _createClass(SpriteRenderer, [{
          key: "spriteFrame",
          get: function get() {
            return this._spriteFrame;
          },
          set: function set(value) {
            if (this._spriteFrame === value) {
              return;
            }
            this._spriteFrame;
            this._spriteFrame = value;
            if (this._spriteFrame) {
              this._spriteFrame.ensureMeshData();
              var mesh = this._spriteFrame.mesh;
              mesh.initialize();
            }
            this._updateModels();
            if (this.enabledInHierarchy) {
              this._attachToScene();
            }
          }
        }, {
          key: "model",
          get: function get() {
            return this._model;
          }
        }]);
        return SpriteRenderer;
      }(ModelRenderer), (_applyDecoratedDescriptor(_class2$2q.prototype, "spriteFrame", [_dec3$1v], Object.getOwnPropertyDescriptor(_class2$2q.prototype, "spriteFrame"), _class2$2q.prototype), _initializer$2h = applyDecoratedInitializer(_class2$2q.prototype, "_spriteFrame", [serializable$p], function () {
        return null;
      }), _initializer2$1W = applyDecoratedInitializer(_class2$2q.prototype, "_mode", [serializable$p], function () {
        return SpriteMode.SIMPLE;
      }), _initializer3$1p = applyDecoratedInitializer(_class2$2q.prototype, "_color", [serializable$p], function () {
        return Color$1.WHITE.clone();
      }), _initializer4$1d = applyDecoratedInitializer(_class2$2q.prototype, "_flipX", [serializable$p], function () {
        return false;
      }), _initializer5$Z = applyDecoratedInitializer(_class2$2q.prototype, "_flipY", [serializable$p], function () {
        return false;
      }), _initializer6$O = applyDecoratedInitializer(_class2$2q.prototype, "_size", [serializable$p], function () {
        return new Vec2();
      })), _class2$2q)) || _class$2G) || _class$2G));

      var _dec$2H, _dec2$24, _dec3$1u, _dec4$15, _dec5$$, _dec6$L, _dec7$A, _dec8$q, _class$2F, _class2$2p, _initializer$2g, _initializer2$1V, _initializer3$1o, _initializer4$1c, _initializer5$Y, _initializer6$N, _initializer7$D, _initializer8$z, _initializer9$u, _initializer10$r, _initializer11$q, _initializer12$n, _initializer13$k, _initializer14$g, _class3$D;
      var _htmlTextParser = new HtmlTextParser();
      var RichTextChildName = 'RICHTEXT_CHILD';
      var RichTextChildImageName = 'RICHTEXT_Image_CHILD';
      var _tempSize = new Vec2();
      var _tempSizeLeft = new Vec2();
      var labelPool = new Pool$1(function (seg) {
        if (!legacyCC.isValid(seg.node)) {
          return false;
        } else {
          var outline = seg.node.getComponent(LabelOutline);
          if (outline) {
            outline.width = 0;
          }
        }
        return true;
      }, 20);
      var imagePool = new Pool$1(function (seg) {
        return legacyCC.isValid(seg.node);
      }, 10);
      function createSegment(type) {
        return {
          node: new Node$1(type),
          comp: null,
          lineCount: 0,
          styleIndex: 0,
          imageOffset: '',
          clickParam: '',
          clickHandler: '',
          type: type
        };
      }
      function getSegmentByPool(type, content) {
        var seg;
        if (type === RichTextChildName) {
          seg = labelPool._get();
        } else if (type === RichTextChildImageName) {
          seg = imagePool._get();
        }
        seg = seg || createSegment(type);
        var node = seg.node;
        if (!node) {
          node = new Node$1(type);
        }
        node.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
        node.active = true;
        if (type === RichTextChildImageName) {
          seg.comp = node.getComponent(Sprite) || node.addComponent(Sprite);
          seg.comp.spriteFrame = content;
          seg.comp.type = Sprite.Type.SLICED;
          seg.comp.sizeMode = Sprite.SizeMode.CUSTOM;
        } else {
          seg.comp = node.getComponent(Label) || node.addComponent(Label);
          seg.comp.string = content;
          seg.comp.horizontalAlign = HorizontalTextAlignment.LEFT;
          seg.comp.verticalAlign = VerticalTextAlignment.TOP;
          seg.comp.underlineHeight = 2;
        }
        node.setPosition(0, 0, 0);
        var trans = node._uiProps.uiTransformComp;
        trans.setAnchorPoint(0.5, 0.5);
        seg.node = node;
        seg.lineCount = 0;
        seg.styleIndex = 0;
        seg.imageOffset = '';
        seg.clickParam = '';
        seg.clickHandler = '';
        return seg;
      }
      var RichText = exports('i', (_dec$2H = ccclass$M('cc.RichText'), _dec2$24 = executionOrder$1(110), _dec3$1u = type$d(HorizontalTextAlignment), _dec4$15 = type$d(VerticalTextAlignment), _dec5$$ = type$d(Color$1), _dec6$L = type$d(Font), _dec7$A = type$d(CacheMode), _dec8$q = type$d(SpriteAtlas), _dec$2H(_class$2F = _dec2$24(_class$2F = (_class2$2p = (_class3$D = function (_Component) {
        _inheritsLoose(RichText, _Component);
        function RichText() {
          var _this;
          _this = _Component.call(this) || this;
          _this._lineHeight = _initializer$2g && _initializer$2g();
          _this._string = _initializer2$1V && _initializer2$1V();
          _this._horizontalAlign = _initializer3$1o && _initializer3$1o();
          _this._verticalAlign = _initializer4$1c && _initializer4$1c();
          _this._fontSize = _initializer5$Y && _initializer5$Y();
          _this._fontColor = _initializer6$N && _initializer6$N();
          _this._maxWidth = _initializer7$D && _initializer7$D();
          _this._fontFamily = _initializer8$z && _initializer8$z();
          _this._font = _initializer9$u && _initializer9$u();
          _this._isSystemFontUsed = _initializer10$r && _initializer10$r();
          _this._userDefinedFont = _initializer11$q && _initializer11$q();
          _this._cacheMode = _initializer12$n && _initializer12$n();
          _this._imageAtlas = _initializer13$k && _initializer13$k();
          _this._handleTouchEvent = _initializer14$g && _initializer14$g();
          _this._textArray = [];
          _this._segments = [];
          _this._labelSegmentsCache = [];
          _this._linesWidth = [];
          _this._lineCount = 1;
          _this._labelWidth = 0;
          _this._labelHeight = 0;
          _this._layoutDirty = true;
          _this._lineOffsetX = 0;
          _this._updateRichTextStatus = void 0;
          _this._labelChildrenNum = 0;
          _this._updateRichTextStatus = _this._updateRichText;
          return _this;
        }
        var _proto = RichText.prototype;
        _proto.onLoad = function onLoad() {
          this.node.on(NodeEventType.LAYER_CHANGED, this._applyLayer, this);
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._updateRichTextPosition, this);
        };
        _proto.onEnable = function onEnable() {
          if (this.handleTouchEvent) {
            this._addEventListeners();
          }
          this._updateRichText();
          this._activateChildren(true);
        };
        _proto.onDisable = function onDisable() {
          if (this.handleTouchEvent) {
            this._removeEventListeners();
          }
          this._activateChildren(false);
        };
        _proto.onRestore = function onRestore() {
          {
            return;
          }
        };
        _proto.onDestroy = function onDestroy() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._segments), _step; !(_step = _iterator()).done;) {
            var seg = _step.value;
            seg.node.removeFromParent();
            if (seg.type === RichTextChildName) {
              labelPool.put(seg);
            } else if (seg.type === RichTextChildImageName) {
              imagePool.put(seg);
            }
          }
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._updateRichTextPosition, this);
          this.node.off(NodeEventType.LAYER_CHANGED, this._applyLayer, this);
        };
        _proto._addEventListeners = function _addEventListeners() {
          this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this);
        };
        _proto._removeEventListeners = function _removeEventListeners() {
          this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this);
        };
        _proto._updateLabelSegmentTextAttributes = function _updateLabelSegmentTextAttributes() {
          var _this2 = this;
          this._segments.forEach(function (item) {
            _this2._applyTextAttribute(item);
          });
        };
        _proto._createFontLabel = function _createFontLabel(str) {
          return getSegmentByPool(RichTextChildName, str);
        };
        _proto._createImage = function _createImage(spriteFrame) {
          return getSegmentByPool(RichTextChildImageName, spriteFrame);
        };
        _proto._onTTFLoaded = function _onTTFLoaded() {
          if (this._font instanceof TTFFont) {
            this._layoutDirty = true;
            this._updateRichText();
          } else {
            this._layoutDirty = true;
            this._updateRichText();
          }
        };
        _proto.splitLongStringApproximatelyIn2048 = function splitLongStringApproximatelyIn2048(text, styleIndex) {
          var approxSize = text.length * this.fontSize;
          var partStringArr = [];
          if (approxSize <= 2048 * 0.8) {
            partStringArr.push(text);
            return partStringArr;
          }
          this._calculateSize(_tempSize, styleIndex, text);
          if (_tempSize.x < 2048) {
            partStringArr.push(text);
          } else {
            var multilineTexts = text.split('\n');
            for (var i = 0; i < multilineTexts.length; i++) {
              this._calculateSize(_tempSize, styleIndex, multilineTexts[i]);
              if (_tempSize.x < 2048) {
                partStringArr.push(multilineTexts[i]);
              } else {
                var thisPartSplitResultArr = this.splitLongStringOver2048(multilineTexts[i], styleIndex);
                partStringArr.push.apply(partStringArr, thisPartSplitResultArr);
              }
            }
          }
          return partStringArr;
        };
        _proto.splitLongStringOver2048 = function splitLongStringOver2048(text, styleIndex) {
          var partStringArr = [];
          var longStr = text;
          var curStart = 0;
          var curEnd = longStr.length / 2;
          var curString = longStr.substring(curStart, curEnd);
          var leftString = longStr.substring(curEnd);
          var curStringSize = this._calculateSize(_tempSize, styleIndex, curString);
          var leftStringSize = this._calculateSize(_tempSizeLeft, styleIndex, leftString);
          var maxWidth = this._maxWidth;
          if (this._maxWidth === 0) {
            maxWidth = 2047.9;
          }
          var lineCountForOnePart = 1;
          var sizeForOnePart = lineCountForOnePart * maxWidth;
          while (curStringSize.x > sizeForOnePart) {
            curEnd /= 2;
            if (curEnd < 1) {
              curEnd *= 2;
              break;
            }
            curString = curString.substring(curStart, curEnd);
            leftString = longStr.substring(curEnd);
            this._calculateSize(curStringSize, styleIndex, curString);
          }
          var leftTryTimes = 1000;
          var curWordStep = 1;
          while (leftTryTimes && curStart < text.length) {
            while (leftTryTimes && curStringSize.x < sizeForOnePart) {
              var nextPartExec = getEnglishWordPartAtFirst(leftString);
              if (nextPartExec && nextPartExec.length > 0) {
                curWordStep = nextPartExec[0].length;
              }
              curEnd += curWordStep;
              curString = longStr.substring(curStart, curEnd);
              leftString = longStr.substring(curEnd);
              this._calculateSize(curStringSize, styleIndex, curString);
              leftTryTimes--;
            }
            while (leftTryTimes && curString.length >= 2 && curStringSize.x > sizeForOnePart) {
              curEnd -= curWordStep;
              curString = longStr.substring(curStart, curEnd);
              this._calculateSize(curStringSize, styleIndex, curString);
              curWordStep = 1;
              leftTryTimes--;
            }
            if (curString.length >= 2) {
              var lastWordExec = getEnglishWordPartAtLast(curString);
              if (lastWordExec && lastWordExec.length > 0 && curString !== lastWordExec[0]) {
                curEnd -= lastWordExec[0].length;
                curString = longStr.substring(curStart, curEnd);
              }
            }
            partStringArr.push(curString);
            var partStep = curString.length;
            curStart = curEnd;
            curEnd += partStep;
            curString = longStr.substring(curStart, curEnd);
            leftString = longStr.substring(curEnd);
            this._calculateSize(leftStringSize, styleIndex, leftString);
            this._calculateSize(curStringSize, styleIndex, curString);
            leftTryTimes--;
            if (leftStringSize.x < 2048 && curStringSize.x < sizeForOnePart) {
              partStringArr.push(curString);
              curStart = text.length;
              curEnd = text.length;
              curString = leftString;
              if (leftString !== '') {
                partStringArr.push(curString);
              }
              break;
            }
          }
          return partStringArr;
        };
        _proto._measureText = function _measureText(styleIndex, string) {
          var _this3 = this;
          var func = function func(s) {
            var width = _this3._calculateSize(_tempSize, styleIndex, s).x;
            return width;
          };
          if (string) {
            return func(string);
          } else {
            return func;
          }
        };
        _proto._calculateSize = function _calculateSize(out, styleIndex, s) {
          var label;
          if (this._labelSegmentsCache.length === 0) {
            label = this._createFontLabel(s);
            this._labelSegmentsCache.push(label);
          } else {
            label = this._labelSegmentsCache[0];
            label.node.getComponent(Label).string = s;
          }
          label.styleIndex = styleIndex;
          this._applyTextAttribute(label);
          var size = label.node._uiProps.uiTransformComp.contentSize;
          Vec2.set(out, size.x, size.y);
          return out;
        };
        _proto._onTouchEnded = function _onTouchEnded(event) {
          var _this4 = this;
          var components = this.node.getComponents(Component);
          var _loop = function _loop() {
            var seg = _step2.value;
            var clickHandler = seg.clickHandler;
            var clickParam = seg.clickParam;
            if (clickHandler && _this4._containsTouchLocation(seg, event.touch.getUILocation())) {
              components.forEach(function (component) {
                var func = component[clickHandler];
                if (component.enabledInHierarchy && func) {
                  func.call(component, event, clickParam);
                }
              });
              event.propagationStopped = true;
            }
          };
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._segments), _step2; !(_step2 = _iterator2()).done;) {
            _loop();
          }
        };
        _proto._containsTouchLocation = function _containsTouchLocation(label, point) {
          var comp = label.node.getComponent(UITransform);
          if (!comp) {
            return false;
          }
          var myRect = comp.getBoundingBoxToWorld();
          return myRect.contains(point);
        };
        _proto._resetState = function _resetState() {
          var children = this.node.children;
          for (var i = children.length - 1; i >= 0; i--) {
            var child = children[i];
            if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
              {
                assert(child.parent === this.node);
              }
              child.parent = null;
              var segment = createSegment(child.name);
              segment.node = child;
              if (child.name === RichTextChildName) {
                segment.comp = child.getComponent(Label);
                labelPool.put(segment);
              } else {
                segment.comp = child.getComponent(Sprite);
                imagePool.put(segment);
              }
              this._labelChildrenNum--;
            }
          }
          this._segments.length = 0;
          this._labelSegmentsCache.length = 0;
          this._linesWidth.length = 0;
          this._lineOffsetX = 0;
          this._lineCount = 1;
          this._labelWidth = 0;
          this._labelHeight = 0;
          this._layoutDirty = true;
        };
        _proto._activateChildren = function _activateChildren(active) {
          for (var i = this.node.children.length - 1; i >= 0; i--) {
            var child = this.node.children[i];
            if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
              child.active = active;
            }
          }
        };
        _proto._addLabelSegment = function _addLabelSegment(stringToken, styleIndex) {
          var labelSegment;
          if (this._labelSegmentsCache.length === 0) {
            labelSegment = this._createFontLabel(stringToken);
          } else {
            labelSegment = this._labelSegmentsCache.pop();
            var label = labelSegment.node.getComponent(Label);
            if (label) {
              label.string = stringToken;
            }
          }
          var labelComp = labelSegment.comp;
          if (labelComp.verticalAlign !== this._verticalAlign) {
            labelComp.verticalAlign = this._verticalAlign;
          }
          labelSegment.styleIndex = styleIndex;
          labelSegment.lineCount = this._lineCount;
          labelSegment.node._uiProps.uiTransformComp.setAnchorPoint(0, 0);
          labelSegment.node.layer = this.node.layer;
          this.node.insertChild(labelSegment.node, this._labelChildrenNum++);
          this._applyTextAttribute(labelSegment);
          this._segments.push(labelSegment);
          return labelSegment;
        };
        _proto._updateRichTextWithMaxWidth = function _updateRichTextWithMaxWidth(labelString, labelWidth, styleIndex) {
          var fragmentWidth = labelWidth;
          var labelSegment;
          if (this._lineOffsetX > 0 && fragmentWidth + this._lineOffsetX > this._maxWidth) {
            var checkStartIndex = 0;
            while (this._lineOffsetX <= this._maxWidth) {
              var checkEndIndex = this._getFirstWordLen(labelString, checkStartIndex, labelString.length);
              var checkString = labelString.substr(checkStartIndex, checkEndIndex);
              var checkStringWidth = this._measureText(styleIndex, checkString);
              if (this._lineOffsetX + checkStringWidth <= this._maxWidth) {
                this._lineOffsetX += checkStringWidth;
                checkStartIndex += checkEndIndex;
              } else {
                if (checkStartIndex > 0) {
                  var remainingString = labelString.substr(0, checkStartIndex);
                  this._addLabelSegment(remainingString, styleIndex);
                  labelString = labelString.substr(checkStartIndex, labelString.length);
                  fragmentWidth = this._measureText(styleIndex, labelString);
                }
                this._updateLineInfo();
                break;
              }
            }
          }
          if (fragmentWidth > this._maxWidth) {
            var fragments = fragmentText(labelString, fragmentWidth, this._maxWidth, this._measureText(styleIndex));
            for (var k = 0; k < fragments.length; ++k) {
              var splitString = fragments[k];
              labelSegment = this._addLabelSegment(splitString, styleIndex);
              var labelSize = labelSegment.node._uiProps.uiTransformComp.contentSize;
              this._lineOffsetX += labelSize.width;
              if (fragments.length > 1 && k < fragments.length - 1) {
                this._updateLineInfo();
              }
            }
          } else {
            this._lineOffsetX += fragmentWidth;
            this._addLabelSegment(labelString, styleIndex);
          }
        };
        _proto._isLastComponentCR = function _isLastComponentCR(stringToken) {
          return stringToken.length - 1 === stringToken.lastIndexOf('\n');
        };
        _proto._updateLineInfo = function _updateLineInfo() {
          this._linesWidth.push(this._lineOffsetX);
          this._lineOffsetX = 0;
          this._lineCount++;
        };
        _proto._needsUpdateTextLayout = function _needsUpdateTextLayout(newTextArray) {
          if (this._layoutDirty || !this._textArray || !newTextArray) {
            return true;
          }
          if (this._textArray.length !== newTextArray.length) {
            return true;
          }
          for (var i = 0; i < this._textArray.length; i++) {
            var oldItem = this._textArray[i];
            var newItem = newTextArray[i];
            if (oldItem.text !== newItem.text) {
              return true;
            } else {
              var oldStyle = oldItem.style;
              var newStyle = newItem.style;
              if (oldStyle) {
                if (newStyle) {
                  if (!!newStyle.outline !== !!oldStyle.outline) {
                    return true;
                  }
                  if (oldStyle.size !== newStyle.size || oldStyle.italic !== newStyle.italic || oldStyle.isImage !== newStyle.isImage) {
                    return true;
                  }
                  if (oldStyle.src !== newStyle.src || oldStyle.imageAlign !== newStyle.imageAlign || oldStyle.imageHeight !== newStyle.imageHeight || oldStyle.imageWidth !== newStyle.imageWidth || oldStyle.imageOffset !== newStyle.imageOffset) {
                    return true;
                  }
                } else if (oldStyle.size || oldStyle.italic || oldStyle.isImage || oldStyle.outline) {
                  return true;
                }
              } else if (newStyle) {
                if (newStyle.size || newStyle.italic || newStyle.isImage || newStyle.outline) {
                  return true;
                }
              }
            }
          }
          return false;
        };
        _proto._addRichTextImageElement = function _addRichTextImageElement(richTextElement) {
          if (!richTextElement.style) {
            return;
          }
          var style = richTextElement.style;
          var spriteFrameName = style.src;
          var spriteFrame = this._imageAtlas && spriteFrameName && this._imageAtlas.getSpriteFrame(spriteFrameName);
          if (!spriteFrame) {
            warnID(4400);
          } else {
            var segment = this._createImage(spriteFrame);
            segment.comp;
            switch (style.imageAlign) {
              case 'top':
                segment.node._uiProps.uiTransformComp.setAnchorPoint(0, 1);
                break;
              case 'center':
                segment.node._uiProps.uiTransformComp.setAnchorPoint(0, 0.5);
                break;
              default:
                segment.node._uiProps.uiTransformComp.setAnchorPoint(0, 0);
                break;
            }
            if (style.imageOffset) {
              segment.imageOffset = style.imageOffset;
            }
            segment.node.layer = this.node.layer;
            this.node.insertChild(segment.node, this._labelChildrenNum++);
            this._segments.push(segment);
            var spriteRect = spriteFrame.rect.clone();
            var scaleFactor = 1;
            var spriteWidth = spriteRect.width;
            var spriteHeight = spriteRect.height;
            var expectWidth = style.imageWidth || 0;
            var expectHeight = style.imageHeight || 0;
            if (expectHeight > 0) {
              scaleFactor = expectHeight / spriteHeight;
              spriteWidth *= scaleFactor;
              spriteHeight *= scaleFactor;
            } else {
              scaleFactor = this._lineHeight / spriteHeight;
              spriteWidth *= scaleFactor;
              spriteHeight *= scaleFactor;
            }
            if (expectWidth > 0) {
              spriteWidth = expectWidth;
            }
            if (this._maxWidth > 0) {
              if (this._lineOffsetX + spriteWidth > this._maxWidth) {
                this._updateLineInfo();
              }
              this._lineOffsetX += spriteWidth;
            } else {
              this._lineOffsetX += spriteWidth;
              if (this._lineOffsetX > this._labelWidth) {
                this._labelWidth = this._lineOffsetX;
              }
            }
            segment.node._uiProps.uiTransformComp.setContentSize(spriteWidth, spriteHeight);
            segment.lineCount = this._lineCount;
            segment.clickHandler = '';
            segment.clickParam = '';
            var event = style.event;
            if (event) {
              segment.clickHandler = event.click;
              segment.clickParam = event.param;
            }
          }
        };
        _proto._updateTextDefaultColor = function _updateTextDefaultColor() {
          for (var i = 0; i < this._segments.length; ++i) {
            var _this$_textArray$segm, _this$_textArray$segm2;
            var segment = this._segments[i];
            var label = segment.node.getComponent(Label);
            if (!label) {
              continue;
            }
            if ((_this$_textArray$segm = this._textArray[segment.styleIndex]) !== null && _this$_textArray$segm !== void 0 && (_this$_textArray$segm2 = _this$_textArray$segm.style) !== null && _this$_textArray$segm2 !== void 0 && _this$_textArray$segm2.color) {
              continue;
            }
            label.color = this._fontColor;
          }
        };
        _proto._updateRichText = function _updateRichText() {
          if (!this.enabledInHierarchy) {
            return;
          }
          var newTextArray = _htmlTextParser.parse(this._string);
          if (!this._needsUpdateTextLayout(newTextArray)) {
            this._textArray = newTextArray.slice();
            this._updateLabelSegmentTextAttributes();
            return;
          }
          this._textArray = newTextArray.slice();
          this._resetState();
          var lastEmptyLine = false;
          var label;
          for (var i = 0; i < this._textArray.length; ++i) {
            var richTextElement = this._textArray[i];
            var text = richTextElement.text;
            if (text === undefined) {
              continue;
            }
            if (text === '') {
              if (richTextElement.style && richTextElement.style.isNewLine) {
                this._updateLineInfo();
                continue;
              }
              if (richTextElement.style && richTextElement.style.isImage && this._imageAtlas) {
                this._addRichTextImageElement(richTextElement);
                continue;
              }
            }
            var splitArr = this.splitLongStringApproximatelyIn2048(text, i);
            text = splitArr.join('\n');
            var multilineTexts = text.split('\n');
            for (var j = 0; j < multilineTexts.length; ++j) {
              var labelString = multilineTexts[j];
              if (labelString === '') {
                if (this._isLastComponentCR(text) && j === multilineTexts.length - 1) {
                  continue;
                }
                this._updateLineInfo();
                lastEmptyLine = true;
                continue;
              }
              lastEmptyLine = false;
              if (this._maxWidth > 0) {
                var labelWidth = this._measureText(i, labelString);
                this._updateRichTextWithMaxWidth(labelString, labelWidth, i);
                if (multilineTexts.length > 1 && j < multilineTexts.length - 1) {
                  this._updateLineInfo();
                }
              } else {
                label = this._addLabelSegment(labelString, i);
                this._lineOffsetX += label.node._uiProps.uiTransformComp.width;
                if (this._lineOffsetX > this._labelWidth) {
                  this._labelWidth = this._lineOffsetX;
                }
                if (multilineTexts.length > 1 && j < multilineTexts.length - 1) {
                  this._updateLineInfo();
                }
              }
            }
          }
          if (!lastEmptyLine) {
            this._linesWidth.push(this._lineOffsetX);
          }
          if (this._maxWidth > 0) {
            this._labelWidth = this._maxWidth;
          }
          this._labelHeight = (this._lineCount + BASELINE_RATIO) * this._lineHeight;
          this.node._uiProps.uiTransformComp.setContentSize(this._labelWidth, this._labelHeight);
          this._updateRichTextPosition();
          this._layoutDirty = false;
        };
        _proto._getFirstWordLen = function _getFirstWordLen(text, startIndex, textLen) {
          var character = getSymbolAt(text, startIndex);
          if (isUnicodeCJK(character) || isUnicodeSpace(character)) {
            return 1;
          }
          var len = 1;
          for (var index = startIndex + 1; index < textLen; ++index) {
            character = getSymbolAt(text, index);
            if (isUnicodeSpace(character) || isUnicodeCJK(character)) {
              break;
            }
            len++;
          }
          return len;
        };
        _proto._updateRichTextPosition = function _updateRichTextPosition() {
          var nextTokenX = 0;
          var nextLineIndex = 1;
          var totalLineCount = this._lineCount;
          var trans = this.node._uiProps.uiTransformComp;
          var anchorX = trans.anchorX;
          var anchorY = trans.anchorY;
          for (var i = 0; i < this._segments.length; ++i) {
            var segment = this._segments[i];
            var lineCount = segment.lineCount;
            if (lineCount > nextLineIndex) {
              nextTokenX = 0;
              nextLineIndex = lineCount;
            }
            var lineOffsetX = this._labelWidth * (this._horizontalAlign * 0.5 - anchorX);
            switch (this._horizontalAlign) {
              case HorizontalTextAlignment.LEFT:
                break;
              case HorizontalTextAlignment.CENTER:
                lineOffsetX -= this._linesWidth[lineCount - 1] / 2;
                break;
              case HorizontalTextAlignment.RIGHT:
                lineOffsetX -= this._linesWidth[lineCount - 1];
                break;
            }
            var pos = segment.node.position;
            segment.node.setPosition(nextTokenX + lineOffsetX, this._lineHeight * (totalLineCount - lineCount) - this._labelHeight * anchorY, pos.z);
            if (lineCount === nextLineIndex) {
              nextTokenX += segment.node._uiProps.uiTransformComp.width;
            }
            var sprite = segment.node.getComponent(Sprite);
            if (sprite) {
              var position = segment.node.position.clone();
              var lineHeightSet = this._lineHeight;
              var lineHeightReal = this._lineHeight * (1 + BASELINE_RATIO);
              switch (segment.node._uiProps.uiTransformComp.anchorY) {
                case 1:
                  position.y += lineHeightSet + (lineHeightReal - lineHeightSet) / 2;
                  break;
                case 0.5:
                  position.y += lineHeightReal / 2;
                  break;
                default:
                  position.y += (lineHeightReal - lineHeightSet) / 2;
                  break;
              }
              if (segment.imageOffset) {
                var offsets = segment.imageOffset.split(',');
                if (offsets.length === 1 && offsets[0]) {
                  var offsetY = parseFloat(offsets[0]);
                  if (Number.isInteger(offsetY)) position.y += offsetY;
                } else if (offsets.length === 2) {
                  var offsetX = parseFloat(offsets[0]);
                  var _offsetY = parseFloat(offsets[1]);
                  if (Number.isInteger(offsetX)) position.x += offsetX;
                  if (Number.isInteger(_offsetY)) position.y += _offsetY;
                }
              }
              segment.node.position = position;
            }
            var outline = segment.node.getComponent(LabelOutline);
            if (outline) {
              var _position = segment.node.position.clone();
              _position.y -= outline.width;
              segment.node.position = _position;
            }
          }
        };
        _proto._convertLiteralColorValue = function _convertLiteralColorValue(color) {
          var colorValue = color.toUpperCase();
          if (Color$1[colorValue]) {
            var colorUse = Color$1[colorValue];
            return colorUse;
          } else {
            var out = new Color$1();
            return out.fromHEX(color);
          }
        };
        _proto._applyTextAttribute = function _applyTextAttribute(labelSeg) {
          var label = labelSeg.node.getComponent(Label);
          if (!label) {
            return;
          }
          this._resetLabelState(label);
          var index = labelSeg.styleIndex;
          var textStyle;
          if (this._textArray[index]) {
            textStyle = this._textArray[index].style;
          }
          if (textStyle) {
            if (textStyle.color) {
              label.color = this._convertLiteralColorValue(textStyle.color);
            } else {
              label.color = this._fontColor;
            }
            label.isBold = !!textStyle.bold;
            label.isItalic = !!textStyle.italic;
            label.isUnderline = !!textStyle.underline;
            if (textStyle.outline) {
              var labelOutline = labelSeg.node.getComponent(LabelOutline);
              if (!labelOutline) {
                labelOutline = labelSeg.node.addComponent(LabelOutline);
              }
              labelOutline.color = this._convertLiteralColorValue(textStyle.outline.color);
              labelOutline.width = textStyle.outline.width;
            }
            label.fontSize = textStyle.size || this._fontSize;
            labelSeg.clickHandler = '';
            labelSeg.clickParam = '';
            var event = textStyle.event;
            if (event) {
              labelSeg.clickHandler = event.click || '';
              labelSeg.clickParam = event.param || '';
            }
          }
          label.cacheMode = this._cacheMode;
          var isAsset = this._font instanceof Font;
          if (isAsset && !this._isSystemFontUsed) {
            label.font = this._font;
          } else {
            label.fontFamily = this._fontFamily;
          }
          label.useSystemFont = this._isSystemFontUsed;
          label.lineHeight = this._lineHeight;
          label.updateRenderData(true);
        };
        _proto._applyLayer = function _applyLayer() {
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._segments), _step3; !(_step3 = _iterator3()).done;) {
            var seg = _step3.value;
            seg.node.layer = this.node.layer;
          }
        };
        _proto._resetLabelState = function _resetLabelState(label) {
          label.fontSize = this._fontSize;
          label.color = this._fontColor;
          label.isBold = false;
          label.isItalic = false;
          label.isUnderline = false;
        };
        _createClass(RichText, [{
          key: "string",
          get: function get() {
            return this._string;
          },
          set: function set(value) {
            if (this._string === value) {
              return;
            }
            this._string = value;
            this._updateRichTextStatus();
          }
        }, {
          key: "horizontalAlign",
          get: function get() {
            return this._horizontalAlign;
          },
          set: function set(value) {
            if (this.horizontalAlign === value) {
              return;
            }
            this._horizontalAlign = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "verticalAlign",
          get: function get() {
            return this._verticalAlign;
          },
          set: function set(value) {
            if (this._verticalAlign === value) {
              return;
            }
            this._verticalAlign = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "fontSize",
          get: function get() {
            return this._fontSize;
          },
          set: function set(value) {
            if (this._fontSize === value) {
              return;
            }
            this._fontSize = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "fontColor",
          get: function get() {
            return this._fontColor;
          },
          set: function set(value) {
            if (this._fontColor === value) {
              return;
            }
            this._fontColor = value;
            this._updateTextDefaultColor();
          }
        }, {
          key: "fontFamily",
          get: function get() {
            return this._fontFamily;
          },
          set: function set(value) {
            if (this._fontFamily === value) return;
            this._fontFamily = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "font",
          get: function get() {
            return this._font;
          },
          set: function set(value) {
            if (this._font === value) {
              return;
            }
            this._font = value;
            this._layoutDirty = true;
            if (this._font) {
              this.useSystemFont = false;
              this._onTTFLoaded();
            } else {
              this.useSystemFont = true;
            }
            this._updateRichTextStatus();
          }
        }, {
          key: "useSystemFont",
          get: function get() {
            return this._isSystemFontUsed;
          },
          set: function set(value) {
            if (this._isSystemFontUsed === value) {
              return;
            }
            this._isSystemFontUsed = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "cacheMode",
          get: function get() {
            return this._cacheMode;
          },
          set: function set(value) {
            if (this._cacheMode === value) {
              return;
            }
            this._cacheMode = value;
            this._updateRichTextStatus();
          }
        }, {
          key: "maxWidth",
          get: function get() {
            return this._maxWidth;
          },
          set: function set(value) {
            if (this._maxWidth === value) {
              return;
            }
            this._maxWidth = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "lineHeight",
          get: function get() {
            return this._lineHeight;
          },
          set: function set(value) {
            if (this._lineHeight === value) {
              return;
            }
            this._lineHeight = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "imageAtlas",
          get: function get() {
            return this._imageAtlas;
          },
          set: function set(value) {
            if (this._imageAtlas === value) {
              return;
            }
            this._imageAtlas = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "handleTouchEvent",
          get: function get() {
            return this._handleTouchEvent;
          },
          set: function set(value) {
            if (this._handleTouchEvent === value) {
              return;
            }
            this._handleTouchEvent = value;
            if (this.enabledInHierarchy) {
              if (this.handleTouchEvent) {
                this._addEventListeners();
              } else {
                this._removeEventListeners();
              }
            }
          }
        }]);
        return RichText;
      }(Component), _class3$D.HorizontalAlign = HorizontalTextAlignment, _class3$D.VerticalAlign = VerticalTextAlignment, _class3$D), (_applyDecoratedDescriptor(_class2$2p.prototype, "horizontalAlign", [_dec3$1u], Object.getOwnPropertyDescriptor(_class2$2p.prototype, "horizontalAlign"), _class2$2p.prototype), _applyDecoratedDescriptor(_class2$2p.prototype, "verticalAlign", [_dec4$15], Object.getOwnPropertyDescriptor(_class2$2p.prototype, "verticalAlign"), _class2$2p.prototype), _applyDecoratedDescriptor(_class2$2p.prototype, "fontColor", [_dec5$$], Object.getOwnPropertyDescriptor(_class2$2p.prototype, "fontColor"), _class2$2p.prototype), _applyDecoratedDescriptor(_class2$2p.prototype, "font", [_dec6$L], Object.getOwnPropertyDescriptor(_class2$2p.prototype, "font"), _class2$2p.prototype), _applyDecoratedDescriptor(_class2$2p.prototype, "cacheMode", [_dec7$A], Object.getOwnPropertyDescriptor(_class2$2p.prototype, "cacheMode"), _class2$2p.prototype), _applyDecoratedDescriptor(_class2$2p.prototype, "imageAtlas", [_dec8$q], Object.getOwnPropertyDescriptor(_class2$2p.prototype, "imageAtlas"), _class2$2p.prototype), _initializer$2g = applyDecoratedInitializer(_class2$2p.prototype, "_lineHeight", [serializable$p], function () {
        return 40;
      }), _initializer2$1V = applyDecoratedInitializer(_class2$2p.prototype, "_string", [serializable$p], function () {
        return '<color=#00ff00>Rich</color><color=#0fffff>Text</color>';
      }), _initializer3$1o = applyDecoratedInitializer(_class2$2p.prototype, "_horizontalAlign", [serializable$p], function () {
        return HorizontalTextAlignment.LEFT;
      }), _initializer4$1c = applyDecoratedInitializer(_class2$2p.prototype, "_verticalAlign", [serializable$p], function () {
        return VerticalTextAlignment.TOP;
      }), _initializer5$Y = applyDecoratedInitializer(_class2$2p.prototype, "_fontSize", [serializable$p], function () {
        return 40;
      }), _initializer6$N = applyDecoratedInitializer(_class2$2p.prototype, "_fontColor", [serializable$p], function () {
        return Color$1.WHITE.clone();
      }), _initializer7$D = applyDecoratedInitializer(_class2$2p.prototype, "_maxWidth", [serializable$p], function () {
        return 0;
      }), _initializer8$z = applyDecoratedInitializer(_class2$2p.prototype, "_fontFamily", [serializable$p], function () {
        return 'Arial';
      }), _initializer9$u = applyDecoratedInitializer(_class2$2p.prototype, "_font", [serializable$p], function () {
        return null;
      }), _initializer10$r = applyDecoratedInitializer(_class2$2p.prototype, "_isSystemFontUsed", [serializable$p], function () {
        return true;
      }), _initializer11$q = applyDecoratedInitializer(_class2$2p.prototype, "_userDefinedFont", [serializable$p], function () {
        return null;
      }), _initializer12$n = applyDecoratedInitializer(_class2$2p.prototype, "_cacheMode", [serializable$p], function () {
        return CacheMode.NONE;
      }), _initializer13$k = applyDecoratedInitializer(_class2$2p.prototype, "_imageAtlas", [serializable$p], function () {
        return null;
      }), _initializer14$g = applyDecoratedInitializer(_class2$2p.prototype, "_handleTouchEvent", [serializable$p], function () {
        return true;
      })), _class2$2p)) || _class$2F) || _class$2F));
      legacyCC.RichText = RichText;

      var _dec$2G, _dec2$23, _class$2E;
      var UIMeshRenderer = exports('k', (_dec$2G = ccclass$M('cc.UIMeshRenderer'), _dec2$23 = executionOrder$1(110), _dec$2G(_class$2E = _dec2$23(_class$2E = function (_Component) {
        _inheritsLoose(UIMeshRenderer, _Component);
        function UIMeshRenderer() {
          var _this;
          _this = _Component.call(this) || this;
          _this._modelComponent = null;
          _this._dirtyVersion = -1;
          _this._internalId = -1;
          _this.stencilStage = Stage.DISABLED;
          _this._renderData = null;
          _this._renderEntity = new RenderEntity(RenderEntityType.DYNAMIC);
          return _this;
        }
        var _proto = UIMeshRenderer.prototype;
        _proto.__preload = function __preload() {
          this.node._uiProps.uiComp = this;
        };
        _proto.onEnable = function onEnable() {
          uiRendererManager.addRenderer(this);
          this.markForUpdateRenderData();
        };
        _proto.onDisable = function onDisable() {
          uiRendererManager.removeRenderer(this);
          this.renderEntity.enabled = this._canRender();
        };
        _proto.onLoad = function onLoad() {
          if (!this.node._uiProps.uiTransformComp) {
            this.node.addComponent('cc.UITransform');
          }
          this._modelComponent = this.getComponent('cc.ModelRenderer');
          if (!this._modelComponent) {
            warn("node '" + (this.node && this.node.name) + "' doesn't have any renderable component");
            return;
          }
          this.renderEntity.setNode(this.node);
        };
        _proto.onDestroy = function onDestroy() {
          this.renderEntity.setNode(null);
          if (this.node._uiProps.uiComp === this) {
            this.node._uiProps.uiComp = null;
          }
          this._modelComponent = this.getComponent('cc.ModelRenderer');
          if (!this._modelComponent) {
            return;
          }
          this._modelComponent._sceneGetter = null;
        };
        _proto._render = function _render(render) {
          if (this._modelComponent) {
            var models = this._modelComponent._collectModels();
            this._modelComponent._detachFromScene();
            for (var i = 0; i < models.length; i++) {
              if (models[i].enabled) {
                render.commitModel(this, models[i], this._modelComponent.material);
              }
            }
            return true;
          }
          return false;
        };
        _proto.fillBuffers = function fillBuffers(render) {
          if (this.enabled) {
            this._render(render);
          }
        };
        _proto.updateRenderer = function updateRenderer() {
        };
        _proto._uploadRenderData = function _uploadRenderData(index) {
        };
        _proto.postUpdateAssembler = function postUpdateAssembler(render) {};
        _proto.update = function update() {
          this._fitUIRenderQueue();
        };
        _proto._fitUIRenderQueue = function _fitUIRenderQueue() {
          if (!this._modelComponent) {
            return;
          }
          var matNum = this._modelComponent.sharedMaterials.length;
          for (var i = 0; i < matNum; i++) {
            var material = this._modelComponent.getMaterialInstance(i);
            if (material == null) {
              continue;
            }
            var passes = material.passes;
            var passNum = passes.length;
            for (var j = 0; j < passNum; j++) {
              var pass = passes[j];
              pass.setPriority(RenderPriority.MAX - 11);
              material.recompileShaders({
                CC_FORCE_FORWARD_SHADING: true
              }, j);
            }
          }
        };
        _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
          uiRendererManager.markDirtyRenderer(this);
        };
        _proto.setNodeDirty = function setNodeDirty() {};
        _proto.setTextureDirty = function setTextureDirty() {};
        _proto._canRender = function _canRender() {
          return this.enabled && this._modelComponent !== null;
        };
        _createClass(UIMeshRenderer, [{
          key: "modelComponent",
          get: function get() {
            return this._modelComponent;
          }
        }, {
          key: "renderEntity",
          get: function get() {
            {
              assert(Boolean(this._renderEntity), 'this._renderEntity should not be invalid');
            }
            return this._renderEntity;
          }
        }, {
          key: "renderData",
          get: function get() {
            return this._renderData;
          }
        }]);
        return UIMeshRenderer;
      }(Component)) || _class$2E) || _class$2E));
      legacyCC.UIMeshRenderer = UIMeshRenderer;

      var UI_VIS_FLAG = Layers.Enum.NONE | Layers.Enum.UI_3D;
      var DrawBatch2D = function () {
        function DrawBatch2D() {
          this.model = null;
          this.texture = null;
          this.sampler = null;
          this.useLocalData = null;
          this.isStatic = false;
          this.textureHash = 0;
          this.samplerHash = 0;
          this._passes = [];
          this._shaders = [];
          this._visFlags = UI_VIS_FLAG;
          this._inputAssembler = null;
          this._descriptorSet = null;
        }
        var _proto = DrawBatch2D.prototype;
        _proto.destroy = function destroy(ui) {
          this._passes = [];
        };
        _proto.clear = function clear() {
          this._inputAssembler = null;
          this._descriptorSet = null;
          this.texture = null;
          this.sampler = null;
          this.textureHash = 0;
          this.samplerHash = 0;
          this.model = null;
          this.isStatic = false;
          this.useLocalData = null;
          this.visFlags = UI_VIS_FLAG;
        };
        _proto.fillPasses = function fillPasses(mat, dss, dssHash, patches) {
          if (mat) {
            var passes = mat.passes;
            if (!passes) {
              return;
            }
            this._shaders.length = passes.length;
            for (var i = 0; i < passes.length; i++) {
              if (!this._passes[i]) {
                this._passes[i] = new Pass(legacyCC.director.root);
              }
              var mtlPass = passes[i];
              var passInUse = this._passes[i];
              mtlPass.update();
              if (!dss) {
                dss = mtlPass.depthStencilState;
                dssHash = 0;
              }
              passInUse._initPassFromTarget(mtlPass, dss, dssHash);
              this._shaders[i] = passInUse.getShaderVariant(patches);
            }
          }
        };
        _createClass(DrawBatch2D, [{
          key: "inputAssembler",
          get: function get() {
            return this._inputAssembler;
          },
          set: function set(ia) {
            this._inputAssembler = ia;
          }
        }, {
          key: "descriptorSet",
          get: function get() {
            return this._descriptorSet;
          },
          set: function set(ds) {
            this._descriptorSet = ds;
          }
        }, {
          key: "visFlags",
          get: function get() {
            return this._visFlags;
          },
          set: function set(vis) {
            this._visFlags = vis;
          }
        }, {
          key: "passes",
          get: function get() {
            return this._passes;
          }
        }, {
          key: "shaders",
          get: function get() {
            return this._shaders;
          }
        }]);
        return DrawBatch2D;
      }();

      var _dec$2F, _dec2$22, _class$2D, _class2$2o;
      var UIStaticBatch = exports('n', (_dec$2F = ccclass$M('cc.UIStaticBatch'), _dec2$22 = executionOrder$1(110), _dec$2F(_class$2D = _dec2$22(_class$2D = (_class2$2o = function (_UIRenderer) {
        _inheritsLoose(UIStaticBatch, _UIRenderer);
        function UIStaticBatch() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _UIRenderer.call.apply(_UIRenderer, [this].concat(args)) || this;
          _this._init = false;
          _this._bufferAccessor = null;
          _this._dirty = true;
          _this._uiDrawBatchList = [];
          return _this;
        }
        var _proto = UIStaticBatch.prototype;
        _proto.postUpdateAssembler = function postUpdateAssembler(render) {};
        _proto.markAsDirty = function markAsDirty() {};
        _proto._requireDrawBatch = function _requireDrawBatch() {
          var batch = new DrawBatch2D();
          batch.isStatic = true;
          this._uiDrawBatchList.push(batch);
          return batch;
        };
        _proto._clearData = function _clearData() {
          if (this._bufferAccessor) {
            this._bufferAccessor.reset();
            var ui = this._getBatcher();
            for (var i = 0; i < this._uiDrawBatchList.length; i++) {
              var element = this._uiDrawBatchList[i];
              element.destroy(ui);
            }
          }
          this._uiDrawBatchList.length = 0;
          this._init = false;
        };
        _proto._getBatcher = function _getBatcher() {
          if (director.root && director.root.batcher2D) {
            return director.root.batcher2D;
          }
          warnID(9301);
          return null;
        };
        _createClass(UIStaticBatch, [{
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(value) {
            if (this._color === value) {
              return;
            }
            this._color.set(value);
          }
        }, {
          key: "drawBatchList",
          get: function get() {
            return this._uiDrawBatchList;
          }
        }]);
        return UIStaticBatch;
      }(UIRenderer), (_applyDecoratedDescriptor(_class2$2o.prototype, "color", [override$1], Object.getOwnPropertyDescriptor(_class2$2o.prototype, "color"), _class2$2o.prototype)), _class2$2o)) || _class$2D) || _class$2D));

      var _dec$2E, _dec2$21, _dec3$1t, _class$2C;
      var LabelShadow = exports('o', (_dec$2E = ccclass$M('cc.LabelShadow'), _dec2$21 = executionOrder$1(110), _dec3$1t = requireComponent(Label), _dec$2E(_class$2C = _dec2$21(_class$2C = _dec3$1t(_class$2C = function (_Component) {
        _inheritsLoose(LabelShadow, _Component);
        function LabelShadow() {
          return _Component.apply(this, arguments) || this;
        }
        var _proto = LabelShadow.prototype;
        _proto.onEnable = function onEnable() {
          var label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.enableShadow = true;
        };
        _proto.onDisable = function onDisable() {
          var label = this.node.getComponent(Label);
          assertIsTrue(label);
          label.enableShadow = false;
        };
        _createClass(LabelShadow, [{
          key: "color",
          get: function get() {
            var label = this.node.getComponent(Label);
            assertIsTrue(label);
            return label.shadowColor;
          },
          set: function set(value) {
            var label = this.node.getComponent(Label);
            assertIsTrue(label);
            label.shadowColor = value;
          }
        }, {
          key: "offset",
          get: function get() {
            var label = this.node.getComponent(Label);
            assertIsTrue(label);
            return label.shadowOffset;
          },
          set: function set(value) {
            var label = this.node.getComponent(Label);
            assertIsTrue(label);
            label.shadowOffset = value;
          }
        }, {
          key: "blur",
          get: function get() {
            var label = this.node.getComponent(Label);
            assertIsTrue(label);
            return label.shadowBlur;
          },
          set: function set(value) {
            var label = this.node.getComponent(Label);
            assertIsTrue(label);
            label.shadowBlur = value;
          }
        }]);
        return LabelShadow;
      }(Component)) || _class$2C) || _class$2C) || _class$2C));

      var _dec$2D, _dec2$20, _class$2B, _class2$2n, _initializer$2f;
      var UIOpacity = exports('p', (_dec$2D = ccclass$M('cc.UIOpacity'), _dec2$20 = executionOrder$1(110), _dec$2D(_class$2B = _dec2$20(_class$2B = disallowMultiple$1(_class$2B = (_class2$2n = function (_Component) {
        _inheritsLoose(UIOpacity, _Component);
        function UIOpacity() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._setByParent = false;
          _this._opacity = _initializer$2f && _initializer$2f();
          return _this;
        }
        var _proto = UIOpacity.prototype;
        _proto.setEntityLocalOpacityDirtyRecursively = function setEntityLocalOpacityDirtyRecursively(dirty) {
        };
        UIOpacity.setEntityLocalOpacityDirtyRecursively = function setEntityLocalOpacityDirtyRecursively(node, dirty, interruptParentOpacity, setByParent) {
          if (!node.isValid) {
            return;
          }
          var render = node._uiProps.uiComp;
          var uiOp = node.getComponent(UIOpacity);
          var interruptOpacity = interruptParentOpacity;
          if (render && render.color) {
            render.renderEntity.colorDirty = dirty;
            if (uiOp) {
              render.renderEntity.localOpacity = interruptOpacity * uiOp.opacity / 255;
              uiOp._setByParent = setByParent;
            } else {
              render.renderEntity.localOpacity = interruptOpacity;
            }
            render.node._uiProps.localOpacity = render.renderEntity.localOpacity;
            interruptOpacity = 1;
          } else if (uiOp) {
            interruptOpacity = interruptOpacity * uiOp.opacity / 255;
            uiOp._setByParent = setByParent;
          }
          for (var i = 0; i < node.children.length; i++) {
            UIOpacity.setEntityLocalOpacityDirtyRecursively(node.children[i], dirty || interruptOpacity < 1, interruptOpacity, true);
          }
        };
        _proto.onEnable = function onEnable() {
          if (this._setByParent) {
            return;
          }
          this.node._uiProps.localOpacity = this._opacity / 255;
          this.setEntityLocalOpacityDirtyRecursively(true);
        };
        _proto.onDisable = function onDisable() {
          if (this._setByParent) {
            return;
          }
          this.node._uiProps.localOpacity = 1;
          this.setEntityLocalOpacityDirtyRecursively(true);
        };
        _createClass(UIOpacity, [{
          key: "opacity",
          get: function get() {
            return this._opacity;
          },
          set: function set(value) {
            if (this._opacity === value) {
              return;
            }
            value = clampf(value, 0, 255);
            this._opacity = value;
            this.node._uiProps.localOpacity = value / 255;
            this.setEntityLocalOpacityDirtyRecursively(true);
          }
        }]);
        return UIOpacity;
      }(Component), (_initializer$2f = applyDecoratedInitializer(_class2$2n.prototype, "_opacity", [serializable$p], function () {
        return 255;
      })), _class2$2n)) || _class$2B) || _class$2B) || _class$2B));

      legacyCC.MaskComponent = Mask;
      setClassAlias(Mask, 'cc.MaskComponent');
      legacyCC.LabelComponent = Label;
      setClassAlias(Label, 'cc.LabelComponent');
      legacyCC.LabelOutlineComponent = LabelOutline;
      setClassAlias(LabelOutline, 'cc.LabelOutlineComponent');
      legacyCC.RichTextComponent = RichText;
      setClassAlias(RichText, 'cc.RichTextComponent');
      legacyCC.SpriteComponent = Sprite;
      setClassAlias(Sprite, 'cc.SpriteComponent');
      legacyCC.UIModelComponent = UIMeshRenderer;
      setClassAlias(UIMeshRenderer, 'cc.UIModelComponent');
      legacyCC.GraphicsComponent = Graphics;
      setClassAlias(Graphics, 'cc.GraphicsComponent');
      setClassAlias(UIStaticBatch, 'cc.UIStaticBatchComponent');
      setClassAlias(UIOpacity, 'cc.UIOpacityComponent');
      replaceProperty(Mask.prototype, 'Mask', [{
        name: 'graphics',
        newName: 'subComp',
        target: Mask.prototype,
        targetName: 'Mask'
      }]);
      replaceProperty(MaskType, 'MaskType', [{
        name: 'RECT',
        newName: 'GRAPHICS_RECT',
        target: MaskType,
        targetName: 'MaskType'
      }, {
        name: 'ELLIPSE',
        newName: 'GRAPHICS_ELLIPSE',
        target: MaskType,
        targetName: 'MaskType'
      }, {
        name: 'IMAGE_STENCIL',
        newName: 'SPRITE_STENCIL',
        target: MaskType,
        targetName: 'MaskType'
      }]);
      markAsWarning(LabelOutline.prototype, 'LabelOutline', [{
        name: 'width',
        suggest: 'Please use Label.outlineWidth instead.'
      }, {
        name: 'color',
        suggest: 'Please use Label.outlineColor instead.'
      }]);
      markAsWarning(LabelShadow.prototype, 'LabelShadow', [{
        name: 'color',
        suggest: 'Please use Label.shadowColor instead.'
      }, {
        name: 'offset',
        suggest: 'Please use Label.shadowOffset instead.'
      }, {
        name: 'blur',
        suggest: 'Please use Label.shadowBlur instead.'
      }]);

      var Aim = function Aim(i, x, y) {
        this.i = void 0;
        this.x = void 0;
        this.y = void 0;
        this.prev = null;
        this.next = null;
        this.z = null;
        this.prevZ = null;
        this.nextZ = null;
        this.steiner = false;
        this.i = i;
        this.x = x;
        this.y = y;
      };
      function linkedList(datas, start, end, dim, clockwise) {
        var i = 0;
        var last = null;
        if (clockwise === signedArea(datas, start, end, dim) > 0) {
          for (i = start; i < end; i += dim) {
            last = insertNode(i, datas[i], datas[i + 1], last);
          }
        } else {
          for (i = end - dim; i >= start; i -= dim) {
            last = insertNode(i, datas[i], datas[i + 1], last);
          }
        }
        if (last && equals$1(last, last.next)) {
          removeNode(last);
          last = last.next;
        }
        return last;
      }
      function filterPoints(start, end) {
        if (end === void 0) {
          end = null;
        }
        if (!start) {
          return start;
        }
        if (!end) {
          end = start;
        }
        var p = start;
        var again = false;
        do {
          again = false;
          if (!p.steiner && (equals$1(p, p.next) || area$1(p.prev, p, p.next) === 0)) {
            removeNode(p);
            p = end = p.prev;
            if (p === p.next) {
              return null;
            }
            again = true;
          } else {
            p = p.next;
          }
        } while (again || p !== end);
        return end;
      }
      function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
        if (pass === void 0) {
          pass = 0;
        }
        if (!ear) {
          return;
        }
        if (!pass && size) {
          indexCurve(ear, minX, minY, size);
        }
        var stop = ear;
        var prev = null;
        var next = null;
        while (ear.prev !== ear.next) {
          prev = ear.prev;
          next = ear.next;
          if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
            triangles.push(prev.i / dim);
            triangles.push(ear.i / dim);
            triangles.push(next.i / dim);
            removeNode(ear);
            ear = next.next;
            stop = next.next;
            continue;
          }
          ear = next;
          if (ear === stop) {
            if (!pass) {
              earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
            } else if (pass === 1) {
              ear = cureLocalIntersections(ear, triangles, dim);
              earcutLinked(ear, triangles, dim, minX, minY, size, 2);
            } else if (pass === 2) {
              splitEarcut(ear, triangles, dim, minX, minY, size);
            }
            break;
          }
        }
      }
      function isEar(ear) {
        var a = ear.prev;
        var b = ear;
        var c = ear.next;
        if (area$1(a, b, c) >= 0) {
          return false;
        }
        var p = ear.next.next;
        while (p !== ear.prev) {
          if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area$1(p.prev, p, p.next) >= 0) {
            return false;
          }
          p = p.next;
        }
        return true;
      }
      function isEarHashed(ear, minX, minY, size) {
        var a = ear.prev;
        var b = ear;
        var c = ear.next;
        if (area$1(a, b, c) >= 0) {
          return false;
        }
        var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x;
        var minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y;
        var maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x;
        var maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y;
        var minZ = zOrder(minTX, minTY, minX, minY, size);
        var maxZ = zOrder(maxTX, maxTY, minX, minY, size);
        var p = ear.nextZ;
        while (p && p.z <= maxZ) {
          if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area$1(p.prev, p, p.next) >= 0) {
            return false;
          }
          p = p.nextZ;
        }
        p = ear.prevZ;
        while (p && p.z >= minZ) {
          if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area$1(p.prev, p, p.next) >= 0) {
            return false;
          }
          p = p.prevZ;
        }
        return true;
      }
      function cureLocalIntersections(start, triangles, dim) {
        var p = start;
        do {
          var a = p.prev;
          var b = p.next.next;
          if (!equals$1(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
            triangles.push(a.i / dim);
            triangles.push(p.i / dim);
            triangles.push(b.i / dim);
            removeNode(p);
            removeNode(p.next);
            p = start = b;
          }
          p = p.next;
        } while (p !== start);
        return p;
      }
      function splitEarcut(start, triangles, dim, minX, minY, size) {
        var a = start;
        do {
          var b = a.next.next;
          while (b !== a.prev) {
            if (a.i !== b.i && isValidDiagonal(a, b)) {
              var c = splitPolygon(a, b);
              a = filterPoints(a, a.next);
              c = filterPoints(c, c.next);
              earcutLinked(a, triangles, dim, minX, minY, size);
              earcutLinked(c, triangles, dim, minX, minY, size);
              return;
            }
            b = b.next;
          }
          a = a.next;
        } while (a !== start);
      }
      function eliminateHoles(datas, holeIndices, outerNode, dim) {
        var queue = [];
        var i = 0;
        var len = 0;
        var start = 0;
        var end = 0;
        var list = null;
        for (i = 0, len = holeIndices.length; i < len; i++) {
          start = holeIndices[i] * dim;
          end = i < len - 1 ? holeIndices[i + 1] * dim : datas.length;
          list = linkedList(datas, start, end, dim, false);
          if (!list) {
            continue;
          }
          if (list === list.next) {
            list.steiner = true;
          }
          queue.push(getLeftmost(list));
        }
        queue.sort(compareX);
        if (!outerNode) {
          return outerNode;
        }
        for (i = 0; i < queue.length; i++) {
          eliminateHole(queue[i], outerNode);
          outerNode = filterPoints(outerNode, outerNode.next);
        }
        return outerNode;
      }
      function compareX(a, b) {
        return a.x - b.x;
      }
      function eliminateHole(hole, outerNode) {
        outerNode = findHoleBridge(hole, outerNode);
        if (outerNode) {
          var b = splitPolygon(outerNode, hole);
          filterPoints(b, b.next);
        }
      }
      function findHoleBridge(hole, outerNode) {
        var p = outerNode;
        var hx = hole.x;
        var hy = hole.y;
        var qx = -Infinity;
        var m = null;
        do {
          if (hy <= p.y && hy >= p.next.y) {
            var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
            if (x <= hx && x > qx) {
              qx = x;
              if (x === hx) {
                if (hy === p.y) {
                  return p;
                }
                if (hy === p.next.y) {
                  return p.next;
                }
              }
              m = p.x < p.next.x ? p : p.next;
            }
          }
          p = p.next;
        } while (p !== outerNode);
        if (!m) {
          return null;
        }
        if (hx === qx) {
          return m.prev;
        }
        var stop = m;
        var mx = m.x;
        var my = m.y;
        var tanMin = Infinity;
        var tan;
        p = m.next;
        while (p !== stop) {
          if (hx >= p.x && p.x >= mx && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
            tan = Math.abs(hy - p.y) / (hx - p.x);
            if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
              m = p;
              tanMin = tan;
            }
          }
          p = p.next;
        }
        return m;
      }
      function indexCurve(start, minX, minY, size) {
        var p = start;
        do {
          if (p.z === null) {
            p.z = zOrder(p.x, p.y, minX, minY, size);
          }
          p.prevZ = p.prev;
          p.nextZ = p.next;
          p = p.next;
        } while (p !== start);
        p.prevZ.nextZ = null;
        p.prevZ = null;
        sortLinked(p);
      }
      function sortLinked(list) {
        var i = 0;
        var p = null;
        var q = null;
        var e = null;
        var tail = null;
        var numMerges = 0;
        var pSize = 0;
        var qSize = 0;
        var inSize = 1;
        do {
          p = list;
          list = null;
          tail = null;
          numMerges = 0;
          while (p) {
            numMerges++;
            q = p;
            pSize = 0;
            for (i = 0; i < inSize; i++) {
              pSize++;
              q = q.nextZ;
              if (!q) {
                break;
              }
            }
            qSize = inSize;
            while (pSize > 0 || qSize > 0 && q) {
              if (pSize === 0) {
                e = q;
                q = q.nextZ;
                qSize--;
              } else if (qSize === 0 || !q) {
                e = p;
                p = p.nextZ;
                pSize--;
              } else if (p.z <= q.z) {
                e = p;
                p = p.nextZ;
                pSize--;
              } else {
                e = q;
                q = q.nextZ;
                qSize--;
              }
              if (tail) {
                tail.nextZ = e;
              } else {
                list = e;
              }
              e.prevZ = tail;
              tail = e;
            }
            p = q;
          }
          tail.nextZ = null;
          inSize *= 2;
        } while (numMerges > 1);
        return list;
      }
      function zOrder(x, y, minX, minY, size) {
        x = 32767 * (x - minX) / size;
        y = 32767 * (y - minY) / size;
        x = (x | x << 8) & 0x00FF00FF;
        x = (x | x << 4) & 0x0F0F0F0F;
        x = (x | x << 2) & 0x33333333;
        x = (x | x << 1) & 0x55555555;
        y = (y | y << 8) & 0x00FF00FF;
        y = (y | y << 4) & 0x0F0F0F0F;
        y = (y | y << 2) & 0x33333333;
        y = (y | y << 1) & 0x55555555;
        return x | y << 1;
      }
      function getLeftmost(start) {
        var p = start;
        var leftmost = start;
        do {
          if (p.x < leftmost.x) {
            leftmost = p;
          }
          p = p.next;
        } while (p !== start);
        return leftmost;
      }
      function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
        return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
      }
      function isValidDiagonal(a, b) {
        return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
      }
      function area$1(p, q, r) {
        return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
      }
      function equals$1(p1, p2) {
        return p1.x === p2.x && p1.y === p2.y;
      }
      function intersects(p1, q1, p2, q2) {
        if (equals$1(p1, q1) && equals$1(p2, q2) || equals$1(p1, q2) && equals$1(p2, q1)) {
          return true;
        }
        return area$1(p1, q1, p2) > 0 !== area$1(p1, q1, q2) > 0 && area$1(p2, q2, p1) > 0 !== area$1(p2, q2, q1) > 0;
      }
      function intersectsPolygon(a, b) {
        var p = a;
        do {
          if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) {
            return true;
          }
          p = p.next;
        } while (p !== a);
        return false;
      }
      function locallyInside(a, b) {
        return area$1(a.prev, a, a.next) < 0 ? area$1(a, b, a.next) >= 0 && area$1(a, a.prev, b) >= 0 : area$1(a, b, a.prev) < 0 || area$1(a, a.next, b) < 0;
      }
      function middleInside(a, b) {
        var p = a;
        var inside = false;
        var px = (a.x + b.x) / 2;
        var py = (a.y + b.y) / 2;
        do {
          if (p.y > py !== p.next.y > py && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) {
            inside = !inside;
          }
          p = p.next;
        } while (p !== a);
        return inside;
      }
      function splitPolygon(a, b) {
        var a2 = new Aim(a.i, a.x, a.y);
        var b2 = new Aim(b.i, b.x, b.y);
        var an = a.next;
        var bp = b.prev;
        a.next = b;
        b.prev = a;
        a2.next = an;
        an.prev = a2;
        b2.next = a2;
        a2.prev = b2;
        bp.next = b2;
        b2.prev = bp;
        return b2;
      }
      function insertNode(i, x, y, last) {
        var p = new Aim(i, x, y);
        if (!last) {
          p.prev = p;
          p.next = p;
        } else {
          p.next = last.next;
          p.prev = last;
          last.next.prev = p;
          last.next = p;
        }
        return p;
      }
      function removeNode(p) {
        p.next.prev = p.prev;
        p.prev.next = p.next;
        if (p.prevZ) {
          p.prevZ.nextZ = p.nextZ;
        }
        if (p.nextZ) {
          p.nextZ.prevZ = p.prevZ;
        }
      }
      function signedArea(datas, start, end, dim) {
        var sum = 0;
        for (var i = start, j = end - dim; i < end; i += dim) {
          sum += (datas[j] - datas[i]) * (datas[i + 1] + datas[j + 1]);
          j = i;
        }
        return sum;
      }
      function earcut(datas, holeIndices, dim) {
        dim = dim || 3;
        var hasHoles = holeIndices ? holeIndices.length : 0;
        var outerLen = hasHoles ? holeIndices[0] * dim : datas.length;
        var outerNode = linkedList(datas, 0, outerLen, dim, true);
        var triangles = [];
        if (!outerNode) {
          return triangles;
        }
        var minX = 0;
        var minY = 0;
        var maxX = 0;
        var maxY = 0;
        var x = 0;
        var y = 0;
        var size = 0;
        if (hasHoles) {
          outerNode = eliminateHoles(datas, holeIndices, outerNode, dim);
        }
        if (datas.length > 80 * dim) {
          minX = maxX = datas[0];
          minY = maxY = datas[1];
          for (var i = dim; i < outerLen; i += dim) {
            x = datas[i];
            y = datas[i + 1];
            if (x < minX) {
              minX = x;
            }
            if (y < minY) {
              minY = y;
            }
            if (x > maxX) {
              maxX = x;
            }
            if (y > maxY) {
              maxY = y;
            }
          }
          size = Math.max(maxX - minX, maxY - minY);
        }
        earcutLinked(outerNode, triangles, dim, minX, minY, size);
        return triangles;
      }

      var MAX_VERTEX = 65535;
      var MAX_INDICES = MAX_VERTEX * 2;
      var PI = Math.PI;
      var min = Math.min;
      var max = Math.max;
      var ceil = Math.ceil;
      var acos = Math.acos;
      var cos = Math.cos;
      var sin = Math.sin;
      var atan2 = Math.atan2;
      var attrBytes = 8;
      var _renderData$1 = null;
      var _impl = null;
      var _curColor = new Color$1();
      var vec3_temps$1 = [];
      for (var i$3 = 0; i$3 < 4; i$3++) {
        vec3_temps$1.push(new Vec3());
      }
      function curveDivs(r, arc, tol) {
        var da = acos(r / (r + tol)) * 2.0;
        return max(2, ceil(arc / da));
      }
      function clamp(v, minNum, maxNum) {
        if (v < minNum) {
          return minNum;
        } else if (v > maxNum) {
          return maxNum;
        }
        return v;
      }
      var graphicsAssembler = {
        useModel: true,
        updateRenderData: function updateRenderData(graphics) {
        },
        fillBuffers: function fillBuffers(graphics, renderer) {},
        renderIA: function renderIA(graphics, renderer) {},
        getRenderData: function getRenderData(graphics, vertexCount) {
          if (!_impl) {
            return null;
          }
          var renderDataList = _impl.getRenderDataList();
          var renderData = renderDataList[_impl.dataOffset];
          if (!renderData) {
            return null;
          }
          var meshBuffer = renderData;
          var maxVertexCount = meshBuffer ? meshBuffer.vertexStart + vertexCount : 0;
          if (maxVertexCount > MAX_VERTEX || maxVertexCount * 3 > MAX_INDICES) {
            ++_impl.dataOffset;
            if (_impl.dataOffset < renderDataList.length) {
              renderData = renderDataList[_impl.dataOffset];
            } else {
              renderData = _impl.requestRenderData();
              renderDataList[_impl.dataOffset] = renderData;
            }
            meshBuffer = renderData;
          }
          if (meshBuffer && meshBuffer.vertexCount < maxVertexCount) {
            meshBuffer.request(vertexCount, vertexCount * 3);
          }
          return renderData;
        },
        stroke: function stroke(graphics) {
          Color$1.copy(_curColor, graphics.strokeColor);
          if (!graphics.impl) {
            return;
          }
          this._flattenPaths(graphics.impl);
          this._expandStroke(graphics);
          graphics.impl.updatePathOffset = true;
          this.end(graphics);
        },
        fill: function fill(graphics) {
          Color$1.copy(_curColor, graphics.fillColor);
          this._expandFill(graphics);
          if (graphics.impl) {
            graphics.impl.updatePathOffset = true;
          }
          this.end(graphics);
        },
        end: function end(graphics) {
          graphics.markForUpdateRenderData();
        },
        _expandStroke: function _expandStroke(graphics) {
          var w = graphics.lineWidth * 0.5;
          var lineCap = graphics.lineCap;
          var lineJoin = graphics.lineJoin;
          var miterLimit = graphics.miterLimit;
          _impl = graphics.impl;
          if (!_impl) {
            return;
          }
          var nCap = curveDivs(w, PI, _impl.tessTol);
          this._calculateJoins(_impl, w, lineJoin, miterLimit);
          var paths = _impl.paths;
          var vertexCount = 0;
          for (var _i = _impl.pathOffset, l = _impl.pathLength; _i < l; _i++) {
            var path = paths[_i];
            var pointsLength = path.points.length;
            if (lineJoin === LineJoin.ROUND) {
              vertexCount += (pointsLength + path.bevel * (nCap + 2) + 1) * 2;
            } else {
              vertexCount += (pointsLength + path.bevel * 5 + 1) * 2;
            }
            if (!path.closed) {
              if (lineCap === LineCap.ROUND) {
                vertexCount += (nCap * 2 + 2) * 2;
              } else {
                vertexCount += (3 + 3) * 2;
              }
            }
          }
          var meshBuffer = _renderData$1 = this.getRenderData(graphics, vertexCount);
          if (!meshBuffer) {
            return;
          }
          var vData = meshBuffer.vData;
          var iData = meshBuffer.iData;
          for (var _i2 = _impl.pathOffset, _l = _impl.pathLength; _i2 < _l; _i2++) {
            var _path = paths[_i2];
            var pts = _path.points;
            var _pointsLength = pts.length;
            var offset = meshBuffer.vertexStart;
            var p0 = void 0;
            var p1 = void 0;
            var start = 0;
            var end = 0;
            var loop = _path.closed;
            if (loop) {
              p0 = pts[_pointsLength - 1];
              p1 = pts[0];
              start = 0;
              end = _pointsLength;
            } else {
              p0 = pts[0];
              p1 = pts[1];
              start = 1;
              end = _pointsLength - 1;
            }
            p1 = p1 || p0;
            if (!loop) {
              var dPos = new Point$2(p1.x, p1.y);
              dPos.subtract(p0);
              dPos.normalize();
              var dx = dPos.x;
              var dy = dPos.y;
              if (lineCap === LineCap.BUTT) {
                this._buttCapStart(p0, dx, dy, w, 0);
              } else if (lineCap === LineCap.SQUARE) {
                this._buttCapStart(p0, dx, dy, w, w);
              } else if (lineCap === LineCap.ROUND) {
                this._roundCapStart(p0, dx, dy, w, nCap);
              }
            }
            for (var j = start; j < end; ++j) {
              if (lineJoin === LineJoin.ROUND) {
                this._roundJoin(p0, p1, w, w, nCap);
              } else if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
                this._bevelJoin(p0, p1, w, w);
              } else {
                this._vSet(p1.x + p1.dmx * w, p1.y + p1.dmy * w, 1);
                this._vSet(p1.x - p1.dmx * w, p1.y - p1.dmy * w, -1);
              }
              p0 = p1;
              p1 = pts[j + 1];
            }
            if (loop) {
              var vDataOffset = offset * attrBytes;
              this._vSet(vData[vDataOffset], vData[vDataOffset + 1], 1);
              this._vSet(vData[vDataOffset + attrBytes], vData[vDataOffset + attrBytes + 1], -1);
            } else {
              var _dPos = new Point$2(p1.x, p1.y);
              _dPos.subtract(p0);
              _dPos.normalize();
              var _dx = _dPos.x;
              var _dy = _dPos.y;
              if (lineCap === LineCap.BUTT) {
                this._buttCapEnd(p1, _dx, _dy, w, 0);
              } else if (lineCap === LineCap.SQUARE) {
                this._buttCapEnd(p1, _dx, _dy, w, w);
              } else if (lineCap === LineCap.ROUND) {
                this._roundCapEnd(p1, _dx, _dy, w, nCap);
              }
            }
            var indicesOffset = meshBuffer.indexStart;
            for (var begin = offset + 2, over = meshBuffer.vertexStart; begin < over; begin++) {
              iData[indicesOffset++] = begin - 2;
              iData[indicesOffset++] = begin - 1;
              iData[indicesOffset++] = begin;
            }
            meshBuffer.indexStart = indicesOffset;
          }
          _renderData$1 = null;
          _impl = null;
        },
        _expandFill: function _expandFill(graphics) {
          _impl = graphics.impl;
          if (!_impl) {
            return;
          }
          var paths = _impl.paths;
          var vertexCount = 0;
          for (var _i3 = _impl.pathOffset, l = _impl.pathLength; _i3 < l; _i3++) {
            var path = paths[_i3];
            var pointsLength = path.points.length;
            vertexCount += pointsLength;
          }
          var renderData = _renderData$1 = this.getRenderData(graphics, vertexCount);
          if (!renderData) {
            return;
          }
          var meshBuffer = renderData;
          var vData = meshBuffer.vData;
          var iData = meshBuffer.iData;
          for (var _i4 = _impl.pathOffset, _l2 = _impl.pathLength; _i4 < _l2; _i4++) {
            var _path2 = paths[_i4];
            var pts = _path2.points;
            var _pointsLength2 = pts.length;
            if (_pointsLength2 === 0) {
              continue;
            }
            var vertexOffset = renderData.vertexStart;
            for (var j = 0; j < _pointsLength2; ++j) {
              this._vSet(pts[j].x, pts[j].y);
            }
            var indicesOffset = renderData.indexStart;
            if (_path2.complex) {
              var earcutData = [];
              for (var _j = vertexOffset, end = renderData.vertexStart; _j < end; _j++) {
                var vDataOffset = _j * attrBytes;
                earcutData.push(vData[vDataOffset++]);
                earcutData.push(vData[vDataOffset++]);
                earcutData.push(vData[vDataOffset++]);
              }
              var newIndices = earcut(earcutData, null, 3);
              if (!newIndices || newIndices.length === 0) {
                continue;
              }
              for (var _j2 = 0, nIndices = newIndices.length; _j2 < nIndices; _j2++) {
                iData[indicesOffset++] = newIndices[_j2] + vertexOffset;
              }
            } else {
              var first = vertexOffset;
              for (var start = vertexOffset + 2, _end = meshBuffer.vertexStart; start < _end; start++) {
                iData[indicesOffset++] = first;
                iData[indicesOffset++] = start - 1;
                iData[indicesOffset++] = start;
              }
            }
            meshBuffer.indexStart = indicesOffset;
          }
          _renderData$1 = null;
          _impl = null;
        },
        _calculateJoins: function _calculateJoins(impl, w, lineJoin, miterLimit) {
          var iw = 0.0;
          if (w > 0.0) {
            iw = 1 / w;
          }
          var paths = impl.paths;
          for (var _i5 = impl.pathOffset, l = impl.pathLength; _i5 < l; _i5++) {
            var path = paths[_i5];
            var pts = path.points;
            var ptsLength = pts.length;
            var p0 = pts[ptsLength - 1];
            var p1 = pts[0];
            path.bevel = 0;
            for (var j = 0; j < ptsLength; j++) {
              var dmr2 = 0;
              var cross = 0;
              var limit = 0;
              var dlx0 = p0.dy;
              var dly0 = -p0.dx;
              var dlx1 = p1.dy;
              var dly1 = -p1.dx;
              p1.dmx = (dlx0 + dlx1) * 0.5;
              p1.dmy = (dly0 + dly1) * 0.5;
              dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy;
              if (dmr2 > 0.000001) {
                var scale = 1 / dmr2;
                if (scale > 600) {
                  scale = 600;
                }
                p1.dmx *= scale;
                p1.dmy *= scale;
              }
              cross = p1.dx * p0.dy - p0.dx * p1.dy;
              if (cross > 0) {
                p1.flags |= PointFlags.PT_LEFT;
              }
              limit = max(11, min(p0.len, p1.len) * iw);
              if (dmr2 * limit * limit < 1) {
                p1.flags |= PointFlags.PT_INNERBEVEL;
              }
              if (p1.flags & PointFlags.PT_CORNER) {
                if (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) {
                  p1.flags |= PointFlags.PT_BEVEL;
                }
              }
              if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
                path.bevel++;
              }
              p0 = p1;
              p1 = pts[j + 1];
            }
          }
        },
        _flattenPaths: function _flattenPaths(impl) {
          var paths = impl.paths;
          for (var _i6 = impl.pathOffset, l = impl.pathLength; _i6 < l; _i6++) {
            var path = paths[_i6];
            var pts = path.points;
            var p0 = pts[pts.length - 1];
            var p1 = pts[0];
            if (pts.length > 2 && p0.equals(p1)) {
              path.closed = true;
              pts.pop();
              p0 = pts[pts.length - 1];
            }
            for (var j = 0, size = pts.length; j < size; j++) {
              var dPos = new Point$2(p1.x, p1.y);
              dPos.subtract(p0);
              p0.len = dPos.length();
              if (dPos.x || dPos.y) {
                dPos.normalize();
              }
              p0.dx = dPos.x;
              p0.dy = dPos.y;
              p0 = p1;
              p1 = pts[j + 1];
            }
          }
        },
        _chooseBevel: function _chooseBevel(bevel, p0, p1, w) {
          var x = p1.x;
          var y = p1.y;
          var x0 = 0;
          var y0 = 0;
          var x1 = 0;
          var y1 = 0;
          if (bevel !== 0) {
            x0 = x + p0.dy * w;
            y0 = y - p0.dx * w;
            x1 = x + p1.dy * w;
            y1 = y - p1.dx * w;
          } else {
            x0 = x1 = x + p1.dmx * w;
            y0 = y1 = y + p1.dmy * w;
          }
          return [x0, y0, x1, y1];
        },
        _buttCapStart: function _buttCapStart(p, dx, dy, w, d) {
          var px = p.x - dx * d;
          var py = p.y - dy * d;
          var dlx = dy;
          var dly = -dx;
          this._vSet(px + dlx * w, py + dly * w, 1);
          this._vSet(px - dlx * w, py - dly * w, -1);
        },
        _buttCapEnd: function _buttCapEnd(p, dx, dy, w, d) {
          var px = p.x + dx * d;
          var py = p.y + dy * d;
          var dlx = dy;
          var dly = -dx;
          this._vSet(px + dlx * w, py + dly * w, 1);
          this._vSet(px - dlx * w, py - dly * w, -1);
        },
        _roundCapStart: function _roundCapStart(p, dx, dy, w, nCap) {
          var px = p.x;
          var py = p.y;
          var dlx = dy;
          var dly = -dx;
          for (var _i7 = 0; _i7 < nCap; _i7++) {
            var a = _i7 / (nCap - 1) * PI;
            var ax = cos(a) * w;
            var ay = sin(a) * w;
            this._vSet(px - dlx * ax - dx * ay, py - dly * ax - dy * ay, 1);
            this._vSet(px, py, 0);
          }
          this._vSet(px + dlx * w, py + dly * w, 1);
          this._vSet(px - dlx * w, py - dly * w, -1);
        },
        _roundCapEnd: function _roundCapEnd(p, dx, dy, w, nCap) {
          var px = p.x;
          var py = p.y;
          var dlx = dy;
          var dly = -dx;
          this._vSet(px + dlx * w, py + dly * w, 1);
          this._vSet(px - dlx * w, py - dly * w, -1);
          for (var _i8 = 0; _i8 < nCap; _i8++) {
            var a = _i8 / (nCap - 1) * PI;
            var ax = cos(a) * w;
            var ay = sin(a) * w;
            this._vSet(px, py, 0);
            this._vSet(px - dlx * ax + dx * ay, py - dly * ax + dy * ay, 1);
          }
        },
        _roundJoin: function _roundJoin(p0, p1, lw, rw, nCap) {
          var dlx0 = p0.dy;
          var dly0 = -p0.dx;
          var dlx1 = p1.dy;
          var dly1 = -p1.dx;
          var p1x = p1.x;
          var p1y = p1.y;
          if ((p1.flags & PointFlags.PT_LEFT) !== 0) {
            var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);
            var lx0 = out[0];
            var ly0 = out[1];
            var lx1 = out[2];
            var ly1 = out[3];
            var a0 = atan2(-dly0, -dlx0);
            var a1 = atan2(-dly1, -dlx1);
            if (a1 > a0) {
              a1 -= PI * 2;
            }
            this._vSet(lx0, ly0, 1);
            this._vSet(p1x - dlx0 * rw, p1.y - dly0 * rw, -1);
            var n = clamp(ceil((a0 - a1) / PI) * nCap, 2, nCap);
            for (var _i9 = 0; _i9 < n; _i9++) {
              var u = _i9 / (n - 1);
              var a = a0 + u * (a1 - a0);
              var rx = p1x + cos(a) * rw;
              var ry = p1y + sin(a) * rw;
              this._vSet(p1x, p1y, 0);
              this._vSet(rx, ry, -1);
            }
            this._vSet(lx1, ly1, 1);
            this._vSet(p1x - dlx1 * rw, p1y - dly1 * rw, -1);
          } else {
            var _out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);
            var rx0 = _out[0];
            var ry0 = _out[1];
            var rx1 = _out[2];
            var ry1 = _out[3];
            var _a = atan2(dly0, dlx0);
            var _a2 = atan2(dly1, dlx1);
            if (_a2 < _a) {
              _a2 += PI * 2;
            }
            this._vSet(p1x + dlx0 * rw, p1y + dly0 * rw, 1);
            this._vSet(rx0, ry0, -1);
            var _n = clamp(ceil((_a2 - _a) / PI) * nCap, 2, nCap);
            for (var _i10 = 0; _i10 < _n; _i10++) {
              var _u = _i10 / (_n - 1);
              var _a3 = _a + _u * (_a2 - _a);
              var lx = p1x + cos(_a3) * lw;
              var ly = p1y + sin(_a3) * lw;
              this._vSet(lx, ly, 1);
              this._vSet(p1x, p1y, 0);
            }
            this._vSet(p1x + dlx1 * rw, p1y + dly1 * rw, 1);
            this._vSet(rx1, ry1, -1);
          }
        },
        _bevelJoin: function _bevelJoin(p0, p1, lw, rw) {
          var rx0 = 0;
          var ry0 = 0;
          var rx1 = 0;
          var ry1 = 0;
          var lx0 = 0;
          var ly0 = 0;
          var lx1 = 0;
          var ly1 = 0;
          var dlx0 = p0.dy;
          var dly0 = -p0.dx;
          var dlx1 = p1.dy;
          var dly1 = -p1.dx;
          if (p1.flags & PointFlags.PT_LEFT) {
            var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);
            lx0 = out[0];
            ly0 = out[1];
            lx1 = out[2];
            ly1 = out[3];
            this._vSet(lx0, ly0, 1);
            this._vSet(p1.x - dlx0 * rw, p1.y - dly0 * rw, -1);
            this._vSet(lx1, ly1, 1);
            this._vSet(p1.x - dlx1 * rw, p1.y - dly1 * rw, -1);
          } else {
            var _out2 = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);
            rx0 = _out2[0];
            ry0 = _out2[1];
            rx1 = _out2[2];
            ry1 = _out2[3];
            this._vSet(p1.x + dlx0 * lw, p1.y + dly0 * lw, 1);
            this._vSet(rx0, ry0, -1);
            this._vSet(p1.x + dlx1 * lw, p1.y + dly1 * lw, 1);
            this._vSet(rx1, ry1, -1);
          }
        },
        _vSet: function _vSet(x, y, distance) {
          if (distance === void 0) {
            distance = 0;
          }
          if (!_renderData$1) {
            return;
          }
          var meshBuffer = _renderData$1;
          var dataOffset = meshBuffer.vertexStart * attrBytes;
          var vData = meshBuffer.vData;
          vData[dataOffset++] = x;
          vData[dataOffset++] = y;
          vData[dataOffset++] = 0;
          Color$1.toArray(vData, _curColor, dataOffset);
          dataOffset += 4;
          vData[dataOffset++] = distance;
          meshBuffer.vertexStart++;
        }
      };

      var graphicsAssemblerManager = exports('g', {
        getAssembler: function getAssembler(sprite) {
          return graphicsAssembler;
        }
      });
      Graphics.Assembler = graphicsAssemblerManager;

      var Alignment = ['left', 'center', 'right'];
      var MAX_SIZE = 2048;
      var _BASELINE_OFFSET = getBaselineOffset();
      var _invisibleAlpha = (1 / 255).toFixed(3);
      var MAX_CALCULATION_NUM = 3;
      var LetterInfo = function LetterInfo() {
        this["char"] = '';
        this.valid = true;
        this.x = 0;
        this.y = 0;
        this.line = 0;
        this.hash = '';
      };
      var TextProcessing = function () {
        function TextProcessing() {
          this._context = null;
          this._canvas = null;
          this._canvasData = null;
          this._lettersInfo = [];
          this._tmpRect = new Rect$1();
          this._maxFontSize = 100;
          this._fontScale = 1;
          this._canvasData = CanvasPool.getInstance().get();
          this._canvas = this._canvasData.canvas;
          this._context = this._canvasData.context;
        }
        var _proto = TextProcessing.prototype;
        _proto.destroy = function destroy() {
          CanvasPool.getInstance().put(this._canvasData);
          this._lettersInfo.length = 0;
        };
        _proto.processingString = function processingString(isBmFont, style, layout, outputLayoutData, inputString, out) {
          if (!isBmFont) {
            var loopTime = 0;
            this._fontScale = this._getStyleFontScale(style.fontSize, style.fontScale);
            this._updatePaddingRect(style, outputLayoutData);
            this._calculateLabelFont(style, layout, outputLayoutData, inputString);
            while ((outputLayoutData.canvasSize.width > MAX_SIZE || outputLayoutData.canvasSize.height > MAX_SIZE) && loopTime <= MAX_CALCULATION_NUM) {
              loopTime++;
              if (loopTime > MAX_CALCULATION_NUM) {
                this._fontScale = 1;
              } else {
                var maxValue = Math.max(outputLayoutData.canvasSize.width, outputLayoutData.canvasSize.height);
                var canvasScaleToMaxSizeRatio = MAX_SIZE / maxValue;
                this._fontScale *= canvasScaleToMaxSizeRatio;
                this._fontScale = Math.max(1, this._fontScale);
              }
              this._updatePaddingRect(style, outputLayoutData);
              this._calculateLabelFont(style, layout, outputLayoutData, inputString);
            }
          } else {
            if (!style.fntConfig) {
              this._fontScale = this._getStyleFontScale(style.originFontSize, style.fontScale);
            } else {
              this._fontScale = 1;
            }
            shareLabelInfo.fontScale = this._fontScale;
            this._setupBMFontOverflowMetrics(layout, outputLayoutData);
            this._updateFontScale(style);
            this._computeHorizontalKerningForText(style, layout, inputString);
            this._alignText(style, layout, outputLayoutData, inputString);
          }
          if (out) {
            out = outputLayoutData.parsedString;
          }
        };
        _proto.generateRenderInfo = function generateRenderInfo(isBmFont, style, layout, outputLayoutData, outputRenderData, inputString, callback) {
          if (!isBmFont) {
            this._updateLabelDimensions(style, layout, outputLayoutData);
            this._updateTexture(style, layout, outputLayoutData, outputRenderData);
            this.generateVertexData(isBmFont, style, layout, outputLayoutData, outputRenderData, inputString, callback);
          } else {
            this._computeAlignmentOffset(style, layout, outputLayoutData);
            this.generateVertexData(isBmFont, style, layout, outputLayoutData, outputRenderData, inputString, callback);
          }
        };
        _proto.setCanvasUsed = function setCanvasUsed(canvas, content) {
          this._canvas = canvas;
          this._context = content;
        };
        _proto._getStyleFontScale = function _getStyleFontScale(fontSize, fontScale) {
          var scale = fontScale;
          if (scale * fontSize > this._maxFontSize && fontSize < this._maxFontSize) {
            scale = this._maxFontSize / fontSize;
          }
          if (scale < 1) {
            scale = 1;
          }
          return scale;
        };
        _proto._calculateLabelFont = function _calculateLabelFont(style, layout, outputLayoutData, inputString) {
          if (!this._context) {
            return;
          }
          style.actualFontSize = style.fontSize * this._fontScale;
          var paragraphedStrings = inputString.split('\n');
          var _splitStrings = outputLayoutData.parsedString = paragraphedStrings;
          var _fontDesc = this._getFontDesc(style.actualFontSize, style.fontFamily, style.isBold, style.isItalic);
          this._context.font = style.fontDesc = _fontDesc;
          switch (layout.overFlow) {
            case Overflow$1.NONE:
              {
                var canvasSizeX = 0;
                var canvasSizeY = 0;
                for (var i = 0; i < paragraphedStrings.length; ++i) {
                  var paraLength = safeMeasureText(this._context, paragraphedStrings[i], _fontDesc);
                  canvasSizeX = canvasSizeX > paraLength ? canvasSizeX : paraLength;
                }
                canvasSizeY = (_splitStrings.length + BASELINE_RATIO) * this._getLineHeight(layout.lineHeight, style.actualFontSize, style.fontSize);
                var rawWidth = canvasSizeX;
                var rawHeight = canvasSizeY;
                outputLayoutData.canvasSize.width = rawWidth + outputLayoutData.canvasPadding.width * this._fontScale;
                outputLayoutData.canvasSize.height = rawHeight + outputLayoutData.canvasPadding.height * this._fontScale;
                outputLayoutData.nodeContentSize.width = (rawWidth + outputLayoutData.contentSizeExtend.width * this._fontScale) / this._fontScale;
                outputLayoutData.nodeContentSize.height = (rawHeight + outputLayoutData.contentSizeExtend.height * this._fontScale) / this._fontScale;
                break;
              }
            case Overflow$1.SHRINK:
              {
                this._calculateShrinkFont(paragraphedStrings, style, layout, outputLayoutData);
                this._calculateWrapText(paragraphedStrings, style, layout, outputLayoutData);
                outputLayoutData.canvasSize.width = outputLayoutData.nodeContentSize.width * this._fontScale;
                outputLayoutData.canvasSize.height = outputLayoutData.nodeContentSize.height * this._fontScale;
                break;
              }
            case Overflow$1.CLAMP:
              {
                this._calculateWrapText(paragraphedStrings, style, layout, outputLayoutData);
                outputLayoutData.canvasSize.width = outputLayoutData.nodeContentSize.width * this._fontScale;
                outputLayoutData.canvasSize.height = outputLayoutData.nodeContentSize.height * this._fontScale;
                break;
              }
            case Overflow$1.RESIZE_HEIGHT:
              {
                this._calculateWrapText(paragraphedStrings, style, layout, outputLayoutData);
                var _rawHeight = (outputLayoutData.parsedString.length + BASELINE_RATIO) * this._getLineHeight(layout.lineHeight, style.actualFontSize, style.fontSize);
                outputLayoutData.canvasSize.width = outputLayoutData.nodeContentSize.width * this._fontScale;
                outputLayoutData.canvasSize.height = _rawHeight + outputLayoutData.canvasPadding.height * this._fontScale;
                outputLayoutData.nodeContentSize.height = (_rawHeight + outputLayoutData.contentSizeExtend.height * this._fontScale) / this._fontScale;
                break;
              }
          }
        };
        _proto._getFontDesc = function _getFontDesc(fontSize, fontFamily, isBold, isItalic) {
          var fontDesc = fontSize.toString() + "px ";
          fontDesc += fontFamily;
          if (isBold) {
            fontDesc = "bold " + fontDesc;
          }
          if (isItalic) {
            fontDesc = "italic " + fontDesc;
          }
          return fontDesc;
        };
        _proto._getLineHeight = function _getLineHeight(lineHeight, fontSize, drawFontsize) {
          var nodeSpacingY = lineHeight;
          if (nodeSpacingY === 0) {
            nodeSpacingY = fontSize;
          } else {
            nodeSpacingY = nodeSpacingY * fontSize / drawFontsize;
          }
          return nodeSpacingY;
        };
        _proto._calculateShrinkFont = function _calculateShrinkFont(paragraphedStrings, style, layout, outputLayoutData) {
          if (!this._context) return;
          var _fontDesc = this._getFontDesc(style.actualFontSize, style.fontFamily, style.isBold, style.isItalic);
          this._context.font = _fontDesc;
          var paragraphLength = this._calculateParagraphLength(paragraphedStrings, this._context, _fontDesc);
          var i = 0;
          var totalHeight = 0;
          var maxLength = 0;
          var _fontSize = style.actualFontSize;
          if (layout.wrapping) {
            var canvasWidthNoMargin = outputLayoutData.nodeContentSize.width * this._fontScale;
            var canvasHeightNoMargin = outputLayoutData.nodeContentSize.height * this._fontScale;
            if (canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) {
              return;
            }
            totalHeight = canvasHeightNoMargin + 1;
            var actualFontSize = style.actualFontSize + 1;
            var textFragment = [];
            var left = 0;
            var right = actualFontSize | 0;
            var mid = 0;
            while (left < right) {
              mid = left + right + 1 >> 1;
              if (mid <= 0) {
                logID(4003);
                break;
              }
              _fontSize = mid;
              _fontDesc = this._getFontDesc(_fontSize, style.fontFamily, style.isBold, style.isItalic);
              this._context.font = _fontDesc;
              var lineHeight = this._getLineHeight(layout.lineHeight, _fontSize, style.fontSize);
              totalHeight = 0;
              for (i = 0; i < paragraphedStrings.length; ++i) {
                var allWidth = safeMeasureText(this._context, paragraphedStrings[i], _fontDesc);
                textFragment = fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(this._context, _fontDesc));
                totalHeight += textFragment.length * lineHeight;
              }
              if (totalHeight > canvasHeightNoMargin) {
                right = mid - 1;
              } else {
                left = mid;
              }
            }
            if (left === 0) {
              logID(4003);
            } else {
              _fontSize = left;
              _fontDesc = this._getFontDesc(_fontSize, style.fontFamily, style.isBold, style.isItalic);
              this._context.font = _fontDesc;
            }
          } else {
            totalHeight = paragraphedStrings.length * this._getLineHeight(layout.lineHeight, _fontSize, style.fontSize);
            for (i = 0; i < paragraphedStrings.length; ++i) {
              if (maxLength < paragraphLength[i]) {
                maxLength = paragraphLength[i];
              }
            }
            var scaleX = (outputLayoutData.canvasSize.width - outputLayoutData.canvasPadding.width) * this._fontScale / maxLength;
            var scaleY = outputLayoutData.canvasSize.height * this._fontScale / totalHeight;
            _fontSize = style.actualFontSize * Math.min(1, scaleX, scaleY) | 0;
            _fontDesc = this._getFontDesc(_fontSize, style.fontFamily, style.isBold, style.isItalic);
            this._context.font = _fontDesc;
          }
          style.actualFontSize = _fontSize;
          style.fontDesc = _fontDesc;
        };
        _proto._calculateWrapText = function _calculateWrapText(paragraphedStrings, style, layout, outputLayoutData) {
          if (!layout.wrapping || !this._context) return;
          var _splitStrings = [];
          var canvasWidthNoMargin = outputLayoutData.nodeContentSize.width * this._fontScale;
          var _fontDesc = this._getFontDesc(style.actualFontSize, style.fontFamily, style.isBold, style.isItalic);
          this._context.font = _fontDesc;
          for (var i = 0; i < paragraphedStrings.length; ++i) {
            var allWidth = safeMeasureText(this._context, paragraphedStrings[i], _fontDesc);
            var textFragment = fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(this._context, _fontDesc));
            _splitStrings = _splitStrings.concat(textFragment);
          }
          outputLayoutData.parsedString = _splitStrings;
          style.fontDesc = _fontDesc;
        };
        _proto._measureText = function _measureText(ctx, fontDesc) {
          return function (str) {
            return safeMeasureText(ctx, str, fontDesc);
          };
        };
        _proto._calculateParagraphLength = function _calculateParagraphLength(paragraphedStrings, ctx, fontDesc) {
          var paragraphLength = [];
          for (var _iterator = _createForOfIteratorHelperLoose(paragraphedStrings), _step; !(_step = _iterator()).done;) {
            var para = _step.value;
            var width = safeMeasureText(ctx, para, fontDesc);
            paragraphLength.push(width);
          }
          return paragraphLength;
        };
        _proto._updatePaddingRect = function _updatePaddingRect(style, outputLayoutData) {
          var top = 0;
          var bottom = 0;
          var left = 0;
          var right = 0;
          var outlineWidth = 0;
          outputLayoutData.contentSizeExtend.width = outputLayoutData.contentSizeExtend.height = 0;
          if (style.isOutlined) {
            outlineWidth = style.outlineWidth;
            top = bottom = left = right = outlineWidth;
            outputLayoutData.contentSizeExtend.width = outputLayoutData.contentSizeExtend.height = outlineWidth * 2;
          }
          if (style.hasShadow) {
            var shadowWidth = style.shadowBlur + outlineWidth;
            var offsetX = style.shadowOffsetX;
            var offsetY = style.shadowOffsetY;
            left = Math.max(left, -offsetX + shadowWidth);
            right = Math.max(right, offsetX + shadowWidth);
            top = Math.max(top, offsetY + shadowWidth);
            bottom = Math.max(bottom, -offsetY + shadowWidth);
          }
          if (style.isItalic) {
            var offset = style.fontSize * Math.tan(12 * 0.0174532925);
            right += offset;
            outputLayoutData.contentSizeExtend.width += offset;
          }
          outputLayoutData.canvasPadding.x = left;
          outputLayoutData.canvasPadding.y = top;
          outputLayoutData.canvasPadding.width = left + right;
          outputLayoutData.canvasPadding.height = top + bottom;
        };
        _proto._updateLabelDimensions = function _updateLabelDimensions(style, layout, outputLayoutData) {
          outputLayoutData.canvasSize.width = Math.min(outputLayoutData.canvasSize.width, MAX_SIZE);
          outputLayoutData.canvasSize.height = Math.min(outputLayoutData.canvasSize.height, MAX_SIZE);
          this._canvas.width = outputLayoutData.canvasSize.width;
          this._canvas.height = outputLayoutData.canvasSize.height;
          this._context.font = style.fontDesc;
          this._context.textAlign = Alignment[layout.horizontalAlign];
          this._context.textBaseline = 'alphabetic';
        };
        _proto._calculateFillTextStartPosition = function _calculateFillTextStartPosition(style, layout, outputLayoutData) {
          var labelX = 0;
          if (layout.horizontalAlign === HorizontalTextAlignment.RIGHT) {
            labelX = outputLayoutData.canvasSize.width - outputLayoutData.canvasPadding.width;
          } else if (layout.horizontalAlign === HorizontalTextAlignment.CENTER) {
            labelX = (outputLayoutData.canvasSize.width - outputLayoutData.canvasPadding.width) / 2;
          }
          var lineHeight = this._getLineHeight(layout.lineHeight, style.actualFontSize, style.fontSize);
          var drawStartY = lineHeight * (outputLayoutData.parsedString.length - 1);
          var firstLinelabelY = style.actualFontSize * (1 - BASELINE_RATIO / 2);
          if (layout.verticalAlign !== VerticalTextAlignment.TOP) {
            var blank = drawStartY + outputLayoutData.canvasPadding.height + style.actualFontSize - outputLayoutData.canvasSize.height;
            if (layout.verticalAlign === VerticalTextAlignment.BOTTOM) {
              blank += BASELINE_RATIO / 2 * style.actualFontSize;
              firstLinelabelY -= blank;
            } else {
              firstLinelabelY -= blank / 2;
            }
          }
          firstLinelabelY += _BASELINE_OFFSET * style.actualFontSize;
          outputLayoutData.startPosition.set(labelX + outputLayoutData.canvasPadding.x, firstLinelabelY + outputLayoutData.canvasPadding.y);
        };
        _proto._updateTexture = function _updateTexture(style, layout, outputLayoutData, outputRenderData) {
          if (!this._context || !this._canvas) {
            return;
          }
          this._context.clearRect(0, 0, this._canvas.width, this._canvas.height);
          this._context.font = style.fontDesc;
          this._calculateFillTextStartPosition(style, layout, outputLayoutData);
          var lineHeight = this._getLineHeight(layout.lineHeight, style.actualFontSize, style.fontSize);
          this._context.lineJoin = 'round';
          if (style.isOutlined) {
            this._context.fillStyle = "rgba(" + style.outlineColor.r + ", " + style.outlineColor.g + ", " + style.outlineColor.b + ", " + _invisibleAlpha + ")";
            this._context.fillRect(0, 0, this._canvas.width, this._canvas.height);
          } else {
            this._context.fillStyle = "rgba(" + style.color.r + ", " + style.color.g + ", " + style.color.b + ", " + _invisibleAlpha + ")";
            this._context.fillRect(0, 0, this._canvas.width, this._canvas.height);
          }
          this._context.fillStyle = "rgb(" + style.color.r + ", " + style.color.g + ", " + style.color.b + ")";
          var tempPos = new Vec2(outputLayoutData.startPosition.x, outputLayoutData.startPosition.y);
          var drawTextPosX = tempPos.x;
          var drawTextPosY = 0;
          this._drawTextEffect(tempPos, lineHeight, style, layout, outputLayoutData);
          for (var i = 0; i < outputLayoutData.parsedString.length; ++i) {
            drawTextPosY = tempPos.y + i * lineHeight;
            if (style.hasShadow) {
              this._setupShadow(style);
              this._context.fillText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
            }
            if (style.isOutlined) {
              this._setupOutline(style);
              this._context.strokeText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
            }
            if (!style.hasShadow || style.isOutlined) {
              this._context.fillText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
            }
          }
          if (style.hasShadow) {
            this._context.shadowColor = 'transparent';
          }
          this._uploadTexture(outputRenderData);
        };
        _proto._uploadTexture = function _uploadTexture(outputRenderData) {
          if (outputRenderData.texture && this._canvas) {
            var tex;
            if (outputRenderData.texture instanceof SpriteFrame) {
              tex = outputRenderData.texture.texture;
            } else {
              tex = outputRenderData.texture;
            }
            var uploadAgain = this._canvas.width !== 0 && this._canvas.height !== 0;
            if (uploadAgain) {
              tex.reset({
                width: this._canvas.width,
                height: this._canvas.height,
                mipmapLevel: 1
              });
              tex.uploadData(this._canvas);
              tex.setWrapMode(WrapMode$1.CLAMP_TO_EDGE, WrapMode$1.CLAMP_TO_EDGE);
              if (outputRenderData.texture instanceof SpriteFrame) {
                outputRenderData.texture.rect = new Rect$1(0, 0, this._canvas.width, this._canvas.height);
                outputRenderData.texture._calculateUV();
              }
              if (legacyCC.director.root && legacyCC.director.root.batcher2D) {
                {
                  legacyCC.director.root.batcher2D._releaseDescriptorSetCache(tex.getHash());
                }
              }
            }
          }
        };
        _proto._drawTextEffect = function _drawTextEffect(startPosition, lineHeight, style, layout, outputLayoutData) {
          if (!style.hasShadow && !style.isOutlined && !style.isUnderline) return;
          var isMultiple = outputLayoutData.parsedString.length > 1 && style.hasShadow;
          var measureText = this._measureText(this._context, style.fontDesc);
          var drawTextPosX = 0;
          var drawTextPosY = 0;
          for (var i = 0; i < outputLayoutData.parsedString.length; ++i) {
            drawTextPosX = startPosition.x;
            drawTextPosY = startPosition.y + i * lineHeight;
            if (isMultiple) {
              if (style.hasShadow) {
                this._setupShadow(style);
                this._context.fillText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
              }
              if (style.isOutlined) {
                this._setupOutline(style);
                this._context.strokeText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
              }
              if (!style.hasShadow || style.isOutlined) {
                this._context.fillText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
              }
            }
            if (style.isUnderline) {
              var _drawUnderlineWidth = measureText(outputLayoutData.parsedString[i]);
              var _drawUnderlinePos = new Vec2();
              if (layout.horizontalAlign === HorizontalTextAlignment.RIGHT) {
                _drawUnderlinePos.x = startPosition.x - _drawUnderlineWidth;
              } else if (layout.horizontalAlign === HorizontalTextAlignment.CENTER) {
                _drawUnderlinePos.x = startPosition.x - _drawUnderlineWidth / 2;
              } else {
                _drawUnderlinePos.x = startPosition.x;
              }
              _drawUnderlinePos.y = drawTextPosY + style.actualFontSize / 8;
              this._context.fillRect(_drawUnderlinePos.x, _drawUnderlinePos.y, _drawUnderlineWidth, style.underlineHeight * this._fontScale);
            }
          }
          if (isMultiple) {
            this._context.shadowColor = 'transparent';
          }
        };
        _proto._setupOutline = function _setupOutline(style) {
          this._context.shadowBlur = 0;
          this._context.shadowOffsetX = 0;
          this._context.shadowOffsetY = 0;
          this._context.strokeStyle = "rgba(" + style.outlineColor.r + ", " + style.outlineColor.g + ", " + style.outlineColor.b + ", " + style.outlineColor.a / 255 + ")";
          this._context.lineWidth = style.outlineWidth * 2 * this._fontScale;
        };
        _proto._setupShadow = function _setupShadow(style) {
          var fontScale = this._fontScale;
          this._context.shadowColor = "rgba(" + style.shadowColor.r + ", " + style.shadowColor.g + ", " + style.shadowColor.b + ", " + style.shadowColor.a / 255 + ")";
          this._context.shadowBlur = style.shadowBlur * fontScale;
          this._context.shadowOffsetX = style.shadowOffsetX * fontScale;
          this._context.shadowOffsetY = -style.shadowOffsetY * fontScale;
        };
        _proto.generateVertexData = function generateVertexData(isBmFont, style, layout, outputLayoutData, outputRenderData, inputString, callback) {
          if (!isBmFont) {
            this.updateQuatCount(outputRenderData);
            callback(style, outputLayoutData, outputRenderData);
          } else {
            this._updateQuads(style, layout, outputLayoutData, outputRenderData, inputString, callback);
          }
        };
        _proto.updateQuatCount = function updateQuatCount(outputRenderData) {
          var data = outputRenderData.vertexBuffer;
          var count = outputRenderData.quadCount;
          if (data.length !== count) {
            for (var i = data.length; i < count; i++) {
              data.push({
                x: 0,
                y: 0,
                z: 0,
                u: 0,
                v: 0,
                color: Color$1.WHITE.clone()
              });
            }
            data.length = count;
          }
        };
        _proto._setupBMFontOverflowMetrics = function _setupBMFontOverflowMetrics(layout, outputLayoutData) {
          var newWidth = outputLayoutData.nodeContentSize.width;
          var newHeight = outputLayoutData.nodeContentSize.height;
          if (layout.overFlow === Overflow$1.RESIZE_HEIGHT) {
            newHeight = 0;
          }
          if (layout.overFlow === Overflow$1.NONE) {
            newWidth = 0;
            newHeight = 0;
          }
          layout.textWidthTemp = newWidth;
          layout.textHeightTemp = newHeight;
          layout.textDimensions.width = newWidth;
          layout.textDimensions.height = newHeight;
          layout.maxLineWidth = newWidth;
        };
        _proto._updateFontScale = function _updateFontScale(style) {
          style.bmfontScale = style.actualFontSize / (style.originFontSize * this._fontScale);
        };
        _proto._computeHorizontalKerningForText = function _computeHorizontalKerningForText(style, layout, inputString) {
          var string = inputString;
          var stringLen = string.length;
          if (!style.fntConfig) return;
          var kerningDict = style.fntConfig.kerningDict;
          var horizontalKerning = layout.horizontalKerning;
          if (!kerningDict || kerningDict.length === 0) {
            return;
          }
          var prev = -1;
          for (var i = 0; i < stringLen; ++i) {
            var key = string.charCodeAt(i);
            var kerningAmount = kerningDict[prev << 16 | key & 0xffff] || 0;
            if (i < stringLen - 1) {
              horizontalKerning[i] = kerningAmount;
            } else {
              horizontalKerning[i] = 0;
            }
            prev = key;
          }
        };
        _proto._alignText = function _alignText(style, layout, outputLayoutData, inputString) {
          this._multilineTextWrap(style, layout, outputLayoutData, inputString, this._getFirstWordLen);
          if (layout.overFlow === Overflow$1.SHRINK) {
            if (style.fontSize > 0 && this._isVerticalClamp(style, layout, outputLayoutData, inputString, this)) {
              this._shrinkLabelToContentSize(style, layout, outputLayoutData, inputString, this._isVerticalClamp);
            }
            if (style.fontSize > 0 && this._isHorizontalNeedShrink(layout, outputLayoutData)) {
              this._shrinkLabelToContentSize(style, layout, outputLayoutData, inputString, this._isHorizontalClamp);
            }
          }
          this._parsedString(outputLayoutData, inputString);
        };
        _proto._parsedString = function _parsedString(outputLayoutData, inputString) {
          var _splitStrings = [];
          var textFragment = '';
          var length = getSymbolLength(inputString);
          for (var i = 0, line = 0, l = length; i < l; ++i) {
            var letterInfo = this._lettersInfo[i];
            if (!letterInfo.valid) {
              continue;
            }
            if (line === letterInfo.line) {
              textFragment += letterInfo["char"];
            } else {
              _splitStrings = _splitStrings.concat(textFragment);
              line = letterInfo.line;
              textFragment = '';
            }
          }
          _splitStrings = _splitStrings.concat(textFragment);
          outputLayoutData.parsedString = _splitStrings;
        };
        _proto._multilineTextWrap = function _multilineTextWrap(style, layout, outputLayoutData, inputString, nextTokenFunc) {
          layout.linesWidth.length = 0;
          var _string = inputString;
          var textLen = _string.length;
          var lineIndex = 0;
          var nextTokenX = 0;
          var nextTokenY = 0;
          var longestLine = 0;
          var letterRight = 0;
          var highestY = 0;
          var lowestY = 0;
          var letterDef = null;
          var _lineSpacing = 0;
          for (var index = 0; index < textLen;) {
            var character = getSymbolAt(_string, index);
            if (character === '\n') {
              layout.linesWidth.push(letterRight);
              letterRight = 0;
              lineIndex++;
              nextTokenX = 0;
              nextTokenY -= layout.lineHeight * this._getFontScale(style, layout) + _lineSpacing;
              this._recordPlaceholderInfo(index, character);
              index++;
              continue;
            }
            var tokenLen = nextTokenFunc(style, layout, _string, index, textLen);
            var tokenHighestY = highestY;
            var tokenLowestY = lowestY;
            var tokenRight = letterRight;
            var nextLetterX = nextTokenX;
            var newLine = false;
            var letterPosition = new Vec2();
            for (var tmp = 0; tmp < tokenLen; ++tmp) {
              var letterIndex = index + tmp;
              character = getSymbolAt(_string, letterIndex);
              if (character === '\r') {
                this._recordPlaceholderInfo(letterIndex, character);
                continue;
              }
              letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo);
              if (!letterDef) {
                this._recordPlaceholderInfo(letterIndex, character);
                if (style.fntConfig != null) {
                  log("Can't find letter definition in texture atlas " + style.fntConfig.atlasName + " for letter:" + character);
                } else {
                  log("Can't find letter definition in font family " + style.fontFamily + " for letter:" + character);
                }
                continue;
              }
              var letterX = nextLetterX + letterDef.offsetX * style.bmfontScale - shareLabelInfo.margin;
              if (layout.wrapping && layout.maxLineWidth > 0 && nextTokenX > 0 && letterX + letterDef.w * style.bmfontScale > layout.maxLineWidth && !isUnicodeSpace(character)) {
                layout.linesWidth.push(letterRight);
                letterRight = 0;
                lineIndex++;
                nextTokenX = 0;
                nextTokenY -= layout.lineHeight * this._getFontScale(style, layout) + _lineSpacing;
                newLine = true;
                break;
              } else {
                letterPosition.x = letterX;
              }
              letterPosition.y = nextTokenY - letterDef.offsetY * style.bmfontScale;
              this._recordLetterInfo(letterPosition, character, letterIndex, lineIndex);
              if (letterIndex + 1 < layout.horizontalKerning.length && letterIndex < textLen - 1) {
                nextLetterX += layout.horizontalKerning[letterIndex + 1] * style.bmfontScale;
              }
              nextLetterX += letterDef.xAdvance * style.bmfontScale + layout.spacingX;
              tokenRight = letterPosition.x + letterDef.w * style.bmfontScale;
              if (tokenHighestY < letterPosition.y) {
                tokenHighestY = letterPosition.y;
              }
              if (tokenLowestY > letterPosition.y - letterDef.h * style.bmfontScale) {
                tokenLowestY = letterPosition.y - letterDef.h * style.bmfontScale;
              }
            }
            if (newLine) {
              continue;
            }
            nextTokenX = nextLetterX;
            letterRight = tokenRight;
            if (highestY < tokenHighestY) {
              highestY = tokenHighestY;
            }
            if (lowestY > tokenLowestY) {
              lowestY = tokenLowestY;
            }
            if (longestLine < letterRight) {
              longestLine = letterRight;
            }
            index += tokenLen;
          }
          layout.linesWidth.push(letterRight);
          layout.numberOfLines = lineIndex + 1;
          layout.textDesiredHeight = layout.numberOfLines * layout.lineHeight * this._getFontScale(style, layout);
          if (layout.numberOfLines > 1) {
            layout.textDesiredHeight += (layout.numberOfLines - 1) * _lineSpacing;
          }
          outputLayoutData.nodeContentSize.width = layout.textWidthTemp;
          outputLayoutData.nodeContentSize.height = layout.textHeightTemp;
          if (layout.textWidthTemp <= 0) {
            outputLayoutData.nodeContentSize.width = parseFloat(longestLine.toFixed(2)) + shareLabelInfo.margin * 2;
          }
          if (layout.textHeightTemp <= 0) {
            outputLayoutData.nodeContentSize.height = parseFloat(layout.textDesiredHeight.toFixed(2)) + shareLabelInfo.margin * 2;
          }
          layout.tailoredTopY = outputLayoutData.nodeContentSize.height;
          layout.tailoredBottomY = 0;
          if (highestY > 0) {
            layout.tailoredTopY = outputLayoutData.nodeContentSize.height + highestY;
          }
          if (lowestY < -layout.textDesiredHeight) {
            layout.tailoredBottomY = layout.textDesiredHeight + lowestY;
          }
          return true;
        };
        _proto._recordPlaceholderInfo = function _recordPlaceholderInfo(letterIndex, _char) {
          if (letterIndex >= this._lettersInfo.length) {
            var tmpInfo = new LetterInfo();
            this._lettersInfo.push(tmpInfo);
          }
          this._lettersInfo[letterIndex]["char"] = _char;
          this._lettersInfo[letterIndex].hash = "" + getSymbolCodeAt(_char, 0) + shareLabelInfo.hash;
          this._lettersInfo[letterIndex].valid = false;
        };
        _proto._recordLetterInfo = function _recordLetterInfo(letterPosition, character, letterIndex, lineIndex) {
          if (letterIndex >= this._lettersInfo.length) {
            var tmpInfo = new LetterInfo();
            this._lettersInfo.push(tmpInfo);
          }
          var _char2 = getSymbolCodeAt(character, 0);
          var key = "" + _char2 + shareLabelInfo.hash;
          this._lettersInfo[letterIndex].line = lineIndex;
          this._lettersInfo[letterIndex]["char"] = character;
          this._lettersInfo[letterIndex].hash = key;
          this._lettersInfo[letterIndex].valid = shareLabelInfo.fontAtlas.getLetter(key).valid;
          this._lettersInfo[letterIndex].x = letterPosition.x;
          this._lettersInfo[letterIndex].y = letterPosition.y;
        };
        _proto._getFirstWordLen = function _getFirstWordLen(style, layout, text, startIndex, textLen) {
          var character = getSymbolAt(text, startIndex);
          if (isUnicodeCJK(character) || character === '\n' || isUnicodeSpace(character)) {
            return 1;
          }
          var len = 1;
          var letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo);
          if (!letterDef) {
            return len;
          }
          var nextLetterX = letterDef.xAdvance * style.bmfontScale + layout.spacingX;
          var letterX = 0;
          for (var index = startIndex + 1; index < textLen; ++index) {
            character = getSymbolAt(text, index);
            letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo);
            if (!letterDef) {
              break;
            }
            letterX = nextLetterX + letterDef.offsetX * style.bmfontScale;
            if (letterX + letterDef.w * style.bmfontScale > layout.maxLineWidth && !isUnicodeSpace(character) && layout.maxLineWidth > 0) {
              return len;
            }
            nextLetterX += letterDef.xAdvance * style.bmfontScale + layout.spacingX;
            if (character === '\n' || isUnicodeSpace(character) || isUnicodeCJK(character)) {
              break;
            }
            len++;
          }
          return len;
        };
        _proto._computeAlignmentOffset = function _computeAlignmentOffset(style, layout, outputLayoutData) {
          layout.linesOffsetX.length = 0;
          layout.letterOffsetY = 0;
          switch (layout.horizontalAlign) {
            case HorizontalTextAlignment.LEFT:
              for (var i = 0; i < layout.numberOfLines; ++i) {
                layout.linesOffsetX.push(0);
              }
              break;
            case HorizontalTextAlignment.CENTER:
              for (var _i = 0, l = layout.linesWidth.length; _i < l; _i++) {
                layout.linesOffsetX.push((outputLayoutData.nodeContentSize.width - layout.linesWidth[_i]) / 2);
              }
              break;
            case HorizontalTextAlignment.RIGHT:
              for (var _i2 = 0, _l = layout.linesWidth.length; _i2 < _l; _i2++) {
                layout.linesOffsetX.push(outputLayoutData.nodeContentSize.width - layout.linesWidth[_i2]);
              }
              break;
          }
          layout.letterOffsetY = outputLayoutData.nodeContentSize.height;
          if (layout.verticalAlign !== VerticalTextAlignment.TOP) {
            var blank = outputLayoutData.nodeContentSize.height - layout.textDesiredHeight + layout.lineHeight * this._getFontScale(style, layout) - style.originFontSize * this._fontScale * style.bmfontScale;
            if (layout.verticalAlign === VerticalTextAlignment.BOTTOM) {
              layout.letterOffsetY -= blank;
            } else {
              layout.letterOffsetY -= blank / 2;
            }
          }
        };
        _proto._getFontScale = function _getFontScale(style, layout) {
          return layout.overFlow === Overflow$1.SHRINK ? style.bmfontScale : 1;
        };
        _proto._isVerticalClamp = function _isVerticalClamp(style, layout, outputLayoutData, inputString, process) {
          if (layout.textDesiredHeight > outputLayoutData.nodeContentSize.height) {
            return true;
          } else {
            return false;
          }
        };
        _proto._isHorizontalClamp = function _isHorizontalClamp(style, layout, outputLayoutData, inputString, process) {
          var letterClamp = false;
          var _string = inputString;
          var _length = getSymbolLength(_string);
          for (var ctr = 0, l = _length; ctr < l; ++ctr) {
            var letterInfo = process._lettersInfo[ctr];
            if (letterInfo.valid) {
              var letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(letterInfo["char"], shareLabelInfo);
              if (!letterDef) {
                continue;
              }
              var px = letterInfo.x + letterDef.w * style.bmfontScale;
              var lineIndex = letterInfo.line;
              if (layout.textWidthTemp > 0) {
                if (!layout.wrapping) {
                  if (px > outputLayoutData.nodeContentSize.width) {
                    letterClamp = true;
                    break;
                  }
                } else {
                  var wordWidth = layout.linesWidth[lineIndex];
                  if (wordWidth > outputLayoutData.nodeContentSize.width && (px > outputLayoutData.nodeContentSize.width || px < 0)) {
                    letterClamp = true;
                    break;
                  }
                }
              }
            }
          }
          return letterClamp;
        };
        _proto._isHorizontalNeedShrink = function _isHorizontalNeedShrink(layout, outputLayoutData) {
          var wordWidth = 0;
          for (var ctr = 0, l = layout.linesWidth.length; ctr < l; ++ctr) {
            wordWidth = layout.linesWidth[ctr];
            if (wordWidth > outputLayoutData.nodeContentSize.width) return true;
          }
          return false;
        };
        _proto._shrinkLabelToContentSize = function _shrinkLabelToContentSize(style, layout, outputLayoutData, inputString, lambda) {
          var fontSize = style.actualFontSize;
          var left = 0;
          var right = fontSize | 0;
          var mid = 0;
          while (left < right) {
            mid = left + right + 1 >> 1;
            var newFontSize = mid;
            if (newFontSize <= 0) {
              break;
            }
            style.bmfontScale = newFontSize / (style.originFontSize * this._fontScale);
            this._multilineTextWrap(style, layout, outputLayoutData, inputString, this._getFirstWordLen);
            this._computeAlignmentOffset(style, layout, outputLayoutData);
            if (lambda(style, layout, outputLayoutData, inputString, this)) {
              right = mid - 1;
            } else {
              left = mid;
            }
          }
          if (left >= 0) {
            this._scaleFontSizeDown(style, layout, outputLayoutData, inputString, left);
          }
        };
        _proto._scaleFontSizeDown = function _scaleFontSizeDown(style, layout, outputLayoutData, inputString, fontSize) {
          var shouldUpdateContent = true;
          if (!fontSize) {
            fontSize = 0.1;
            shouldUpdateContent = false;
          }
          style.actualFontSize = fontSize;
          if (shouldUpdateContent) {
            this._updateFontScale(style);
            this._multilineTextWrap(style, layout, outputLayoutData, inputString, this._getFirstWordLen);
          }
        };
        _proto._updateQuads = function _updateQuads(style, layout, outputLayoutData, outputRenderData, inputString, callback) {
          var texture = style.spriteFrame ? style.spriteFrame.texture : shareLabelInfo.fontAtlas.getTexture();
          var appX = outputRenderData.uiTransAnchorX * outputLayoutData.nodeContentSize.width;
          var appY = outputRenderData.uiTransAnchorY * outputLayoutData.nodeContentSize.height;
          var ret = true;
          var _length = getSymbolLength(inputString);
          for (var ctr = 0, l = _length; ctr < l; ++ctr) {
            var letterInfo = this._lettersInfo[ctr];
            if (!letterInfo.valid) {
              continue;
            }
            var letterDef = shareLabelInfo.fontAtlas.getLetter(letterInfo.hash);
            if (!letterDef) {
              warn('Can\'t find letter in this bitmap-font');
              continue;
            }
            this._tmpRect.height = letterDef.h;
            this._tmpRect.width = letterDef.w;
            this._tmpRect.x = letterDef.u;
            this._tmpRect.y = letterDef.v;
            var py = letterInfo.y + layout.letterOffsetY;
            if (layout.textHeightTemp > 0) {
              if (py > layout.tailoredTopY) {
                var clipTop = py - layout.tailoredTopY;
                this._tmpRect.y += clipTop;
                this._tmpRect.height -= clipTop;
                py -= clipTop;
              }
              if (py - this._tmpRect.height * style.bmfontScale < layout.tailoredBottomY && layout.overFlow === Overflow$1.CLAMP) {
                this._tmpRect.height = py < layout.tailoredBottomY ? 0 : (py - layout.tailoredBottomY) / style.bmfontScale;
              }
            }
            var lineIndex = letterInfo.line;
            var px = letterInfo.x + letterDef.w / 2 * style.bmfontScale + layout.linesOffsetX[lineIndex];
            if (layout.textWidthTemp > 0) {
              if (this._isHorizontalClamped(layout, outputLayoutData, px, lineIndex)) {
                if (layout.overFlow === Overflow$1.CLAMP) {
                  this._tmpRect.width = 0;
                }
              }
            }
            if (this._tmpRect.height > 0 && this._tmpRect.width > 0) {
              var isRotated = this._determineRect(style);
              var letterPositionX = letterInfo.x + layout.linesOffsetX[letterInfo.line];
              var offset = outputRenderData.quadCount;
              outputRenderData.quadCount += 4;
              this.updateQuatCount(outputRenderData);
              callback(style, outputLayoutData, outputRenderData, offset, texture, this._tmpRect, isRotated, letterPositionX - appX, py - appY);
            }
          }
          return ret;
        };
        _proto._isHorizontalClamped = function _isHorizontalClamped(layout, outputLayoutData, px, lineIndex) {
          var wordWidth = layout.linesWidth[lineIndex];
          var letterOverClamp = px > outputLayoutData.nodeContentSize.width || px < 0;
          if (!layout.wrapping) {
            return letterOverClamp;
          } else {
            return wordWidth > outputLayoutData.nodeContentSize.width && letterOverClamp;
          }
        };
        _proto._determineRect = function _determineRect(style) {
          var _spriteFrame = style.spriteFrame;
          if (!_spriteFrame) return false;
          var isRotated = _spriteFrame.isRotated();
          var originalSize = _spriteFrame.getOriginalSize();
          var rect = _spriteFrame.getRect();
          var offset = _spriteFrame.getOffset();
          var trimmedLeft = offset.x + (originalSize.width - rect.width) / 2;
          var trimmedTop = offset.y - (originalSize.height - rect.height) / 2;
          if (!isRotated) {
            this._tmpRect.x += rect.x - trimmedLeft;
            this._tmpRect.y += rect.y + trimmedTop;
          } else {
            var originalX = this._tmpRect.x;
            this._tmpRect.x = rect.x + rect.height - this._tmpRect.y - this._tmpRect.height - trimmedTop;
            this._tmpRect.y = originalX + rect.y - trimmedLeft;
            if (this._tmpRect.y < 0) {
              this._tmpRect.height += trimmedTop;
            }
          }
          return isRotated;
        };
        return TextProcessing;
      }();
      TextProcessing.instance = void 0;
      TextProcessing.instance = new TextProcessing();

      var _defaultLetterAtlas = new LetterAtlas(64, 64);
      var _defaultFontAtlas = new FontAtlas(null);
      var _comp$1 = null;
      var _uiTrans = null;
      var _fntConfig = null;
      var _spriteFrame = null;
      var QUAD_INDICES$6;
      var bmfontUtils = {
        updateProcessingData: function updateProcessingData(style, layout, outputLayoutData, outputRenderData, comp, trans) {
          style.fontSize = comp.fontSize;
          style.actualFontSize = comp.fontSize;
          style.originFontSize = _fntConfig ? _fntConfig.fontSize : comp.fontSize;
          layout.horizontalAlign = comp.horizontalAlign;
          layout.verticalAlign = comp.verticalAlign;
          layout.spacingX = comp.spacingX;
          var overflow = comp.overflow;
          layout.overFlow = overflow;
          layout.lineHeight = comp.lineHeight;
          outputLayoutData.nodeContentSize.width = trans.width;
          outputLayoutData.nodeContentSize.height = trans.height;
          if (overflow === Overflow$1.NONE) {
            layout.wrapping = false;
            outputLayoutData.nodeContentSize.width += shareLabelInfo.margin * 2;
            outputLayoutData.nodeContentSize.height += shareLabelInfo.margin * 2;
          } else if (overflow === Overflow$1.RESIZE_HEIGHT) {
            layout.wrapping = true;
            outputLayoutData.nodeContentSize.height += shareLabelInfo.margin * 2;
          } else {
            layout.wrapping = comp.enableWrapText;
          }
          outputRenderData.uiTransAnchorX = trans.anchorX;
          outputRenderData.uiTransAnchorY = trans.anchorY;
          shareLabelInfo.lineHeight = comp.lineHeight;
          shareLabelInfo.fontSize = comp.fontSize;
          style.spriteFrame = _spriteFrame;
          style.fntConfig = _fntConfig;
          style.fontFamily = shareLabelInfo.fontFamily;
          style.color.set(comp.color);
        },
        updateRenderData: function updateRenderData(comp) {
          if (!comp.renderData) {
            return;
          }
          if (_comp$1 === comp) {
            return;
          }
          if (comp.renderData.vertDirty) {
            _comp$1 = comp;
            _uiTrans = _comp$1.node._uiProps.uiTransformComp;
            var renderData = comp.renderData;
            var processing = TextProcessing.instance;
            var style = comp.textStyle;
            var layout = comp.textLayout;
            var outputLayoutData = comp.textLayoutData;
            var outputRenderData = comp.textRenderData;
            style.fontScale = view.getScaleX();
            this._updateFontFamily(comp);
            this.updateProcessingData(style, layout, outputLayoutData, outputRenderData, comp, _uiTrans);
            this._updateLabelInfo(comp);
            style.fontDesc = shareLabelInfo.fontDesc;
            processing.processingString(true, style, layout, outputLayoutData, comp.string);
            outputRenderData.quadCount = 0;
            processing.generateRenderInfo(true, style, layout, outputLayoutData, outputRenderData, comp.string, this.generateVertexData);
            var isResized = false;
            if (renderData.dataLength !== outputRenderData.quadCount) {
              this.resetRenderData(comp);
              renderData.dataLength = outputRenderData.quadCount;
              renderData.resize(renderData.dataLength, renderData.dataLength / 2 * 3);
              isResized = true;
            }
            var datalist = renderData.data;
            for (var i = 0, l = outputRenderData.quadCount; i < l; i++) {
              datalist[i] = outputRenderData.vertexBuffer[i];
            }
            var indexCount = renderData.indexCount;
            this.createQuadIndices(indexCount);
            renderData.chunk.setIndexBuffer(QUAD_INDICES$6);
            _comp$1.actualFontSize = style.actualFontSize;
            _uiTrans.setContentSize(outputLayoutData.nodeContentSize);
            this.updateUVs(comp);
            if (_comp$1.renderEntity.colorDirty || isResized) {
              this.updateColor(comp);
              _comp$1.node._uiProps.colorDirty = false;
            }
            renderData.vertDirty = false;
            _comp$1 = null;
            this._resetProperties();
          }
          if (comp.spriteFrame) {
            var _renderData = comp.renderData;
            _renderData.updateRenderData(comp, comp.spriteFrame);
          }
        },
        updateUVs: function updateUVs(label) {
          var renderData = label.renderData;
          var vData = renderData.chunk.vb;
          var vertexCount = renderData.vertexCount;
          var dataList = renderData.data;
          var vertexOffset = 3;
          for (var i = 0; i < vertexCount; i++) {
            var vert = dataList[i];
            vData[vertexOffset] = vert.u;
            vData[vertexOffset + 1] = vert.v;
            vertexOffset += 9;
          }
        },
        updateColor: function updateColor(label) {
        },
        resetRenderData: function resetRenderData(comp) {
          var renderData = comp.renderData;
          renderData.dataLength = 0;
          renderData.resize(0, 0);
        },
        generateVertexData: function generateVertexData(style, outputLayoutData, outputRenderData, offset, spriteFrame, rect, rotated, x, y) {
          var dataOffset = offset;
          var scale = style.bmfontScale;
          var dataList = outputRenderData.vertexBuffer;
          var texW = spriteFrame.width;
          var texH = spriteFrame.height;
          var rectWidth = rect.width;
          var rectHeight = rect.height;
          var l = 0;
          var b = 0;
          var t = 0;
          var r = 0;
          if (!rotated) {
            l = rect.x / texW;
            r = (rect.x + rectWidth) / texW;
            b = (rect.y + rectHeight) / texH;
            t = rect.y / texH;
            dataList[dataOffset].u = l;
            dataList[dataOffset].v = b;
            dataList[dataOffset + 1].u = r;
            dataList[dataOffset + 1].v = b;
            dataList[dataOffset + 2].u = l;
            dataList[dataOffset + 2].v = t;
            dataList[dataOffset + 3].u = r;
            dataList[dataOffset + 3].v = t;
          } else {
            l = rect.x / texW;
            r = (rect.x + rectHeight) / texW;
            b = (rect.y + rectWidth) / texH;
            t = rect.y / texH;
            dataList[dataOffset].u = l;
            dataList[dataOffset].v = t;
            dataList[dataOffset + 1].u = l;
            dataList[dataOffset + 1].v = b;
            dataList[dataOffset + 2].u = r;
            dataList[dataOffset + 2].v = t;
            dataList[dataOffset + 3].u = r;
            dataList[dataOffset + 3].v = b;
          }
          dataList[dataOffset].x = x;
          dataList[dataOffset].y = y - rectHeight * scale;
          dataList[dataOffset + 1].x = x + rectWidth * scale;
          dataList[dataOffset + 1].y = y - rectHeight * scale;
          dataList[dataOffset + 2].x = x;
          dataList[dataOffset + 2].y = y;
          dataList[dataOffset + 3].x = x + rectWidth * scale;
          dataList[dataOffset + 3].y = y;
        },
        _updateFontFamily: function _updateFontFamily(comp) {
          var fontAsset = comp.font;
          _spriteFrame = fontAsset.spriteFrame;
          _fntConfig = fontAsset.fntConfig;
          shareLabelInfo.fontAtlas = fontAsset.fontDefDictionary;
          if (!shareLabelInfo.fontAtlas) {
            if (comp.cacheMode === CacheMode.CHAR) {
              shareLabelInfo.fontAtlas = _defaultLetterAtlas;
            } else {
              shareLabelInfo.fontAtlas = _defaultFontAtlas;
            }
          }
          dynamicAtlasManager.packToDynamicAtlas(comp, _spriteFrame);
        },
        _updateLabelInfo: function _updateLabelInfo(comp) {
          shareLabelInfo.hash = '';
          shareLabelInfo.margin = 0;
        },
        _resetProperties: function _resetProperties() {
          _fntConfig = null;
          _spriteFrame = null;
          shareLabelInfo.hash = '';
          shareLabelInfo.margin = 0;
        },
        createQuadIndices: function createQuadIndices(indexCount) {
          if (indexCount % 6 !== 0) {
            console.error('illegal index count!');
            return;
          }
          var quadCount = indexCount / 6;
          QUAD_INDICES$6 = null;
          QUAD_INDICES$6 = new Uint16Array(indexCount);
          var offset = 0;
          for (var i = 0; i < quadCount; i++) {
            QUAD_INDICES$6[offset++] = 0 + i * 4;
            QUAD_INDICES$6[offset++] = 1 + i * 4;
            QUAD_INDICES$6[offset++] = 2 + i * 4;
            QUAD_INDICES$6[offset++] = 1 + i * 4;
            QUAD_INDICES$6[offset++] = 3 + i * 4;
            QUAD_INDICES$6[offset++] = 2 + i * 4;
          }
        }
      };

      var tempColor$2 = new Color$1(255, 255, 255, 255);
      var bmfont = {
        createData: function createData(comp) {
          var renderData = comp.requestRenderData();
          renderData.resize(0, 0);
          return renderData;
        },
        fillBuffers: function fillBuffers(comp, renderer) {
          var node = comp.node;
          tempColor$2.set(comp.color);
          tempColor$2.a = node._uiProps.opacity * 255;
          fillMeshVertices3D(node, renderer, comp.renderData, tempColor$2);
        },
        appendQuad: function appendQuad(comp, spriteFrame, rect, rotated, x, y, scale) {
          var renderData = comp.renderData;
          if (!renderData) {
            return;
          }
          var dataOffset = renderData.dataLength;
          renderData.dataLength += 4;
          renderData.resize(renderData.dataLength, renderData.dataLength / 2 * 3);
          var dataList = renderData.data;
          var texW = spriteFrame.width;
          var texH = spriteFrame.height;
          var rectWidth = rect.width;
          var rectHeight = rect.height;
          var l = 0;
          var b = 0;
          var t = 0;
          var r = 0;
          if (!rotated) {
            l = rect.x / texW;
            r = (rect.x + rectWidth) / texW;
            b = (rect.y + rectHeight) / texH;
            t = rect.y / texH;
            dataList[dataOffset].u = l;
            dataList[dataOffset].v = b;
            dataList[dataOffset + 1].u = r;
            dataList[dataOffset + 1].v = b;
            dataList[dataOffset + 2].u = l;
            dataList[dataOffset + 2].v = t;
            dataList[dataOffset + 3].u = r;
            dataList[dataOffset + 3].v = t;
          } else {
            l = rect.x / texW;
            r = (rect.x + rectHeight) / texW;
            b = (rect.y + rectWidth) / texH;
            t = rect.y / texH;
            dataList[dataOffset].u = l;
            dataList[dataOffset].v = t;
            dataList[dataOffset + 1].u = l;
            dataList[dataOffset + 1].v = b;
            dataList[dataOffset + 2].u = r;
            dataList[dataOffset + 2].v = t;
            dataList[dataOffset + 3].u = r;
            dataList[dataOffset + 3].v = b;
          }
          dataList[dataOffset].x = x;
          dataList[dataOffset].y = y - rectHeight * scale;
          dataList[dataOffset + 1].x = x + rectWidth * scale;
          dataList[dataOffset + 1].y = y - rectHeight * scale;
          dataList[dataOffset + 2].x = x;
          dataList[dataOffset + 2].y = y;
          dataList[dataOffset + 3].x = x + rectWidth * scale;
          dataList[dataOffset + 3].y = y;
        }
      };
      addon(bmfont, bmfontUtils);

      var _atlasWidth = 1024;
      var _atlasHeight = 1024;
      var _shareAtlas = null;
      var letterFont = mixin(bmfontUtils, {
        getAssemblerData: function getAssemblerData() {
          if (!_shareAtlas) {
            _shareAtlas = new LetterAtlas(_atlasWidth, _atlasHeight);
          }
          return _shareAtlas.getTexture();
        },
        _updateFontFamily: function _updateFontFamily(comp) {
          shareLabelInfo.fontAtlas = _shareAtlas;
          shareLabelInfo.fontFamily = this._getFontFamily(comp);
          var isOutlined = comp.enableOutline && comp.outlineWidth > 0;
          if (isOutlined) {
            shareLabelInfo.isOutlined = true;
            shareLabelInfo.margin = comp.outlineWidth;
            shareLabelInfo.out = comp.outlineColor.clone();
            shareLabelInfo.out.a = comp.outlineColor.a * comp.color.a / 255.0;
          } else {
            shareLabelInfo.isOutlined = false;
            shareLabelInfo.margin = 0;
          }
        },
        _getFontFamily: function _getFontFamily(comp) {
          var fontFamily = 'Arial';
          if (!comp.useSystemFont) {
            if (comp.font) {
              fontFamily = comp.font._nativeAsset || 'Arial';
            }
          } else {
            fontFamily = comp.fontFamily || 'Arial';
          }
          return fontFamily;
        },
        _updateLabelInfo: function _updateLabelInfo(comp) {
          shareLabelInfo.fontDesc = this._getFontDesc();
          shareLabelInfo.color = comp.color;
          shareLabelInfo.hash = computeHash(shareLabelInfo);
        },
        _getFontDesc: function _getFontDesc() {
          var fontDesc = shareLabelInfo.fontSize.toString() + "px ";
          fontDesc += shareLabelInfo.fontFamily;
          return fontDesc;
        }
      });

      var tempColor$1 = new Color$1(255, 255, 255, 255);
      var letter = {
        createData: function createData(comp) {
          var renderData = comp.requestRenderData();
          renderData.resize(0, 0);
          return renderData;
        },
        fillBuffers: function fillBuffers(comp, renderer) {
          if (!comp.renderData) {
            return;
          }
          var node = comp.node;
          tempColor$1.a = node._uiProps.opacity * 255;
          fillMeshVertices3D(node, renderer, comp.renderData, tempColor$1);
        },
        updateColor: function updateColor(label) {
        }
      };
      addon(letter, letterFont);

      var Overflow = Label.Overflow;
      var ttfUtils = {
        updateProcessingData: function updateProcessingData(style, layout, outputLayoutData, outputRenderData, comp, trans) {
          style.isSystemFontUsed = comp.useSystemFont;
          style.fontSize = comp.fontSize;
          outputLayoutData.nodeContentSize.width = outputLayoutData.canvasSize.width = trans.width;
          outputLayoutData.nodeContentSize.height = outputLayoutData.canvasSize.height = trans.height;
          layout.lineHeight = comp.lineHeight;
          layout.overFlow = comp.overflow;
          if (comp.overflow === Overflow.NONE) {
            layout.wrapping = false;
          } else if (comp.overflow === Overflow.RESIZE_HEIGHT) {
            layout.wrapping = true;
          } else {
            layout.wrapping = comp.enableWrapText;
          }
          style.isBold = comp.isBold;
          style.isItalic = comp.isItalic;
          style.isUnderline = comp.isUnderline;
          style.underlineHeight = comp.underlineHeight;
          var isOutlined = comp.enableOutline && comp.outlineWidth > 0;
          if (isOutlined) {
            style.isOutlined = true;
            style.outlineColor.set(comp.outlineColor);
            style.outlineWidth = comp.outlineWidth;
          } else {
            style.isOutlined = false;
          }
          var isShadow = comp.enableShadow && (comp.shadowBlur > 0 || !approx(comp.shadowOffset.x, 0) || !approx(comp.shadowOffset.y, 0));
          if (isShadow) {
            style.hasShadow = true;
            style.shadowColor.set(comp.shadowColor);
            style.shadowBlur = comp.shadowBlur;
            style.shadowOffsetX = comp.shadowOffset.x;
            style.shadowOffsetY = comp.shadowOffset.y;
          } else {
            style.hasShadow = false;
          }
          style.color.set(comp.color);
          outputRenderData.texture = comp.spriteFrame;
          outputRenderData.uiTransAnchorX = trans.anchorX;
          outputRenderData.uiTransAnchorY = trans.anchorY;
          layout.horizontalAlign = comp.horizontalAlign;
          layout.verticalAlign = comp.verticalAlign;
        },
        getAssemblerData: function getAssemblerData() {
          var sharedLabelData = Label._canvasPool.get();
          sharedLabelData.canvas.width = sharedLabelData.canvas.height = 1;
          return sharedLabelData;
        },
        resetAssemblerData: function resetAssemblerData(assemblerData) {
          if (assemblerData) {
            Label._canvasPool.put(assemblerData);
          }
        },
        updateRenderData: function updateRenderData(comp) {
          if (!comp.renderData) {
            return;
          }
          if (comp.renderData.vertDirty) {
            var trans = comp.node._uiProps.uiTransformComp;
            var processing = TextProcessing.instance;
            var style = comp.textStyle;
            var layout = comp.textLayout;
            var outputLayoutData = comp.textLayoutData;
            var outputRenderData = comp.textRenderData;
            style.fontScale = view.getScaleX();
            this.updateProcessingData(style, layout, outputLayoutData, outputRenderData, comp, trans);
            processing.setCanvasUsed(comp.assemblerData.canvas, comp.assemblerData.context);
            style.fontFamily = this._updateFontFamily(comp);
            this._resetDynamicAtlas(comp);
            processing.processingString(false, style, layout, outputLayoutData, comp.string);
            processing.generateRenderInfo(false, style, layout, outputLayoutData, outputRenderData, comp.string, this.generateVertexData);
            var renderData = comp.renderData;
            renderData.textureDirty = true;
            this._calDynamicAtlas(comp, outputLayoutData);
            comp.actualFontSize = style.actualFontSize;
            trans.setContentSize(outputLayoutData.nodeContentSize);
            var datalist = renderData.data;
            datalist[0] = outputRenderData.vertexBuffer[0];
            datalist[1] = outputRenderData.vertexBuffer[1];
            datalist[2] = outputRenderData.vertexBuffer[2];
            datalist[3] = outputRenderData.vertexBuffer[3];
            this.updateUVs(comp);
            comp.renderData.vertDirty = false;
            comp.contentWidth = outputLayoutData.nodeContentSize.width;
          }
          if (comp.spriteFrame) {
            var _renderData = comp.renderData;
            _renderData.updateRenderData(comp, comp.spriteFrame);
          }
        },
        generateVertexData: function generateVertexData(style, outputLayoutData, outputRenderData) {
          var data = outputRenderData.vertexBuffer;
          var width = outputLayoutData.nodeContentSize.width;
          var height = outputLayoutData.nodeContentSize.height;
          var appX = outputRenderData.uiTransAnchorX * width;
          var appY = outputRenderData.uiTransAnchorY * height;
          data[0].x = -appX;
          data[0].y = -appY;
          data[1].x = width - appX;
          data[1].y = -appY;
          data[2].x = -appX;
          data[2].y = height - appY;
          data[3].x = width - appX;
          data[3].y = height - appY;
        },
        updateVertexData: function updateVertexData(comp) {},
        updateUVs: function updateUVs(comp) {},
        _updateFontFamily: function _updateFontFamily(comp) {
          var _fontFamily = '';
          if (!comp.useSystemFont) {
            if (comp.font) {
              _fontFamily = comp.font._nativeAsset || 'Arial';
            } else {
              _fontFamily = 'Arial';
            }
          } else {
            _fontFamily = comp.fontFamily || 'Arial';
          }
          return _fontFamily;
        },
        _calDynamicAtlas: function _calDynamicAtlas(comp, outputLayoutData) {
          if (comp.cacheMode !== Label.CacheMode.BITMAP || outputLayoutData.canvasSize.width <= 0 || outputLayoutData.canvasSize.height <= 0) return;
          var frame = comp.ttfSpriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(comp, frame);
        },
        _resetDynamicAtlas: function _resetDynamicAtlas(comp) {
          if (comp.cacheMode !== Label.CacheMode.BITMAP) return;
          var frame = comp.ttfSpriteFrame;
          dynamicAtlasManager.deleteAtlasSpriteFrame(frame);
          frame._resetDynamicAtlasFrame();
        }
      };

      var WHITE = Color$1.WHITE.clone();
      var QUAD_INDICES$5 = Uint16Array.from([0, 1, 2, 1, 3, 2]);
      var ttf = {
        createData: function createData(comp) {
          var renderData = comp.requestRenderData();
          renderData.dataLength = 4;
          renderData.resize(4, 6);
          comp.textRenderData.quadCount = 4;
          var vData = renderData.chunk.vb;
          vData[3] = vData[21] = vData[22] = vData[31] = 0;
          vData[4] = vData[12] = vData[13] = vData[30] = 1;
          var offset = 5;
          for (var i = 0; i < 4; i++) {
            Color$1.toArray(vData, WHITE, offset);
            offset += 9;
          }
          renderData.chunk.setIndexBuffer(QUAD_INDICES$5);
          return renderData;
        },
        fillBuffers: function fillBuffers(comp, renderer) {
          var renderData = comp.renderData;
          var chunk = renderData.chunk;
          var dataList = renderData.data;
          var node = comp.node;
          var vData = chunk.vb;
          var m = node.worldMatrix;
          var stride = renderData.floatStride;
          var offset = 0;
          var length = dataList.length;
          for (var i = 0; i < length; i++) {
            var curData = dataList[i];
            var x = curData.x;
            var y = curData.y;
            var rhw = m.m03 * x + m.m07 * y + m.m15;
            rhw = rhw ? 1 / rhw : 1;
            offset = i * stride;
            vData[offset + 0] = (m.m00 * x + m.m04 * y + m.m12) * rhw;
            vData[offset + 1] = (m.m01 * x + m.m05 * y + m.m13) * rhw;
            vData[offset + 2] = (m.m02 * x + m.m06 * y + m.m14) * rhw;
          }
          var vid = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          ib[indexOffset++] = vid;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 2;
          ib[indexOffset++] = vid + 2;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 3;
          meshBuffer.indexOffset += 6;
        },
        updateVertexData: function updateVertexData(comp) {
          var renderData = comp.renderData;
          if (!renderData) {
            return;
          }
          var uiTrans = comp.node._uiProps.uiTransformComp;
          var width = uiTrans.width;
          var height = uiTrans.height;
          var appX = uiTrans.anchorX * width;
          var appY = uiTrans.anchorY * height;
          var data = renderData.data;
          data[0].x = -appX;
          data[0].y = -appY;
          data[1].x = width - appX;
          data[1].y = -appY;
          data[2].x = -appX;
          data[2].y = height - appY;
          data[3].x = width - appX;
          data[3].y = height - appY;
        },
        updateUVs: function updateUVs(comp) {
          var renderData = comp.renderData;
          if (!renderData || !comp.ttfSpriteFrame) {
            return;
          }
          var vData = renderData.chunk.vb;
          var uv = comp.ttfSpriteFrame.uv;
          vData[3] = uv[0];
          vData[4] = uv[1];
          vData[12] = uv[2];
          vData[13] = uv[3];
          vData[21] = uv[4];
          vData[22] = uv[5];
          vData[30] = uv[6];
          vData[31] = uv[7];
        },
        updateColor: function updateColor(comp) {}
      };
      addon(ttf, ttfUtils);

      var labelAssembler = exports('l', {
        getAssembler: function getAssembler(comp) {
          var assembler = ttf;
          if (comp.font instanceof BitmapFont) {
            assembler = bmfont;
          } else if (comp.cacheMode === Label.CacheMode.CHAR) {
            assembler = letter;
          }
          return assembler;
        }
      });
      Label.Assembler = labelAssembler;

      var FillType$1 = Sprite.FillType;
      var m$3 = new Mat4();
      var QUAD_INDICES$4 = Uint16Array.from([0, 1, 2, 1, 3, 2]);
      var barFilled = {
        updateRenderData: function updateRenderData(sprite) {
          var frame = sprite.spriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
          var renderData = sprite.renderData;
          if (renderData && frame) {
            var vertDirty = renderData.vertDirty;
            if (!vertDirty) {
              return;
            }
            var fillStart = sprite.fillStart;
            var fillRange = sprite.fillRange;
            if (fillRange < 0) {
              fillStart += fillRange;
              fillRange = -fillRange;
            }
            fillRange = fillStart + fillRange;
            fillStart = fillStart > 1.0 ? 1.0 : fillStart;
            fillStart = fillStart < 0.0 ? 0.0 : fillStart;
            fillRange = fillRange > 1.0 ? 1.0 : fillRange;
            fillRange = fillRange < 0.0 ? 0.0 : fillRange;
            fillRange -= fillStart;
            fillRange = fillRange < 0 ? 0 : fillRange;
            var fillEnd = fillStart + fillRange;
            fillEnd = fillEnd > 1 ? 1 : fillEnd;
            this.updateUVs(sprite, fillStart, fillEnd);
            this.updateVertexData(sprite, fillStart, fillEnd);
            renderData.updateRenderData(sprite, frame);
          }
        },
        updateUVs: function updateUVs(sprite, fillStart, fillEnd) {
          var spriteFrame = sprite.spriteFrame;
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var atlasWidth = spriteFrame.width;
          var atlasHeight = spriteFrame.height;
          var textureRect = spriteFrame.rect;
          var ul = 0;
          var vb = 0;
          var ur = 0;
          var vt = 0;
          var quadUV0 = 0;
          var quadUV1 = 0;
          var quadUV2 = 0;
          var quadUV3 = 0;
          var quadUV4 = 0;
          var quadUV5 = 0;
          var quadUV6 = 0;
          var quadUV7 = 0;
          if (spriteFrame.isRotated()) {
            ul = textureRect.x / atlasWidth;
            vb = (textureRect.y + textureRect.width) / atlasHeight;
            ur = (textureRect.x + textureRect.height) / atlasWidth;
            vt = textureRect.y / atlasHeight;
            quadUV0 = quadUV2 = ul;
            quadUV4 = quadUV6 = ur;
            quadUV3 = quadUV7 = vb;
            quadUV1 = quadUV5 = vt;
          } else {
            ul = textureRect.x / atlasWidth;
            vb = (textureRect.y + textureRect.height) / atlasHeight;
            ur = (textureRect.x + textureRect.width) / atlasWidth;
            vt = textureRect.y / atlasHeight;
            quadUV0 = quadUV4 = ul;
            quadUV2 = quadUV6 = ur;
            quadUV1 = quadUV3 = vb;
            quadUV5 = quadUV7 = vt;
          }
          switch (sprite.fillType) {
            case FillType$1.HORIZONTAL:
              vData[3] = quadUV0 + (quadUV2 - quadUV0) * fillStart;
              vData[4] = quadUV1 + (quadUV3 - quadUV1) * fillStart;
              vData[12] = quadUV0 + (quadUV2 - quadUV0) * fillEnd;
              vData[13] = quadUV1 + (quadUV3 - quadUV1) * fillEnd;
              vData[21] = quadUV4 + (quadUV6 - quadUV4) * fillStart;
              vData[22] = quadUV5 + (quadUV7 - quadUV5) * fillStart;
              vData[30] = quadUV4 + (quadUV6 - quadUV4) * fillEnd;
              vData[31] = quadUV5 + (quadUV7 - quadUV5) * fillEnd;
              break;
            case FillType$1.VERTICAL:
              vData[3] = quadUV0 + (quadUV4 - quadUV0) * fillStart;
              vData[4] = quadUV1 + (quadUV5 - quadUV1) * fillStart;
              vData[12] = quadUV2 + (quadUV6 - quadUV2) * fillStart;
              vData[13] = quadUV3 + (quadUV7 - quadUV3) * fillStart;
              vData[21] = quadUV0 + (quadUV4 - quadUV0) * fillEnd;
              vData[22] = quadUV1 + (quadUV5 - quadUV1) * fillEnd;
              vData[30] = quadUV2 + (quadUV6 - quadUV2) * fillEnd;
              vData[31] = quadUV3 + (quadUV7 - quadUV3) * fillEnd;
              break;
            default:
              errorID(2626);
              break;
          }
        },
        updateVertexData: function updateVertexData(sprite, fillStart, fillEnd) {
          var renderData = sprite.renderData;
          var dataList = renderData.data;
          var uiTrans = sprite.node._uiProps.uiTransformComp;
          var width = uiTrans.width;
          var height = uiTrans.height;
          var appX = uiTrans.anchorX * width;
          var appY = uiTrans.anchorY * height;
          var l = -appX;
          var b = -appY;
          var r = width - appX;
          var t = height - appY;
          var progressStart = 0;
          var progressEnd = 0;
          switch (sprite.fillType) {
            case FillType$1.HORIZONTAL:
              progressStart = l + (r - l) * fillStart;
              progressEnd = l + (r - l) * fillEnd;
              l = progressStart;
              r = progressEnd;
              break;
            case FillType$1.VERTICAL:
              progressStart = b + (t - b) * fillStart;
              progressEnd = b + (t - b) * fillEnd;
              b = progressStart;
              t = progressEnd;
              break;
            default:
              errorID(2626);
              break;
          }
          dataList[0].x = l;
          dataList[0].y = b;
          dataList[1].x = r;
          dataList[1].y = b;
          dataList[2].x = l;
          dataList[2].y = t;
          dataList[3].x = r;
          dataList[3].y = t;
        },
        createData: function createData(sprite) {
          var renderData = sprite.requestRenderData();
          renderData.dataLength = 4;
          renderData.resize(4, 6);
          renderData.chunk.setIndexBuffer(QUAD_INDICES$4);
          var dataList = renderData.data;
          for (var _iterator = _createForOfIteratorHelperLoose(dataList), _step; !(_step = _iterator()).done;) {
            var data = _step.value;
            data.z = 0;
          }
          return renderData;
        },
        updateWorldVertexData: function updateWorldVertexData(sprite, chunk) {
          var node = sprite.node;
          node.getWorldMatrix(m$3);
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = sprite.renderData.data;
          var vData = chunk.vb;
          var offset = 0;
          for (var i = 0; i < 4; i++) {
            var local = dataList[i];
            var x = local.x;
            var y = local.y;
            var rhw = m$3.m03 * x + m$3.m07 * y + m$3.m15;
            rhw = rhw ? 1 / rhw : 1;
            offset = i * stride;
            vData[offset] = (m$3.m00 * x + m$3.m04 * y + m$3.m12) * rhw;
            vData[offset + 1] = (m$3.m01 * x + m$3.m05 * y + m$3.m13) * rhw;
            vData[offset + 2] = (m$3.m02 * x + m$3.m06 * y + m$3.m14) * rhw;
          }
        },
        fillBuffers: function fillBuffers(sprite, renderer) {
          var renderData = sprite.renderData;
          var chunk = renderData.chunk;
          if (sprite._flagChangedVersion !== sprite.node.flagChangedVersion || renderData.vertDirty) {
            this.updateWorldVertexData(sprite, chunk);
            renderData.vertDirty = false;
            sprite._flagChangedVersion = sprite.node.flagChangedVersion;
          }
          chunk.bufferId;
          var vid = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          ib[indexOffset++] = vid;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 2;
          ib[indexOffset++] = vid + 2;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 3;
          meshBuffer.indexOffset += 6;
        },
        updateColor: function updateColor(sprite) {
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var stride = renderData.floatStride;
          var colorOffset = 5;
          var color = sprite.color;
          var colorR = color.r / 255;
          var colorG = color.g / 255;
          var colorB = color.b / 255;
          var colorA = sprite.node._uiProps.opacity;
          for (var i = 0; i < 4; i++) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
            colorOffset += stride;
          }
        }
      };

      var PI_2 = Math.PI * 2;
      var EPSILON$1 = 1e-6;
      var m$2 = new Mat4();
      var _vertPos = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
      var _vertices$1 = new Array(4);
      var _uvs$2 = new Array(8);
      var _intersectPoint_1 = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
      var _intersectPoint_2 = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
      var _center = new Vec2();
      var _triangles = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
      var QUAD_INDICES$3 = null;
      function _calcIntersectedPoints(left, right, bottom, top, center, angle, intersectPoints) {
        var sinAngle = Math.sin(angle);
        sinAngle = Math.abs(sinAngle) > EPSILON$1 ? sinAngle : 0;
        var cosAngle = Math.cos(angle);
        cosAngle = Math.abs(cosAngle) > EPSILON$1 ? cosAngle : 0;
        var tanAngle = 0;
        var cotAngle = 0;
        if (cosAngle !== 0) {
          tanAngle = sinAngle / cosAngle;
          if ((left - center.x) * cosAngle > 0) {
            var yLeft = center.y + tanAngle * (left - center.x);
            intersectPoints[0].x = left;
            intersectPoints[0].y = yLeft;
          }
          if ((right - center.x) * cosAngle > 0) {
            var yRight = center.y + tanAngle * (right - center.x);
            intersectPoints[2].x = right;
            intersectPoints[2].y = yRight;
          }
        }
        if (sinAngle !== 0) {
          cotAngle = cosAngle / sinAngle;
          if ((top - center.y) * sinAngle > 0) {
            var xTop = center.x + cotAngle * (top - center.y);
            intersectPoints[3].x = xTop;
            intersectPoints[3].y = top;
          }
          if ((bottom - center.y) * sinAngle > 0) {
            var xBottom = center.x + cotAngle * (bottom - center.y);
            intersectPoints[1].x = xBottom;
            intersectPoints[1].y = bottom;
          }
        }
      }
      function _calculateVertices(sprite) {
        var uiTrans = sprite.node._uiProps.uiTransformComp;
        var width = uiTrans.width;
        var height = uiTrans.height;
        var appX = uiTrans.anchorX * width;
        var appY = uiTrans.anchorY * height;
        var l = -appX;
        var b = -appY;
        var r = width - appX;
        var t = height - appY;
        var vertices = _vertices$1;
        vertices[0] = l;
        vertices[1] = b;
        vertices[2] = r;
        vertices[3] = t;
        var fillCenter = sprite.fillCenter;
        var cx = _center.x = Math.min(Math.max(0, fillCenter.x), 1) * (r - l) + l;
        var cy = _center.y = Math.min(Math.max(0, fillCenter.y), 1) * (t - b) + b;
        _vertPos[0].x = _vertPos[3].x = l;
        _vertPos[1].x = _vertPos[2].x = r;
        _vertPos[0].y = _vertPos[1].y = b;
        _vertPos[2].y = _vertPos[3].y = t;
        for (var _i = 0, _triangles2 = _triangles; _i < _triangles2.length; _i++) {
          var num = _triangles2[_i];
          Vec2.set(num, 0, 0);
        }
        if (cx !== vertices[0]) {
          Vec2.set(_triangles[0], 3, 0);
        }
        if (cx !== vertices[2]) {
          Vec2.set(_triangles[2], 1, 2);
        }
        if (cy !== vertices[1]) {
          Vec2.set(_triangles[1], 0, 1);
        }
        if (cy !== vertices[3]) {
          Vec2.set(_triangles[3], 2, 3);
        }
      }
      function _calculateUVs(spriteFrame) {
        var atlasWidth = spriteFrame.width;
        var atlasHeight = spriteFrame.height;
        var textureRect = spriteFrame.getRect();
        var u0 = 0;
        var u1 = 0;
        var v0 = 0;
        var v1 = 0;
        var uvs = _uvs$2;
        if (spriteFrame.isRotated()) {
          u0 = textureRect.x / atlasWidth;
          u1 = (textureRect.x + textureRect.height) / atlasWidth;
          v0 = textureRect.y / atlasHeight;
          v1 = (textureRect.y + textureRect.width) / atlasHeight;
          uvs[0] = uvs[2] = u0;
          uvs[4] = uvs[6] = u1;
          uvs[3] = uvs[7] = v1;
          uvs[1] = uvs[5] = v0;
        } else {
          u0 = textureRect.x / atlasWidth;
          u1 = (textureRect.x + textureRect.width) / atlasWidth;
          v0 = textureRect.y / atlasHeight;
          v1 = (textureRect.y + textureRect.height) / atlasHeight;
          uvs[0] = uvs[4] = u0;
          uvs[2] = uvs[6] = u1;
          uvs[1] = uvs[3] = v1;
          uvs[5] = uvs[7] = v0;
        }
      }
      function _getVertAngle(start, end) {
        var placementX = end.x - start.x;
        var placementY = end.y - start.y;
        if (placementX === 0 && placementY === 0) {
          return 0;
        } else if (placementX === 0) {
          if (placementY > 0) {
            return Math.PI * 0.5;
          } else {
            return Math.PI * 1.5;
          }
        } else {
          var angle = Math.atan(placementY / placementX);
          if (placementX < 0) {
            angle += Math.PI;
          }
          return angle;
        }
      }
      function _generateTriangle(dataList, offset, vert0, vert1, vert2) {
        var vertices = _vertices$1;
        var v0x = vertices[0];
        var v0y = vertices[1];
        var v1x = vertices[2];
        var v1y = vertices[3];
        dataList[offset].x = vert0.x;
        dataList[offset].y = vert0.y;
        dataList[offset + 1].x = vert1.x;
        dataList[offset + 1].y = vert1.y;
        dataList[offset + 2].x = vert2.x;
        dataList[offset + 2].y = vert2.y;
        var progressX = 0;
        var progressY = 0;
        progressX = (vert0.x - v0x) / (v1x - v0x);
        progressY = (vert0.y - v0y) / (v1y - v0y);
        _generateUV(progressX, progressY, dataList, offset);
        progressX = (vert1.x - v0x) / (v1x - v0x);
        progressY = (vert1.y - v0y) / (v1y - v0y);
        _generateUV(progressX, progressY, dataList, offset + 1);
        progressX = (vert2.x - v0x) / (v1x - v0x);
        progressY = (vert2.y - v0y) / (v1y - v0y);
        _generateUV(progressX, progressY, dataList, offset + 2);
      }
      function _generateUV(progressX, progressY, data, offset) {
        var uvs = _uvs$2;
        var px1 = uvs[0] + (uvs[2] - uvs[0]) * progressX;
        var px2 = uvs[4] + (uvs[6] - uvs[4]) * progressX;
        var py1 = uvs[1] + (uvs[3] - uvs[1]) * progressX;
        var py2 = uvs[5] + (uvs[7] - uvs[5]) * progressX;
        var uv = data[offset];
        uv.u = px1 + (px2 - px1) * progressY;
        uv.v = py1 + (py2 - py1) * progressY;
      }
      var radialFilled = {
        useModel: false,
        createData: function createData(sprite) {
          return sprite.requestRenderData();
        },
        updateRenderData: function updateRenderData(sprite) {
          var frame = sprite.spriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
          this.updateUVs(sprite);
          var renderData = sprite.renderData;
          if (renderData && frame) {
            if (!renderData.vertDirty) {
              return;
            }
            var dataList = renderData.data;
            var fillStart = sprite.fillStart;
            var fillRange = sprite.fillRange;
            if (fillRange < 0) {
              fillStart += fillRange;
              fillRange = -fillRange;
            }
            while (fillStart >= 1.0) {
              fillStart -= 1.0;
            }
            while (fillStart < 0.0) {
              fillStart += 1.0;
            }
            fillStart *= PI_2;
            fillRange *= PI_2;
            var fillEnd = fillStart + fillRange;
            _calculateVertices(sprite);
            _calculateUVs(frame);
            _calcIntersectedPoints(_vertices$1[0], _vertices$1[2], _vertices$1[1], _vertices$1[3], _center, fillStart, _intersectPoint_1);
            _calcIntersectedPoints(_vertices$1[0], _vertices$1[2], _vertices$1[1], _vertices$1[3], _center, fillStart + fillRange, _intersectPoint_2);
            var offset = 0;
            for (var triangleIndex = 0; triangleIndex < 4; ++triangleIndex) {
              var triangle = _triangles[triangleIndex];
              if (!triangle) {
                continue;
              }
              if (fillRange >= PI_2) {
                renderData.dataLength = offset + 3;
                _generateTriangle(dataList, offset, _center, _vertPos[triangle.x], _vertPos[triangle.y]);
                offset += 3;
                continue;
              }
              var startAngle = _getVertAngle(_center, _vertPos[triangle.x]);
              var endAngle = _getVertAngle(_center, _vertPos[triangle.y]);
              if (endAngle < startAngle) {
                endAngle += PI_2;
              }
              startAngle -= PI_2;
              endAngle -= PI_2;
              for (var testIndex = 0; testIndex < 3; ++testIndex) {
                if (startAngle >= fillEnd) ; else if (startAngle >= fillStart) {
                  renderData.dataLength = offset + 3;
                  if (endAngle >= fillEnd) {
                    _generateTriangle(dataList, offset, _center, _vertPos[triangle.x], _intersectPoint_2[triangleIndex]);
                  } else {
                    _generateTriangle(dataList, offset, _center, _vertPos[triangle.x], _vertPos[triangle.y]);
                  }
                  offset += 3;
                } else if (endAngle > fillStart) {
                  if (endAngle <= fillEnd) {
                    renderData.dataLength = offset + 3;
                    _generateTriangle(dataList, offset, _center, _intersectPoint_1[triangleIndex], _vertPos[triangle.y]);
                    offset += 3;
                  } else {
                    renderData.dataLength = offset + 3;
                    _generateTriangle(dataList, offset, _center, _intersectPoint_1[triangleIndex], _intersectPoint_2[triangleIndex]);
                    offset += 3;
                  }
                }
                startAngle += PI_2;
                endAngle += PI_2;
              }
            }
            if (offset === 0) {
              renderData.dataLength = 0;
            }
            renderData.resize(offset, offset);
            renderData.updateRenderData(sprite, frame);
          }
        },
        createQuadIndices: function createQuadIndices(indexCount) {
          QUAD_INDICES$3 = null;
          QUAD_INDICES$3 = new Uint16Array(indexCount);
          var offset = 0;
          for (var i = 0; i < indexCount; i++) {
            QUAD_INDICES$3[offset++] = i;
          }
        },
        fillBuffers: function fillBuffers(comp, renderer) {
          var node = comp.node;
          var renderData = comp.renderData;
          var chunk = renderData.chunk;
          if (comp._flagChangedVersion !== node.flagChangedVersion || renderData.vertDirty) {
            this.updateWorldVertexAndUVData(comp, chunk);
            renderData.vertDirty = false;
            comp._flagChangedVersion = node.flagChangedVersion;
          }
          this.updateColorLate(comp);
          chunk.bufferId;
          var vid = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          for (var i = 0; i < renderData.indexCount; i++) {
            ib[indexOffset + i] = vid + i;
          }
          meshBuffer.indexOffset += renderData.indexCount;
          meshBuffer.setDirty();
        },
        updateWorldUVData: function updateWorldUVData(sprite, chunk) {
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = renderData.data;
          var vData = renderData.chunk.vb;
          for (var i = 0; i < dataList.length; i++) {
            var offset = i * stride;
            vData[offset + 3] = dataList[i].u;
            vData[offset + 4] = dataList[i].v;
          }
        },
        updateWorldVertexAndUVData: function updateWorldVertexAndUVData(sprite, chunk) {
          var node = sprite.node;
          node.getWorldMatrix(m$2);
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = sprite.renderData.data;
          var vData = chunk.vb;
          var vertexCount = renderData.vertexCount;
          var vertexOffset = 0;
          for (var i = 0; i < vertexCount; i++) {
            var vert = dataList[i];
            var x = vert.x;
            var y = vert.y;
            var rhw = m$2.m03 * x + m$2.m07 * y + m$2.m15;
            rhw = rhw ? 1 / rhw : 1;
            vData[vertexOffset + 0] = (m$2.m00 * x + m$2.m04 * y + m$2.m12) * rhw;
            vData[vertexOffset + 1] = (m$2.m01 * x + m$2.m05 * y + m$2.m13) * rhw;
            vData[vertexOffset + 2] = (m$2.m02 * x + m$2.m06 * y + m$2.m14) * rhw;
            vData[vertexOffset + 3] = vert.u;
            vData[vertexOffset + 4] = vert.v;
            vertexOffset += stride;
          }
        },
        updateUVs: function updateUVs(sprite) {
          var renderData = sprite.renderData;
          renderData.vertDirty = true;
          sprite.markForUpdateRenderData();
        },
        updateColorLate: function updateColorLate(sprite) {
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var stride = renderData.floatStride;
          var vertexCount = renderData.vertexCount;
          var colorOffset = 5;
          var color = sprite.color;
          var colorR = color.r / 255;
          var colorG = color.g / 255;
          var colorB = color.b / 255;
          var colorA = sprite.node._uiProps.opacity;
          for (var i = 0; i < vertexCount; i++) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
            colorOffset += stride;
          }
        },
        updateColor: function updateColor(sprite) {}
      };

      var QUAD_INDICES$2 = Uint16Array.from([0, 1, 2, 1, 3, 2]);
      var simple$3 = {
        createData: function createData(sprite) {
          var renderData = sprite.requestRenderData();
          renderData.dataLength = 4;
          renderData.resize(4, 6);
          renderData.chunk.setIndexBuffer(QUAD_INDICES$2);
          return renderData;
        },
        updateRenderData: function updateRenderData(sprite) {
          var frame = sprite.spriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
          this.updateUVs(sprite);
          var renderData = sprite.renderData;
          if (renderData && frame) {
            if (renderData.vertDirty) {
              this.updateVertexData(sprite);
            }
            renderData.updateRenderData(sprite, frame);
          }
        },
        updateWorldVerts: function updateWorldVerts(sprite, chunk) {
          var renderData = sprite.renderData;
          var vData = chunk.vb;
          var dataList = renderData.data;
          var node = sprite.node;
          var m = node.worldMatrix;
          var stride = renderData.floatStride;
          var offset = 0;
          var length = dataList.length;
          for (var i = 0; i < length; i++) {
            var curData = dataList[i];
            var x = curData.x;
            var y = curData.y;
            var rhw = m.m03 * x + m.m07 * y + m.m15;
            rhw = rhw ? 1 / rhw : 1;
            offset = i * stride;
            vData[offset + 0] = (m.m00 * x + m.m04 * y + m.m12) * rhw;
            vData[offset + 1] = (m.m01 * x + m.m05 * y + m.m13) * rhw;
            vData[offset + 2] = (m.m02 * x + m.m06 * y + m.m14) * rhw;
          }
        },
        fillBuffers: function fillBuffers(sprite, renderer) {
          if (sprite === null) {
            return;
          }
          var renderData = sprite.renderData;
          var chunk = renderData.chunk;
          if (sprite._flagChangedVersion !== sprite.node.flagChangedVersion || renderData.vertDirty) {
            this.updateWorldVerts(sprite, chunk);
            renderData.vertDirty = false;
            sprite._flagChangedVersion = sprite.node.flagChangedVersion;
          }
          var vidOrigin = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          var vid = vidOrigin;
          ib[indexOffset++] = vid;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 2;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 3;
          ib[indexOffset++] = vid + 2;
          meshBuffer.indexOffset += 6;
        },
        updateVertexData: function updateVertexData(sprite) {
          var renderData = sprite.renderData;
          if (!renderData) {
            return;
          }
          var uiTrans = sprite.node._uiProps.uiTransformComp;
          var dataList = renderData.data;
          var cw = uiTrans.width;
          var ch = uiTrans.height;
          var appX = uiTrans.anchorX * cw;
          var appY = uiTrans.anchorY * ch;
          var l = 0;
          var b = 0;
          var r = 0;
          var t = 0;
          if (sprite.trim) {
            l = -appX;
            b = -appY;
            r = cw - appX;
            t = ch - appY;
          } else {
            var frame = sprite.spriteFrame;
            var originSize = frame.originalSize;
            var ow = originSize.width;
            var oh = originSize.height;
            var scaleX = cw / ow;
            var scaleY = ch / oh;
            var trimmedBorder = frame.trimmedBorder;
            l = trimmedBorder.x * scaleX - appX;
            b = trimmedBorder.z * scaleY - appY;
            r = cw + trimmedBorder.y * scaleX - appX;
            t = ch + trimmedBorder.w * scaleY - appY;
          }
          dataList[0].x = l;
          dataList[0].y = b;
          dataList[1].x = r;
          dataList[1].y = b;
          dataList[2].x = l;
          dataList[2].y = t;
          dataList[3].x = r;
          dataList[3].y = t;
          renderData.vertDirty = true;
        },
        updateUVs: function updateUVs(sprite) {
          if (!sprite.spriteFrame) return;
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var uv = sprite.spriteFrame.uv;
          vData[3] = uv[0];
          vData[4] = uv[1];
          vData[12] = uv[2];
          vData[13] = uv[3];
          vData[21] = uv[4];
          vData[22] = uv[5];
          vData[30] = uv[6];
          vData[31] = uv[7];
        },
        updateColor: function updateColor(sprite) {
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var colorOffset = 5;
          var color = sprite.color;
          var colorR = color.r / 255;
          var colorG = color.g / 255;
          var colorB = color.b / 255;
          var colorA = color.a / 255;
          for (var i = 0; i < 4; i++, colorOffset += renderData.floatStride) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
          }
        }
      };

      var m$1 = new Mat4();
      var tempRenderData$1 = [];
      for (var i$2 = 0; i$2 < 4; i$2++) {
        tempRenderData$1.push({
          x: 0,
          y: 0,
          z: 0,
          u: 0,
          v: 0,
          color: new Color$1()
        });
      }
      var sliced = {
        createData: function createData(sprite) {
          var renderData = sprite.requestRenderData();
          renderData.dataLength = 16;
          renderData.resize(16, 54);
          this.QUAD_INDICES = new Uint16Array(54);
          this.createQuadIndices(4, 4);
          renderData.chunk.setIndexBuffer(this.QUAD_INDICES);
          return renderData;
        },
        createQuadIndices: function createQuadIndices(vertexRow, vertexCol) {
          var offset = 0;
          for (var curRow = 0; curRow < vertexRow - 1; curRow++) {
            for (var curCol = 0; curCol < vertexCol - 1; curCol++) {
              var vid = curRow * vertexCol + curCol;
              this.QUAD_INDICES[offset++] = vid;
              this.QUAD_INDICES[offset++] = vid + 1;
              this.QUAD_INDICES[offset++] = vid + vertexCol;
              this.QUAD_INDICES[offset++] = vid + 1;
              this.QUAD_INDICES[offset++] = vid + 1 + vertexCol;
              this.QUAD_INDICES[offset++] = vid + vertexCol;
            }
          }
        },
        updateRenderData: function updateRenderData(sprite) {
          var frame = sprite.spriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
          this.updateUVs(sprite);
          var renderData = sprite.renderData;
          if (renderData && frame) {
            var vertDirty = renderData.vertDirty;
            if (vertDirty) {
              this.updateVertexData(sprite);
            }
            renderData.updateRenderData(sprite, frame);
          }
        },
        updateVertexData: function updateVertexData(sprite) {
          var renderData = sprite.renderData;
          var dataList = renderData.data;
          var uiTrans = sprite.node._uiProps.uiTransformComp;
          var width = uiTrans.width;
          var height = uiTrans.height;
          var appX = uiTrans.anchorX * width;
          var appY = uiTrans.anchorY * height;
          var frame = sprite.spriteFrame;
          var leftWidth = frame.insetLeft;
          var rightWidth = frame.insetRight;
          var topHeight = frame.insetTop;
          var bottomHeight = frame.insetBottom;
          var sizableWidth = width - leftWidth - rightWidth;
          var sizableHeight = height - topHeight - bottomHeight;
          var xScale = width / (leftWidth + rightWidth);
          var yScale = height / (topHeight + bottomHeight);
          xScale = Number.isNaN(xScale) || xScale > 1 ? 1 : xScale;
          yScale = Number.isNaN(yScale) || yScale > 1 ? 1 : yScale;
          sizableWidth = sizableWidth < 0 ? 0 : sizableWidth;
          sizableHeight = sizableHeight < 0 ? 0 : sizableHeight;
          tempRenderData$1[0].x = -appX;
          tempRenderData$1[0].y = -appY;
          tempRenderData$1[1].x = leftWidth * xScale - appX;
          tempRenderData$1[1].y = bottomHeight * yScale - appY;
          tempRenderData$1[2].x = tempRenderData$1[1].x + sizableWidth;
          tempRenderData$1[2].y = tempRenderData$1[1].y + sizableHeight;
          tempRenderData$1[3].x = width - appX;
          tempRenderData$1[3].y = height - appY;
          for (var curRow = 0; curRow < 4; curRow++) {
            for (var curCol = 0; curCol < 4; curCol++) {
              var curIndex = curRow * 4 + curCol;
              if (curIndex < renderData.dataLength && curRow < tempRenderData$1.length && curCol < tempRenderData$1.length) {
                dataList[curIndex].x = tempRenderData$1[curCol].x;
                dataList[curIndex].y = tempRenderData$1[curRow].y;
              }
            }
          }
        },
        fillBuffers: function fillBuffers(sprite, renderer) {
          var renderData = sprite.renderData;
          var chunk = renderData.chunk;
          if (sprite._flagChangedVersion !== sprite.node.flagChangedVersion || renderData.vertDirty) {
            this.updateWorldVertexData(sprite, chunk);
            renderData.vertDirty = false;
            sprite._flagChangedVersion = sprite.node.flagChangedVersion;
          }
          chunk.bufferId;
          var vid = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          for (var r = 0; r < 3; ++r) {
            for (var c = 0; c < 3; ++c) {
              var start = vid + r * 4 + c;
              ib[indexOffset++] = start;
              ib[indexOffset++] = start + 1;
              ib[indexOffset++] = start + 4;
              ib[indexOffset++] = start + 1;
              ib[indexOffset++] = start + 5;
              ib[indexOffset++] = start + 4;
            }
          }
          meshBuffer.indexOffset = indexOffset;
        },
        updateWorldVertexData: function updateWorldVertexData(sprite, chunk) {
          var node = sprite.node;
          node.getWorldMatrix(m$1);
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = renderData.data;
          var vData = chunk.vb;
          var offset = 0;
          for (var row = 0; row < 4; ++row) {
            var rowD = dataList[row * 4];
            for (var col = 0; col < 4; ++col) {
              var colD = dataList[col];
              var x = colD.x;
              var y = rowD.y;
              var rhw = m$1.m03 * x + m$1.m07 * y + m$1.m15;
              rhw = rhw ? 1 / rhw : 1;
              offset = (row * 4 + col) * stride;
              vData[offset + 0] = (m$1.m00 * x + m$1.m04 * y + m$1.m12) * rhw;
              vData[offset + 1] = (m$1.m01 * x + m$1.m05 * y + m$1.m13) * rhw;
              vData[offset + 2] = (m$1.m02 * x + m$1.m06 * y + m$1.m14) * rhw;
            }
          }
        },
        updateUVs: function updateUVs(sprite) {
          if (!sprite.spriteFrame) return;
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var stride = renderData.floatStride;
          var uv = sprite.spriteFrame.uvSliced;
          var uvOffset = 3;
          for (var _i = 0; _i < 16; _i++) {
            vData[uvOffset] = uv[_i].u;
            vData[uvOffset + 1] = uv[_i].v;
            uvOffset += stride;
          }
        },
        updateColor: function updateColor(sprite) {
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var stride = renderData.floatStride;
          var colorOffset = 5;
          var color = sprite.color;
          var colorR = color.r / 255;
          var colorG = color.g / 255;
          var colorB = color.b / 255;
          var colorA = sprite.node._uiProps.opacity;
          for (var _i2 = 0; _i2 < 16; _i2++) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
            colorOffset += stride;
          }
        }
      };

      var m = new Mat4();
      var origin;
      var leftInner;
      var rightInner;
      var rightOuter;
      var bottomInner;
      var topInner;
      var topOuter;
      var tempRenderDataLength = 0;
      var tempRenderData = [];
      var QUAD_INDICES$1 = null;
      function has9SlicedOffsetVertexCount(spriteFrame) {
        if (spriteFrame) {
          if (spriteFrame.insetTop > 0 || spriteFrame.insetBottom > 0 || spriteFrame.insetLeft > 0 || spriteFrame.insetRight > 0) {
            return 2;
          }
        }
        return 0;
      }
      var tiled = {
        createData: function createData(sprite) {
          return sprite.requestRenderData();
        },
        updateRenderData: function updateRenderData(sprite) {
          var renderData = sprite.renderData;
          var frame = sprite.spriteFrame;
          if (!frame || !renderData) {
            return;
          }
          if (!renderData.vertDirty) {
            return;
          }
          var uiTrans = sprite.node._uiProps.uiTransformComp;
          var contentWidth = Math.abs(uiTrans.width);
          var contentHeight = Math.abs(uiTrans.height);
          var rect = frame.getRect();
          var leftWidth = frame.insetLeft;
          var rightWidth = frame.insetRight;
          var centerWidth = rect.width - leftWidth - rightWidth;
          var topHeight = frame.insetTop;
          var bottomHeight = frame.insetBottom;
          var centerHeight = rect.height - topHeight - bottomHeight;
          var sizableWidth = contentWidth - leftWidth - rightWidth;
          var sizableHeight = contentHeight - topHeight - bottomHeight;
          sizableWidth = sizableWidth > 0 ? sizableWidth : 0;
          sizableHeight = sizableHeight > 0 ? sizableHeight : 0;
          var hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth;
          var vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight;
          var offsetVertexCount = has9SlicedOffsetVertexCount(frame);
          var row = Math.ceil(vRepeat + offsetVertexCount);
          var col = Math.ceil(hRepeat + offsetVertexCount);
          renderData.dataLength = row * 2 * (col * 2);
          this.updateVerts(sprite, sizableWidth, sizableHeight, row, col);
          if (renderData.vertexCount !== row * col * 4) {
            sprite.renderEntity.colorDirty = true;
          }
          renderData.resize(row * col * 4, row * col * 6);
          renderData.updateRenderData(sprite, frame);
        },
        createQuadIndices: function createQuadIndices(indexCount) {
          if (indexCount % 6 !== 0) {
            error('illegal index count!');
            return;
          }
          var quadCount = indexCount / 6;
          QUAD_INDICES$1 = null;
          QUAD_INDICES$1 = new Uint16Array(indexCount);
          var offset = 0;
          for (var i = 0; i < quadCount; i++) {
            QUAD_INDICES$1[offset++] = 0 + i * 4;
            QUAD_INDICES$1[offset++] = 1 + i * 4;
            QUAD_INDICES$1[offset++] = 2 + i * 4;
            QUAD_INDICES$1[offset++] = 1 + i * 4;
            QUAD_INDICES$1[offset++] = 3 + i * 4;
            QUAD_INDICES$1[offset++] = 2 + i * 4;
          }
        },
        updateUVs: function updateUVs(sprite) {
          var renderData = sprite.renderData;
          renderData.vertDirty = true;
          sprite.markForUpdateRenderData();
        },
        fillBuffers: function fillBuffers(sprite, renderer) {
          var node = sprite.node;
          var renderData = sprite.renderData;
          var chunk = renderData.chunk;
          if (chunk === null) {
            return;
          }
          if (sprite._flagChangedVersion !== node.flagChangedVersion || renderData.vertDirty) {
            this.updateWorldVertexAndUVData(sprite, chunk);
            renderData.vertDirty = false;
            sprite._flagChangedVersion = node.flagChangedVersion;
          }
          this.updateColorLate(sprite);
          chunk.bufferId;
          var vid = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          for (var i = 0; i < renderData.indexCount; i += 6) {
            ib[indexOffset++] = vid;
            ib[indexOffset++] = vid + 1;
            ib[indexOffset++] = vid + 2;
            ib[indexOffset++] = vid + 1;
            ib[indexOffset++] = vid + 3;
            ib[indexOffset++] = vid + 2;
            vid += 4;
            meshBuffer.indexOffset += 6;
          }
          meshBuffer.setDirty();
        },
        updateWorldUVData: function updateWorldUVData(sprite) {
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = renderData.data;
          var vData = renderData.chunk.vb;
          for (var i = 0; i < dataList.length; i++) {
            var offset = i * stride;
            vData[offset + 3] = dataList[i].u;
            vData[offset + 4] = dataList[i].v;
          }
        },
        updateWorldVertexAndUVData: function updateWorldVertexAndUVData(sprite, chunk) {
          var node = sprite.node;
          node.getWorldMatrix(m);
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = renderData.data;
          var vData = chunk.vb;
          var length = dataList.length;
          for (var i = 0; i < length; i++) {
            var x = dataList[i].x;
            var y = dataList[i].y;
            var z = dataList[i].z;
            var rhw = m.m03 * x + m.m07 * y + m.m11 * z + m.m15;
            rhw = rhw ? 1 / rhw : 1;
            var offset = i * stride;
            vData[offset] = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) * rhw;
            vData[offset + 1] = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) * rhw;
            vData[offset + 2] = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) * rhw;
          }
          this.updateWorldUVData(sprite);
        },
        updateVerts: function updateVerts(sprite, sizableWidth, sizableHeight, row, col) {
          var uiTrans = sprite.node._uiProps.uiTransformComp;
          var renderData = sprite.renderData;
          var dataList = renderData.data;
          var frame = sprite.spriteFrame;
          var rect = frame.rect;
          var contentWidth = Math.abs(uiTrans.width);
          var contentHeight = Math.abs(uiTrans.height);
          var appx = uiTrans.anchorX * contentWidth;
          var appy = uiTrans.anchorY * contentHeight;
          var leftWidth = frame.insetLeft;
          var rightWidth = frame.insetRight;
          var centerWidth = rect.width - leftWidth - rightWidth;
          var topHeight = frame.insetTop;
          var bottomHeight = frame.insetBottom;
          var centerHeight = rect.height - topHeight - bottomHeight;
          var xScale = uiTrans.width / (leftWidth + rightWidth) > 1 ? 1 : uiTrans.width / (leftWidth + rightWidth);
          var yScale = uiTrans.height / (topHeight + bottomHeight) > 1 ? 1 : uiTrans.height / (topHeight + bottomHeight);
          var offsetWidth = 0;
          var offsetHeight = 0;
          if (centerWidth > 0) {
            offsetWidth = Math.floor(sizableWidth * 1000) / 1000 % centerWidth === 0 ? centerWidth : sizableWidth % centerWidth;
          } else {
            offsetWidth = sizableWidth;
          }
          if (centerHeight > 0) {
            offsetHeight = Math.floor(sizableHeight * 1000) / 1000 % centerHeight === 0 ? centerHeight : sizableHeight % centerHeight;
          } else {
            offsetHeight = sizableHeight;
          }
          tempRenderData.length = 0;
          tempRenderDataLength = Math.max(row + 1, col + 1);
          for (var i = 0; i < tempRenderDataLength; i++) {
            tempRenderData.push({
              x: 0,
              y: 0,
              z: 0,
              u: 0,
              v: 0,
              color: new Color$1()
            });
          }
          var offsetVertexCount = has9SlicedOffsetVertexCount(frame);
          if (offsetVertexCount === 0) {
            for (var _i = 0; _i < tempRenderDataLength; _i++) {
              if (_i >= col) {
                tempRenderData[_i].x = contentWidth - appx;
              } else {
                tempRenderData[_i].x = -appx + _i * centerWidth;
              }
              if (_i >= row) {
                tempRenderData[_i].y = contentHeight - appy;
              } else {
                tempRenderData[_i].y = -appy + _i * centerHeight;
              }
            }
          } else {
            for (var _i2 = 0; _i2 < tempRenderDataLength; _i2++) {
              if (_i2 === 0) {
                tempRenderData[_i2].x = -appx;
              } else if (_i2 === 1) {
                tempRenderData[_i2].x = -appx + leftWidth * xScale;
              } else if (_i2 > 1 && _i2 < col - 1) {
                if (centerWidth > 0) {
                  tempRenderData[_i2].x = -appx + leftWidth * xScale + centerWidth * (_i2 - 1);
                } else {
                  tempRenderData[_i2].x = leftWidth + sizableWidth - appx;
                }
              } else if (_i2 === col - 1) {
                tempRenderData[_i2].x = -appx + leftWidth * xScale + offsetWidth + centerWidth * (_i2 - 2);
              } else if (_i2 >= col) {
                tempRenderData[_i2].x = Math.min(leftWidth + sizableWidth + rightWidth, contentWidth) - appx;
              }
              if (_i2 === 0) {
                tempRenderData[_i2].y = -appy;
              } else if (_i2 === 1) {
                tempRenderData[_i2].y = -appy + bottomHeight * yScale;
              } else if (_i2 > 1 && _i2 < row - 1) {
                if (centerHeight > 0) {
                  tempRenderData[_i2].y = -appy + bottomHeight * yScale + centerHeight * (_i2 - 1);
                } else {
                  tempRenderData[_i2].y = bottomHeight + sizableHeight - appy;
                }
              } else if (_i2 === row - 1) {
                tempRenderData[_i2].y = -appy + bottomHeight * yScale + offsetHeight + centerHeight * (_i2 - 2);
              } else if (_i2 >= row) {
                tempRenderData[_i2].y = Math.min(bottomHeight + sizableHeight + topHeight, contentHeight) - appy;
              }
            }
          }
          var x = 0;
          var x1 = 0;
          var y = 0;
          var y1 = 0;
          for (var yIndex = 0; yIndex < row; ++yIndex) {
            y = tempRenderData[yIndex].y;
            y1 = tempRenderData[yIndex + 1].y;
            for (var xIndex = 0; xIndex < col; ++xIndex) {
              x = tempRenderData[xIndex].x;
              x1 = tempRenderData[xIndex + 1].x;
              var curIndex = 4 * (yIndex * col + xIndex);
              dataList[curIndex].x = x;
              dataList[curIndex].y = y;
              dataList[curIndex + 1].x = x1;
              dataList[curIndex + 1].y = y;
              dataList[curIndex + 2].x = x;
              dataList[curIndex + 2].y = y1;
              dataList[curIndex + 3].x = x1;
              dataList[curIndex + 3].y = y1;
            }
          }
          var rotated = frame.rotated;
          frame.uv;
          var uvSliced = frame.uvSliced;
          origin = uvSliced[0];
          leftInner = uvSliced[1];
          rightInner = uvSliced[2];
          rightOuter = uvSliced[3];
          bottomInner = uvSliced[4];
          topInner = uvSliced[8];
          topOuter = uvSliced[12];
          var coefU = 0;
          var coefV = 0;
          var hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth;
          var vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight;
          var tempXVerts = [];
          var tempYVerts = [];
          for (var yIndexUV = 0; yIndexUV < row; ++yIndexUV) {
            if (sizableHeight > centerHeight) {
              var curYRectCount = offsetVertexCount > 0 ? yIndexUV : yIndexUV + 1;
              if (sizableHeight >= curYRectCount * centerHeight) {
                coefV = 1;
              } else {
                coefV = vRepeat % 1;
              }
            } else {
              coefV = vRepeat;
            }
            for (var xIndexUV = 0; xIndexUV < col; ++xIndexUV) {
              if (sizableWidth > centerWidth) {
                var curXRectCount = offsetVertexCount > 0 ? xIndexUV : xIndexUV + 1;
                if (sizableWidth >= curXRectCount * centerWidth) {
                  coefU = 1;
                } else {
                  coefU = hRepeat % 1;
                }
              } else {
                coefU = hRepeat;
              }
              if (rotated) {
                if (offsetVertexCount === 0) {
                  tempXVerts[0] = bottomInner.u;
                  tempXVerts[1] = bottomInner.u;
                  tempXVerts[2] = bottomInner.u + (topInner.u - bottomInner.u) * coefV;
                  tempYVerts[0] = leftInner.v;
                  tempYVerts[1] = leftInner.v + (rightInner.v - leftInner.v) * coefU;
                  tempYVerts[2] = leftInner.v;
                } else {
                  if (yIndexUV === 0) {
                    tempXVerts[0] = origin.u;
                    tempXVerts[1] = origin.u;
                    tempXVerts[2] = bottomInner.u;
                  } else if (yIndexUV < row - 1) {
                    tempXVerts[0] = bottomInner.u;
                    tempXVerts[1] = bottomInner.u;
                    tempXVerts[2] = bottomInner.u + (topInner.u - bottomInner.u) * coefV;
                  } else if (yIndexUV === row - 1) {
                    tempXVerts[0] = topInner.u;
                    tempXVerts[1] = topInner.u;
                    tempXVerts[2] = topOuter.u;
                  }
                  if (xIndexUV === 0) {
                    tempYVerts[0] = origin.v;
                    tempYVerts[1] = leftInner.v;
                    tempYVerts[2] = origin.v;
                  } else if (xIndexUV < col - 1) {
                    tempYVerts[0] = leftInner.v;
                    tempYVerts[1] = leftInner.v + (rightInner.v - leftInner.v) * coefU;
                    tempYVerts[2] = leftInner.v;
                  } else if (xIndexUV === col - 1) {
                    tempYVerts[0] = rightInner.v;
                    tempYVerts[1] = rightOuter.v;
                    tempYVerts[2] = rightInner.v;
                  }
                }
                tempXVerts[3] = tempXVerts[2];
                tempYVerts[3] = tempYVerts[1];
              } else {
                if (offsetVertexCount === 0) {
                  tempXVerts[0] = leftInner.u;
                  tempXVerts[1] = leftInner.u + (rightInner.u - leftInner.u) * coefU;
                  tempXVerts[2] = leftInner.u;
                  tempYVerts[0] = bottomInner.v;
                  tempYVerts[1] = bottomInner.v;
                  tempYVerts[2] = bottomInner.v + (topInner.v - bottomInner.v) * coefV;
                } else {
                  if (xIndexUV === 0) {
                    tempXVerts[0] = origin.u;
                    tempXVerts[1] = leftInner.u;
                    tempXVerts[2] = origin.u;
                  } else if (xIndexUV < col - 1) {
                    tempXVerts[0] = leftInner.u;
                    tempXVerts[1] = leftInner.u + (rightInner.u - leftInner.u) * coefU;
                    tempXVerts[2] = leftInner.u;
                  } else if (xIndexUV === col - 1) {
                    tempXVerts[0] = rightInner.u;
                    tempXVerts[1] = rightOuter.u;
                    tempXVerts[2] = rightInner.u;
                  }
                  if (yIndexUV === 0) {
                    tempYVerts[0] = origin.v;
                    tempYVerts[1] = origin.v;
                    tempYVerts[2] = bottomInner.v;
                  } else if (yIndexUV < row - 1) {
                    tempYVerts[0] = bottomInner.v;
                    tempYVerts[1] = bottomInner.v;
                    tempYVerts[2] = bottomInner.v + (topInner.v - bottomInner.v) * coefV;
                  } else if (yIndexUV === row - 1) {
                    tempYVerts[0] = topInner.v;
                    tempYVerts[1] = topInner.v;
                    tempYVerts[2] = topOuter.v;
                  }
                }
                tempXVerts[3] = tempXVerts[1];
                tempYVerts[3] = tempYVerts[2];
              }
              var _curIndex = 4 * (yIndexUV * col + xIndexUV);
              dataList[_curIndex].u = tempXVerts[0];
              dataList[_curIndex].v = tempYVerts[0];
              dataList[_curIndex + 1].u = tempXVerts[1];
              dataList[_curIndex + 1].v = tempYVerts[1];
              dataList[_curIndex + 2].u = tempXVerts[2];
              dataList[_curIndex + 2].v = tempYVerts[2];
              dataList[_curIndex + 3].u = tempXVerts[3];
              dataList[_curIndex + 3].v = tempYVerts[3];
            }
          }
        },
        updateColorLate: function updateColorLate(sprite) {
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var stride = renderData.floatStride;
          var vertexCount = renderData.vertexCount;
          var colorOffset = 5;
          var color = sprite.color;
          var colorR = color.r / 255;
          var colorG = color.g / 255;
          var colorB = color.b / 255;
          var colorA = sprite.node._uiProps.opacity;
          for (var i = 0; i < vertexCount; i++) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
            colorOffset += stride;
          }
        },
        updateColor: function updateColor(sprite) {}
      };

      var SpriteType = Sprite.Type;
      var FillType = Sprite.FillType;
      var spriteAssembler = exports('s', {
        getAssembler: function getAssembler(spriteComp) {
          var util = simple$3;
          var comp = spriteComp;
          switch (comp.type) {
            case SpriteType.SLICED:
              util = sliced;
              break;
            case SpriteType.TILED:
              util = tiled;
              break;
            case SpriteType.FILLED:
              if (comp.fillType === FillType.RADIAL) {
                util = radialFilled;
              } else {
                util = barFilled;
              }
              break;
          }
          return util;
        }
      });
      Sprite.Assembler = spriteAssembler;

      var mouseEvents = [Input.EventType.MOUSE_DOWN, Input.EventType.MOUSE_MOVE, Input.EventType.MOUSE_UP, Input.EventType.MOUSE_WHEEL];
      var touchEvents = [Input.EventType.TOUCH_START, Input.EventType.TOUCH_MOVE, Input.EventType.TOUCH_END, Input.EventType.TOUCH_CANCEL];
      var PointerEventDispatcher = function () {
        function PointerEventDispatcher() {
          this.priority = EventDispatcherPriority.UI;
          this._isListDirty = false;
          this._inDispatchCount = 0;
          this._pointerEventProcessorList = [];
          this._processorListToAdd = [];
          this._processorListToRemove = [];
          input$1._registerEventDispatcher(this);
          NodeEventProcessor.callbacksInvoker.on(DispatcherEventType.ADD_POINTER_EVENT_PROCESSOR, this.addPointerEventProcessor, this);
          NodeEventProcessor.callbacksInvoker.on(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, this.removePointerEventProcessor, this);
          NodeEventProcessor.callbacksInvoker.on(DispatcherEventType.MARK_LIST_DIRTY, this._markListDirty, this);
        }
        var _proto = PointerEventDispatcher.prototype;
        _proto.dispatchEvent = function dispatchEvent(event) {
          var eventType = event.type;
          if (touchEvents.includes(eventType)) {
            return this.dispatchEventTouch(event);
          } else if (mouseEvents.includes(eventType)) {
            return this.dispatchEventMouse(event);
          }
          return true;
        };
        _proto.addPointerEventProcessor = function addPointerEventProcessor(pointerEventProcessor) {
          if (this._inDispatchCount === 0) {
            if (!this._pointerEventProcessorList.includes(pointerEventProcessor)) {
              this._pointerEventProcessorList.push(pointerEventProcessor);
              this._isListDirty = true;
            }
          } else if (!this._processorListToAdd.includes(pointerEventProcessor)) {
            this._processorListToAdd.push(pointerEventProcessor);
          }
          remove(this._processorListToRemove, pointerEventProcessor);
        };
        _proto.removePointerEventProcessor = function removePointerEventProcessor(pointerEventProcessor) {
          if (this._inDispatchCount === 0) {
            remove(this._pointerEventProcessorList, pointerEventProcessor);
            this._isListDirty = true;
          } else if (!this._processorListToRemove.includes(pointerEventProcessor)) {
            this._processorListToRemove.push(pointerEventProcessor);
          }
          remove(this._processorListToAdd, pointerEventProcessor);
        };
        _proto.dispatchEventMouse = function dispatchEventMouse(eventMouse) {
          this._inDispatchCount++;
          this._sortPointerEventProcessorList();
          var pointerEventProcessorList = this._pointerEventProcessorList;
          var length = pointerEventProcessorList.length;
          var dispatchToNextEventDispatcher = true;
          for (var i = 0; i < length; ++i) {
            var pointerEventProcessor = pointerEventProcessorList[i];
            if (pointerEventProcessor.isEnabled && pointerEventProcessor.shouldHandleEventMouse && pointerEventProcessor._handleEventMouse(eventMouse)) {
              dispatchToNextEventDispatcher = false;
              if (!eventMouse.preventSwallow) {
                break;
              } else {
                eventMouse.preventSwallow = false;
              }
            }
          }
          if (--this._inDispatchCount <= 0) {
            this._updatePointerEventProcessorList();
          }
          return dispatchToNextEventDispatcher;
        };
        _proto.dispatchEventTouch = function dispatchEventTouch(eventTouch) {
          this._inDispatchCount++;
          this._sortPointerEventProcessorList();
          var pointerEventProcessorList = this._pointerEventProcessorList;
          var length = pointerEventProcessorList.length;
          var touch = eventTouch.touch;
          var dispatchToNextEventDispatcher = true;
          for (var i = 0; i < length; ++i) {
            var pointerEventProcessor = pointerEventProcessorList[i];
            if (pointerEventProcessor.isEnabled && pointerEventProcessor.shouldHandleEventTouch) {
              if (eventTouch.type === InputEventType.TOUCH_START) {
                if (pointerEventProcessor._handleEventTouch(eventTouch)) {
                  if (pointerEventProcessor.isEnabled) {
                    pointerEventProcessor.claimedTouchIdList.push(touch.getID());
                  } else {
                    var cancelEvent = new EventTouch([eventTouch.touch], true, InputEventType.TOUCH_CANCEL);
                    cancelEvent.touch = eventTouch.touch;
                    pointerEventProcessor.dispatchEvent(cancelEvent);
                    pointerEventProcessor.claimedTouchIdList.length = 0;
                  }
                  dispatchToNextEventDispatcher = false;
                  if (!eventTouch.preventSwallow) {
                    break;
                  } else {
                    eventTouch.preventSwallow = false;
                  }
                }
              } else if (pointerEventProcessor.claimedTouchIdList.length > 0) {
                var index = pointerEventProcessor.claimedTouchIdList.indexOf(touch.getID());
                if (index !== -1) {
                  pointerEventProcessor._handleEventTouch(eventTouch);
                  if (eventTouch.type === InputEventType.TOUCH_END || eventTouch.type === InputEventType.TOUCH_CANCEL) {
                    removeAt(pointerEventProcessor.claimedTouchIdList, index);
                  }
                  dispatchToNextEventDispatcher = false;
                  if (!eventTouch.preventSwallow) {
                    break;
                  } else {
                    eventTouch.preventSwallow = false;
                  }
                }
              }
            }
          }
          if (--this._inDispatchCount <= 0) {
            this._updatePointerEventProcessorList();
          }
          return dispatchToNextEventDispatcher;
        };
        _proto._updatePointerEventProcessorList = function _updatePointerEventProcessorList() {
          var listToAdd = this._processorListToAdd;
          var addLength = listToAdd.length;
          for (var i = 0; i < addLength; ++i) {
            this.addPointerEventProcessor(listToAdd[i]);
          }
          listToAdd.length = 0;
          var listToRemove = this._processorListToRemove;
          var removeLength = listToRemove.length;
          for (var _i = 0; _i < removeLength; ++_i) {
            this.removePointerEventProcessor(listToRemove[_i]);
          }
          listToRemove.length = 0;
        };
        _proto._sortPointerEventProcessorList = function _sortPointerEventProcessorList() {
          if (!this._isListDirty) {
            return;
          }
          var pointerEventProcessorList = this._pointerEventProcessorList;
          var length = pointerEventProcessorList.length;
          for (var i = 0; i < length; ++i) {
            var pointerEventProcessor = pointerEventProcessorList[i];
            var node = pointerEventProcessor.node;
            if (node._uiProps) {
              var trans = node._uiProps.uiTransformComp;
              pointerEventProcessor.cachedCameraPriority = trans.cameraPriority;
            }
          }
          pointerEventProcessorList.sort(this._sortByPriority);
          this._isListDirty = false;
        };
        _proto._sortByPriority = function _sortByPriority(p1, p2) {
          var node1 = p1.node;
          var node2 = p2.node;
          if (!p2 || !node2 || !node2.activeInHierarchy || !node2._uiProps.uiTransformComp) {
            return -1;
          } else if (!p1 || !node1 || !node1.activeInHierarchy || !node1._uiProps.uiTransformComp) {
            return 1;
          }
          if (p1.cachedCameraPriority !== p2.cachedCameraPriority) {
            return p2.cachedCameraPriority - p1.cachedCameraPriority;
          }
          var n1 = node1;
          var n2 = node2;
          var ex = false;
          while (((_parent = n1.parent) === null || _parent === void 0 ? void 0 : _parent.uuid) !== ((_parent2 = n2.parent) === null || _parent2 === void 0 ? void 0 : _parent2.uuid)) {
            var _parent, _parent2, _n, _n$parent, _n2, _n2$parent;
            n1 = ((_n = n1) === null || _n === void 0 ? void 0 : (_n$parent = _n.parent) === null || _n$parent === void 0 ? void 0 : _n$parent.parent) === null ? (ex = true) && node2 : n1 && n1.parent;
            n2 = ((_n2 = n2) === null || _n2 === void 0 ? void 0 : (_n2$parent = _n2.parent) === null || _n2$parent === void 0 ? void 0 : _n2$parent.parent) === null ? (ex = true) && node1 : n2 && n2.parent;
          }
          if (n1.uuid === n2.uuid) {
            if (n1.uuid === node2.uuid) {
              return -1;
            }
            if (n1.uuid === node1.uuid) {
              return 1;
            }
          }
          var priority1 = n1 ? n1.getSiblingIndex() : 0;
          var priority2 = n2 ? n2.getSiblingIndex() : 0;
          return ex ? priority1 - priority2 : priority2 - priority1;
        };
        _proto._markListDirty = function _markListDirty() {
          this._isListDirty = true;
        };
        return PointerEventDispatcher;
      }();
      new PointerEventDispatcher();

      var _dsInfo = new DescriptorSetInfo(null);
      var m4_1$5 = new Mat4();
      var Batcher2D = exports('x', function () {
        function Batcher2D(_root) {
          var _this = this;
          this.device = void 0;
          this._screens = [];
          this._staticVBBuffer = null;
          this._bufferAccessors = new Map();
          this._drawBatchPool = void 0;
          this._batches = void 0;
          this._currBID = -1;
          this._indexStart = 0;
          this._emptyMaterial = new Material();
          this._currRenderData = null;
          this._currMaterial = this._emptyMaterial;
          this._currTexture = null;
          this._currSampler = null;
          this._currStaticRoot = null;
          this._currComponent = null;
          this._currTransform = null;
          this._currTextureHash = 0;
          this._currSamplerHash = 0;
          this._currLayer = 0;
          this._currDepthStencilStateStage = null;
          this._currIsStatic = false;
          this._currHash = 0;
          this._currIsMiddleware = false;
          this._middlewareEnableBatch = false;
          this._middlewareBuffer = null;
          this._middlewareIndexStart = 0;
          this._middlewareIndexCount = 0;
          this._pOpacity = 1;
          this._opacityDirty = 0;
          this._descriptorSetCache = new DescriptorSetCache();
          this._meshDataArray = [];
          this._maskClearModel = null;
          this._maskClearMtl = null;
          this._maskModelMesh = null;
          this._root = _root;
          this.device = _root.device;
          this._batches = new CachedArray(64);
          this._drawBatchPool = new Pool(function () {
            return new DrawBatch2D();
          }, 128, function (obj) {
            return obj.destroy(_this);
          });
        }
        var _proto = Batcher2D.prototype;
        _proto.initialize = function initialize() {
          return true;
        };
        _proto.destroy = function destroy() {
          for (var i = 0; i < this._batches.length; i++) {
            if (this._batches.array[i]) {
              this._batches.array[i].destroy(this);
            }
          }
          this._batches.destroy();
          for (var _iterator = _createForOfIteratorHelperLoose(this._bufferAccessors.values()), _step; !(_step = _iterator()).done;) {
            var accessor = _step.value;
            accessor.destroy();
          }
          this._bufferAccessors.clear();
          if (this._drawBatchPool) {
            this._drawBatchPool.destroy();
          }
          this._descriptorSetCache.destroy();
          StencilManager.sharedManager.destroy();
          if (this._maskClearModel && this._maskModelMesh) {
            legacyCC.director.root.destroyModel(this._maskClearModel);
            this._maskModelMesh.destroy();
          }
          if (this._maskClearMtl) {
            this._maskClearMtl.destroy();
          }
        };
        _proto.syncRootNodesToNative = function syncRootNodesToNative() {
        };
        _proto.addScreen = function addScreen(comp) {
          this._screens.push(comp);
          this._screens.sort(this._screenSort);
        };
        _proto.removeScreen = function removeScreen(comp) {
          var idx = this._screens.indexOf(comp);
          if (idx === -1) {
            return;
          }
          this._screens.splice(idx, 1);
        };
        _proto.sortScreens = function sortScreens() {
          this._screens.sort(this._screenSort);
        };
        _proto.getFirstRenderCamera = function getFirstRenderCamera(node) {
          if (node.scene && node.scene.renderScene) {
            var cameras = node.scene.renderScene.cameras;
            for (var i = 0; i < cameras.length; i++) {
              var camera = cameras[i];
              if (camera.visibility & node.layer) {
                return camera;
              }
            }
          }
          return null;
        };
        _proto.update = function update() {
          var screens = this._screens;
          var offset = 0;
          for (var i = 0; i < screens.length; ++i) {
            var screen = screens[i];
            var _scene = screen._getRenderScene();
            if (!screen.enabledInHierarchy || !_scene) {
              continue;
            }
            this._opacityDirty = 0;
            this._pOpacity = 1;
            this.walk(screen.node);
            this.autoMergeBatches(this._currComponent);
            this.resetRenderStates();
            var batchPriority = 0;
            if (this._batches.length > offset) {
              for (; offset < this._batches.length; ++offset) {
                var batch = this._batches.array[offset];
                if (batch.model) {
                  var subModels = batch.model.subModels;
                  for (var j = 0; j < subModels.length; j++) {
                    subModels[j].priority = batchPriority++;
                  }
                } else {
                  batch.descriptorSet = this._descriptorSetCache.getDescriptorSet(batch);
                }
                _scene.addBatch(batch);
              }
            }
          }
        };
        _proto.uploadBuffers = function uploadBuffers() {
          if (this._batches.length > 0) {
            var length = this._meshDataArray.length;
            for (var i = 0; i < length; i++) {
              this._meshDataArray[i].uploadBuffers();
            }
            for (var _iterator3 = _createForOfIteratorHelperLoose(this._bufferAccessors.values()), _step3; !(_step3 = _iterator3()).done;) {
              var accessor = _step3.value;
              accessor.uploadBuffers();
              accessor.reset();
            }
            this._descriptorSetCache.update();
          }
        };
        _proto.reset = function reset() {
          {
            for (var i = 0; i < this._batches.length; ++i) {
              var batch = this._batches.array[i];
              if (batch.isStatic) {
                continue;
              }
              batch.clear();
              this._drawBatchPool.free(batch);
            }
            for (var _iterator4 = _createForOfIteratorHelperLoose(this._bufferAccessors.values()), _step4; !(_step4 = _iterator4()).done;) {
              var accessor = _step4.value;
              accessor.reset();
            }
            var length = this._meshDataArray.length;
            for (var _i = 0; _i < length; _i++) {
              this._meshDataArray[_i].freeIAPool();
            }
            this._meshDataArray.length = 0;
            this._staticVBBuffer = null;
            this._currBID = -1;
            this._indexStart = 0;
            this._currHash = 0;
            this._currLayer = 0;
            this._currRenderData = null;
            this._currMaterial = this._emptyMaterial;
            this._currTexture = null;
            this._currSampler = null;
            this._currComponent = null;
            this._currTransform = null;
            this._batches.clear();
            StencilManager.sharedManager.reset();
          }
        };
        _proto.switchBufferAccessor = function switchBufferAccessor(attributes) {
          if (attributes === void 0) {
            attributes = vfmtPosUvColor;
          }
          var strideBytes = attributes === vfmtPosUvColor ? 36 : getAttributeStride(attributes);
          if (!this._staticVBBuffer || this._staticVBBuffer.vertexFormatBytes !== strideBytes) {
            var accessor = this._bufferAccessors.get(strideBytes);
            if (!accessor) {
              accessor = new StaticVBAccessor(this.device, attributes);
              this._bufferAccessors.set(strideBytes, accessor);
            }
            this._staticVBBuffer = accessor;
            this._currBID = -1;
          }
          return this._staticVBBuffer;
        };
        _proto.registerBufferAccessor = function registerBufferAccessor(key, accessor) {
          this._bufferAccessors.set(key, accessor);
        };
        _proto.updateBuffer = function updateBuffer(attributes, bid) {
          var accessor = this.switchBufferAccessor(attributes);
          if (this._currBID !== bid) {
            this._currBID = bid;
            this._indexStart = accessor.getMeshBuffer(bid).indexOffset;
          }
        };
        _proto.commitComp = function commitComp(comp, renderData, frame, assembler, transform) {
          var dataHash = 0;
          var mat;
          var bufferID = -1;
          if (renderData && renderData.chunk) {
            if (!renderData.isValid()) return;
            dataHash = renderData.dataHash;
            mat = renderData.material;
            bufferID = renderData.chunk.bufferId;
          }
          if (comp.stencilStage === Stage.ENTER_LEVEL || comp.stencilStage === Stage.ENTER_LEVEL_INVERTED) {
            this._insertMaskBatch(comp);
          } else {
            comp.stencilStage = StencilManager.sharedManager.stage;
          }
          var depthStencilStateStage = comp.stencilStage;
          if (this._currHash !== dataHash || dataHash === 0 || this._currMaterial !== mat || this._currDepthStencilStateStage !== depthStencilStateStage) {
            this.autoMergeBatches(this._currComponent);
            if (renderData && !renderData._isMeshBuffer) {
              this.updateBuffer(renderData.vertexFormat, bufferID);
            }
            this._currRenderData = renderData;
            this._currHash = renderData ? renderData.dataHash : 0;
            this._currComponent = comp;
            this._currTransform = transform;
            this._currMaterial = comp.getRenderMaterial(0);
            this._currDepthStencilStateStage = depthStencilStateStage;
            this._currLayer = comp.node.layer;
            if (frame) {
              {
                assert(frame.isValid, 'frame should not be invalid, it may have been released');
              }
              this._currTexture = frame.getGFXTexture();
              this._currSampler = frame.getGFXSampler();
              this._currTextureHash = frame.getHash();
              this._currSamplerHash = this._currSampler.hash;
            } else {
              this._currTexture = null;
              this._currSampler = null;
              this._currTextureHash = 0;
              this._currSamplerHash = 0;
            }
          }
          assembler.fillBuffers(comp, this);
        };
        _proto.commitIA = function commitIA(renderComp, ia, tex, mat, transform) {
          if (this._currMaterial !== this._emptyMaterial) {
            this.autoMergeBatches(this._currComponent);
            this.resetRenderStates();
          }
          var depthStencil;
          var dssHash = 0;
          if (renderComp) {
            renderComp.stencilStage = StencilManager.sharedManager.stage;
            if (renderComp.customMaterial !== null) {
              depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage, mat);
            } else {
              depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage);
            }
            dssHash = StencilManager.sharedManager.getStencilHash(renderComp.stencilStage);
          }
          var curDrawBatch = this._currStaticRoot ? this._currStaticRoot._requireDrawBatch() : this._drawBatchPool.alloc();
          curDrawBatch.visFlags = renderComp.node.layer;
          curDrawBatch.inputAssembler = ia;
          curDrawBatch.useLocalData = transform || null;
          if (tex) {
            curDrawBatch.texture = tex.getGFXTexture();
            curDrawBatch.sampler = tex.getGFXSampler();
            curDrawBatch.textureHash = tex.getHash();
            curDrawBatch.samplerHash = curDrawBatch.sampler.hash;
          }
          curDrawBatch.fillPasses(mat || null, depthStencil, dssHash, null);
          this._batches.push(curDrawBatch);
        };
        _proto.commitMiddleware = function commitMiddleware(comp, meshBuffer, indexOffset, indexCount, tex, mat, enableBatch) {
          var texture = tex.getGFXTexture();
          if (enableBatch && this._middlewareEnableBatch && this._middlewareBuffer === meshBuffer && this._currTexture === texture && this._currMaterial.hash === mat.hash && this._middlewareIndexStart + this._middlewareIndexCount === indexOffset && this._currLayer === comp.node.layer) {
            this._middlewareIndexCount += indexCount;
          } else {
            this.autoMergeBatches(this._currComponent);
            this.resetRenderStates();
            this._currComponent = comp;
            this._currTexture = texture;
            this._currSampler = tex.getGFXSampler();
            this._currTextureHash = tex.getHash();
            this._currLayer = comp.node.layer;
            this._currSamplerHash = this._currSampler.hash;
            this._currHash = 0;
            this._currTransform = enableBatch ? null : comp.node;
            this._middlewareEnableBatch = enableBatch;
            this._middlewareBuffer = meshBuffer;
            this._currMaterial = mat;
            this._middlewareIndexStart = indexOffset;
            this._middlewareIndexCount = indexCount;
          }
          this._currIsMiddleware = true;
        };
        _proto.commitModel = function commitModel(comp, model, mat) {
          if (this._currMaterial !== this._emptyMaterial) {
            this.autoMergeBatches(this._currComponent);
            this.resetRenderStates();
          }
          var depthStencil;
          var dssHash = 0;
          if (mat) {
            if (comp.stencilStage === Stage.ENTER_LEVEL || comp.stencilStage === Stage.ENTER_LEVEL_INVERTED) {
              this._insertMaskBatch(comp);
            } else {
              comp.stencilStage = StencilManager.sharedManager.stage;
            }
            depthStencil = StencilManager.sharedManager.getStencilStage(comp.stencilStage, mat);
            dssHash = StencilManager.sharedManager.getStencilHash(comp.stencilStage);
          }
          var stamp = legacyCC.director.getTotalFrames();
          if (model) {
            model.updateTransform(stamp);
            model.updateUBOs(stamp);
          }
          for (var i = 0; i < model.subModels.length; i++) {
            var curDrawBatch = this._drawBatchPool.alloc();
            var subModel = model.subModels[i];
            curDrawBatch.visFlags = comp.node.layer;
            curDrawBatch.model = model;
            curDrawBatch.texture = null;
            curDrawBatch.sampler = null;
            curDrawBatch.useLocalData = null;
            if (!depthStencil) {
              depthStencil = null;
            }
            curDrawBatch.fillPasses(mat, depthStencil, dssHash, subModel.patches);
            curDrawBatch.inputAssembler = subModel.inputAssembler;
            curDrawBatch.model.visFlags = curDrawBatch.visFlags;
            curDrawBatch.descriptorSet = subModel.descriptorSet;
            this._batches.push(curDrawBatch);
          }
        };
        _proto.setupStaticBatch = function setupStaticBatch(staticComp, bufferAccessor) {
          this.finishMergeBatches();
          this._staticVBBuffer = bufferAccessor;
          this.currStaticRoot = staticComp;
        };
        _proto.endStaticBatch = function endStaticBatch() {
          this.finishMergeBatches();
          this.currStaticRoot = null;
          this._staticVBBuffer = null;
          this.switchBufferAccessor();
        };
        _proto.commitStaticBatch = function commitStaticBatch(comp) {
          this._batches.concat(comp.drawBatchList);
          this.finishMergeBatches();
        };
        _proto.autoMergeBatches = function autoMergeBatches(renderComp) {
          if (this._currIsMiddleware) {
            this.mergeBatchesForMiddleware(renderComp);
            return;
          }
          var mat = this._currMaterial;
          if (!mat) {
            return;
          }
          var ia;
          var rd = this._currRenderData;
          var accessor = this._staticVBBuffer;
          if (rd && rd._isMeshBuffer) {
            ia = rd.requestIA(this.device);
            if (this._meshDataArray.indexOf(rd) === -1) {
              this._meshDataArray.push(rd);
            }
          } else if (accessor) {
            var bid = this._currBID;
            var buf = accessor.getMeshBuffer(bid);
            if (!buf) {
              return;
            }
            var indexCount = buf.indexOffset - this._indexStart;
            if (indexCount <= 0) return;
            assertIsTrue(this._indexStart < buf.indexOffset);
            buf.setDirty();
            ia = buf.requireFreeIA(this.device);
            ia.firstIndex = this._indexStart;
            ia.indexCount = indexCount;
            this._indexStart = buf.indexOffset;
          }
          this._currBID = -1;
          if (!ia || !this._currTexture) {
            return;
          }
          var depthStencil;
          var dssHash = 0;
          if (renderComp) {
            if (renderComp.customMaterial !== null) {
              depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage, mat);
            } else {
              depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage);
            }
            dssHash = StencilManager.sharedManager.getStencilHash(renderComp.stencilStage);
          }
          var curDrawBatch = this._currStaticRoot ? this._currStaticRoot._requireDrawBatch() : this._drawBatchPool.alloc();
          curDrawBatch.visFlags = this._currLayer;
          curDrawBatch.texture = this._currTexture;
          curDrawBatch.sampler = this._currSampler;
          curDrawBatch.inputAssembler = ia;
          curDrawBatch.useLocalData = this._currTransform;
          curDrawBatch.textureHash = this._currTextureHash;
          curDrawBatch.samplerHash = this._currSamplerHash;
          curDrawBatch.fillPasses(mat, depthStencil, dssHash, null);
          this._batches.push(curDrawBatch);
        };
        _proto.mergeBatchesForMiddleware = function mergeBatchesForMiddleware(renderComp) {
          var depthStencil;
          var dssHash = 0;
          renderComp.stencilStage = StencilManager.sharedManager.stage;
          if (renderComp.customMaterial !== null) {
            depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage, this._currMaterial);
          } else {
            depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage);
          }
          dssHash = StencilManager.sharedManager.getStencilHash(renderComp.stencilStage);
          var curDrawBatch = this._currStaticRoot ? this._currStaticRoot._requireDrawBatch() : this._drawBatchPool.alloc();
          curDrawBatch.visFlags = renderComp.node.layer;
          var ia = this._middlewareBuffer.requireFreeIA(this.device);
          ia.firstIndex = this._middlewareIndexStart;
          ia.indexCount = this._middlewareIndexCount;
          curDrawBatch.inputAssembler = ia;
          curDrawBatch.useLocalData = this._currTransform;
          curDrawBatch.texture = this._currTexture;
          curDrawBatch.sampler = this._currSampler;
          curDrawBatch.textureHash = this._currTextureHash;
          curDrawBatch.samplerHash = this._currSamplerHash;
          curDrawBatch.fillPasses(this._currMaterial || null, depthStencil, dssHash, null);
          this._batches.push(curDrawBatch);
          this._currIsMiddleware = false;
          this._middlewareBuffer = null;
        };
        _proto.forceMergeBatches = function forceMergeBatches(material, frame, renderComp) {
          this._currMaterial = material;
          if (frame) {
            this._currTexture = frame.getGFXTexture();
            this._currSampler = frame.getGFXSampler();
            this._currTextureHash = frame.getHash();
            this._currSamplerHash = this._currSampler.hash;
          } else {
            this._currTexture = this._currSampler = null;
            this._currTextureHash = this._currSamplerHash = 0;
          }
          this._currLayer = renderComp.node.layer;
          this.autoMergeBatches(renderComp);
        };
        _proto.resetRenderStates = function resetRenderStates() {
          this._currMaterial = this._emptyMaterial;
          this._currRenderData = null;
          this._currTexture = null;
          this._currComponent = null;
          this._currTransform = null;
          this._currTextureHash = 0;
          this._currSamplerHash = 0;
          this._currLayer = 0;
        };
        _proto.finishMergeBatches = function finishMergeBatches() {
          this.autoMergeBatches();
          this.resetRenderStates();
        };
        _proto.flushMaterial = function flushMaterial(mat) {
          this._currMaterial = mat;
        };
        _proto.walk = function walk(node, level) {
          if (level === void 0) {
            level = 0;
          }
          if (!node.activeInHierarchy) {
            return;
          }
          var children = node.children;
          var uiProps = node._uiProps;
          var render = uiProps.uiComp;
          var parentOpacity = this._pOpacity;
          var opacity = parentOpacity;
          var selfOpacity = render && render.color ? render.color.a / 255 : 1;
          this._pOpacity = opacity *= selfOpacity * uiProps.localOpacity;
          uiProps.setOpacity(opacity);
          if (!approx(opacity, 0, EPSILON$3)) {
            if (uiProps.colorDirty) {
              this._opacityDirty++;
            }
            if (render && render.enabledInHierarchy) {
              render.fillBuffers(this);
            }
            if (this._opacityDirty && render && !render.useVertexOpacity && render.renderData && render.renderData.vertexCount > 0) {
              updateOpacity(render.renderData, opacity);
              var buffer = render.renderData.getMeshBuffer();
              if (buffer) {
                buffer.setDirty();
              }
            }
            if (children.length > 0 && !node._static) {
              for (var i = 0; i < children.length; ++i) {
                var child = children[i];
                this.walk(child, level);
              }
            }
            if (uiProps.colorDirty) {
              this._opacityDirty--;
              uiProps.colorDirty = false;
            }
          }
          this._pOpacity = parentOpacity;
          if (render && render.enabledInHierarchy) {
            render.postUpdateAssembler(this);
            if ((render.stencilStage === Stage.ENTER_LEVEL || render.stencilStage === Stage.ENTER_LEVEL_INVERTED) && StencilManager.sharedManager.getMaskStackSize() > 0) {
              this.autoMergeBatches(this._currComponent);
              this.resetRenderStates();
              StencilManager.sharedManager.exitMask();
            }
          }
          level += 1;
        };
        _proto._screenSort = function _screenSort(a, b) {
          return a.node.getSiblingIndex() - b.node.getSiblingIndex();
        };
        _proto._releaseDescriptorSetCache = function _releaseDescriptorSetCache(textureHash, sampler) {
          {
            this._descriptorSetCache.releaseDescriptorSetCache(textureHash);
          }
        };
        _proto._createClearModel = function _createClearModel() {
          if (!this._maskClearModel) {
            this._maskClearMtl = builtinResMgr.get('default-clear-stencil');
            this._maskClearModel = legacyCC.director.root.createModel(Model);
            var stride = getAttributeStride(vfmt);
            var gfxDevice = deviceManager.gfxDevice;
            var vertexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 4 * stride, stride));
            var vb = new Float32Array([-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]);
            vertexBuffer.update(vb);
            var indexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 6 * Uint16Array.BYTES_PER_ELEMENT, Uint16Array.BYTES_PER_ELEMENT));
            var ib = new Uint16Array([0, 1, 2, 2, 1, 3]);
            indexBuffer.update(ib);
            this._maskModelMesh = new RenderingSubMesh([vertexBuffer], vfmt, PrimitiveMode.TRIANGLE_LIST, indexBuffer);
            this._maskModelMesh.subMeshIdx = 0;
            this._maskClearModel.initSubModel(0, this._maskModelMesh, this._maskClearMtl);
          }
        };
        _proto._insertMaskBatch = function _insertMaskBatch(comp) {
          this.autoMergeBatches(this._currComponent);
          this.resetRenderStates();
          this._createClearModel();
          this._maskClearModel.node = this._maskClearModel.transform = comp.node;
          var _stencilManager = StencilManager.sharedManager;
          _stencilManager.pushMask(1);
          var stage = _stencilManager.clear(comp);
          var depthStencil;
          var dssHash = 0;
          var mat = this._maskClearMtl;
          if (mat) {
            depthStencil = _stencilManager.getStencilStage(stage, mat);
            dssHash = _stencilManager.getStencilHash(stage);
          }
          var model = this._maskClearModel;
          var stamp = legacyCC.director.getTotalFrames();
          if (model) {
            model.updateTransform(stamp);
            model.updateUBOs(stamp);
          }
          for (var i = 0; i < model.subModels.length; i++) {
            var curDrawBatch = this._drawBatchPool.alloc();
            var subModel = model.subModels[i];
            curDrawBatch.visFlags = comp.node.layer;
            curDrawBatch.model = model;
            curDrawBatch.texture = null;
            curDrawBatch.sampler = null;
            curDrawBatch.useLocalData = null;
            if (!depthStencil) {
              depthStencil = null;
            }
            curDrawBatch.fillPasses(mat, depthStencil, dssHash, subModel.patches);
            curDrawBatch.inputAssembler = subModel.inputAssembler;
            curDrawBatch.model.visFlags = curDrawBatch.visFlags;
            curDrawBatch.descriptorSet = subModel.descriptorSet;
            this._batches.push(curDrawBatch);
          }
          _stencilManager.enableMask();
        };
        _proto.syncMeshBuffersToNative = function syncMeshBuffersToNative(accId, buffers) {
        };
        _createClass(Batcher2D, [{
          key: "nativeObj",
          get: function get() {
            return this._nativeObj;
          }
        }, {
          key: "currBufferAccessor",
          get: function get() {
            if (this._staticVBBuffer) return this._staticVBBuffer;
            this._staticVBBuffer = this.switchBufferAccessor();
            return this._staticVBBuffer;
          }
        }, {
          key: "batches",
          get: function get() {
            return this._batches;
          }
        }, {
          key: "currStaticRoot",
          set: function set(value) {
            this._currStaticRoot = value;
          }
        }, {
          key: "currIsStatic",
          set: function set(value) {
            this._currIsStatic = value;
          }
        }]);
        return Batcher2D;
      }());
      var LocalDescriptorSet = function () {
        function LocalDescriptorSet() {
          this._descriptorSet = null;
          this._transform = null;
          this._textureHash = 0;
          this._samplerHash = 0;
          this._localBuffer = null;
          this._transformUpdate = true;
          var device = deviceManager.gfxDevice;
          this._localData = new Float32Array(UBOLocal.COUNT);
          this._localBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOLocal.SIZE, UBOLocal.SIZE));
        }
        var _proto2 = LocalDescriptorSet.prototype;
        _proto2.initialize = function initialize(batch) {
          var device = deviceManager.gfxDevice;
          this._transform = batch.useLocalData;
          this._textureHash = batch.textureHash;
          this._samplerHash = batch.samplerHash;
          _dsInfo.layout = batch.passes[0].localSetLayout;
          this._descriptorSet = device.createDescriptorSet(_dsInfo);
          this._descriptorSet.bindBuffer(UBOLocal.BINDING, this._localBuffer);
          var binding = ModelLocalBindings.SAMPLER_SPRITE;
          this._descriptorSet.bindTexture(binding, batch.texture);
          this._descriptorSet.bindSampler(binding, batch.sampler);
          this._descriptorSet.update();
          this._transformUpdate = true;
        };
        _proto2.updateTransform = function updateTransform(transform) {
          if (transform === this._transform) return;
          this._transform = transform;
          this._transformUpdate = true;
          this.uploadLocalData();
        };
        _proto2.equals = function equals(transform, textureHash, samplerHash) {
          return this._transform === transform && this._textureHash === textureHash && this._samplerHash === samplerHash;
        };
        _proto2.reset = function reset() {
          this._transform = null;
          this._textureHash = 0;
          this._samplerHash = 0;
        };
        _proto2.destroy = function destroy() {
          if (this._localBuffer) {
            this._localBuffer.destroy();
            this._localBuffer = null;
          }
          if (this._descriptorSet) {
            this._descriptorSet.destroy();
            this._descriptorSet = null;
          }
          this._localData = null;
        };
        _proto2.isValid = function isValid() {
          return this._transform && this._transform.isValid;
        };
        _proto2.uploadLocalData = function uploadLocalData() {
          var node = this._transform;
          if (node.hasChangedFlags || node.isTransformDirty()) {
            node.updateWorldTransform();
            this._transformUpdate = true;
          }
          if (this._transformUpdate) {
            var worldMatrix = node.worldMatrix;
            Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET);
            Mat4.invert(m4_1$5, worldMatrix);
            Mat4.transpose(m4_1$5, m4_1$5);
            {
              var det = Mat4.determinant(m4_1$5);
              var factor = 1.0 / Math.sqrt(det);
              Mat4.multiplyScalar(m4_1$5, m4_1$5, factor);
            }
            Mat4.toArray(this._localData, m4_1$5, UBOLocal.MAT_WORLD_IT_OFFSET);
            this._localBuffer.update(this._localData);
            this._transformUpdate = false;
          }
        };
        _createClass(LocalDescriptorSet, [{
          key: "descriptorSet",
          get: function get() {
            return this._descriptorSet;
          }
        }]);
        return LocalDescriptorSet;
      }();
      var DescriptorSetCache = function () {
        function DescriptorSetCache() {
          this._descriptorSetCache = new Map();
          this._dsCacheHashByTexture = new Map();
          this._localDescriptorSetCache = [];
          this._localCachePool = void 0;
          this._localCachePool = new Pool(function () {
            return new LocalDescriptorSet();
          }, 16, function (obj) {
            return obj.destroy();
          });
        }
        var _proto3 = DescriptorSetCache.prototype;
        _proto3.getDescriptorSet = function getDescriptorSet(batch) {
          legacyCC.director.root;
          var hash;
          if (batch.useLocalData) {
            var caches = this._localDescriptorSetCache;
            for (var i = 0, len = caches.length; i < len; i++) {
              var cache = caches[i];
              if (cache.equals(batch.useLocalData, batch.textureHash, batch.samplerHash)) {
                return cache.descriptorSet;
              }
            }
            var localDs = this._localCachePool.alloc();
            localDs.initialize(batch);
            this._localDescriptorSetCache.push(localDs);
            return localDs.descriptorSet;
          } else {
            hash = batch.textureHash ^ batch.samplerHash;
            if (this._descriptorSetCache.has(hash)) {
              return this._descriptorSetCache.get(hash);
            } else {
              _dsInfo.layout = batch.passes[0].localSetLayout;
              var descriptorSet = deviceManager.gfxDevice.createDescriptorSet(_dsInfo);
              var binding = ModelLocalBindings.SAMPLER_SPRITE;
              descriptorSet.bindTexture(binding, batch.texture);
              descriptorSet.bindSampler(binding, batch.sampler);
              descriptorSet.update();
              this._descriptorSetCache.set(hash, descriptorSet);
              this._dsCacheHashByTexture.set(batch.textureHash, hash);
              return descriptorSet;
            }
          }
        };
        _proto3.update = function update() {
          var caches = this._localDescriptorSetCache;
          var length = caches.length;
          if (length === 0) {
            return;
          }
          var uselessArray = [];
          for (var i = 0; i < length; i++) {
            var value = caches[i];
            if (value.isValid()) {
              value.uploadLocalData();
            } else {
              value.reset();
              var pos = caches.indexOf(value);
              uselessArray.push(pos);
            }
          }
          for (var _i2 = uselessArray.length - 1; _i2 >= 0; _i2--) {
            var index = uselessArray[_i2];
            var localDs = caches[index];
            caches.splice(index, 1);
            this._localCachePool.free(localDs);
          }
        };
        _proto3.reset = function reset() {
          var caches = this._localDescriptorSetCache;
          var length = caches.length;
          for (var i = 0; i < length; i++) {
            var value = caches[i];
            this._localCachePool.free(value);
          }
          this._localDescriptorSetCache.length = 0;
        };
        _proto3.releaseDescriptorSetCache = function releaseDescriptorSetCache(textureHash) {
          var key = this._dsCacheHashByTexture.get(textureHash);
          if (key && this._descriptorSetCache.has(key)) {
            this._descriptorSetCache.get(key).destroy();
            this._descriptorSetCache["delete"](key);
            this._dsCacheHashByTexture["delete"](textureHash);
          }
        };
        _proto3.destroy = function destroy() {
          for (var _iterator5 = _createForOfIteratorHelperLoose(this._descriptorSetCache.values()), _step5; !(_step5 = _iterator5()).done;) {
            var value = _step5.value;
            value.destroy();
          }
          this._descriptorSetCache.clear();
          this._dsCacheHashByTexture.clear();
          this._localDescriptorSetCache.length = 0;
          this._localCachePool.destroy();
        };
        return DescriptorSetCache;
      }();
      legacyCC.internal.Batcher2D = Batcher2D;

      var UIDrawBatch = exports('y', function (_DrawBatch2D) {
        _inheritsLoose(UIDrawBatch, _DrawBatch2D);
        function UIDrawBatch() {
          return _DrawBatch2D.apply(this, arguments) || this;
        }
        return UIDrawBatch;
      }(DrawBatch2D));
      markAsWarning(MeshBuffer.prototype, 'MeshBuffer', ['byteStart', 'vertexStart', 'indicesStart', 'request'].map(function (item) {
        return {
          name: item,
          suggest: "please use meshBuffer.accessor." + item + " instead"
        };
      }));
      replaceProperty(MeshBuffer.prototype, 'MeshBuffer', [{
        name: 'indicesOffset',
        newName: 'indexOffset'
      }]);
      removeProperty(MeshBuffer.prototype, 'MeshBuffer', [{
        name: 'vertexBuffers'
      }, {
        name: 'indexBuffer'
      }]);
      replaceProperty(Batcher2D.prototype, 'Batcher2D', [{
        name: 'currBufferBatch',
        newName: 'currBufferAccessor'
      }, {
        name: 'acquireBufferBatch',
        newName: 'switchBufferAccessor'
      }]);
      removeProperty(MeshRenderData.prototype, 'MeshRenderData', [{
        name: 'formatByte'
      }, {
        name: 'byteStart'
      }, {
        name: 'byteCount'
      }]);
      replaceProperty(MeshRenderData.prototype, 'MeshRenderData', [{
        name: 'indicesStart',
        newName: 'indexStart'
      }]);
      var QuadRenderData = exports('Q', function (_MeshRenderData) {
        _inheritsLoose(QuadRenderData, _MeshRenderData);
        function QuadRenderData(vertexFormat) {
          var _this;
          _this = _MeshRenderData.call(this, vertexFormat) || this;
          warnID(9006);
          return _this;
        }
        return QuadRenderData;
      }(MeshRenderData));

      legacyCC.UI = {
        MeshBuffer: MeshBuffer,
        spriteAssembler: spriteAssembler,
        graphicsAssembler: graphicsAssemblerManager,
        labelAssembler: labelAssembler,
        RenderData: RenderData,
        MeshRenderData: MeshRenderData
      };

      var SortingLayer = {
        "default": 0
      };
      game.on(Game.EVENT_POST_SUBSYSTEM_INIT, function () {
        SortingLayers.init();
      });
      var SortingLayers = exports('a5', function () {
        function SortingLayers() {}
        SortingLayers.getSortingPriority = function getSortingPriority(layer, order) {
          if (layer === void 0) {
            layer = 0;
          }
          if (order === void 0) {
            order = 0;
          }
          return (layer + (1 << 15) << 16 | order + (1 << 15)) >>> 0;
        };
        SortingLayers.getLayerIndex = function getLayerIndex(layer) {
          if (layer === void 0) {
            layer = 0;
          }
          var index = 0;
          if (this.indexMap.has(layer)) {
            index = this.indexMap.get(layer);
          } else {
            errorID(2105);
          }
          return index;
        };
        SortingLayers.getLayerIndexByName = function getLayerIndexByName(name) {
          var id = this.getLayerByName(name);
          return this.getLayerIndex(id);
        };
        SortingLayers.getLayerName = function getLayerName(layer) {
          if (layer === void 0) {
            layer = 0;
          }
          var name = '';
          if (this.nameMap.has(layer)) {
            name = this.nameMap.get(layer);
          } else {
            errorID(2105);
          }
          return name;
        };
        SortingLayers.getLayerByName = function getLayerByName(name) {
          var count = this.nameMap.size;
          var keyIterator = this.nameMap.keys();
          var key = 0;
          for (var i = 0; i < count; i++) {
            key = keyIterator.next().value;
            if (this.nameMap.get(key) === name) return key;
          }
          errorID(2106);
          return 0;
        };
        SortingLayers.isLayerValid = function isLayerValid(id) {
          if (this.indexMap.has(id)) {
            return true;
          } else {
            errorID(2105);
            return false;
          }
        };
        SortingLayers.getBuiltinLayers = function getBuiltinLayers() {
          return [{
            id: 0,
            name: 'default',
            value: 0
          }];
        };
        SortingLayers.init = function init() {
          var sortingLayers = settings.querySettings(Settings.Category.ENGINE, 'sortingLayers');
          if (!sortingLayers || sortingLayers.length === 0) {
            sortingLayers = this.getBuiltinLayers();
          }
          SortingLayers.resetState();
          for (var i = 0; i < sortingLayers.length; i++) {
            var layer = sortingLayers[i];
            SortingLayers.setLayer(layer.id, layer.name, layer.value);
            SortingLayers.Enum[layer.name] = layer.id;
          }
          Enum.update(SortingLayers.Enum);
          Enum.sortList(SortingLayers.Enum, function (a, b) {
            return SortingLayers.getLayerIndex(a.value) - SortingLayers.getLayerIndex(b.value);
          });
        };
        SortingLayers.setLayer = function setLayer(layer, layerName, layerIndex) {
          this.nameMap.set(layer, layerName);
          this.indexMap.set(layer, layerIndex);
        };
        SortingLayers.resetState = function resetState() {
          var oldItem = Object.keys(SortingLayers.Enum);
          for (var i = 0; i < oldItem.length; i++) {
            delete SortingLayers.Enum[SortingLayers.Enum[oldItem[i]]];
            delete SortingLayers.Enum[oldItem[i]];
          }
          SortingLayers.indexMap.clear();
          SortingLayers.nameMap.clear();
        };
        return SortingLayers;
      }());
      SortingLayers.nameMap = new Map();
      SortingLayers.indexMap = new Map();
      SortingLayers.Enum = Enum(SortingLayer);

      var _dec$2C, _dec2$1$, _class$2A, _class2$2m, _initializer$2e, _initializer2$1U;
      var MAX_INT16 = (1 << 15) - 1;
      var MIN_INT16 = -1 << 15;
      var Sorting = exports('a6', (_dec$2C = ccclass$M('cc.Sorting'), _dec2$1$ = type$d(SortingLayers.Enum), _dec$2C(_class$2A = disallowMultiple$1(_class$2A = (_class2$2m = function (_Component) {
        _inheritsLoose(Sorting, _Component);
        function Sorting() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._sortingLayer = _initializer$2e && _initializer$2e();
          _this._sortingOrder = _initializer2$1U && _initializer2$1U();
          _this._modelRenderer = null;
          return _this;
        }
        var _proto = Sorting.prototype;
        _proto.__preload = function __preload() {
          this._modelRenderer = this.getComponent('cc.ModelRenderer');
          if (!this._modelRenderer) {
            warnID(16301, this.node.name);
          }
          this._updateSortingPriority();
        };
        _proto._updateSortingPriority = function _updateSortingPriority() {
          var sortingLayerValue = SortingLayers.getLayerIndex(this._sortingLayer);
          var sortingPriority = SortingLayers.getSortingPriority(sortingLayerValue, this._sortingOrder);
          if (this._modelRenderer && this._modelRenderer.isValid) {
            this._modelRenderer.priority = sortingPriority;
          }
        };
        _createClass(Sorting, [{
          key: "sortingLayer",
          get: function get() {
            return this._sortingLayer;
          },
          set: function set(val) {
            if (val === this._sortingLayer || !SortingLayers.isLayerValid(val)) return;
            this._sortingLayer = val;
            this._updateSortingPriority();
          }
        }, {
          key: "sortingOrder",
          get: function get() {
            return this._sortingOrder;
          },
          set: function set(val) {
            if (val === this._sortingOrder) return;
            this._sortingOrder = clamp$1(val, MIN_INT16, MAX_INT16);
            this._updateSortingPriority();
          }
        }]);
        return Sorting;
      }(Component), (_applyDecoratedDescriptor(_class2$2m.prototype, "sortingLayer", [_dec2$1$], Object.getOwnPropertyDescriptor(_class2$2m.prototype, "sortingLayer"), _class2$2m.prototype), _initializer$2e = applyDecoratedInitializer(_class2$2m.prototype, "_sortingLayer", [serializable$p], function () {
        return SortingLayers.Enum["default"];
      }), _initializer2$1U = applyDecoratedInitializer(_class2$2m.prototype, "_sortingOrder", [serializable$p], function () {
        return 0;
      })), _class2$2m)) || _class$2A) || _class$2A));

      var MorphModel = function (_Model) {
        _inheritsLoose(MorphModel, _Model);
        function MorphModel() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Model.call.apply(_Model, [this].concat(args)) || this;
          _this._morphRenderingInstance = null;
          _this._usedMaterials = new Set();
          return _this;
        }
        var _proto = MorphModel.prototype;
        _proto.getMacroPatches = function getMacroPatches(subModelIndex) {
          var superMacroPatches = _Model.prototype.getMacroPatches.call(this, subModelIndex);
          if (this._morphRenderingInstance) {
            var morphInstanceMacroPatches = this._morphRenderingInstance.requiredPatches(subModelIndex);
            if (morphInstanceMacroPatches) {
              return morphInstanceMacroPatches.concat(superMacroPatches !== null && superMacroPatches !== void 0 ? superMacroPatches : []);
            }
          }
          return superMacroPatches;
        };
        _proto.initSubModel = function initSubModel(subModelIndex, subMeshData, material) {
          return _Model.prototype.initSubModel.call(this, subModelIndex, subMeshData, this._launderMaterial(material));
        };
        _proto.destroy = function destroy() {
          _Model.prototype.destroy.call(this);
          this._morphRenderingInstance = null;
        };
        _proto.setSubModelMaterial = function setSubModelMaterial(subModelIndex, material) {
          return _Model.prototype.setSubModelMaterial.call(this, subModelIndex, this._launderMaterial(material));
        };
        _proto.setMorphRendering = function setMorphRendering(morphRendering) {
          this._morphRenderingInstance = morphRendering;
        };
        _proto._updateLocalDescriptors = function _updateLocalDescriptors(submodelIdx, descriptorSet) {
          _Model.prototype._updateLocalDescriptors.call(this, submodelIdx, descriptorSet);
          if (this._morphRenderingInstance) {
            this._morphRenderingInstance.adaptPipelineState(submodelIdx, descriptorSet);
          }
        };
        _proto._launderMaterial = function _launderMaterial(material) {
          return material;
        };
        return MorphModel;
      }(Model);

      var _dec$2B, _dec2$1_, _dec3$1s, _dec4$14, _dec5$_, _dec6$K, _dec7$z, _class$2z, _class2$2l, _initializer$2d, _initializer2$1T, _initializer3$1n, _initializer4$1b, _initializer5$X, _initializer6$M, _initializer7$C, _initializer8$y, _initializer9$t, _initializer10$q, _class3$C, _dec8$p, _dec9$l, _dec10$d, _dec11$9, _dec12$8, _dec13$6, _dec14$5, _dec15$4, _class4$s, _class5$t, _initializer11$p, _initializer12$m, _initializer13$j, _initializer14$f, _initializer15$c, _initializer16$c, _initializer17$9, _initializer18$9, _initializer19$8, _initializer20$6, _initializer21$6, _class6$9;
      var ccclass$I = ccclass$M,
        executionOrder = executionOrder$1,
        type$a = type$d,
        formerlySerializedAs$3 = formerlySerializedAs$4,
        serializable$m = serializable$p;
      var _phaseID = getPhaseID('specular-pass');
      function getSkinPassIndex(subModel) {
        var passes = subModel.passes;
        var r = legacyCC.rendering;
        if (isEnableEffect()) _phaseID = r.getPhaseID(r.getPassID('specular-pass'), 'default');
        for (var k = 0; k < passes.length; k++) {
          if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseID || isEnableEffect() && passes[k].phaseID === _phaseID) {
            return k;
          }
        }
        return -1;
      }
      var ModelShadowCastingMode = Enum({
        OFF: 0,
        ON: 1
      });
      var ModelShadowReceivingMode = Enum({
        OFF: 0,
        ON: 1
      });
      var ModelBakeSettings = (_dec$2B = ccclass$I('cc.ModelBakeSettings'), _dec2$1_ = formerlySerializedAs$3('_recieveShadow'), _dec3$1s = type$a(CCInteger), _dec4$14 = type$a(CCBoolean), _dec5$_ = type$a(CCBoolean), _dec6$K = type$a(Enum(ReflectionProbeType)), _dec7$z = type$a(CCBoolean), _dec$2B(_class$2z = (_class2$2l = (_class3$C = function (_EventTarget) {
        _inheritsLoose(ModelBakeSettings, _EventTarget);
        function ModelBakeSettings() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EventTarget.call.apply(_EventTarget, [this].concat(args)) || this;
          _this.texture = _initializer$2d && _initializer$2d();
          _this.uvParam = _initializer2$1T && _initializer2$1T();
          _this._bakeable = _initializer3$1n && _initializer3$1n();
          _this._castShadow = _initializer4$1b && _initializer4$1b();
          _this._receiveShadow = _initializer5$X && _initializer5$X();
          _this._lightmapSize = _initializer6$M && _initializer6$M();
          _this._useLightProbe = _initializer7$C && _initializer7$C();
          _this._bakeToLightProbe = _initializer8$y && _initializer8$y();
          _this._reflectionProbeType = _initializer9$t && _initializer9$t();
          _this._bakeToReflectionProbe = _initializer10$q && _initializer10$q();
          _this.probeCubemap = null;
          _this.probeBlendCubemap = null;
          _this.probePlanarmap = null;
          return _this;
        }
        _createClass(ModelBakeSettings, [{
          key: "bakeable",
          get: function get() {
            return this._bakeable;
          },
          set: function set(val) {
            this._bakeable = val;
          }
        }, {
          key: "castShadow",
          get: function get() {
            return this._castShadow;
          },
          set: function set(val) {
            this._castShadow = val;
          }
        }, {
          key: "receiveShadow",
          get: function get() {
            return this._receiveShadow;
          },
          set: function set(val) {
            this._receiveShadow = val;
          }
        }, {
          key: "lightmapSize",
          get: function get() {
            return this._lightmapSize;
          },
          set: function set(val) {
            this._lightmapSize = val;
          }
        }, {
          key: "useLightProbe",
          get: function get() {
            return this._useLightProbe;
          },
          set: function set(val) {
            this._useLightProbe = val;
            this.emit(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED);
          }
        }, {
          key: "bakeToLightProbe",
          get: function get() {
            return this._bakeToLightProbe;
          },
          set: function set(val) {
            this._bakeToLightProbe = val;
          }
        }, {
          key: "reflectionProbe",
          get: function get() {
            return this._reflectionProbeType;
          },
          set: function set(val) {
            this._reflectionProbeType = val;
            this.emit(ModelBakeSettings.REFLECTION_PROBE_CHANGED);
          }
        }, {
          key: "bakeToReflectionProbe",
          get: function get() {
            return this._bakeToReflectionProbe;
          },
          set: function set(val) {
            this._bakeToReflectionProbe = val;
            this.emit(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED);
          }
        }]);
        return ModelBakeSettings;
      }(EventTarget), _class3$C.USE_LIGHT_PROBE_CHANGED = 'use_light_probe_changed', _class3$C.REFLECTION_PROBE_CHANGED = 'reflection_probe_changed', _class3$C.BAKE_TO_REFLECTION_PROBE_CHANGED = 'bake_to_reflection_probe_changed', _class3$C), (_initializer$2d = applyDecoratedInitializer(_class2$2l.prototype, "texture", [serializable$m], function () {
        return null;
      }), _initializer2$1T = applyDecoratedInitializer(_class2$2l.prototype, "uvParam", [serializable$m], function () {
        return new Vec4();
      }), _initializer3$1n = applyDecoratedInitializer(_class2$2l.prototype, "_bakeable", [serializable$m], function () {
        return false;
      }), _initializer4$1b = applyDecoratedInitializer(_class2$2l.prototype, "_castShadow", [serializable$m], function () {
        return false;
      }), _initializer5$X = applyDecoratedInitializer(_class2$2l.prototype, "_receiveShadow", [_dec2$1_], function () {
        return false;
      }), _initializer6$M = applyDecoratedInitializer(_class2$2l.prototype, "_lightmapSize", [serializable$m], function () {
        return 64;
      }), _initializer7$C = applyDecoratedInitializer(_class2$2l.prototype, "_useLightProbe", [serializable$m], function () {
        return false;
      }), _initializer8$y = applyDecoratedInitializer(_class2$2l.prototype, "_bakeToLightProbe", [serializable$m], function () {
        return true;
      }), _initializer9$t = applyDecoratedInitializer(_class2$2l.prototype, "_reflectionProbeType", [serializable$m], function () {
        return ReflectionProbeType.NONE;
      }), _initializer10$q = applyDecoratedInitializer(_class2$2l.prototype, "_bakeToReflectionProbe", [serializable$m], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$2l.prototype, "lightmapSize", [_dec3$1s], Object.getOwnPropertyDescriptor(_class2$2l.prototype, "lightmapSize"), _class2$2l.prototype), _applyDecoratedDescriptor(_class2$2l.prototype, "useLightProbe", [_dec4$14], Object.getOwnPropertyDescriptor(_class2$2l.prototype, "useLightProbe"), _class2$2l.prototype), _applyDecoratedDescriptor(_class2$2l.prototype, "bakeToLightProbe", [_dec5$_], Object.getOwnPropertyDescriptor(_class2$2l.prototype, "bakeToLightProbe"), _class2$2l.prototype), _applyDecoratedDescriptor(_class2$2l.prototype, "reflectionProbe", [_dec6$K], Object.getOwnPropertyDescriptor(_class2$2l.prototype, "reflectionProbe"), _class2$2l.prototype), _applyDecoratedDescriptor(_class2$2l.prototype, "bakeToReflectionProbe", [_dec7$z], Object.getOwnPropertyDescriptor(_class2$2l.prototype, "bakeToReflectionProbe"), _class2$2l.prototype)), _class2$2l)) || _class$2z);
      var MeshRenderer = exports('ab', (_dec8$p = ccclass$I('cc.MeshRenderer'), _dec9$l = executionOrder(100), _dec10$d = type$a(CCFloat), _dec11$9 = type$a(CCFloat), _dec12$8 = type$a(ModelShadowCastingMode), _dec13$6 = type$a(ModelShadowReceivingMode), _dec14$5 = type$a(Mesh), _dec15$4 = type$a(CCBoolean), _dec8$p(_class4$s = _dec9$l(_class4$s = (_class5$t = (_class6$9 = function (_ModelRenderer) {
        _inheritsLoose(MeshRenderer, _ModelRenderer);
        var _proto = MeshRenderer.prototype;
        _proto.onUpdateReceiveDirLight = function onUpdateReceiveDirLight(visibility, forceClose) {
          if (forceClose === void 0) {
            forceClose = false;
          }
          if (!this._model) {
            return;
          }
          if (forceClose) {
            this._model.receiveDirLight = false;
            return;
          }
          if (this.node && (visibility & this.node.layer) === this.node.layer || visibility & this._model.visFlags) {
            this._model.receiveDirLight = true;
          } else {
            this._model.receiveDirLight = false;
          }
        };
        _proto.clearGlobalStandardSkinObjectFlag = function clearGlobalStandardSkinObjectFlag() {
          this._enabledGlobalStandardSkinObject = false;
        };
        function MeshRenderer() {
          var _this2;
          _this2 = _ModelRenderer.call(this) || this;
          _this2.bakeSettings = _initializer11$p && _initializer11$p();
          _this2._mesh = _initializer12$m && _initializer12$m();
          _this2._shadowCastingMode = _initializer13$j && _initializer13$j();
          _this2._shadowReceivingMode = _initializer14$f && _initializer14$f();
          _this2._shadowBias = _initializer15$c && _initializer15$c();
          _this2._shadowNormalBias = _initializer16$c && _initializer16$c();
          _this2._reflectionProbeId = _initializer17$9 && _initializer17$9();
          _this2._reflectionProbeBlendId = _initializer18$9 && _initializer18$9();
          _this2._reflectionProbeBlendWeight = _initializer19$8 && _initializer19$8();
          _this2._enabledGlobalStandardSkinObject = _initializer20$6 && _initializer20$6();
          _this2._reflectionProbeDataMap = null;
          _this2._subMeshShapesWeights = [];
          _this2._modelType = void 0;
          _this2._model = null;
          _this2._morphInstance = null;
          _this2._enableMorph = _initializer21$6 && _initializer21$6();
          _this2._modelType = Model;
          var highQualityMode = settings.querySettings(Settings.Category.RENDERING, 'highQualityMode');
          if (highQualityMode) {
            _this2._shadowCastingMode = ModelShadowCastingMode.ON;
            _this2.bakeSettings.castShadow = true;
            _this2.bakeSettings.receiveShadow = true;
          }
          return _this2;
        }
        _proto.onLoad = function onLoad() {
          if (this._mesh) {
            this._mesh.initialize();
          }
          if (!this._validateShapeWeights()) {
            this._initSubMeshShapesWeights();
          }
          this._watchMorphInMesh();
          this._updateModels();
          this._updateCastShadow();
          this._updateReceiveShadow();
          this._updateShadowBias();
          this._updateShadowNormalBias();
          this._updateUseLightProbe();
          this._updateBakeToReflectionProbe();
          this._updateUseReflectionProbe();
          this._updateReceiveDirLight();
          this._updateStandardSkin();
        };
        _proto.onRestore = function onRestore() {
          this._updateModels();
          if (this.enabledInHierarchy) {
            this._attachToScene();
          }
          this._updateCastShadow();
          this._updateReceiveShadow();
          this._updateShadowBias();
          this._updateShadowNormalBias();
          this._updateUseLightProbe();
          this._updateBakeToReflectionProbe();
          this._updateUseReflectionProbe();
          this._updateReceiveDirLight();
          this._updateStandardSkin();
        };
        _proto.onEnable = function onEnable() {
          _ModelRenderer.prototype.onEnable.call(this);
          this.node.on(NodeEventType.MOBILITY_CHANGED, this.onMobilityChanged, this);
          this.node.on(NodeEventType.LIGHT_PROBE_BAKING_CHANGED, this.onLightProbeBakingChanged, this);
          this.bakeSettings.on(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this);
          this.bakeSettings.on(ModelBakeSettings.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this);
          this.bakeSettings.on(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this);
          if (!this._model) {
            this._updateModels();
          }
          this._model.onGlobalPipelineStateChanged();
          this._updateCastShadow();
          this._updateReceiveShadow();
          this._updateShadowBias();
          this._updateShadowNormalBias();
          this._updateBakeToReflectionProbe();
          this._updateUseReflectionProbe();
          this._onUpdateLocalShadowBiasAndProbeId();
          this._updateUseLightProbe();
          this._updateReceiveDirLight();
          this._onUpdateReflectionProbeDataMap();
          this._onUpdateLocalReflectionProbeData();
          this._updateStandardSkin();
          this._attachToScene();
        };
        _proto.onDisable = function onDisable() {
          if (this._model) {
            this._detachFromScene();
          }
          this.node.off(NodeEventType.MOBILITY_CHANGED, this.onMobilityChanged, this);
          this.node.off(NodeEventType.LIGHT_PROBE_BAKING_CHANGED, this.onLightProbeBakingChanged, this);
          this.bakeSettings.off(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this);
          this.bakeSettings.off(ModelBakeSettings.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this);
          this.bakeSettings.off(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this);
        };
        _proto.onDestroy = function onDestroy() {
          if (this._model) {
            legacyCC.director.root.destroyModel(this._model);
            this._model = null;
            this._models.length = 0;
          }
          if (this._morphInstance) {
            this._morphInstance.destroy();
          }
        };
        _proto.onGeometryChanged = function onGeometryChanged() {
          if (this._model && this._mesh) {
            var meshStruct = this._mesh.struct;
            this._model.createBoundingShape(meshStruct.minPosition, meshStruct.maxPosition);
            this._model.updateWorldBound();
            this._model.onGeometryChanged();
          }
        };
        _proto.getWeight = function getWeight(subMeshIndex, shapeIndex) {
          var subMeshShapesWeights = this._subMeshShapesWeights;
          assertIsTrue(subMeshIndex < subMeshShapesWeights.length);
          var shapeWeights = this._subMeshShapesWeights[subMeshIndex];
          assertIsTrue(shapeIndex < shapeWeights.length);
          return shapeWeights[shapeIndex];
        };
        _proto.setWeights = function setWeights(weights, subMeshIndex) {
          var subMeshShapesWeights = this._subMeshShapesWeights;
          if (subMeshIndex >= subMeshShapesWeights.length) {
            return;
          }
          var shapeWeights = subMeshShapesWeights[subMeshIndex];
          if (shapeWeights.length !== weights.length) {
            return;
          }
          subMeshShapesWeights[subMeshIndex] = weights.slice(0);
          this._uploadSubMeshShapesWeights(subMeshIndex);
        };
        _proto.setWeight = function setWeight(weight, subMeshIndex, shapeIndex) {
          var subMeshShapesWeights = this._subMeshShapesWeights;
          if (subMeshIndex >= subMeshShapesWeights.length) {
            return;
          }
          var shapeWeights = subMeshShapesWeights[subMeshIndex];
          if (shapeIndex >= shapeWeights.length) {
            return;
          }
          shapeWeights[shapeIndex] = weight;
          this._uploadSubMeshShapesWeights(subMeshIndex);
        };
        _proto.setInstancedAttribute = function setInstancedAttribute(name, value) {
          if (!this.model) {
            return;
          }
          {
            var subModels = this.model.subModels;
            for (var i = 0; i < subModels.length; i++) {
              var subModel = subModels[i];
              var _subModel$instancedAt = subModel.instancedAttributeBlock,
                attributes = _subModel$instancedAt.attributes,
                views = _subModel$instancedAt.views;
              for (var _i = 0; _i < attributes.length; _i++) {
                if (attributes[_i].name === name) {
                  views[_i].set(value);
                  break;
                }
              }
            }
          }
        };
        _proto._updateLightmap = function _updateLightmap(lightmap, uOff, vOff, scale, lum) {
          this.bakeSettings.texture = lightmap;
          this.bakeSettings.uvParam.x = uOff;
          this.bakeSettings.uvParam.y = vOff;
          this.bakeSettings.uvParam.z = scale;
          this.bakeSettings.uvParam.w = lum;
          this._onUpdateLightingmap();
          this._updateReceiveDirLight();
        };
        _proto.updateProbeCubemap = function updateProbeCubemap(cubeMap) {
          if (this.bakeSettings.probeCubemap && this.bakeSettings.probeCubemap === cubeMap) {
            return;
          }
          this.bakeSettings.probeCubemap = cubeMap;
          if (this.model !== null) {
            this.model.updateReflectionProbeCubemap(this.bakeSettings.probeCubemap);
          }
        };
        _proto.updateProbeBlendCubemap = function updateProbeBlendCubemap(cubeMap) {
          if (this.bakeSettings.probeBlendCubemap && this.bakeSettings.probeBlendCubemap === cubeMap) {
            return;
          }
          this.bakeSettings.probeBlendCubemap = cubeMap;
          if (this.model !== null) {
            this.model.updateReflectionProbeBlendCubemap(this.bakeSettings.probeBlendCubemap);
          }
        };
        _proto.updateProbePlanarMap = function updateProbePlanarMap(planarMap) {
          if (this.bakeSettings.probePlanarmap === planarMap) {
            return;
          }
          this.bakeSettings.probePlanarmap = planarMap;
          if (this.model !== null) {
            this.model.updateReflectionProbePlanarMap(this.bakeSettings.probePlanarmap);
          }
        };
        _proto.updateReflectionProbeDataMap = function updateReflectionProbeDataMap(dataMap) {
          this._reflectionProbeDataMap = dataMap;
          if (this.model !== null) {
            this.model.updateReflectionProbeDataMap(dataMap);
          }
        };
        _proto.updateReflectionProbeId = function updateReflectionProbeId(probeId) {
          this._reflectionProbeId = probeId;
          if (this.model) {
            this.model.reflectionProbeId = probeId;
          }
          this._onUpdateLocalShadowBiasAndProbeId();
        };
        _proto.updateReflectionProbeBlendId = function updateReflectionProbeBlendId(blendProbeId) {
          this._reflectionProbeBlendId = blendProbeId;
          if (this.model) {
            this.model.reflectionProbeBlendId = blendProbeId;
          }
          this._onUpdateLocalShadowBiasAndProbeId();
        };
        _proto.updateReflectionProbeBlendWeight = function updateReflectionProbeBlendWeight(weight) {
          this._reflectionProbeBlendWeight = weight;
          if (this.model) {
            this.model.reflectionProbeBlendWeight = weight;
          }
          this._onUpdateLocalReflectionProbeData();
        };
        _proto._updateReflectionProbeTexture = function _updateReflectionProbeTexture() {
          if (!this.model) return;
          var bakeSettings = this.bakeSettings;
          var reflectionProbe = bakeSettings.reflectionProbe;
          var probeBlendCubemap = bakeSettings.probeBlendCubemap;
          var probePlanarMap = bakeSettings.probePlanarmap;
          var probeCubeMap = bakeSettings.probeCubemap;
          if (reflectionProbe === ReflectionProbeType.BAKED_CUBEMAP) {
            this.model.updateReflectionProbeCubemap(probeCubeMap);
            this.model.updateReflectionProbePlanarMap(null);
            this.model.updateReflectionProbeBlendCubemap(null);
          } else if (reflectionProbe === ReflectionProbeType.BLEND_PROBES || reflectionProbe === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
            this.model.updateReflectionProbeCubemap(probeCubeMap);
            this.model.updateReflectionProbeBlendCubemap(probeBlendCubemap);
            this.model.updateReflectionProbePlanarMap(null);
          } else if (reflectionProbe === ReflectionProbeType.PLANAR_REFLECTION) {
            this.model.updateReflectionProbePlanarMap(probePlanarMap);
            this.model.updateReflectionProbeCubemap(null);
            this.model.updateReflectionProbeBlendCubemap(null);
          } else {
            this.model.updateReflectionProbeCubemap(null);
            this.model.updateReflectionProbePlanarMap(null);
            this.model.updateReflectionProbeBlendCubemap(null);
          }
        };
        _proto._updateModels = function _updateModels() {
          if (!this.enabledInHierarchy) {
            return;
          }
          var model = this._model;
          if (model) {
            model.destroy();
            model.initialize();
            model.node = model.transform = this.node;
          } else {
            this._createModel();
          }
          if (this._model) {
            if (this._mesh) {
              var meshStruct = this._mesh.struct;
              this._model.createBoundingShape(meshStruct.minPosition, meshStruct.maxPosition);
              this._model.updateWorldBound();
            }
            this._model.initLightingmap(this.bakeSettings.texture, this.bakeSettings.uvParam);
            this._updateUseLightProbe();
            this._updateUseReflectionProbeType();
            this._updateModelParams();
            this._onUpdateLightingmap();
            this._onUpdateLocalShadowBiasAndProbeId();
            this._updateUseReflectionProbe();
            this._updateReceiveDirLight();
            this._onUpdateReflectionProbeDataMap();
            this._onUpdateLocalReflectionProbeData();
          }
        };
        _proto._updateReceiveDirLight = function _updateReceiveDirLight() {
          if (!this._model) {
            return;
          }
          var scene = this.node.scene;
          if (!scene || !scene.renderScene) {
            return;
          }
          var mainLight = scene.renderScene.mainLight;
          if (!mainLight) {
            return;
          }
          var visibility = mainLight.visibility;
          if (!mainLight.node) {
            return;
          }
          if (mainLight.node.mobility === MobilityMode.Static) {
            var forceClose = false;
            if (this.bakeSettings.texture && !this.node.scene.globals.disableLightmap) {
              forceClose = true;
            }
            if (this.node.scene.globals.lightProbeInfo.data && this.node.scene.globals.lightProbeInfo.data.hasCoefficients() && this._model.useLightProbe) {
              forceClose = true;
            }
            this.onUpdateReceiveDirLight(visibility, forceClose);
          } else {
            this.onUpdateReceiveDirLight(visibility);
          }
        };
        _proto._createModel = function _createModel() {
          var preferMorphOverPlain = !!this._morphInstance;
          var modelType = preferMorphOverPlain && this._modelType === Model ? MorphModel : this._modelType;
          var model = this._model = legacyCC.director.root.createModel(modelType);
          model.visFlags = this.visibility;
          model.node = model.transform = this.node;
          this._models.length = 0;
          this._models.push(this._model);
          if (this._morphInstance && model instanceof MorphModel) {
            model.setMorphRendering(this._morphInstance);
          }
        };
        _proto._attachToScene = function _attachToScene() {
          if (!this.node.scene || !this._model) {
            return;
          }
          var renderScene = this._getRenderScene();
          if (this._model.scene !== null) {
            this._detachFromScene();
          }
          renderScene.addModel(this._model);
        };
        _proto._detachFromScene = function _detachFromScene() {
          if (this._model && this._model.scene) {
            this._model.scene.removeModel(this._model);
          }
        };
        _proto._updateModelParams = function _updateModelParams() {
          if (!this._mesh || !this._model) {
            return;
          }
          this.node.hasChangedFlags |= TransformBit.POSITION;
          this._model.transform.hasChangedFlags |= TransformBit.POSITION;
          this._model.isDynamicBatching = this._isBatchingEnabled();
          var meshCount = this._mesh ? this._mesh.renderingSubMeshes.length : 0;
          var renderingMesh = this._mesh.renderingSubMeshes;
          if (renderingMesh) {
            for (var i = 0; i < meshCount; ++i) {
              var material = this.getRenderMaterial(i);
              if (material && !material.isValid) {
                material = null;
              }
              var subMeshData = renderingMesh[i];
              if (subMeshData) {
                this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial());
              }
            }
          }
          this._model.enabled = true;
        };
        _proto._onUpdateLightingmap = function _onUpdateLightingmap() {
          if (this.model !== null) {
            this.model.updateLightingmap(this.bakeSettings.texture, this.bakeSettings.uvParam);
          }
          this.setInstancedAttribute('a_lightingMapUVParam', [this.bakeSettings.uvParam.x, this.bakeSettings.uvParam.y, this.bakeSettings.uvParam.z, this.bakeSettings.uvParam.w]);
        };
        _proto._onUpdateLocalShadowBiasAndProbeId = function _onUpdateLocalShadowBiasAndProbeId() {
          if (this.model !== null) {
            this.model.updateLocalShadowBias();
            this.model.updateReflectionProbeId();
          }
          this.setInstancedAttribute('a_localShadowBiasAndProbeId', [this._shadowBias, this._shadowNormalBias, this._reflectionProbeId, this._reflectionProbeBlendId]);
        };
        _proto._onUpdateLocalReflectionProbeData = function _onUpdateLocalReflectionProbeData() {
          if (this.bakeSettings.reflectionProbe === ReflectionProbeType.BAKED_CUBEMAP || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
            if (this.model !== null) {
              this.model.updateReflectionProbeId();
            }
            this.setInstancedAttribute('a_reflectionProbeData', [this._reflectionProbeBlendWeight, 0.0, 0.0, 0.0]);
          }
        };
        _proto._onUpdateReflectionProbeDataMap = function _onUpdateReflectionProbeDataMap() {
          if (this.model !== null) {
            this.model.updateReflectionProbeDataMap(this._reflectionProbeDataMap);
          }
        };
        _proto._onMaterialModified = function _onMaterialModified(idx, material) {
          if (!this._model || !this._model.inited) {
            return;
          }
          this._onRebuildPSO(idx, material || this._getBuiltinMaterial());
          this._updateStandardSkin();
        };
        _proto._onRebuildPSO = function _onRebuildPSO(idx, material) {
          if (!this._model || !this._model.inited) {
            return;
          }
          this._model.isDynamicBatching = this._isBatchingEnabled();
          this._model.setSubModelMaterial(idx, material);
          this._onUpdateLightingmap();
          this._onUpdateLocalShadowBiasAndProbeId();
          this._updateReflectionProbeTexture();
          this._onUpdateReflectionProbeDataMap();
          this._onUpdateLocalReflectionProbeData();
        };
        _proto._onMeshChanged = function _onMeshChanged(old) {};
        _proto._clearMaterials = function _clearMaterials() {
          if (!this._model) {
            return;
          }
          var subModels = this._model.subModels;
          for (var i = 0; i < subModels.length; ++i) {
            this._onMaterialModified(i, null);
          }
        };
        _proto._getBuiltinMaterial = function _getBuiltinMaterial() {
          return builtinResMgr.get('missing-material');
        };
        _proto._onVisibilityChange = function _onVisibilityChange(val) {
          if (!this._model) {
            return;
          }
          this._model.visFlags = val;
        };
        _proto._updateShadowBias = function _updateShadowBias() {
          if (!this._model) {
            return;
          }
          this._model.shadowBias = this._shadowBias;
        };
        _proto._updateShadowNormalBias = function _updateShadowNormalBias() {
          if (!this._model) {
            return;
          }
          this._model.shadowNormalBias = this._shadowNormalBias;
        };
        _proto._updateCastShadow = function _updateCastShadow() {
          if (!this._model) {
            return;
          }
          if (this._shadowCastingMode === ModelShadowCastingMode.OFF) {
            this._model.castShadow = false;
          } else {
            assertIsTrue(this._shadowCastingMode === ModelShadowCastingMode.ON, "ShadowCastingMode " + this._shadowCastingMode + " is not supported.");
            this._model.castShadow = true;
          }
        };
        _proto._updateReceiveShadow = function _updateReceiveShadow() {
          if (!this._model) {
            return;
          }
          if (this._shadowReceivingMode === ModelShadowReceivingMode.OFF) {
            this._model.receiveShadow = false;
          } else {
            this._model.receiveShadow = true;
          }
        };
        _proto.onMobilityChanged = function onMobilityChanged() {
          this._updateUseLightProbe();
          this._updateReceiveDirLight();
        };
        _proto.onLightProbeBakingChanged = function onLightProbeBakingChanged() {
          this._updateReceiveDirLight();
        };
        _proto.onUseLightProbeChanged = function onUseLightProbeChanged() {
          this._updateUseLightProbe();
        };
        _proto.onReflectionProbeChanged = function onReflectionProbeChanged() {
          this._updateUseReflectionProbe();
          this._onUpdateLocalShadowBiasAndProbeId();
          if (this.bakeSettings.reflectionProbe === ReflectionProbeType.BAKED_CUBEMAP || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
            legacyCC.internal.reflectionProbeManager.selectReflectionProbe(this._model);
            if (!legacyCC.internal.reflectionProbeManager.getUsedReflectionProbe(this._model, false)) {
              warnID(16302);
            }
          } else if (this.bakeSettings.reflectionProbe === ReflectionProbeType.PLANAR_REFLECTION) {
            legacyCC.internal.reflectionProbeManager.selectPlanarReflectionProbe(this._model);
            if (!legacyCC.internal.reflectionProbeManager.getUsedReflectionProbe(this._model, true)) {
              warnID(16302);
            }
          }
        };
        _proto.onBakeToReflectionProbeChanged = function onBakeToReflectionProbeChanged() {
          this._updateBakeToReflectionProbe();
        };
        _proto._updateUseLightProbe = function _updateUseLightProbe() {
          if (!this._model) {
            return;
          }
          var node = this.node;
          if (this._mesh && node && node.mobility === MobilityMode.Movable && this.bakeSettings.useLightProbe) {
            this._model.useLightProbe = true;
          } else {
            this._model.useLightProbe = false;
          }
        };
        _proto._isBatchingEnabled = function _isBatchingEnabled() {
          for (var i = 0; i < this._materials.length; ++i) {
            var mat = this._materials[i];
            if (!mat) {
              continue;
            }
            for (var p = 0; p < mat.passes.length; ++p) {
              var pass = mat.passes[p];
              if (pass.batchingScheme) {
                return true;
              }
            }
          }
          return false;
        };
        _proto._updateUseReflectionProbe = function _updateUseReflectionProbe() {
          if (!this._model) return;
          this._model.reflectionProbeType = this.bakeSettings.reflectionProbe;
          this._updateReflectionProbeTexture();
        };
        _proto._updateUseReflectionProbeType = function _updateUseReflectionProbeType() {
          if (!this._model) return;
          this._model.reflectionProbeType = this.bakeSettings.reflectionProbe;
        };
        _proto._updateBakeToReflectionProbe = function _updateBakeToReflectionProbe() {
          if (!this._model) {
            return;
          }
          this._model.bakeToReflectionProbe = this.bakeSettings.bakeToReflectionProbe;
        };
        _proto._watchMorphInMesh = function _watchMorphInMesh() {
          if (this._morphInstance) {
            this._morphInstance.destroy();
            this._morphInstance = null;
          }
          if (!this._enableMorph) {
            return;
          }
          if (!this._mesh || !this._mesh.struct.morph || !this._mesh.morphRendering) {
            return;
          }
          this._morphInstance = this._mesh.morphRendering.createInstance();
          var nSubMeshes = this._mesh.struct.primitives.length;
          for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
            this._uploadSubMeshShapesWeights(iSubMesh);
          }
          if (this._model && this._model instanceof MorphModel) {
            this._model.setMorphRendering(this._morphInstance);
          }
        };
        _proto._initSubMeshShapesWeights = function _initSubMeshShapesWeights() {
          var mesh = this._mesh;
          this._subMeshShapesWeights.length = 0;
          if (!mesh) {
            return;
          }
          var morph = mesh.struct.morph;
          if (!morph) {
            return;
          }
          var commonWeights = morph.weights;
          this._subMeshShapesWeights = morph.subMeshMorphs.map(function (subMeshMorph) {
            if (!subMeshMorph) {
              return [];
            } else if (subMeshMorph.weights) {
              return subMeshMorph.weights.slice(0);
            } else if (commonWeights) {
              assertIsTrue(commonWeights.length === subMeshMorph.targets.length);
              return commonWeights.slice(0);
            } else {
              return new Array(subMeshMorph.targets.length).fill(0.0);
            }
          });
        };
        _proto._validateShapeWeights = function _validateShapeWeights() {
          var mesh = this._mesh,
            subMeshShapesWeights = this._subMeshShapesWeights;
          if (!mesh || !mesh.struct.morph) {
            return subMeshShapesWeights.length === 0;
          }
          var morph = mesh.struct.morph;
          if (morph.subMeshMorphs.length !== subMeshShapesWeights.length) {
            return false;
          }
          return subMeshShapesWeights.every(function (_ref, subMeshIndex) {
            var _morph$subMeshMorphs$, _morph$subMeshMorphs$2;
            var shapeCount = _ref.length;
            return ((_morph$subMeshMorphs$ = (_morph$subMeshMorphs$2 = morph.subMeshMorphs[subMeshIndex]) === null || _morph$subMeshMorphs$2 === void 0 ? void 0 : _morph$subMeshMorphs$2.targets.length) !== null && _morph$subMeshMorphs$ !== void 0 ? _morph$subMeshMorphs$ : 0) === shapeCount;
          });
        };
        _proto._uploadSubMeshShapesWeights = function _uploadSubMeshShapesWeights(subMeshIndex) {
          var _this$_morphInstance;
          (_this$_morphInstance = this._morphInstance) === null || _this$_morphInstance === void 0 ? void 0 : _this$_morphInstance.setWeights(subMeshIndex, this._subMeshShapesWeights[subMeshIndex]);
        };
        _proto._updateStandardSkin = function _updateStandardSkin() {
          var pipelineSceneData = legacyCC.director.root.pipeline.pipelineSceneData;
          if (this._enabledGlobalStandardSkinObject) {
            pipelineSceneData.standardSkinMeshRenderer = this;
            pipelineSceneData.standardSkinModel = this.model;
          }
          if (!pipelineSceneData.skinMaterialModel && this._model) {
            var subModels = this._model.subModels;
            for (var j = 0; j < subModels.length; j++) {
              var subModel = subModels[j];
              var skinPassIdx = getSkinPassIndex(subModel);
              if (skinPassIdx < 0) {
                continue;
              }
              pipelineSceneData.skinMaterialModel = this._model;
              return;
            }
          }
        };
        _createClass(MeshRenderer, [{
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
            this._updateShadowBias();
            this._onUpdateLocalShadowBiasAndProbeId();
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
            this._updateShadowNormalBias();
            this._onUpdateLocalShadowBiasAndProbeId();
          }
        }, {
          key: "shadowCastingMode",
          get: function get() {
            return this._shadowCastingMode;
          },
          set: function set(val) {
            this._shadowCastingMode = val;
            this._updateCastShadow();
          }
        }, {
          key: "shadowCastingModeForInspector",
          get: function get() {
            return this.shadowCastingMode === ModelShadowCastingMode.ON;
          },
          set: function set(val) {
            this.shadowCastingMode = val === true ? ModelShadowCastingMode.ON : ModelShadowCastingMode.OFF;
          }
        }, {
          key: "receiveShadow",
          get: function get() {
            return this._shadowReceivingMode;
          },
          set: function set(val) {
            this._shadowReceivingMode = val;
            this._updateReceiveShadow();
          }
        }, {
          key: "receiveShadowForInspector",
          get: function get() {
            return this._shadowReceivingMode === ModelShadowReceivingMode.ON;
          },
          set: function set(val) {
            this._shadowReceivingMode = val === true ? ModelShadowReceivingMode.ON : ModelShadowReceivingMode.OFF;
            this._updateReceiveShadow();
          }
        }, {
          key: "mesh",
          get: function get() {
            return this._mesh;
          },
          set: function set(val) {
            var old = this._mesh;
            var mesh = this._mesh = val;
            mesh === null || mesh === void 0 ? void 0 : mesh.initialize();
            this._initSubMeshShapesWeights();
            this._watchMorphInMesh();
            this._onMeshChanged(old);
            this._updateModels();
            if (this.enabledInHierarchy) {
              this._attachToScene();
            }
            this._updateCastShadow();
            this._updateReceiveShadow();
            this._updateUseLightProbe();
            this._updateUseReflectionProbe();
            this._updateReceiveDirLight();
          }
        }, {
          key: "model",
          get: function get() {
            return this._model;
          }
        }, {
          key: "enableMorph",
          get: function get() {
            return this._enableMorph;
          },
          set: function set(value) {
            this._enableMorph = value;
          }
        }, {
          key: "isGlobalStandardSkinObject",
          get: function get() {
            return this._enabledGlobalStandardSkinObject;
          },
          set: function set(val) {
            legacyCC.director.root.pipeline.pipelineSceneData.standardSkinMeshRenderer = val ? this : null;
            this._enabledGlobalStandardSkinObject = val;
          }
        }]);
        return MeshRenderer;
      }(ModelRenderer), _class6$9.ShadowCastingMode = ModelShadowCastingMode, _class6$9.ShadowReceivingMode = ModelShadowReceivingMode, _class6$9), (_initializer11$p = applyDecoratedInitializer(_class5$t.prototype, "bakeSettings", [serializable$m], function () {
        return new ModelBakeSettings(this);
      }), _initializer12$m = applyDecoratedInitializer(_class5$t.prototype, "_mesh", [serializable$m], function () {
        return null;
      }), _initializer13$j = applyDecoratedInitializer(_class5$t.prototype, "_shadowCastingMode", [serializable$m], function () {
        return ModelShadowCastingMode.OFF;
      }), _initializer14$f = applyDecoratedInitializer(_class5$t.prototype, "_shadowReceivingMode", [serializable$m], function () {
        return ModelShadowReceivingMode.ON;
      }), _initializer15$c = applyDecoratedInitializer(_class5$t.prototype, "_shadowBias", [serializable$m], function () {
        return 0;
      }), _initializer16$c = applyDecoratedInitializer(_class5$t.prototype, "_shadowNormalBias", [serializable$m], function () {
        return 0;
      }), _initializer17$9 = applyDecoratedInitializer(_class5$t.prototype, "_reflectionProbeId", [serializable$m], function () {
        return -1;
      }), _initializer18$9 = applyDecoratedInitializer(_class5$t.prototype, "_reflectionProbeBlendId", [serializable$m], function () {
        return -1;
      }), _initializer19$8 = applyDecoratedInitializer(_class5$t.prototype, "_reflectionProbeBlendWeight", [serializable$m], function () {
        return 0;
      }), _initializer20$6 = applyDecoratedInitializer(_class5$t.prototype, "_enabledGlobalStandardSkinObject", [serializable$m], function () {
        return false;
      }), _applyDecoratedDescriptor(_class5$t.prototype, "shadowBias", [_dec10$d], Object.getOwnPropertyDescriptor(_class5$t.prototype, "shadowBias"), _class5$t.prototype), _applyDecoratedDescriptor(_class5$t.prototype, "shadowNormalBias", [_dec11$9], Object.getOwnPropertyDescriptor(_class5$t.prototype, "shadowNormalBias"), _class5$t.prototype), _applyDecoratedDescriptor(_class5$t.prototype, "shadowCastingMode", [_dec12$8], Object.getOwnPropertyDescriptor(_class5$t.prototype, "shadowCastingMode"), _class5$t.prototype), _applyDecoratedDescriptor(_class5$t.prototype, "receiveShadow", [_dec13$6], Object.getOwnPropertyDescriptor(_class5$t.prototype, "receiveShadow"), _class5$t.prototype), _applyDecoratedDescriptor(_class5$t.prototype, "mesh", [_dec14$5], Object.getOwnPropertyDescriptor(_class5$t.prototype, "mesh"), _class5$t.prototype), _applyDecoratedDescriptor(_class5$t.prototype, "isGlobalStandardSkinObject", [_dec15$4], Object.getOwnPropertyDescriptor(_class5$t.prototype, "isGlobalStandardSkinObject"), _class5$t.prototype), _initializer21$6 = applyDecoratedInitializer(_class5$t.prototype, "_enableMorph", [serializable$m], function () {
        return true;
      })), _class5$t)) || _class4$s) || _class4$s));

      function checkMaterialisSame(comp1, comp2) {
        var matNum = comp1.sharedMaterials.length;
        if (matNum !== comp2.sharedMaterials.length) {
          return false;
        }
        for (var i = 0; i < matNum; i++) {
          if (comp1.getRenderMaterial(i) !== comp2.getRenderMaterial(i)) {
            return false;
          }
        }
        return true;
      }
      var BatchingUtility = exports('a8', function () {
        function BatchingUtility() {}
        BatchingUtility.batchStaticModel = function batchStaticModel(staticModelRoot, batchedRoot) {
          var models = staticModelRoot.getComponentsInChildren(MeshRenderer);
          if (models.length < 2) {
            console.error('the number of static models to batch is less than 2,it needn\'t batch.');
            return false;
          }
          for (var i = 1; i < models.length; i++) {
            if (!models[0].mesh.validateMergingMesh(models[i].mesh)) {
              console.error("the meshes of " + models[0].node.name + " and " + models[i].node.name + " can't be merged");
              return false;
            }
            if (!checkMaterialisSame(models[0], models[i])) {
              console.error("the materials of " + models[0].node.name + " and " + models[i].node.name + " can't be merged");
              return false;
            }
          }
          var batchedMesh = new Mesh();
          var worldMat = new Mat4();
          var rootWorldMatInv = new Mat4();
          staticModelRoot.getWorldMatrix(rootWorldMatInv);
          Mat4.invert(rootWorldMatInv, rootWorldMatInv);
          for (var _i = 0; _i < models.length; _i++) {
            var comp = models[_i];
            comp.node.getWorldMatrix(worldMat);
            Mat4.multiply(worldMat, rootWorldMatInv, worldMat);
            batchedMesh.merge(models[_i].mesh, worldMat);
            comp.enabled = false;
          }
          var batchedModel = batchedRoot.addComponent(MeshRenderer);
          batchedModel.mesh = batchedMesh;
          batchedModel.sharedMaterials = models[0].sharedMaterials;
          return true;
        };
        BatchingUtility.unbatchStaticModel = function unbatchStaticModel(staticModelRoot, batchedRoot) {
          var models = staticModelRoot.getComponentsInChildren(MeshRenderer);
          for (var i = 0; i < models.length; i++) {
            var comp = models[i];
            comp.enabled = true;
          }
          var batchedModel = batchedRoot.getComponent(MeshRenderer);
          if (batchedModel) {
            if (batchedModel.mesh) {
              batchedModel.mesh.destroyRenderingMesh();
            }
            batchedModel.destroy();
          }
          return true;
        };
        return BatchingUtility;
      }());

      replaceProperty(Mesh.prototype, 'Mesh.prototype', [{
        name: 'renderingMesh',
        newName: 'renderingSubMeshes'
      }]);
      removeProperty(Mesh.prototype, 'Mesh.prototype', [{
        name: 'hasFlatBuffers'
      }, {
        name: 'destroyFlatBuffers'
      }]);

      var _dec$2A, _dec2$1Z, _dec3$1r, _class$2y, _class2$2k, _initializer$2c, _initializer2$1S, _initializer3$1m;
      var Skeleton$1 = exports('aa', (_dec$2A = ccclass$M('cc.Skeleton'), _dec2$1Z = type$d([CCString]), _dec3$1r = type$d([Mat4]), _dec$2A(_class$2y = (_class2$2k = function (_Asset) {
        _inheritsLoose(Skeleton, _Asset);
        function Skeleton() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this._joints = _initializer$2c && _initializer$2c();
          _this._bindposes = _initializer2$1S && _initializer2$1S();
          _this._hash = _initializer3$1m && _initializer3$1m();
          _this._invBindposes = null;
          return _this;
        }
        var _proto = Skeleton.prototype;
        _proto.destroy = function destroy() {
          var _cclegacy$director$ro, _cclegacy$director$ro2;
          (_cclegacy$director$ro = legacyCC.director.root) === null || _cclegacy$director$ro === void 0 ? void 0 : (_cclegacy$director$ro2 = _cclegacy$director$ro.dataPoolManager) === null || _cclegacy$director$ro2 === void 0 ? void 0 : _cclegacy$director$ro2.releaseSkeleton(this);
          return _Asset.prototype.destroy.call(this);
        };
        _proto.validate = function validate() {
          return this.joints.length > 0 && this.bindposes.length > 0;
        };
        _createClass(Skeleton, [{
          key: "joints",
          get: function get() {
            return this._joints;
          },
          set: function set(value) {
            this._joints = value;
          }
        }, {
          key: "bindposes",
          get: function get() {
            return this._bindposes;
          },
          set: function set(value) {
            this._bindposes = value;
          }
        }, {
          key: "inverseBindposes",
          get: function get() {
            if (!this._invBindposes) {
              this._invBindposes = [];
              for (var i = 0; i < this._bindposes.length; i++) {
                var inv = new Mat4();
                Mat4.invert(inv, this._bindposes[i]);
                this._invBindposes.push(inv);
              }
            }
            return this._invBindposes;
          }
        }, {
          key: "hash",
          get: function get() {
            if (!this._hash) {
              var str = '';
              for (var i = 0; i < this._bindposes.length; i++) {
                var ibm = this._bindposes[i];
                str += ibm.m00.toPrecision(2) + " " + ibm.m01.toPrecision(2) + " " + ibm.m02.toPrecision(2) + " " + ibm.m03.toPrecision(2) + " " + ibm.m04.toPrecision(2) + " " + ibm.m05.toPrecision(2) + " " + ibm.m06.toPrecision(2) + " " + ibm.m07.toPrecision(2) + " " + ibm.m08.toPrecision(2) + " " + ibm.m09.toPrecision(2) + " " + ibm.m10.toPrecision(2) + " " + ibm.m11.toPrecision(2) + " " + ibm.m12.toPrecision(2) + " " + ibm.m13.toPrecision(2) + " " + ibm.m14.toPrecision(2) + " " + ibm.m15.toPrecision(2) + "\n";
              }
              this._hash = murmurhash2_32_gc(str, 666);
            }
            return this._hash;
          }
        }]);
        return Skeleton;
      }(Asset), (_initializer$2c = applyDecoratedInitializer(_class2$2k.prototype, "_joints", [_dec2$1Z], function () {
        return [];
      }), _initializer2$1S = applyDecoratedInitializer(_class2$2k.prototype, "_bindposes", [_dec3$1r], function () {
        return [];
      }), _initializer3$1m = applyDecoratedInitializer(_class2$2k.prototype, "_hash", [serializable$p], function () {
        return 0;
      })), _class2$2k)) || _class$2y));
      legacyCC.Skeleton = Skeleton$1;

      removeProperty(MeshRenderer.prototype, 'MeshRenderer.prototype', [{
        name: 'enableDynamicBatching'
      }, {
        name: 'recieveShadows'
      }]);
      legacyCC.ModelComponent = MeshRenderer;
      setClassAlias(MeshRenderer, 'cc.ModelComponent');

      var _dec$2z, _class$2x, _class2$2j, _initializer$2b, _initializer2$1R, _initializer3$1l, _dec2$1Y, _dec3$1q, _dec4$13, _class4$r, _class5$s, _initializer4$1a, _initializer5$W, _initializer6$L, _initializer7$B, _initializer8$x, _class6$8;
      var _color_tmp = new Vec3();
      var PhotometricTerm = Enum({
        LUMINOUS_FLUX: 0,
        LUMINANCE: 1
      });
      var StaticLightSettings = (_dec$2z = ccclass$M('cc.StaticLightSettings'), _dec$2z(_class$2x = (_class2$2j = function () {
        function StaticLightSettings() {
          this._baked = _initializer$2b && _initializer$2b();
          this._editorOnly = _initializer2$1R && _initializer2$1R();
          this._castShadow = _initializer3$1l && _initializer3$1l();
        }
        _createClass(StaticLightSettings, [{
          key: "editorOnly",
          get: function get() {
            return this._editorOnly;
          },
          set: function set(val) {
            this._editorOnly = val;
          }
        }, {
          key: "baked",
          get: function get() {
            return this._baked;
          },
          set: function set(val) {
            this._baked = val;
          }
        }, {
          key: "castShadow",
          get: function get() {
            return this._castShadow;
          },
          set: function set(val) {
            this._castShadow = val;
          }
        }]);
        return StaticLightSettings;
      }(), (_initializer$2b = applyDecoratedInitializer(_class2$2j.prototype, "_baked", [serializable$p], function () {
        return false;
      }), _initializer2$1R = applyDecoratedInitializer(_class2$2j.prototype, "_editorOnly", [serializable$p], function () {
        return false;
      }), _initializer3$1l = applyDecoratedInitializer(_class2$2j.prototype, "_castShadow", [serializable$p], function () {
        return false;
      })), _class2$2j)) || _class$2x);
      var Light = exports('ad', (_dec2$1Y = ccclass$M('cc.Light'), _dec3$1q = type$d(StaticLightSettings), _dec4$13 = type$d(Layers.BitMask), _dec2$1Y(_class4$r = (_class5$s = (_class6$8 = function (_Component) {
        _inheritsLoose(Light, _Component);
        function Light() {
          var _this;
          _this = _Component.call(this) || this;
          _this._color = _initializer4$1a && _initializer4$1a();
          _this._useColorTemperature = _initializer5$W && _initializer5$W();
          _this._colorTemperature = _initializer6$L && _initializer6$L();
          _this._staticSettings = _initializer7$B && _initializer7$B();
          _this._visibility = _initializer8$x && _initializer8$x();
          _this._type = LightType.UNKNOWN;
          _this._lightType = void 0;
          _this._light = null;
          _this._lightType = Light$1;
          return _this;
        }
        var _proto = Light.prototype;
        _proto.onLoad = function onLoad() {
          this._createLight();
        };
        _proto.onEnable = function onEnable() {
          this._attachToScene();
        };
        _proto.onDisable = function onDisable() {
          this._detachFromScene();
        };
        _proto.onDestroy = function onDestroy() {
          this._destroyLight();
        };
        _proto._createLight = function _createLight() {
          if (!this._light) {
            this._light = legacyCC.director.root.createLight(this._lightType);
          }
          this.color = this._color;
          this.useColorTemperature = this._useColorTemperature;
          this.colorTemperature = this._colorTemperature;
          this._light.node = this.node;
          this._light.baked = this.baked;
          this._light.visibility = this.visibility;
        };
        _proto._destroyLight = function _destroyLight() {
          if (this._light) {
            legacyCC.director.root.recycleLight(this._light);
            this._light = null;
          }
        };
        _proto._attachToScene = function _attachToScene() {
          this._detachFromScene();
          if (this._light && !this._light.scene && this.node.scene) {
            var renderScene = this._getRenderScene();
            switch (this._type) {
              case LightType.DIRECTIONAL:
                renderScene.addDirectionalLight(this._light);
                renderScene.setMainLight(this._light);
                break;
              case LightType.SPHERE:
                renderScene.addSphereLight(this._light);
                break;
              case LightType.SPOT:
                renderScene.addSpotLight(this._light);
                break;
              case LightType.POINT:
                renderScene.addPointLight(this._light);
                break;
              case LightType.RANGED_DIRECTIONAL:
                renderScene.addRangedDirLight(this._light);
                break;
            }
          }
        };
        _proto._detachFromScene = function _detachFromScene() {
          if (this._light && this._light.scene) {
            var renderScene = this._light.scene;
            switch (this._type) {
              case LightType.DIRECTIONAL:
                renderScene.removeDirectionalLight(this._light);
                renderScene.unsetMainLight(this._light);
                break;
              case LightType.SPHERE:
                renderScene.removeSphereLight(this._light);
                break;
              case LightType.SPOT:
                renderScene.removeSpotLight(this._light);
                break;
              case LightType.POINT:
                renderScene.removePointLight(this._light);
                break;
              case LightType.RANGED_DIRECTIONAL:
                renderScene.removeRangedDirLight(this._light);
                break;
            }
          }
        };
        _proto._onUpdateReceiveDirLight = function _onUpdateReceiveDirLight() {};
        _createClass(Light, [{
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(val) {
            this._color = val;
            if (this._light) {
              _color_tmp.x = val.r / 255.0;
              _color_tmp.y = val.g / 255.0;
              _color_tmp.z = val.b / 255.0;
              this._light.color = _color_tmp;
            }
          }
        }, {
          key: "useColorTemperature",
          get: function get() {
            return this._useColorTemperature;
          },
          set: function set(enable) {
            this._useColorTemperature = enable;
            if (this._light) {
              this._light.useColorTemperature = enable;
            }
          }
        }, {
          key: "colorTemperature",
          get: function get() {
            return this._colorTemperature;
          },
          set: function set(val) {
            this._colorTemperature = val;
            if (this._light) {
              this._light.colorTemperature = val;
            }
          }
        }, {
          key: "staticSettings",
          get: function get() {
            return this._staticSettings;
          },
          set: function set(val) {
            this._staticSettings = val;
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "baked",
          get: function get() {
            return this.staticSettings.baked;
          },
          set: function set(val) {
            this.staticSettings.baked = val;
            if (this._light !== null) {
              this._light.baked = val;
            }
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(vis) {
            this._visibility = vis;
            if (this._light) {
              this._light.visibility = vis;
            }
            this._onUpdateReceiveDirLight();
          }
        }]);
        return Light;
      }(Component), _class6$8.Type = LightType, _class6$8.PhotometricTerm = PhotometricTerm, _class6$8), (_initializer4$1a = applyDecoratedInitializer(_class5$s.prototype, "_color", [serializable$p], function () {
        return Color$1.WHITE.clone();
      }), _initializer5$W = applyDecoratedInitializer(_class5$s.prototype, "_useColorTemperature", [serializable$p], function () {
        return false;
      }), _initializer6$L = applyDecoratedInitializer(_class5$s.prototype, "_colorTemperature", [serializable$p], function () {
        return 6550;
      }), _initializer7$B = applyDecoratedInitializer(_class5$s.prototype, "_staticSettings", [serializable$p], function () {
        return new StaticLightSettings();
      }), _initializer8$x = applyDecoratedInitializer(_class5$s.prototype, "_visibility", [serializable$p], function () {
        return CAMERA_DEFAULT_MASK;
      }), _applyDecoratedDescriptor(_class5$s.prototype, "staticSettings", [_dec3$1q], Object.getOwnPropertyDescriptor(_class5$s.prototype, "staticSettings"), _class5$s.prototype), _applyDecoratedDescriptor(_class5$s.prototype, "visibility", [_dec4$13], Object.getOwnPropertyDescriptor(_class5$s.prototype, "visibility"), _class5$s.prototype)), _class5$s)) || _class4$r));

      var _dec$2y, _dec2$1X, _dec3$1p, _dec4$12, _dec5$Z, _dec6$J, _dec7$y, _dec8$o, _dec9$k, _dec10$c, _dec11$8, _dec12$7, _dec13$5, _dec14$4, _dec15$3, _dec16$3, _dec17$3, _dec18$3, _dec19$3, _dec20$3, _dec21$3, _dec22$3, _dec23$3, _dec24$3, _dec25$3, _dec26$3, _dec27$3, _dec28$3, _dec29$3, _dec30$2, _dec31$2, _dec32$2, _dec33$2, _dec34$2, _dec35$2, _dec36$2, _dec37$2, _dec38$2, _dec39$2, _class$2w, _class2$2i, _initializer$2a, _initializer2$1Q, _initializer3$1k, _initializer4$19, _initializer5$V, _initializer6$K, _initializer7$A, _initializer8$w, _initializer9$s, _initializer10$p, _initializer11$o, _initializer12$l, _initializer13$i, _initializer14$e, _initializer15$b, _initializer16$b, _initializer17$8, _initializer18$8, _initializer19$7;
      var ccclass$H = ccclass$M,
        property$1 = property$3,
        serializable$l = serializable$p,
        formerlySerializedAs$2 = formerlySerializedAs$4,
        type$9 = type$d;
      var DirectionalLight = exports('ac', (_dec$2y = ccclass$H('cc.DirectionalLight'), _dec2$1X = formerlySerializedAs$2('_illuminance'), _dec3$1p = type$9(CCInteger), _dec4$12 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 1
        }
      }), _dec5$Z = type$9(CCBoolean), _dec6$J = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 5
        }
      }), _dec7$y = type$9(PCFType), _dec8$o = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 6
        }
      }), _dec9$k = type$9(CCFloat), _dec10$c = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 7
        }
      }), _dec11$8 = type$9(CCFloat), _dec12$7 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 8
        }
      }), _dec13$5 = type$9(CCFloat), _dec14$4 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 9
        }
      }), _dec15$3 = type$9(CCFloat), _dec16$3 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 22
        }
      }), _dec17$3 = type$9(CCFloat), _dec18$3 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 10
        }
      }), _dec19$3 = type$9(CSMLevel), _dec20$3 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 11
        }
      }), _dec21$3 = type$9(CCBoolean), _dec22$3 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 12
        }
      }), _dec23$3 = type$9(CCFloat), _dec24$3 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 13
        }
      }), _dec25$3 = type$9(CSMOptimizationMode), _dec26$3 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 14
        }
      }), _dec27$3 = type$9(CCBoolean), _dec28$3 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 15
        }
      }), _dec29$3 = type$9(CCFloat), _dec30$2 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 16
        }
      }), _dec31$2 = type$9(CCFloat), _dec32$2 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 17
        }
      }), _dec33$2 = type$9(CCFloat), _dec34$2 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 19
        }
      }), _dec35$2 = type$9(CCBoolean), _dec36$2 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 20
        }
      }), _dec37$2 = type$9(CCBoolean), _dec38$2 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 21
        }
      }), _dec39$2 = type$9(CCFloat), _dec$2y(_class$2w = (_class2$2i = function (_Light) {
        _inheritsLoose(DirectionalLight, _Light);
        function DirectionalLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._illuminanceHDR = _initializer$2a && _initializer$2a();
          _this._illuminanceLDR = _initializer2$1Q && _initializer2$1Q();
          _this._shadowEnabled = _initializer3$1k && _initializer3$1k();
          _this._shadowPcf = _initializer4$19 && _initializer4$19();
          _this._shadowBias = _initializer5$V && _initializer5$V();
          _this._shadowNormalBias = _initializer6$K && _initializer6$K();
          _this._shadowSaturation = _initializer7$A && _initializer7$A();
          _this._shadowDistance = _initializer8$w && _initializer8$w();
          _this._shadowInvisibleOcclusionRange = _initializer9$s && _initializer9$s();
          _this._csmLevel = _initializer10$p && _initializer10$p();
          _this._csmLayerLambda = _initializer11$o && _initializer11$o();
          _this._csmOptimizationMode = _initializer12$l && _initializer12$l();
          _this._csmAdvancedOptions = _initializer13$i && _initializer13$i();
          _this._csmLayersTransition = _initializer14$e && _initializer14$e();
          _this._csmTransitionRange = _initializer15$b && _initializer15$b();
          _this._shadowFixedArea = _initializer16$b && _initializer16$b();
          _this._shadowNear = _initializer17$8 && _initializer17$8();
          _this._shadowFar = _initializer18$8 && _initializer18$8();
          _this._shadowOrthoSize = _initializer19$7 && _initializer19$7();
          _this._lightType = DirectionalLight$1;
          var highQualityMode = settings.querySettings(Settings.Category.RENDERING, 'highQualityMode');
          if (highQualityMode) {
            _this._shadowPcf = PCFType.SOFT_2X;
            _this._shadowDistance = 50;
            _this.enableCSM = true;
            _this.staticSettings.castShadow = true;
          }
          return _this;
        }
        var _proto = DirectionalLight.prototype;
        _proto._createLight = function _createLight() {
          _Light.prototype._createLight.call(this);
          this._type = LightType.DIRECTIONAL;
          if (this._light) {
            var dirLight = this._light;
            dirLight.illuminanceHDR = this._illuminanceHDR;
            dirLight.illuminanceLDR = this._illuminanceLDR;
            dirLight.shadowEnabled = this._shadowEnabled;
            dirLight.shadowPcf = this._shadowPcf;
            dirLight.shadowBias = this._shadowBias;
            dirLight.shadowNormalBias = this._shadowNormalBias;
            dirLight.shadowSaturation = this._shadowSaturation;
            dirLight.shadowDistance = this._shadowDistance;
            dirLight.shadowInvisibleOcclusionRange = this._shadowInvisibleOcclusionRange;
            dirLight.shadowFixedArea = this._shadowFixedArea;
            dirLight.shadowNear = this._shadowNear;
            dirLight.shadowFar = this._shadowFar;
            dirLight.shadowOrthoSize = this._shadowOrthoSize;
            dirLight.csmLevel = this._csmLevel;
            dirLight.csmLayerLambda = this._csmLayerLambda;
            dirLight.csmOptimizationMode = this._csmOptimizationMode;
            dirLight.csmLayersTransition = this._csmLayersTransition;
            dirLight.csmTransitionRange = this._csmTransitionRange;
          }
        };
        _proto._onUpdateReceiveDirLight = function _onUpdateReceiveDirLight() {
          if (!this._light) {
            return;
          }
          _Light.prototype._onUpdateReceiveDirLight.call(this);
          var scene = this.node.scene;
          if (!scene || !scene.renderScene) {
            return;
          }
          if (scene.renderScene.mainLight !== this._light) {
            return;
          }
          var models = scene.renderScene.models;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (!model.node) continue;
            var meshRender = model.node.getComponent(MeshRenderer);
            if (!meshRender) continue;
            meshRender.onUpdateReceiveDirLight(this._visibility);
          }
        };
        _createClass(DirectionalLight, [{
          key: "illuminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._illuminanceHDR;
            } else {
              return this._illuminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._illuminanceHDR = val;
              this._light && (this._light.illuminanceHDR = this._illuminanceHDR);
            } else {
              this._illuminanceLDR = val;
              this._light && (this._light.illuminanceLDR = this._illuminanceLDR);
            }
          }
        }, {
          key: "shadowEnabled",
          get: function get() {
            return this._shadowEnabled;
          },
          set: function set(val) {
            this._shadowEnabled = val;
            if (this._light) {
              this._light.shadowEnabled = this._shadowEnabled;
            }
          }
        }, {
          key: "shadowPcf",
          get: function get() {
            return this._shadowPcf;
          },
          set: function set(val) {
            this._shadowPcf = val;
            if (this._light) {
              this._light.shadowPcf = this._shadowPcf;
            }
          }
        }, {
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
            if (this._light) {
              this._light.shadowBias = this._shadowBias;
            }
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
            if (this._light) {
              this._light.shadowNormalBias = this._shadowNormalBias;
            }
          }
        }, {
          key: "shadowSaturation",
          get: function get() {
            return this._shadowSaturation;
          },
          set: function set(val) {
            this._shadowSaturation = clamp$1(val, 0.0, 1.0);
            if (this._light) {
              this._light.shadowSaturation = this._shadowSaturation;
            }
          }
        }, {
          key: "shadowDistance",
          get: function get() {
            return this._shadowDistance;
          },
          set: function set(val) {
            this._shadowDistance = Math.min(val, Shadows.MAX_FAR);
            if (this._shadowDistance / 0.1 < 10.0) {
              warnID(15003, this._shadowDistance);
            }
            if (this._light) {
              this._light.shadowDistance = this._shadowDistance;
              this._light.csmNeedUpdate = true;
            }
          }
        }, {
          key: "shadowInvisibleOcclusionRange",
          get: function get() {
            return this._shadowInvisibleOcclusionRange;
          },
          set: function set(val) {
            this._shadowInvisibleOcclusionRange = Math.min(val, Shadows.MAX_FAR);
            if (this._light) {
              this._light.shadowInvisibleOcclusionRange = this._shadowInvisibleOcclusionRange;
            }
          }
        }, {
          key: "csmLevel",
          get: function get() {
            return this._csmLevel;
          },
          set: function set(val) {
            this._csmLevel = val;
            if (this._light) {
              this._light.csmLevel = this._csmLevel;
              this._light.csmNeedUpdate = true;
            }
          }
        }, {
          key: "enableCSM",
          get: function get() {
            return this._csmLevel > CSMLevel.LEVEL_1;
          },
          set: function set(val) {
            this._csmLevel = val ? CSMLevel.LEVEL_4 : CSMLevel.LEVEL_1;
            if (this._light) {
              this._light.csmLevel = this._csmLevel;
              this._light.csmNeedUpdate = true;
            }
          }
        }, {
          key: "csmLayerLambda",
          get: function get() {
            return this._csmLayerLambda;
          },
          set: function set(val) {
            this._csmLayerLambda = val;
            if (this._light) {
              this._light.csmLayerLambda = this._csmLayerLambda;
              this._light.csmNeedUpdate = true;
            }
          }
        }, {
          key: "csmOptimizationMode",
          get: function get() {
            return this._csmOptimizationMode;
          },
          set: function set(val) {
            this._csmOptimizationMode = val;
            if (this._light) {
              this._light.csmOptimizationMode = this._csmOptimizationMode;
            }
          }
        }, {
          key: "shadowFixedArea",
          get: function get() {
            return this._shadowFixedArea;
          },
          set: function set(val) {
            this._shadowFixedArea = val;
            if (this._light) {
              this._light.shadowFixedArea = this._shadowFixedArea;
            }
          }
        }, {
          key: "shadowNear",
          get: function get() {
            return this._shadowNear;
          },
          set: function set(val) {
            this._shadowNear = val;
            if (this._light) {
              this._light.shadowNear = this._shadowNear;
            }
          }
        }, {
          key: "shadowFar",
          get: function get() {
            return this._shadowFar;
          },
          set: function set(val) {
            this._shadowFar = Math.min(val, Shadows.MAX_FAR);
            if (this._light) {
              this._light.shadowFar = this._shadowFar;
            }
          }
        }, {
          key: "shadowOrthoSize",
          get: function get() {
            return this._shadowOrthoSize;
          },
          set: function set(val) {
            this._shadowOrthoSize = val;
            if (this._light) {
              this._light.shadowOrthoSize = this._shadowOrthoSize;
            }
          }
        }, {
          key: "csmAdvancedOptions",
          get: function get() {
            return this._csmAdvancedOptions;
          },
          set: function set(val) {
            this._csmAdvancedOptions = val;
          }
        }, {
          key: "csmLayersTransition",
          get: function get() {
            return this._csmLayersTransition;
          },
          set: function set(val) {
            this._csmLayersTransition = val;
            if (this._light) {
              this._light.csmLayersTransition = val;
            }
          }
        }, {
          key: "csmTransitionRange",
          get: function get() {
            return this._csmTransitionRange;
          },
          set: function set(val) {
            this._csmTransitionRange = val;
            if (this._light) {
              this._light.csmTransitionRange = val;
            }
          }
        }]);
        return DirectionalLight;
      }(Light), (_initializer$2a = applyDecoratedInitializer(_class2$2i.prototype, "_illuminanceHDR", [property$1, _dec2$1X], function () {
        return 65000;
      }), _initializer2$1Q = applyDecoratedInitializer(_class2$2i.prototype, "_illuminanceLDR", [serializable$l], function () {
        return 65000 * Camera$1.standardExposureValue;
      }), _initializer3$1k = applyDecoratedInitializer(_class2$2i.prototype, "_shadowEnabled", [serializable$l], function () {
        return false;
      }), _initializer4$19 = applyDecoratedInitializer(_class2$2i.prototype, "_shadowPcf", [serializable$l], function () {
        return PCFType.HARD;
      }), _initializer5$V = applyDecoratedInitializer(_class2$2i.prototype, "_shadowBias", [serializable$l], function () {
        return 0.00001;
      }), _initializer6$K = applyDecoratedInitializer(_class2$2i.prototype, "_shadowNormalBias", [serializable$l], function () {
        return 0.0;
      }), _initializer7$A = applyDecoratedInitializer(_class2$2i.prototype, "_shadowSaturation", [serializable$l], function () {
        return 1.0;
      }), _initializer8$w = applyDecoratedInitializer(_class2$2i.prototype, "_shadowDistance", [serializable$l], function () {
        return 50;
      }), _initializer9$s = applyDecoratedInitializer(_class2$2i.prototype, "_shadowInvisibleOcclusionRange", [serializable$l], function () {
        return 200;
      }), _initializer10$p = applyDecoratedInitializer(_class2$2i.prototype, "_csmLevel", [serializable$l], function () {
        return CSMLevel.LEVEL_4;
      }), _initializer11$o = applyDecoratedInitializer(_class2$2i.prototype, "_csmLayerLambda", [serializable$l], function () {
        return 0.75;
      }), _initializer12$l = applyDecoratedInitializer(_class2$2i.prototype, "_csmOptimizationMode", [serializable$l], function () {
        return CSMOptimizationMode.RemoveDuplicates;
      }), _initializer13$i = applyDecoratedInitializer(_class2$2i.prototype, "_csmAdvancedOptions", [serializable$l], function () {
        return false;
      }), _initializer14$e = applyDecoratedInitializer(_class2$2i.prototype, "_csmLayersTransition", [serializable$l], function () {
        return false;
      }), _initializer15$b = applyDecoratedInitializer(_class2$2i.prototype, "_csmTransitionRange", [serializable$l], function () {
        return 0.05;
      }), _initializer16$b = applyDecoratedInitializer(_class2$2i.prototype, "_shadowFixedArea", [serializable$l], function () {
        return false;
      }), _initializer17$8 = applyDecoratedInitializer(_class2$2i.prototype, "_shadowNear", [serializable$l], function () {
        return 0.1;
      }), _initializer18$8 = applyDecoratedInitializer(_class2$2i.prototype, "_shadowFar", [serializable$l], function () {
        return 10.0;
      }), _initializer19$7 = applyDecoratedInitializer(_class2$2i.prototype, "_shadowOrthoSize", [serializable$l], function () {
        return 5;
      }), _applyDecoratedDescriptor(_class2$2i.prototype, "illuminance", [_dec3$1p], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "illuminance"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "shadowEnabled", [_dec4$12, _dec5$Z], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "shadowEnabled"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "shadowPcf", [_dec6$J, _dec7$y], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "shadowPcf"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "shadowBias", [_dec8$o, _dec9$k], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "shadowBias"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "shadowNormalBias", [_dec10$c, _dec11$8], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "shadowNormalBias"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "shadowSaturation", [_dec12$7, _dec13$5], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "shadowSaturation"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "shadowDistance", [_dec14$4, _dec15$3], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "shadowDistance"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "shadowInvisibleOcclusionRange", [_dec16$3, _dec17$3], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "shadowInvisibleOcclusionRange"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "csmLevel", [_dec18$3, _dec19$3], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "csmLevel"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "enableCSM", [_dec20$3, _dec21$3], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "enableCSM"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "csmLayerLambda", [_dec22$3, _dec23$3], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "csmLayerLambda"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "csmOptimizationMode", [_dec24$3, _dec25$3], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "csmOptimizationMode"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "shadowFixedArea", [_dec26$3, _dec27$3], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "shadowFixedArea"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "shadowNear", [_dec28$3, _dec29$3], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "shadowNear"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "shadowFar", [_dec30$2, _dec31$2], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "shadowFar"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "shadowOrthoSize", [_dec32$2, _dec33$2], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "shadowOrthoSize"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "csmAdvancedOptions", [_dec34$2, _dec35$2], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "csmAdvancedOptions"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "csmLayersTransition", [_dec36$2, _dec37$2], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "csmLayersTransition"), _class2$2i.prototype), _applyDecoratedDescriptor(_class2$2i.prototype, "csmTransitionRange", [_dec38$2, _dec39$2], Object.getOwnPropertyDescriptor(_class2$2i.prototype, "csmTransitionRange"), _class2$2i.prototype)), _class2$2i)) || _class$2w));

      var _dec$2x, _dec2$1W, _dec3$1o, _dec4$11, _dec5$Y, _dec6$I, _dec7$x, _class$2v, _class2$2h, _initializer$29, _initializer2$1P, _initializer3$1j, _initializer4$18, _initializer5$U;
      var SphereLight = exports('ae', (_dec$2x = ccclass$M('cc.SphereLight'), _dec2$1W = formerlySerializedAs$4('_luminance'), _dec3$1o = type$d(CCInteger), _dec4$11 = type$d(CCInteger), _dec5$Y = type$d(PhotometricTerm), _dec6$I = type$d(CCFloat), _dec7$x = type$d(CCFloat), _dec$2x(_class$2v = (_class2$2h = function (_Light) {
        _inheritsLoose(SphereLight, _Light);
        function SphereLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._size = _initializer$29 && _initializer$29();
          _this._luminanceHDR = _initializer2$1P && _initializer2$1P();
          _this._luminanceLDR = _initializer3$1j && _initializer3$1j();
          _this._term = _initializer4$18 && _initializer4$18();
          _this._range = _initializer5$U && _initializer5$U();
          _this._lightType = SphereLight$1;
          return _this;
        }
        var _proto = SphereLight.prototype;
        _proto._createLight = function _createLight() {
          _Light.prototype._createLight.call(this);
          this._type = LightType.SPHERE;
          this.size = this._size;
          this.range = this._range;
          if (this._light) {
            this._light.luminanceHDR = this._luminanceHDR;
            this._light.luminanceLDR = this._luminanceLDR;
          }
        };
        _createClass(SphereLight, [{
          key: "luminousFlux",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR * nt2lm(this._size);
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            var result = 0;
            if (isHDR) {
              this._luminanceHDR = val / nt2lm(this._size);
              result = this._luminanceHDR;
            } else {
              this._luminanceLDR = val;
              result = this._luminanceLDR;
            }
            this._light && (this._light.luminance = result);
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._luminanceHDR = val;
              this._light && (this._light.luminanceHDR = this._luminanceHDR);
            } else {
              this._luminanceLDR = val;
              this._light && (this._light.luminanceLDR = this._luminanceLDR);
            }
          }
        }, {
          key: "term",
          get: function get() {
            return this._term;
          },
          set: function set(val) {
            this._term = val;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(val) {
            this._size = val;
            if (this._light) {
              this._light.size = val;
            }
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(val) {
            this._range = val;
            if (this._light) {
              this._light.range = val;
            }
          }
        }]);
        return SphereLight;
      }(Light), (_initializer$29 = applyDecoratedInitializer(_class2$2h.prototype, "_size", [serializable$p], function () {
        return 0.15;
      }), _initializer2$1P = applyDecoratedInitializer(_class2$2h.prototype, "_luminanceHDR", [serializable$p, _dec2$1W], function () {
        return 1700 / nt2lm(0.15);
      }), _initializer3$1j = applyDecoratedInitializer(_class2$2h.prototype, "_luminanceLDR", [serializable$p], function () {
        return 1700 / nt2lm(0.15) * Camera$1.standardExposureValue * Camera$1.standardLightMeterScale;
      }), _initializer4$18 = applyDecoratedInitializer(_class2$2h.prototype, "_term", [serializable$p], function () {
        return PhotometricTerm.LUMINOUS_FLUX;
      }), _initializer5$U = applyDecoratedInitializer(_class2$2h.prototype, "_range", [serializable$p], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$2h.prototype, "luminousFlux", [_dec3$1o], Object.getOwnPropertyDescriptor(_class2$2h.prototype, "luminousFlux"), _class2$2h.prototype), _applyDecoratedDescriptor(_class2$2h.prototype, "luminance", [_dec4$11], Object.getOwnPropertyDescriptor(_class2$2h.prototype, "luminance"), _class2$2h.prototype), _applyDecoratedDescriptor(_class2$2h.prototype, "term", [_dec5$Y], Object.getOwnPropertyDescriptor(_class2$2h.prototype, "term"), _class2$2h.prototype), _applyDecoratedDescriptor(_class2$2h.prototype, "size", [_dec6$I], Object.getOwnPropertyDescriptor(_class2$2h.prototype, "size"), _class2$2h.prototype), _applyDecoratedDescriptor(_class2$2h.prototype, "range", [_dec7$x], Object.getOwnPropertyDescriptor(_class2$2h.prototype, "range"), _class2$2h.prototype)), _class2$2h)) || _class$2v));

      var _dec$2w, _dec2$1V, _dec3$1n, _dec4$10, _dec5$X, _dec6$H, _dec7$w, _dec8$n, _dec9$j, _dec10$b, _dec11$7, _dec12$6, _class$2u, _class2$2g, _initializer$28, _initializer2$1O, _initializer3$1i, _initializer4$17, _initializer5$T, _initializer6$J, _initializer7$z, _initializer8$v, _initializer9$r, _initializer10$o, _initializer11$n;
      var ccclass$G = ccclass$M,
        type$8 = type$d,
        serializable$k = serializable$p,
        formerlySerializedAs$1 = formerlySerializedAs$4,
        property = property$3;
      var SpotLight = exports('af', (_dec$2w = ccclass$G('cc.SpotLight'), _dec2$1V = formerlySerializedAs$1('_luminance'), _dec3$1n = type$8(PhotometricTerm), _dec4$10 = type$8(CCFloat), _dec5$X = property({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 1
        }
      }), _dec6$H = type$8(CCBoolean), _dec7$w = property({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 2
        }
      }), _dec8$n = type$8(PCFType), _dec9$j = property({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 3
        }
      }), _dec10$b = type$8(CCFloat), _dec11$7 = property({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 4
        }
      }), _dec12$6 = type$8(CCFloat), _dec$2w(_class$2u = (_class2$2g = function (_Light) {
        _inheritsLoose(SpotLight, _Light);
        function SpotLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._size = _initializer$28 && _initializer$28();
          _this._luminanceHDR = _initializer2$1O && _initializer2$1O();
          _this._luminanceLDR = _initializer3$1i && _initializer3$1i();
          _this._term = _initializer4$17 && _initializer4$17();
          _this._range = _initializer5$T && _initializer5$T();
          _this._spotAngle = _initializer6$J && _initializer6$J();
          _this._angleAttenuationStrength = _initializer7$z && _initializer7$z();
          _this._shadowEnabled = _initializer8$v && _initializer8$v();
          _this._shadowPcf = _initializer9$r && _initializer9$r();
          _this._shadowBias = _initializer10$o && _initializer10$o();
          _this._shadowNormalBias = _initializer11$n && _initializer11$n();
          _this._lightType = SpotLight$1;
          return _this;
        }
        var _proto = SpotLight.prototype;
        _proto._createLight = function _createLight() {
          _Light.prototype._createLight.call(this);
          this._type = LightType.SPOT;
          this.size = this._size;
          this.range = this._range;
          this.spotAngle = this._spotAngle;
          this.angleAttenuationStrength = this._angleAttenuationStrength;
          if (this._light) {
            var spotLight = this._light;
            spotLight.luminanceHDR = this._luminanceHDR;
            spotLight.luminanceLDR = this._luminanceLDR;
            spotLight.shadowEnabled = this._shadowEnabled;
            spotLight.shadowPcf = this._shadowPcf;
            spotLight.shadowBias = this._shadowBias;
            spotLight.shadowNormalBias = this._shadowNormalBias;
          }
        };
        _createClass(SpotLight, [{
          key: "luminousFlux",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR * nt2lm(this._size);
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            var result = 0;
            if (isHDR) {
              this._luminanceHDR = val / nt2lm(this._size);
              result = this._luminanceHDR;
            } else {
              this._luminanceLDR = val;
              result = this._luminanceLDR;
            }
            this._light && (this._light.luminance = result);
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._luminanceHDR = val;
              this._light && (this._light.luminanceHDR = this._luminanceHDR);
            } else {
              this._luminanceLDR = val;
              this._light && (this._light.luminanceLDR = this._luminanceLDR);
            }
          }
        }, {
          key: "term",
          get: function get() {
            return this._term;
          },
          set: function set(val) {
            this._term = val;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(val) {
            this._size = val;
            if (this._light) {
              this._light.size = val;
            }
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(val) {
            this._range = val;
            if (this._light) {
              this._light.range = val;
            }
          }
        }, {
          key: "spotAngle",
          get: function get() {
            return this._spotAngle;
          },
          set: function set(val) {
            this._spotAngle = val;
            if (this._light) {
              this._light.spotAngle = toRadian(val);
            }
          }
        }, {
          key: "angleAttenuationStrength",
          get: function get() {
            return this._angleAttenuationStrength;
          },
          set: function set(val) {
            this._angleAttenuationStrength = val;
            if (this._light) {
              this._light.angleAttenuationStrength = val;
            }
          }
        }, {
          key: "shadowEnabled",
          get: function get() {
            return this._shadowEnabled;
          },
          set: function set(val) {
            this._shadowEnabled = val;
            if (this._light) {
              this._light.shadowEnabled = val;
            }
          }
        }, {
          key: "shadowPcf",
          get: function get() {
            return this._shadowPcf;
          },
          set: function set(val) {
            this._shadowPcf = val;
            if (this._light) {
              this._light.shadowPcf = val;
            }
          }
        }, {
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
            if (this._light) {
              this._light.shadowBias = val;
            }
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
            if (this._light) {
              this._light.shadowNormalBias = val;
            }
          }
        }]);
        return SpotLight;
      }(Light), (_initializer$28 = applyDecoratedInitializer(_class2$2g.prototype, "_size", [serializable$k], function () {
        return 0.15;
      }), _initializer2$1O = applyDecoratedInitializer(_class2$2g.prototype, "_luminanceHDR", [serializable$k, _dec2$1V], function () {
        return 1700 / nt2lm(0.15);
      }), _initializer3$1i = applyDecoratedInitializer(_class2$2g.prototype, "_luminanceLDR", [serializable$k], function () {
        return 1700 / nt2lm(0.15) * Camera$1.standardExposureValue * Camera$1.standardLightMeterScale;
      }), _initializer4$17 = applyDecoratedInitializer(_class2$2g.prototype, "_term", [serializable$k], function () {
        return PhotometricTerm.LUMINOUS_FLUX;
      }), _initializer5$T = applyDecoratedInitializer(_class2$2g.prototype, "_range", [serializable$k], function () {
        return 1;
      }), _initializer6$J = applyDecoratedInitializer(_class2$2g.prototype, "_spotAngle", [serializable$k], function () {
        return 60;
      }), _initializer7$z = applyDecoratedInitializer(_class2$2g.prototype, "_angleAttenuationStrength", [serializable$k], function () {
        return 0;
      }), _initializer8$v = applyDecoratedInitializer(_class2$2g.prototype, "_shadowEnabled", [serializable$k], function () {
        return false;
      }), _initializer9$r = applyDecoratedInitializer(_class2$2g.prototype, "_shadowPcf", [serializable$k], function () {
        return PCFType.HARD;
      }), _initializer10$o = applyDecoratedInitializer(_class2$2g.prototype, "_shadowBias", [serializable$k], function () {
        return 0.00001;
      }), _initializer11$n = applyDecoratedInitializer(_class2$2g.prototype, "_shadowNormalBias", [serializable$k], function () {
        return 0.0;
      }), _applyDecoratedDescriptor(_class2$2g.prototype, "term", [_dec3$1n], Object.getOwnPropertyDescriptor(_class2$2g.prototype, "term"), _class2$2g.prototype), _applyDecoratedDescriptor(_class2$2g.prototype, "size", [_dec4$10], Object.getOwnPropertyDescriptor(_class2$2g.prototype, "size"), _class2$2g.prototype), _applyDecoratedDescriptor(_class2$2g.prototype, "shadowEnabled", [_dec5$X, _dec6$H], Object.getOwnPropertyDescriptor(_class2$2g.prototype, "shadowEnabled"), _class2$2g.prototype), _applyDecoratedDescriptor(_class2$2g.prototype, "shadowPcf", [_dec7$w, _dec8$n], Object.getOwnPropertyDescriptor(_class2$2g.prototype, "shadowPcf"), _class2$2g.prototype), _applyDecoratedDescriptor(_class2$2g.prototype, "shadowBias", [_dec9$j, _dec10$b], Object.getOwnPropertyDescriptor(_class2$2g.prototype, "shadowBias"), _class2$2g.prototype), _applyDecoratedDescriptor(_class2$2g.prototype, "shadowNormalBias", [_dec11$7, _dec12$6], Object.getOwnPropertyDescriptor(_class2$2g.prototype, "shadowNormalBias"), _class2$2g.prototype)), _class2$2g)) || _class$2u));

      var _dec$2v, _dec2$1U, _dec3$1m, _dec4$$, _dec5$W, _dec6$G, _class$2t, _class2$2f, _initializer$27, _initializer2$1N, _initializer3$1h, _initializer4$16;
      var PointLight = exports('ag', (_dec$2v = ccclass$M('cc.PointLight'), _dec2$1U = formerlySerializedAs$4('_luminance'), _dec3$1m = type$d(CCInteger), _dec4$$ = type$d(CCInteger), _dec5$W = type$d(PhotometricTerm), _dec6$G = type$d(CCFloat), _dec$2v(_class$2t = (_class2$2f = function (_Light) {
        _inheritsLoose(PointLight, _Light);
        function PointLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._luminanceHDR = _initializer$27 && _initializer$27();
          _this._luminanceLDR = _initializer2$1N && _initializer2$1N();
          _this._term = _initializer3$1h && _initializer3$1h();
          _this._range = _initializer4$16 && _initializer4$16();
          _this._lightType = PointLight$1;
          return _this;
        }
        var _proto = PointLight.prototype;
        _proto._createLight = function _createLight() {
          _Light.prototype._createLight.call(this);
          this._type = LightType.POINT;
          this.range = this._range;
          if (this._light) {
            this._light.luminanceHDR = this._luminanceHDR;
            this._light.luminanceLDR = this._luminanceLDR;
          }
        };
        _createClass(PointLight, [{
          key: "luminousFlux",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR * nt2lm(1.0);
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            var result = 0;
            if (isHDR) {
              this._luminanceHDR = val / nt2lm(1.0);
              result = this._luminanceHDR;
            } else {
              this._luminanceLDR = val;
              result = this._luminanceLDR;
            }
            this._light && (this._light.luminance = result);
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._luminanceHDR = val;
              this._light && (this._light.luminanceHDR = this._luminanceHDR);
            } else {
              this._luminanceLDR = val;
              this._light && (this._light.luminanceLDR = this._luminanceLDR);
            }
          }
        }, {
          key: "term",
          get: function get() {
            return this._term;
          },
          set: function set(val) {
            this._term = val;
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(val) {
            this._range = val;
            if (this._light) {
              this._light.range = val;
            }
          }
        }]);
        return PointLight;
      }(Light), (_initializer$27 = applyDecoratedInitializer(_class2$2f.prototype, "_luminanceHDR", [serializable$p, _dec2$1U], function () {
        return 1700 / nt2lm(0.15);
      }), _initializer2$1N = applyDecoratedInitializer(_class2$2f.prototype, "_luminanceLDR", [serializable$p], function () {
        return 1700 / nt2lm(0.15) * Camera$1.standardExposureValue * Camera$1.standardLightMeterScale;
      }), _initializer3$1h = applyDecoratedInitializer(_class2$2f.prototype, "_term", [serializable$p], function () {
        return PhotometricTerm.LUMINOUS_FLUX;
      }), _initializer4$16 = applyDecoratedInitializer(_class2$2f.prototype, "_range", [serializable$p], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$2f.prototype, "luminousFlux", [_dec3$1m], Object.getOwnPropertyDescriptor(_class2$2f.prototype, "luminousFlux"), _class2$2f.prototype), _applyDecoratedDescriptor(_class2$2f.prototype, "luminance", [_dec4$$], Object.getOwnPropertyDescriptor(_class2$2f.prototype, "luminance"), _class2$2f.prototype), _applyDecoratedDescriptor(_class2$2f.prototype, "term", [_dec5$W], Object.getOwnPropertyDescriptor(_class2$2f.prototype, "term"), _class2$2f.prototype), _applyDecoratedDescriptor(_class2$2f.prototype, "range", [_dec6$G], Object.getOwnPropertyDescriptor(_class2$2f.prototype, "range"), _class2$2f.prototype)), _class2$2f)) || _class$2t));

      var _dec$2u, _dec2$1T, _dec3$1l, _class$2s, _class2$2e, _initializer$26, _initializer2$1M;
      var RangedDirectionalLight = exports('ah', (_dec$2u = ccclass$M('cc.RangedDirectionalLight'), _dec2$1T = formerlySerializedAs$4('_illuminance'), _dec3$1l = type$d(CCInteger), _dec$2u(_class$2s = (_class2$2e = function (_Light) {
        _inheritsLoose(RangedDirectionalLight, _Light);
        function RangedDirectionalLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._illuminanceHDR = _initializer$26 && _initializer$26();
          _this._illuminanceLDR = _initializer2$1M && _initializer2$1M();
          _this._lightType = RangedDirectionalLight$1;
          return _this;
        }
        var _proto = RangedDirectionalLight.prototype;
        _proto._createLight = function _createLight() {
          _Light.prototype._createLight.call(this);
          this._type = LightType.RANGED_DIRECTIONAL;
          if (this._light) {
            this._light.illuminanceHDR = this._illuminanceHDR;
            this._light.illuminanceLDR = this._illuminanceLDR;
          }
        };
        _createClass(RangedDirectionalLight, [{
          key: "illuminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._illuminanceHDR;
            } else {
              return this._illuminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._illuminanceHDR = val;
              this._light && (this._light.illuminanceHDR = this._illuminanceHDR);
            } else {
              this._illuminanceLDR = val;
              this._light && (this._light.illuminanceLDR = this._illuminanceLDR);
            }
          }
        }]);
        return RangedDirectionalLight;
      }(Light), (_initializer$26 = applyDecoratedInitializer(_class2$2e.prototype, "_illuminanceHDR", [property$3, _dec2$1T], function () {
        return 65000;
      }), _initializer2$1M = applyDecoratedInitializer(_class2$2e.prototype, "_illuminanceLDR", [serializable$p], function () {
        return 65000 * Camera$1.standardExposureValue;
      }), _applyDecoratedDescriptor(_class2$2e.prototype, "illuminance", [_dec3$1l], Object.getOwnPropertyDescriptor(_class2$2e.prototype, "illuminance"), _class2$2e.prototype)), _class2$2e)) || _class$2s));

      legacyCC.LightComponent = Light;
      setClassAlias(Light, 'cc.LightComponent');
      legacyCC.DirectionalLightComponent = DirectionalLight;
      setClassAlias(DirectionalLight, 'cc.DirectionalLightComponent');
      legacyCC.SphereLightComponent = SphereLight;
      setClassAlias(SphereLight, 'cc.SphereLightComponent');
      legacyCC.SpotLightComponent = SpotLight;
      setClassAlias(SpotLight, 'cc.SpotLightComponent');
      replaceProperty(SpotLight.prototype, 'SpotLight.prototype', [{
        name: 'luminousPower',
        newName: 'luminousFlux',
        customGetter: function customGetter() {
          return this.luminousFlux;
        },
        customSetter: function customSetter(value) {
          this.luminousFlux = value;
        }
      }]);
      replaceProperty(SphereLight.prototype, 'SphereLight.prototype', [{
        name: 'luminousPower',
        newName: 'luminousFlux',
        customGetter: function customGetter() {
          return this.luminousFlux;
        },
        customSetter: function customSetter(value) {
          this.luminousFlux = value;
        }
      }]);
      replaceProperty(Light.PhotometricTerm, 'Light.PhotometricTerm', [{
        name: 'LUMINOUS_POWER',
        newName: 'LUMINOUS_FLUX'
      }]);

      var BAKE_SKELETON_CURVE_SYMBOL = Symbol('BakeNodeCurves');

      var SkelAnimDataHub = exports('gb', function () {
        function SkelAnimDataHub() {}
        SkelAnimDataHub.getOrExtract = function getOrExtract(clip) {
          var data = SkelAnimDataHub.pool.get(clip);
          if (!data || data.samples !== clip.sample) {
            if (data) {
              legacyCC.director.root.dataPoolManager.releaseAnimationClip(clip);
            }
            var frames = Math.ceil(clip.sample * clip.duration) + 1;
            var step = clip.sample;
            data = clip[BAKE_SKELETON_CURVE_SYMBOL](0, step, frames);
            SkelAnimDataHub.pool.set(clip, data);
          }
          return data;
        };
        SkelAnimDataHub.destroy = function destroy(clip) {
          SkelAnimDataHub.pool["delete"](clip);
        };
        return SkelAnimDataHub;
      }());
      SkelAnimDataHub.pool = new Map();

      var m4_1$4 = new Mat4();
      function getPathFromRoot(target, root) {
        var node = target;
        var path = '';
        while (node !== null && node !== root) {
          path = node.name + "/" + path;
          node = node.parent;
        }
        return path.slice(0, -1);
      }
      function getWorldTransformUntilRoot(target, root, outMatrix) {
        Mat4.identity(outMatrix);
        while (target !== root) {
          Mat4.fromRTS(m4_1$4, target.rotation, target.position, target.scale);
          Mat4.multiply(outMatrix, m4_1$4, outMatrix);
          target = target.parent;
        }
        return outMatrix;
      }

      var jointTextureSamplerInfo = new SamplerInfo(Filter$1.POINT, Filter$1.POINT, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP);

      var uploadJointData = uploadJointDataLBS;
      var MINIMUM_JOINT_TEXTURE_SIZE = 480;
      function selectJointsMediumFormat(device) {
        if (device.getFormatFeatures(Format.RGBA32F) & FormatFeatureBit.SAMPLED_TEXTURE) {
          return Format.RGBA32F;
        }
        return Format.RGBA8;
      }
      function uploadJointDataLBS(out, base, mat, firstBone) {
        out[base + 0] = mat.m00;
        out[base + 1] = mat.m01;
        out[base + 2] = mat.m02;
        out[base + 3] = mat.m12;
        out[base + 4] = mat.m04;
        out[base + 5] = mat.m05;
        out[base + 6] = mat.m06;
        out[base + 7] = mat.m13;
        out[base + 8] = mat.m08;
        out[base + 9] = mat.m09;
        out[base + 10] = mat.m10;
        out[base + 11] = mat.m14;
      }
      new Quat();
      new Quat();
      new Vec3();
      new Quat();
      new Vec3();
      function roundUpTextureSize(targetLength, formatSize) {
        var formatScale = 4 / Math.sqrt(formatSize);
        return Math.ceil(Math.max(MINIMUM_JOINT_TEXTURE_SIZE * formatScale, targetLength) / 12) * 12;
      }
      var v3_3 = new Vec3();
      var v3_4 = new Vec3();
      var v3_min$1 = new Vec3();
      var v3_max$1 = new Vec3();
      var m4_1$3 = new Mat4();
      var m4_2$2 = new Mat4();
      var ab_1$1 = new AABB();
      var Inf = Number.MAX_SAFE_INTEGER;
      var JointTexturePool = function () {
        function JointTexturePool(device) {
          this._device = void 0;
          this._pool = void 0;
          this._textureBuffers = new Map();
          this._formatSize = void 0;
          this._pixelsPerJoint = void 0;
          this._customPool = void 0;
          this._chunkIdxMap = new Map();
          this._device = device;
          var format = selectJointsMediumFormat(this._device);
          this._formatSize = FormatInfos[format].size;
          this._pixelsPerJoint = 48 / this._formatSize;
          this._pool = new TextureBufferPool(device);
          this._pool.initialize({
            format: format,
            roundUpFn: roundUpTextureSize
          });
          this._customPool = new TextureBufferPool(device);
          this._customPool.initialize({
            format: format,
            roundUpFn: roundUpTextureSize
          });
        }
        var _proto = JointTexturePool.prototype;
        _proto.clear = function clear() {
          this._pool.destroy();
          this._textureBuffers.clear();
        };
        _proto.registerCustomTextureLayouts = function registerCustomTextureLayouts(layouts) {
          for (var i = 0; i < layouts.length; i++) {
            var layout = layouts[i];
            var textureLength = layout.textureLength;
            if (!(this._device.getFormatFeatures(Format.RGBA32F) & FormatFeatureBit.SAMPLED_TEXTURE)) {
              textureLength *= 2;
            }
            var chunkIdx = this._customPool.createChunk(textureLength);
            for (var j = 0; j < layout.contents.length; j++) {
              var content = layout.contents[j];
              var skeleton = content.skeleton;
              this._chunkIdxMap.set(skeleton, chunkIdx);
              for (var k = 0; k < content.clips.length; k++) {
                var clip = content.clips[k];
                this._chunkIdxMap.set(skeleton ^ clip, chunkIdx);
              }
            }
          }
        };
        _proto.getDefaultPoseTexture = function getDefaultPoseTexture(skeleton, mesh, skinningRoot) {
          var hash = skeleton.hash ^ 0;
          var texture = this._textureBuffers.get(hash) || null;
          if (texture && texture.bounds.has(mesh.hash)) {
            texture.refCount++;
            return texture;
          }
          var joints = skeleton.joints,
            bindposes = skeleton.bindposes;
          var textureBuffer = null;
          var buildTexture = false;
          var jointCount = joints.length;
          if (!texture) {
            var bufSize = jointCount * 12;
            var customChunkIdx = this._chunkIdxMap.get(hash);
            var handle = customChunkIdx !== undefined ? this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) : this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT);
            if (!handle) {
              return texture;
            }
            texture = {
              pixelOffset: handle.start / this._formatSize,
              refCount: 1,
              bounds: new Map(),
              skeletonHash: skeleton.hash,
              clipHash: 0,
              readyToBeDeleted: false,
              handle: handle
            };
            textureBuffer = new Float32Array(bufSize);
            buildTexture = true;
          } else {
            texture.refCount++;
          }
          Vec3.set(v3_min$1, Inf, Inf, Inf);
          Vec3.set(v3_max$1, -Inf, -Inf, -Inf);
          var boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton);
          for (var j = 0, offset = 0; j < jointCount; j++, offset += 12) {
            var node = skinningRoot.getChildByPath(joints[j]);
            var mat = node ? getWorldTransformUntilRoot(node, skinningRoot, m4_1$3) : skeleton.inverseBindposes[j];
            var bound = boneSpaceBounds[j];
            if (bound) {
              AABB.transform(ab_1$1, bound, mat);
              ab_1$1.getBoundary(v3_3, v3_4);
              Vec3.min(v3_min$1, v3_min$1, v3_3);
              Vec3.max(v3_max$1, v3_max$1, v3_4);
            }
            if (buildTexture) {
              if (node) {
                Mat4.multiply(mat, mat, bindposes[j]);
              }
              uploadJointData(textureBuffer, offset, node ? mat : Mat4.IDENTITY);
            }
          }
          var bounds = [new AABB()];
          texture.bounds.set(mesh.hash, bounds);
          AABB.fromPoints(bounds[0], v3_min$1, v3_max$1);
          if (buildTexture) {
            this._pool.update(texture.handle, textureBuffer.buffer);
            this._textureBuffers.set(hash, texture);
          }
          return texture;
        };
        _proto.getSequencePoseTexture = function getSequencePoseTexture(skeleton, clip, mesh, skinningRoot) {
          var hash = skeleton.hash ^ clip.hash;
          var texture = this._textureBuffers.get(hash) || null;
          if (texture && texture.bounds.has(mesh.hash)) {
            texture.refCount++;
            return texture;
          }
          var joints = skeleton.joints,
            bindposes = skeleton.bindposes;
          var clipData = SkelAnimDataHub.getOrExtract(clip);
          var frames = clipData.frames;
          var textureBuffer = null;
          var buildTexture = false;
          var jointCount = joints.length;
          if (!texture) {
            var bufSize = jointCount * 12 * frames;
            var customChunkIdx = this._chunkIdxMap.get(hash);
            var handle = customChunkIdx !== undefined ? this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) : this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT);
            if (!handle) {
              return null;
            }
            var animInfos = this._createAnimInfos(skeleton, clip, skinningRoot);
            texture = {
              pixelOffset: handle.start / this._formatSize,
              refCount: 1,
              bounds: new Map(),
              skeletonHash: skeleton.hash,
              clipHash: clip.hash,
              readyToBeDeleted: false,
              handle: handle,
              animInfos: animInfos
            };
            textureBuffer = new Float32Array(bufSize);
            buildTexture = true;
          } else {
            texture.refCount++;
          }
          var boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton);
          var bounds = [];
          texture.bounds.set(mesh.hash, bounds);
          for (var f = 0; f < frames; f++) {
            bounds.push(new AABB(Inf, Inf, Inf, -Inf, -Inf, -Inf));
          }
          for (var _f = 0, offset = 0; _f < frames; _f++) {
            var bound = bounds[_f];
            for (var j = 0; j < jointCount; j++, offset += 12) {
              var _j = texture.animInfos[j],
                curveData = _j.curveData,
                downstream = _j.downstream,
                bindposeIdx = _j.bindposeIdx,
                bindposeCorrection = _j.bindposeCorrection;
              var mat = void 0;
              var transformValid = true;
              if (curveData && downstream) {
                mat = Mat4.multiply(m4_1$3, curveData[_f], downstream);
              } else if (curveData) {
                mat = curveData[_f];
              } else if (downstream) {
                mat = downstream;
              } else {
                mat = skeleton.inverseBindposes[bindposeIdx];
                transformValid = false;
              }
              var boneSpaceBound = boneSpaceBounds[j];
              if (boneSpaceBound) {
                var transform = bindposeCorrection ? Mat4.multiply(m4_2$2, mat, bindposeCorrection) : mat;
                AABB.transform(ab_1$1, boneSpaceBound, transform);
                ab_1$1.getBoundary(v3_3, v3_4);
                Vec3.min(bound.center, bound.center, v3_3);
                Vec3.max(bound.halfExtents, bound.halfExtents, v3_4);
              }
              if (buildTexture) {
                if (transformValid) {
                  Mat4.multiply(m4_1$3, mat, bindposes[bindposeIdx]);
                }
                uploadJointData(textureBuffer, offset, transformValid ? m4_1$3 : Mat4.IDENTITY);
              }
            }
            AABB.fromPoints(bound, bound.center, bound.halfExtents);
          }
          if (buildTexture) {
            this._pool.update(texture.handle, textureBuffer.buffer);
            this._textureBuffers.set(hash, texture);
          }
          return texture;
        };
        _proto.releaseHandle = function releaseHandle(handle) {
          if (handle.refCount > 0) {
            handle.refCount--;
          }
          if (!handle.refCount && handle.readyToBeDeleted) {
            var hash = handle.skeletonHash ^ handle.clipHash;
            var customChunkIdx = this._chunkIdxMap.get(hash);
            (customChunkIdx !== undefined ? this._customPool : this._pool).free(handle.handle);
            if (this._textureBuffers.get(hash) === handle) {
              this._textureBuffers["delete"](hash);
            }
          }
        };
        _proto.releaseSkeleton = function releaseSkeleton(skeleton) {
          var it = this._textureBuffers.values();
          var res = it.next();
          while (!res.done) {
            var handle = res.value;
            if (handle.skeletonHash === skeleton.hash) {
              handle.readyToBeDeleted = true;
              if (handle.refCount) {
                this._textureBuffers["delete"](handle.skeletonHash ^ handle.clipHash);
              } else {
                this.releaseHandle(handle);
              }
            }
            res = it.next();
          }
        };
        _proto.releaseAnimationClip = function releaseAnimationClip(clip) {
          var it = this._textureBuffers.values();
          var res = it.next();
          while (!res.done) {
            var handle = res.value;
            if (handle.clipHash === clip.hash) {
              handle.readyToBeDeleted = true;
              if (handle.refCount) {
                this._textureBuffers["delete"](handle.skeletonHash ^ handle.clipHash);
              } else {
                this.releaseHandle(handle);
              }
            }
            res = it.next();
          }
        };
        _proto._createAnimInfos = function _createAnimInfos(skeleton, clip, skinningRoot) {
          var animInfos = [];
          var joints = skeleton.joints,
            bindposes = skeleton.bindposes;
          var jointCount = joints.length;
          var clipData = SkelAnimDataHub.getOrExtract(clip);
          for (var j = 0; j < jointCount; j++) {
            var animPath = joints[j];
            var source = clipData.joints[animPath];
            var animNode = skinningRoot.getChildByPath(animPath);
            var downstream = void 0;
            var correctionPath = void 0;
            while (!source) {
              var idx = animPath.lastIndexOf('/');
              animPath = animPath.substring(0, idx);
              source = clipData.joints[animPath];
              if (animNode) {
                if (!downstream) {
                  downstream = new Mat4();
                }
                Mat4.fromRTS(m4_1$3, animNode.rotation, animNode.position, animNode.scale);
                Mat4.multiply(downstream, m4_1$3, downstream);
                animNode = animNode.parent;
              } else {
                correctionPath = animPath;
              }
              if (idx < 0) {
                break;
              }
            }
            var bindposeIdx = j;
            var bindposeCorrection = void 0;
            if (correctionPath !== undefined && source) {
              bindposeIdx = j - 1;
              for (var t = 0; t < jointCount; t++) {
                if (joints[t] === correctionPath) {
                  bindposeIdx = t;
                  bindposeCorrection = new Mat4();
                  Mat4.multiply(bindposeCorrection, bindposes[t], skeleton.inverseBindposes[j]);
                  break;
                }
              }
            }
            animInfos.push({
              curveData: source && source.transforms,
              downstream: downstream,
              bindposeIdx: bindposeIdx,
              bindposeCorrection: bindposeCorrection
            });
          }
          return animInfos;
        };
        _createClass(JointTexturePool, [{
          key: "pixelsPerJoint",
          get: function get() {
            return this._pixelsPerJoint;
          }
        }]);
        return JointTexturePool;
      }();
      var JointAnimationInfo = function () {
        function JointAnimationInfo(device) {
          this._pool = new Map();
          this._device = void 0;
          this._device = device;
        }
        var _proto2 = JointAnimationInfo.prototype;
        _proto2.getData = function getData(nodeID) {
          if (nodeID === void 0) {
            nodeID = '-1';
          }
          var res = this._pool.get(nodeID);
          if (res) {
            return res;
          }
          var buffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOSkinningAnimation.SIZE, UBOSkinningAnimation.SIZE));
          var data = new Float32Array([0, 0, 0, 0]);
          buffer.update(data);
          var info = {
            buffer: buffer,
            data: data,
            dirty: false,
            dirtyForJSB: new Uint8Array([0]),
            currentClip: null
          };
          this._pool.set(nodeID, info);
          return info;
        };
        _proto2.destroy = function destroy(nodeID) {
          var info = this._pool.get(nodeID);
          if (!info) {
            return;
          }
          info.buffer.destroy();
          this._pool["delete"](nodeID);
        };
        _proto2.switchClip = function switchClip(info, clip) {
          info.currentClip = clip;
          info.data[0] = 0;
          info.buffer.update(info.data);
          info.dirty = false;
          return info;
        };
        _proto2.clear = function clear() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._pool.values()), _step; !(_step = _iterator()).done;) {
            var info = _step.value;
            info.buffer.destroy();
          }
          this._pool.clear();
        };
        return JointAnimationInfo;
      }();

      var stack = [];
      var pool$1 = new Map();
      function getWorldMatrix(transform, stamp) {
        var i = 0;
        var res = Mat4.IDENTITY;
        while (transform) {
          if (transform.stamp === stamp || transform.stamp + 1 === stamp && !transform.node.hasChangedFlags) {
            res = transform.world;
            transform.stamp = stamp;
            break;
          }
          transform.stamp = stamp;
          stack[i++] = transform;
          transform = transform.parent;
        }
        while (i > 0) {
          transform = stack[--i];
          stack[i] = null;
          var node = transform.node;
          Mat4.fromRTS(transform.local, node.rotation, node.position, node.scale);
          res = Mat4.multiply(transform.world, res, transform.local);
        }
        return res;
      }
      function getTransform(node, root) {
        var joint = null;
        var i = 0;
        while (node !== root) {
          var id = node.uuid;
          if (pool$1.has(id)) {
            joint = pool$1.get(id);
            break;
          } else {
            joint = {
              node: node,
              local: new Mat4(),
              world: new Mat4(),
              stamp: -1,
              parent: null
            };
            pool$1.set(id, joint);
          }
          stack[i++] = joint;
          node = node.parent;
          joint = null;
        }
        var child;
        while (i > 0) {
          child = stack[--i];
          stack[i] = null;
          child.parent = joint;
          joint = child;
        }
        return joint;
      }
      function deleteTransform(node) {
        var transform = pool$1.get(node.uuid) || null;
        while (transform) {
          pool$1["delete"](transform.node.uuid);
          transform = transform.parent;
        }
      }

      var uniformPatches = [{
        name: 'CC_USE_SKINNING',
        value: true
      }, {
        name: 'CC_USE_REAL_TIME_JOINT_TEXTURE',
        value: false
      }];
      var texturePatches = [{
        name: 'CC_USE_SKINNING',
        value: true
      }, {
        name: 'CC_USE_REAL_TIME_JOINT_TEXTURE',
        value: true
      }];
      function getRelevantBuffers(outIndices, outBuffers, jointMaps, targetJoint) {
        for (var i = 0; i < jointMaps.length; i++) {
          var idxMap = jointMaps[i];
          var index = -1;
          for (var j = 0; j < idxMap.length; j++) {
            if (idxMap[j] === targetJoint) {
              index = j;
              break;
            }
          }
          if (index >= 0) {
            outBuffers.push(i);
            outIndices.push(index);
          }
        }
      }
      var v3_min = new Vec3();
      var v3_max = new Vec3();
      var v3_1$4 = new Vec3();
      var v3_2$1 = new Vec3();
      var m4_1$2 = new Mat4();
      var ab_1 = new AABB();
      var RealTimeJointTexture = function RealTimeJointTexture() {
        this._format = PixelFormat.RGBA32F;
        this._textures = [];
        this._buffers = [];
      };
      RealTimeJointTexture.WIDTH = 256;
      RealTimeJointTexture.HEIGHT = 3;
      var SkinningModel = function (_MorphModel) {
        _inheritsLoose(SkinningModel, _MorphModel);
        function SkinningModel() {
          var _this;
          _this = _MorphModel.call(this) || this;
          _this._buffers = [];
          _this._dataArray = [];
          _this._joints = [];
          _this._bufferIndices = null;
          _this._realTimeJointTexture = new RealTimeJointTexture();
          _this._realTimeTextureMode = false;
          _this.type = ModelType.SKINNING;
          return _this;
        }
        var _proto = SkinningModel.prototype;
        _proto.destroy = function destroy() {
          this.bindSkeleton();
          if (this._buffers.length) {
            for (var i = 0; i < this._buffers.length; i++) {
              this._buffers[i].destroy();
            }
            this._buffers.length = 0;
          }
          this._dataArray.length = 0;
          this._realTimeJointTexture._textures.forEach(function (tex) {
            tex.destroy();
          });
          this._realTimeJointTexture._textures.length = 0;
          this._realTimeJointTexture._buffers.length = 0;
          _MorphModel.prototype.destroy.call(this);
        };
        _proto.uploadAnimation = function uploadAnimation() {};
        _proto.bindSkeleton = function bindSkeleton(skeleton, skinningRoot, mesh) {
          if (skeleton === void 0) {
            skeleton = null;
          }
          if (skinningRoot === void 0) {
            skinningRoot = null;
          }
          if (mesh === void 0) {
            mesh = null;
          }
          for (var i = 0; i < this._joints.length; i++) {
            deleteTransform(this._joints[i].target);
          }
          this._bufferIndices = null;
          this._joints.length = 0;
          if (!skeleton || !skinningRoot || !mesh) {
            return;
          }
          this._realTimeTextureMode = false;
          if (UBOSkinning.JOINT_UNIFORM_CAPACITY < skeleton.joints.length) {
            this._realTimeTextureMode = true;
          }
          this.transform = skinningRoot;
          var boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton);
          var jointMaps = mesh.struct.jointMaps;
          this._ensureEnoughBuffers(jointMaps && jointMaps.length || 1);
          this._bufferIndices = mesh.jointBufferIndices;
          this._initRealTimeJointTexture();
          for (var index = 0; index < skeleton.joints.length; index++) {
            var bound = boneSpaceBounds[index];
            var target = skinningRoot.getChildByPath(skeleton.joints[index]);
            if (!bound || !target) {
              continue;
            }
            var transform = getTransform(target, skinningRoot);
            var bindpose = skeleton.bindposes[index];
            var indices = [];
            var buffers = [];
            if (!jointMaps) {
              indices.push(index);
              buffers.push(0);
            } else {
              getRelevantBuffers(indices, buffers, jointMaps, index);
            }
            this._joints.push({
              indices: indices,
              buffers: buffers,
              bound: bound,
              target: target,
              bindpose: bindpose,
              transform: transform
            });
          }
        };
        _proto.updateTransform = function updateTransform(stamp) {
          var root = this.transform;
          if (root.hasChangedFlags || root.isTransformDirty()) {
            root.updateWorldTransform();
            this._localDataUpdated = true;
          }
          Vec3.set(v3_min, Infinity, Infinity, Infinity);
          Vec3.set(v3_max, -Infinity, -Infinity, -Infinity);
          for (var i = 0; i < this._joints.length; i++) {
            var _this$_joints$i = this._joints[i],
              bound = _this$_joints$i.bound,
              transform = _this$_joints$i.transform;
            var worldMatrix = getWorldMatrix(transform, stamp);
            AABB.transform(ab_1, bound, worldMatrix);
            ab_1.getBoundary(v3_1$4, v3_2$1);
            Vec3.min(v3_min, v3_min, v3_1$4);
            Vec3.max(v3_max, v3_max, v3_2$1);
          }
          var worldBounds = this._worldBounds;
          if (this._modelBounds && worldBounds) {
            AABB.fromPoints(this._modelBounds, v3_min, v3_max);
            this._modelBounds.transform(root._mat, root._pos, root._rot, root._scale, this._worldBounds);
          }
        };
        _proto.updateUBOs = function updateUBOs(stamp) {
          _MorphModel.prototype.updateUBOs.call(this, stamp);
          for (var i = 0; i < this._joints.length; i++) {
            var _this$_joints$i2 = this._joints[i],
              indices = _this$_joints$i2.indices,
              buffers = _this$_joints$i2.buffers,
              transform = _this$_joints$i2.transform,
              bindpose = _this$_joints$i2.bindpose;
            Mat4.multiply(m4_1$2, transform.world, bindpose);
            for (var b = 0; b < buffers.length; b++) {
              uploadJointData(this._dataArray[buffers[b]], indices[b] * 12, m4_1$2);
            }
          }
          if (this._realTimeTextureMode) {
            this._updateRealTimeJointTextureBuffer();
          } else {
            for (var _b = 0; _b < this._buffers.length; _b++) {
              this._buffers[_b].update(this._dataArray[_b]);
            }
          }
          return true;
        };
        _proto.initSubModel = function initSubModel(idx, subMeshData, mat) {
          var original = subMeshData.vertexBuffers;
          var iaInfo = subMeshData.iaInfo;
          iaInfo.vertexBuffers = subMeshData.jointMappedBuffers;
          _MorphModel.prototype.initSubModel.call(this, idx, subMeshData, mat);
          iaInfo.vertexBuffers = original;
        };
        _proto.getMacroPatches = function getMacroPatches(subModelIndex) {
          var superMacroPatches = _MorphModel.prototype.getMacroPatches.call(this, subModelIndex);
          var myPatches = uniformPatches;
          if (this._realTimeTextureMode) {
            myPatches = texturePatches;
          }
          if (superMacroPatches) {
            return myPatches.concat(superMacroPatches);
          }
          return myPatches;
        };
        _proto._updateLocalDescriptors = function _updateLocalDescriptors(submodelIdx, descriptorSet) {
          _MorphModel.prototype._updateLocalDescriptors.call(this, submodelIdx, descriptorSet);
          var idx = this._bufferIndices[submodelIdx];
          if (this._realTimeTextureMode) {
            this._bindRealTimeJointTexture(idx, descriptorSet);
          } else {
            var buffer = this._buffers[idx];
            if (buffer) {
              descriptorSet.bindBuffer(UBOSkinning.BINDING, buffer);
            }
          }
        };
        _proto._updateInstancedAttributes = function _updateInstancedAttributes(attributes, subModel) {
          var pass = subModel.passes[0];
          if (pass.batchingScheme !== BatchingSchemes.NONE) {
            warnID(3936, this.node.getPathInHierarchy());
          }
          _MorphModel.prototype._updateInstancedAttributes.call(this, attributes, subModel);
        };
        _proto._ensureEnoughBuffers = function _ensureEnoughBuffers(count) {
          if (this._buffers.length) {
            for (var i = 0; i < this._buffers.length; i++) {
              this._buffers[i].destroy();
            }
            this._buffers.length = 0;
          }
          if (this._dataArray.length) this._dataArray.length = 0;
          if (!this._realTimeTextureMode) {
            for (var _i = 0; _i < count; _i++) {
              this._buffers[_i] = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOSkinning.SIZE, UBOSkinning.SIZE));
              var maxJoints = UBOSkinning.JOINT_UNIFORM_CAPACITY;
              this._dataArray[_i] = new Float32Array(12 * maxJoints);
            }
          } else {
            for (var _i2 = 0; _i2 < count; _i2++) {
              var _maxJoints = RealTimeJointTexture.WIDTH;
              this._dataArray[_i2] = new Float32Array(12 * _maxJoints);
            }
          }
        };
        _proto._initRealTimeJointTexture = function _initRealTimeJointTexture() {
          if (this._realTimeJointTexture._textures.length) {
            this._realTimeJointTexture._textures.forEach(function (tex) {
              tex.destroy();
            });
            this._realTimeJointTexture._textures.length = 0;
          }
          this._realTimeJointTexture._buffers.length = 0;
          if (!this._realTimeTextureMode) return;
          var gfxDevice = director.root.device;
          var width = RealTimeJointTexture.WIDTH;
          var height = RealTimeJointTexture.HEIGHT;
          var hasFeatureFloatTexture = gfxDevice.getFormatFeatures(Format.RGBA32F) & FormatFeatureBit.SAMPLED_TEXTURE;
          if (hasFeatureFloatTexture === 0) {
            this._realTimeJointTexture._format = PixelFormat.RGBA8888;
            width = 4 * RealTimeJointTexture.WIDTH;
          }
          var textures = this._realTimeJointTexture._textures;
          var buffers = this._realTimeJointTexture._buffers;
          var pixelFormat = this._realTimeJointTexture._format;
          for (var i = 0; i < this._dataArray.length; i++) {
            buffers[i] = new Float32Array(4 * RealTimeJointTexture.HEIGHT * RealTimeJointTexture.WIDTH);
            var arrayBuffer = buffers[i];
            var updateView = pixelFormat === PixelFormat.RGBA32F ? arrayBuffer : new Uint8Array(arrayBuffer.buffer);
            var image = new ImageAsset({
              width: width,
              height: height,
              _data: updateView,
              _compressed: false,
              format: pixelFormat
            });
            var texture = new Texture2D();
            texture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
            texture.setMipFilter(Texture2D.Filter.NONE);
            texture.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE);
            texture.image = image;
            textures[i] = texture;
          }
        };
        _proto._bindRealTimeJointTexture = function _bindRealTimeJointTexture(idx, descriptorSet) {
          if (!this._realTimeTextureMode) return;
          var jointTexture = this._realTimeJointTexture._textures[idx];
          if (jointTexture) {
            var gfxTexture = jointTexture.getGFXTexture();
            var sampler = jointTexture.getGFXSampler();
            descriptorSet.bindTexture(UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, gfxTexture);
            descriptorSet.bindSampler(UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, sampler);
          }
        };
        _proto._updateRealTimeJointTextureBuffer = function _updateRealTimeJointTextureBuffer() {
          if (!this._realTimeTextureMode) return;
          var textures = this._realTimeJointTexture._textures;
          var buffers = this._realTimeJointTexture._buffers;
          for (var idx = 0; idx < textures.length; idx++) {
            var arrayBuffer = buffers[idx];
            var src = this._dataArray[idx];
            var count = src.length / 12;
            var idxSrc = 0;
            var idxDst = 0;
            for (var i = 0; i < count; i++) {
              idxDst = 4 * i;
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              idxDst = 4 * (i + RealTimeJointTexture.WIDTH);
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              idxDst = 4 * (i + 2 * RealTimeJointTexture.WIDTH);
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
            }
            var pixelFormat = this._realTimeJointTexture._format;
            var updateView = pixelFormat === PixelFormat.RGBA32F ? arrayBuffer : new Uint8Array(arrayBuffer.buffer);
            textures[idx].uploadData(updateView);
          }
        };
        return SkinningModel;
      }(MorphModel);

      var myPatches = [{
        name: 'CC_USE_SKINNING',
        value: true
      }, {
        name: 'CC_USE_BAKED_ANIMATION',
        value: true
      }];
      var BakedSkinningModel = function (_MorphModel) {
        _inheritsLoose(BakedSkinningModel, _MorphModel);
        function BakedSkinningModel() {
          var _this;
          _this = _MorphModel.call(this) || this;
          _this.uploadedAnim = undefined;
          _this._jointsMedium = void 0;
          _this._skeleton = null;
          _this._mesh = null;
          _this._dataPoolManager = void 0;
          _this._instAnimInfoIdx = -1;
          _this.type = ModelType.BAKED_SKINNING;
          _this._dataPoolManager = legacyCC.director.root.dataPoolManager;
          var jointTextureInfo = new Float32Array(4);
          var animInfo = _this._dataPoolManager.jointAnimationInfo.getData();
          _this._jointsMedium = {
            buffer: null,
            jointTextureInfo: jointTextureInfo,
            animInfo: animInfo,
            texture: null,
            boundsInfo: null
          };
          return _this;
        }
        var _proto = BakedSkinningModel.prototype;
        _proto.destroy = function destroy() {
          this.uploadedAnim = undefined;
          this._jointsMedium.boundsInfo = null;
          if (this._jointsMedium.buffer) {
            this._jointsMedium.buffer.destroy();
            this._jointsMedium.buffer = null;
          }
          this._applyJointTexture();
          _MorphModel.prototype.destroy.call(this);
        };
        _proto.bindSkeleton = function bindSkeleton(skeleton, skinningRoot, mesh) {
          if (skeleton === void 0) {
            skeleton = null;
          }
          if (skinningRoot === void 0) {
            skinningRoot = null;
          }
          if (mesh === void 0) {
            mesh = null;
          }
          this._skeleton = skeleton;
          this._mesh = mesh;
          if (!skeleton || !skinningRoot || !mesh) {
            return;
          }
          this.transform = skinningRoot;
          var resMgr = this._dataPoolManager;
          this._jointsMedium.animInfo = resMgr.jointAnimationInfo.getData(skinningRoot.uuid);
          if (!this._jointsMedium.buffer) {
            this._jointsMedium.buffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOSkinningTexture.SIZE, UBOSkinningTexture.SIZE));
          }
        };
        _proto.updateTransform = function updateTransform(stamp) {
          _MorphModel.prototype.updateTransform.call(this, stamp);
          if (!this.uploadedAnim) {
            return;
          }
          var _this$_jointsMedium = this._jointsMedium,
            animInfo = _this$_jointsMedium.animInfo,
            boundsInfo = _this$_jointsMedium.boundsInfo;
          var skelBound = boundsInfo[animInfo.data[0]];
          var worldBounds = this._worldBounds;
          if (worldBounds && skelBound) {
            var node = this.transform;
            skelBound.transform(node._mat, node._pos, node._rot, node._scale, worldBounds);
          }
        };
        _proto.updateUBOs = function updateUBOs(stamp) {
          _MorphModel.prototype.updateUBOs.call(this, stamp);
          var info = this._jointsMedium.animInfo;
          var hasNonInstancingPass = false;
          var idx = this._instAnimInfoIdx;
          for (var i = 0; i < this._subModels.length; i++) {
            var subModel = this._subModels[i];
            if (idx >= 0) {
              var view = subModel.instancedAttributeBlock.views[idx];
              view[0] = info.data[0];
            } else {
              hasNonInstancingPass = true;
            }
          }
          if (hasNonInstancingPass && info.dirty) {
            info.buffer.update(info.data);
            info.dirty = false;
          }
          return true;
        };
        _proto.getMacroPatches = function getMacroPatches(subModelIndex) {
          var patches = _MorphModel.prototype.getMacroPatches.call(this, subModelIndex);
          return patches ? patches.concat(myPatches) : myPatches;
        };
        _proto.uploadAnimation = function uploadAnimation(anim) {
          if (!this._skeleton || !this._mesh || this.uploadedAnim === anim) {
            return;
          }
          this.uploadedAnim = anim;
          var resMgr = this._dataPoolManager;
          var texture = null;
          if (anim) {
            texture = resMgr.jointTexturePool.getSequencePoseTexture(this._skeleton, anim, this._mesh, this.transform);
            this._jointsMedium.boundsInfo = texture && texture.bounds.get(this._mesh.hash);
            this._modelBounds = null;
          } else {
            texture = resMgr.jointTexturePool.getDefaultPoseTexture(this._skeleton, this._mesh, this.transform);
            this._jointsMedium.boundsInfo = null;
            this._modelBounds = texture && texture.bounds.get(this._mesh.hash)[0];
          }
          this._applyJointTexture(texture);
        };
        _proto._applyJointTexture = function _applyJointTexture(texture) {
          if (texture === void 0) {
            texture = null;
          }
          var oldTex = this._jointsMedium.texture;
          if (oldTex && oldTex !== texture) {
            this._dataPoolManager.jointTexturePool.releaseHandle(oldTex);
          }
          this._jointsMedium.texture = texture;
          if (!texture) {
            return;
          }
          var _this$_jointsMedium2 = this._jointsMedium,
            buffer = _this$_jointsMedium2.buffer,
            jointTextureInfo = _this$_jointsMedium2.jointTextureInfo;
          jointTextureInfo[0] = texture.handle.texture.width;
          jointTextureInfo[1] = this._skeleton.joints.length;
          jointTextureInfo[2] = texture.pixelOffset + 0.1;
          jointTextureInfo[3] = 1 / jointTextureInfo[0];
          this.updateInstancedJointTextureInfo();
          if (buffer) {
            buffer.update(jointTextureInfo);
          }
          var tex = texture.handle.texture;
          for (var i = 0; i < this._subModels.length; ++i) {
            var descriptorSet = this._subModels[i].descriptorSet;
            descriptorSet.bindTexture(UNIFORM_JOINT_TEXTURE_BINDING, tex);
          }
        };
        _proto._updateLocalDescriptors = function _updateLocalDescriptors(submodelIdx, descriptorSet) {
          _MorphModel.prototype._updateLocalDescriptors.call(this, submodelIdx, descriptorSet);
          var _this$_jointsMedium3 = this._jointsMedium,
            buffer = _this$_jointsMedium3.buffer,
            texture = _this$_jointsMedium3.texture,
            animInfo = _this$_jointsMedium3.animInfo;
          descriptorSet.bindBuffer(UBOSkinningTexture.BINDING, buffer);
          descriptorSet.bindBuffer(UBOSkinningAnimation.BINDING, animInfo.buffer);
          if (texture) {
            var sampler = this._device.getSampler(jointTextureSamplerInfo);
            descriptorSet.bindTexture(UNIFORM_JOINT_TEXTURE_BINDING, texture.handle.texture);
            descriptorSet.bindSampler(UNIFORM_JOINT_TEXTURE_BINDING, sampler);
          }
        };
        _proto._updateInstancedAttributes = function _updateInstancedAttributes(attributes, subModel) {
          _MorphModel.prototype._updateInstancedAttributes.call(this, attributes, subModel);
          this._instAnimInfoIdx = subModel.getInstancedAttributeIndex(INST_JOINT_ANIM_INFO);
          this.updateInstancedJointTextureInfo();
        };
        _proto.updateInstancedJointTextureInfo = function updateInstancedJointTextureInfo() {
          var _this$_jointsMedium4 = this._jointsMedium,
            jointTextureInfo = _this$_jointsMedium4.jointTextureInfo,
            animInfo = _this$_jointsMedium4.animInfo;
          var idx = this._instAnimInfoIdx;
          for (var i = 0; i < this._subModels.length; i++) {
            var subModel = this._subModels[i];
            var views = subModel.instancedAttributeBlock.views;
            if (idx >= 0 && views.length > 0) {
              var view = views[idx];
              view[0] = animInfo.data[0];
              view[1] = jointTextureInfo[1];
              view[2] = jointTextureInfo[2];
            }
          }
        };
        return BakedSkinningModel;
      }(MorphModel);

      var _dec$2t, _dec2$1S, _dec3$1k, _dec4$_, _dec5$V, _dec6$F, _class$2r, _class2$2d, _initializer$25, _initializer2$1L;
      var SkinnedMeshRenderer = exports('ai', (_dec$2t = ccclass$M('cc.SkinnedMeshRenderer'), _dec2$1S = executionOrder$1(100), _dec3$1k = type$d(Skeleton$1), _dec4$_ = type$d(Node$1), _dec5$V = type$d(Skeleton$1), _dec6$F = type$d(Node$1), _dec$2t(_class$2r = _dec2$1S(_class$2r = (_class2$2d = function (_MeshRenderer) {
        _inheritsLoose(SkinnedMeshRenderer, _MeshRenderer);
        function SkinnedMeshRenderer() {
          var _this;
          _this = _MeshRenderer.call(this) || this;
          _this._skeleton = _initializer$25 && _initializer$25();
          _this._skinningRoot = _initializer2$1L && _initializer2$1L();
          _this._clip = null;
          _this.associatedAnimation = null;
          _this._modelType = BakedSkinningModel;
          return _this;
        }
        var _proto = SkinnedMeshRenderer.prototype;
        _proto.onLoad = function onLoad() {
          _MeshRenderer.prototype.onLoad.call(this);
          this._tryBindAnimation();
        };
        _proto.onDestroy = function onDestroy() {
          if (this.associatedAnimation) {
            this.associatedAnimation.notifySkinnedMeshRemoved(this);
            assertIsTrue(this.associatedAnimation === null);
          }
          _MeshRenderer.prototype.onDestroy.call(this);
        };
        _proto.uploadAnimation = function uploadAnimation(clip) {
          this._clip = clip;
          if (this.model && this.model.uploadAnimation) {
            this.model.uploadAnimation(clip);
          }
        };
        _proto.setUseBakedAnimation = function setUseBakedAnimation(val, force) {
          if (val === void 0) {
            val = true;
          }
          if (force === void 0) {
            force = false;
          }
          var modelType = val ? BakedSkinningModel : SkinningModel;
          if (!force && this._modelType === modelType) {
            return;
          }
          this._modelType = modelType;
          if (this._model) {
            legacyCC.director.root.destroyModel(this._model);
            this._model = null;
            this._models.length = 0;
            this._updateModels();
            this._updateCastShadow();
            this._updateReceiveShadow();
            this._updateUseLightProbe();
            if (this.enabledInHierarchy) {
              this._attachToScene();
            }
          }
        };
        _proto.setSharedMaterial = function setSharedMaterial(material, index) {
          _MeshRenderer.prototype.setSharedMaterial.call(this, material, index);
          if (this._modelType === SkinningModel) {
            this.getMaterialInstance(index);
          }
        };
        _proto._updateModelParams = function _updateModelParams() {
          this._update();
          _MeshRenderer.prototype._updateModelParams.call(this);
        };
        _proto._tryBindAnimation = function _tryBindAnimation() {
          var skinningRoot = this._skinningRoot;
          if (!skinningRoot) {
            return;
          }
          var skinningRootIsParent = false;
          for (var current = this.node; current; current = current.parent) {
            if (current === skinningRoot) {
              skinningRootIsParent = true;
              break;
            }
          }
          if (!skinningRootIsParent) {
            return;
          }
          var animation = skinningRoot.getComponent('cc.SkeletalAnimation');
          if (animation && animation.enabledInHierarchy) {
            animation.notifySkinnedMeshAdded(this);
          } else {
            this.setUseBakedAnimation(false);
          }
        };
        _proto._update = function _update() {
          if (this.model) {
            this.model.bindSkeleton(this._skeleton, this._skinningRoot, this._mesh);
            if (this.model.uploadAnimation) {
              this.model.uploadAnimation(this._clip);
            }
          }
        };
        _createClass(SkinnedMeshRenderer, [{
          key: "skeleton",
          get: function get() {
            return this._skeleton;
          },
          set: function set(val) {
            if (val === this._skeleton) {
              return;
            }
            this._skeleton = val;
            this._update();
          }
        }, {
          key: "skinningRoot",
          get: function get() {
            return this._skinningRoot;
          },
          set: function set(value) {
            if (value === this._skinningRoot) {
              return;
            }
            this._skinningRoot = value;
            this._tryBindAnimation();
            this._update();
          }
        }, {
          key: "model",
          get: function get() {
            return this._model;
          }
        }]);
        return SkinnedMeshRenderer;
      }(MeshRenderer), (_initializer$25 = applyDecoratedInitializer(_class2$2d.prototype, "_skeleton", [_dec3$1k], function () {
        return null;
      }), _initializer2$1L = applyDecoratedInitializer(_class2$2d.prototype, "_skinningRoot", [_dec4$_], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$2d.prototype, "skeleton", [_dec5$V], Object.getOwnPropertyDescriptor(_class2$2d.prototype, "skeleton"), _class2$2d.prototype), _applyDecoratedDescriptor(_class2$2d.prototype, "skinningRoot", [_dec6$F], Object.getOwnPropertyDescriptor(_class2$2d.prototype, "skinningRoot"), _class2$2d.prototype)), _class2$2d)) || _class$2r) || _class$2r));

      var _dec$2s, _dec2$1R, _dec3$1j, _dec4$Z, _dec5$U, _class$2q, _class2$2c, _initializer$24, _initializer2$1K, _initializer3$1g, _initializer4$15, _initializer5$S, _initializer6$I, _dec6$E, _dec7$v, _dec8$m, _dec9$i, _class4$q, _class5$r, _initializer7$y, _initializer8$u, _initializer9$q;
      var repeat$1 = function repeat(n) {
        return n - Math.floor(n);
      };
      var batch_id = new Attribute(AttributeName.ATTR_BATCH_ID, Format.R32F);
      var batch_uv = new Attribute(AttributeName.ATTR_BATCH_UV, Format.RG32F);
      var batch_extras_size = FormatInfos[batch_id.format].size + FormatInfos[batch_uv.format].size;
      var SkinnedMeshUnit = exports('ak', (_dec$2s = ccclass$M('cc.SkinnedMeshUnit'), _dec2$1R = type$d(Mesh), _dec3$1j = type$d(Skeleton$1), _dec4$Z = type$d(Material), _dec5$U = type$d(SkinnedMeshRenderer), _dec$2s(_class$2q = (_class2$2c = function () {
        function SkinnedMeshUnit() {
          this.mesh = _initializer$24 && _initializer$24();
          this.skeleton = _initializer2$1K && _initializer2$1K();
          this.material = _initializer3$1g && _initializer3$1g();
          this._localTransform = _initializer4$15 && _initializer4$15();
          this._offset = _initializer5$S && _initializer5$S();
          this._size = _initializer6$I && _initializer6$I();
        }
        _createClass(SkinnedMeshUnit, [{
          key: "offset",
          get: function get() {
            return this._offset;
          },
          set: function set(offset) {
            Vec2.copy(this._offset, offset);
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(size) {
            Vec2.copy(this._size, size);
          }
        }, {
          key: "copyFrom",
          get: function get() {
            return null;
          },
          set: function set(comp) {
            if (!comp) {
              return;
            }
            this.mesh = comp.mesh;
            this.skeleton = comp.skeleton;
            this.material = comp.getSharedMaterial(0);
            if (comp.skinningRoot) {
              getWorldTransformUntilRoot(comp.node, comp.skinningRoot, this._localTransform);
            }
          }
        }]);
        return SkinnedMeshUnit;
      }(), (_initializer$24 = applyDecoratedInitializer(_class2$2c.prototype, "mesh", [_dec2$1R], function () {
        return null;
      }), _initializer2$1K = applyDecoratedInitializer(_class2$2c.prototype, "skeleton", [_dec3$1j], function () {
        return null;
      }), _initializer3$1g = applyDecoratedInitializer(_class2$2c.prototype, "material", [_dec4$Z], function () {
        return null;
      }), _initializer4$15 = applyDecoratedInitializer(_class2$2c.prototype, "_localTransform", [serializable$p], function () {
        return new Mat4();
      }), _initializer5$S = applyDecoratedInitializer(_class2$2c.prototype, "_offset", [serializable$p], function () {
        return new Vec2(0, 0);
      }), _initializer6$I = applyDecoratedInitializer(_class2$2c.prototype, "_size", [serializable$p], function () {
        return new Vec2(1, 1);
      }), _applyDecoratedDescriptor(_class2$2c.prototype, "copyFrom", [_dec5$U], Object.getOwnPropertyDescriptor(_class2$2c.prototype, "copyFrom"), _class2$2c.prototype)), _class2$2c)) || _class$2q));
      var m4_local = new Mat4();
      new Mat4();
      var v3_1$3 = new Vec3();
      var SkinnedMeshBatchRenderer = exports('aj', (_dec6$E = ccclass$M('cc.SkinnedMeshBatchRenderer'), _dec7$v = executionOrder$1(100), _dec8$m = type$d([CCString]), _dec9$i = type$d([SkinnedMeshUnit]), _dec6$E(_class4$q = _dec7$v(_class4$q = (_class5$r = function (_SkinnedMeshRenderer) {
        _inheritsLoose(SkinnedMeshBatchRenderer, _SkinnedMeshRenderer);
        function SkinnedMeshBatchRenderer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _SkinnedMeshRenderer.call.apply(_SkinnedMeshRenderer, [this].concat(args)) || this;
          _this.atlasSize = _initializer7$y && _initializer7$y();
          _this.batchableTextureNames = _initializer8$u && _initializer8$u();
          _this.units = _initializer9$q && _initializer9$q();
          _this._textures = {};
          _this._batchMaterial = null;
          return _this;
        }
        var _proto = SkinnedMeshBatchRenderer.prototype;
        _proto.onLoad = function onLoad() {
          _SkinnedMeshRenderer.prototype.onLoad.call(this);
          this.cook();
        };
        _proto.onDestroy = function onDestroy() {
          for (var tex in this._textures) {
            this._textures[tex].destroy();
          }
          this._textures = {};
          if (this._mesh) {
            this._mesh.destroy();
            this._mesh = null;
          }
          _SkinnedMeshRenderer.prototype.onDestroy.call(this);
        };
        _proto._onMaterialModified = function _onMaterialModified(idx, material) {
          this.cookMaterials();
          _SkinnedMeshRenderer.prototype._onMaterialModified.call(this, idx, this.getMaterialInstance(idx));
        };
        _proto.cook = function cook() {
          this.cookMaterials();
          this.cookSkeletons();
          this.cookMeshes();
        };
        _proto.cookMaterials = function cookMaterials() {
          var _this2 = this;
          if (!this._batchMaterial) {
            this._batchMaterial = this.getSharedMaterial(0);
          }
          var mat = this.getMaterialInstance(0);
          if (!mat || !this._batchMaterial || !this._batchMaterial.effectAsset) {
            console.warn('incomplete batch material!');
            return;
          }
          mat.copy(this._batchMaterial);
          this.resizeAtlases();
          var tech = mat.effectAsset.techniques[mat.technique];
          var _loop = function _loop(i) {
            var pass = tech.passes[i];
            if (!pass.properties) {
              return 1;
            }
            var _loop2 = function _loop2(prop) {
              if (pass.properties[prop].type >= Type$1.SAMPLER1D) {
                var tex = null;
                if (_this2.batchableTextureNames.find(function (n) {
                  return n === prop;
                })) {
                  tex = _this2._textures[prop];
                  if (!tex) {
                    tex = _this2.createTexture(prop);
                  }
                  _this2.cookTextures(tex, prop, i);
                } else {
                  _this2.units.some(function (u) {
                    return tex = u.material && u.material.getProperty(prop, i);
                  });
                }
                if (tex) {
                  mat.setProperty(prop, tex, i);
                }
              } else {
                var value = [];
                for (var u = 0; u < _this2.units.length; u++) {
                  var unit = _this2.units[u];
                  if (!unit.material) {
                    continue;
                  }
                  value.push(unit.material.getProperty(prop.slice(0, -3), i));
                }
                mat.setProperty(prop, value, i);
              }
            };
            for (var prop in pass.properties) {
              _loop2(prop);
            }
          };
          for (var i = 0; i < tech.passes.length; i++) {
            if (_loop(i)) continue;
          }
        };
        _proto.cookSkeletons = function cookSkeletons() {
          if (!this._skinningRoot) {
            console.warn('no skinning root specified!');
            return;
          }
          var joints = [];
          var bindposes = [];
          for (var u = 0; u < this.units.length; u++) {
            var unit = this.units[u];
            if (!unit || !unit.skeleton) {
              continue;
            }
            var partial = unit.skeleton;
            Mat4.invert(m4_local, unit._localTransform);
            var _loop3 = function _loop3() {
              var path = partial.joints[i];
              var idx = joints.findIndex(function (p) {
                return p === path;
              });
              if (idx >= 0) {
                return 1;
              }
              joints.push(path);
              bindposes.push(Mat4.multiply(new Mat4(), partial.bindposes[i] || Mat4.IDENTITY, m4_local));
            };
            for (var i = 0; i < partial.joints.length; i++) {
              if (_loop3()) continue;
            }
          }
          var idxMap = Array.from(Array(joints.length).keys()).sort(function (a, b) {
            if (joints[a] > joints[b]) {
              return 1;
            }
            if (joints[a] < joints[b]) {
              return -1;
            }
            return 0;
          });
          var skeleton = new Skeleton$1();
          skeleton.joints = joints.map(function (_, idx, arr) {
            return arr[idxMap[idx]];
          });
          skeleton.bindposes = bindposes.map(function (_, idx, arr) {
            return arr[idxMap[idx]];
          });
          if (this._skeleton) {
            this._skeleton.destroy();
          }
          this.skeleton = skeleton;
        };
        _proto.cookMeshes = function cookMeshes() {
          var _this4 = this;
          var isValid = false;
          for (var u = 0; u < this.units.length; u++) {
            var unit = this.units[u];
            if (unit.mesh) {
              isValid = true;
              break;
            }
          }
          if (!isValid || !this._skinningRoot) {
            return;
          }
          if (this._mesh) {
            this._mesh.destroyRenderingMesh();
          } else {
            this._mesh = new Mesh();
          }
          var posOffset = 0;
          var posFormat = Format.UNKNOWN;
          var normalOffset = 0;
          var normalFormat = Format.UNKNOWN;
          var tangentOffset = 0;
          var tangentFormat = Format.UNKNOWN;
          var uvOffset = 0;
          var uvFormat = Format.UNKNOWN;
          var jointOffset = 0;
          var jointFormat = Format.UNKNOWN;
          var jointIndexMap = new Array(this.units.length);
          var unitLen = this.units.length;
          for (var i = 0; i < unitLen; i++) {
            var _unit = this.units[i];
            if (!_unit || !_unit.skeleton) {
              continue;
            }
            jointIndexMap[i] = _unit.skeleton.joints.map(function (j) {
              return _this4._skeleton.joints.findIndex(function (ref) {
                return j === ref;
              });
            });
          }
          var _loop4 = function _loop4() {
            var unit = _this4.units[_i];
            if (!unit || !unit.mesh || !unit.mesh.data) {
              return 1;
            }
            var newMesh = _this4._createUnitMesh(_i, unit.mesh);
            var dataView = new DataView(newMesh.data.buffer);
            Mat4.invert(m4_local, unit._localTransform);
            Mat4.transpose(m4_local, m4_local);
            var offset = unit.offset;
            var size = unit.size;
            var _loop5 = function _loop5() {
              var bundle = newMesh.struct.vertexBundles[b];
              posOffset = bundle.view.offset;
              posFormat = Format.UNKNOWN;
              for (var a = 0; a < bundle.attributes.length; a++) {
                var attr = bundle.attributes[a];
                if (attr.name === AttributeName.ATTR_POSITION) {
                  posFormat = attr.format;
                  break;
                }
                posOffset += FormatInfos[attr.format].size;
              }
              if (posFormat) {
                var pos = readBuffer(dataView, posFormat, posOffset, bundle.view.length, bundle.view.stride);
                for (var j = 0; j < pos.length; j += 3) {
                  Vec3.fromArray(v3_1$3, pos, j);
                  Vec3.transformMat4(v3_1$3, v3_1$3, unit._localTransform);
                  Vec3.toArray(pos, v3_1$3, j);
                }
                writeBuffer(dataView, pos, posFormat, posOffset, bundle.view.stride);
              }
              normalOffset = bundle.view.offset;
              normalFormat = Format.UNKNOWN;
              for (var _a = 0; _a < bundle.attributes.length; _a++) {
                var _attr = bundle.attributes[_a];
                if (_attr.name === AttributeName.ATTR_NORMAL) {
                  normalFormat = _attr.format;
                  break;
                }
                normalOffset += FormatInfos[_attr.format].size;
              }
              if (normalFormat) {
                var normal = readBuffer(dataView, normalFormat, normalOffset, bundle.view.length, bundle.view.stride);
                for (var _j = 0; _j < normal.length; _j += 3) {
                  Vec3.fromArray(v3_1$3, normal, _j);
                  Vec3.transformMat4Normal(v3_1$3, v3_1$3, m4_local);
                  Vec3.toArray(normal, v3_1$3, _j);
                }
                writeBuffer(dataView, normal, normalFormat, normalOffset, bundle.view.stride);
              }
              tangentOffset = bundle.view.offset;
              tangentFormat = Format.UNKNOWN;
              for (var _a2 = 0; _a2 < bundle.attributes.length; _a2++) {
                var _attr2 = bundle.attributes[_a2];
                if (_attr2.name === AttributeName.ATTR_TANGENT) {
                  tangentFormat = _attr2.format;
                  break;
                }
                tangentOffset += FormatInfos[_attr2.format].size;
              }
              if (tangentFormat) {
                var tangent = readBuffer(dataView, tangentFormat, tangentOffset, bundle.view.length, bundle.view.stride);
                for (var _j2 = 0; _j2 < tangent.length; _j2 += 3) {
                  Vec3.fromArray(v3_1$3, tangent, _j2);
                  Vec3.transformMat4Normal(v3_1$3, v3_1$3, m4_local);
                  Vec3.toArray(tangent, v3_1$3, _j2);
                }
                writeBuffer(dataView, tangent, tangentFormat, tangentOffset, bundle.view.stride);
              }
              uvOffset = bundle.view.offset;
              uvFormat = Format.UNKNOWN;
              for (var _a3 = 0; _a3 < bundle.attributes.length; _a3++) {
                var _attr3 = bundle.attributes[_a3];
                if (_attr3.name === AttributeName.ATTR_BATCH_UV) {
                  uvFormat = _attr3.format;
                  break;
                }
                uvOffset += FormatInfos[_attr3.format].size;
              }
              if (uvFormat) {
                mapBuffer(dataView, function (cur, idx) {
                  cur = repeat$1(cur);
                  var comp = idx === 0 ? 'x' : 'y';
                  return cur * size[comp] + offset[comp];
                }, uvFormat, uvOffset, bundle.view.length, bundle.view.stride, dataView);
              }
              var idxMap = jointIndexMap[_i];
              if (!idxMap) {
                return 1;
              }
              jointOffset = bundle.view.offset;
              jointFormat = Format.UNKNOWN;
              for (var _a4 = 0; _a4 < bundle.attributes.length; _a4++) {
                var _attr4 = bundle.attributes[_a4];
                if (_attr4.name === AttributeName.ATTR_JOINTS) {
                  jointFormat = _attr4.format;
                  break;
                }
                jointOffset += FormatInfos[_attr4.format].size;
              }
              if (jointFormat) {
                mapBuffer(dataView, function (cur) {
                  return idxMap[cur];
                }, jointFormat, jointOffset, bundle.view.length, bundle.view.stride, dataView);
              }
            };
            for (var b = 0; b < newMesh.struct.vertexBundles.length; b++) {
              if (_loop5()) continue;
            }
            _this4._mesh.merge(newMesh);
          };
          for (var _i = 0; _i < unitLen; _i++) {
            if (_loop4()) continue;
          }
          this._onMeshChanged(this._mesh);
          this._updateModels();
        };
        _proto.cookTextures = function cookTextures(target, prop, passIdx) {
          var texImages = [];
          var texImageRegions = [];
          var texBuffers = [];
          var texBufferRegions = [];
          for (var u = 0; u < this.units.length; u++) {
            var unit = this.units[u];
            if (!unit.material) {
              continue;
            }
            var partial = unit.material.getProperty(prop, passIdx);
            if (partial && partial.image && partial.image.data) {
              var region = new BufferTextureCopy();
              region.texOffset.x = unit.offset.x * this.atlasSize;
              region.texOffset.y = unit.offset.y * this.atlasSize;
              region.texExtent.width = unit.size.x * this.atlasSize;
              region.texExtent.height = unit.size.y * this.atlasSize;
              var data = partial.image.data;
              if (!ArrayBuffer.isView(data)) {
                texImages.push(data);
                texImageRegions.push(region);
              } else {
                texBuffers.push(data);
                texBufferRegions.push(region);
              }
            }
          }
          var gfxTex = target.getGFXTexture();
          var _ref = legacyCC.director.root,
            device = _ref.device;
          if (texBuffers.length > 0) {
            device.copyBuffersToTexture(texBuffers, gfxTex, texBufferRegions);
          }
          if (texImages.length > 0) {
            device.copyTexImagesToTexture(texImages, gfxTex, texImageRegions);
          }
        };
        _proto.createTexture = function createTexture(prop) {
          var tex = new Texture2D();
          tex.setFilters(Filter.LINEAR, Filter.LINEAR);
          tex.setMipFilter(Filter.NEAREST);
          tex.reset({
            width: this.atlasSize,
            height: this.atlasSize,
            format: PixelFormat.RGBA8888
          });
          this._textures[prop] = tex;
          return tex;
        };
        _proto.resizeAtlases = function resizeAtlases() {
          for (var prop in this._textures) {
            var tex = this._textures[prop];
            tex.reset({
              width: this.atlasSize,
              height: this.atlasSize,
              format: PixelFormat.RGBA8888
            });
          }
        };
        _proto._createUnitMesh = function _createUnitMesh(unitIdx, mesh) {
          var newMeshStruct = JSON.parse(JSON.stringify(mesh.struct));
          var modifiedBundles = {};
          for (var p = 0; p < mesh.struct.primitives.length; p++) {
            var primitive = mesh.struct.primitives[p];
            var uvOffset = 0;
            var uvFormat = Format.UNKNOWN;
            var bundleIdx = 0;
            for (; bundleIdx < primitive.vertexBundelIndices.length; bundleIdx++) {
              var bundle = mesh.struct.vertexBundles[primitive.vertexBundelIndices[bundleIdx]];
              uvOffset = bundle.view.offset;
              uvFormat = Format.UNKNOWN;
              for (var a = 0; a < bundle.attributes.length; a++) {
                var attr = bundle.attributes[a];
                if (attr.name === AttributeName.ATTR_TEX_COORD) {
                  uvFormat = attr.format;
                  break;
                }
                uvOffset += FormatInfos[attr.format].size;
              }
              if (uvFormat) {
                break;
              }
            }
            if (modifiedBundles[bundleIdx] !== undefined) {
              continue;
            }
            modifiedBundles[bundleIdx] = [uvFormat, uvOffset];
            var newBundle = newMeshStruct.vertexBundles[bundleIdx];
            newBundle.attributes.push(batch_id);
            newBundle.attributes.push(batch_uv);
            newBundle.view.offset = 0;
            newBundle.view.length += newBundle.view.count * batch_extras_size;
            newBundle.view.stride += batch_extras_size;
          }
          var totalLength = 0;
          for (var b = 0; b < newMeshStruct.vertexBundles.length; b++) {
            totalLength += newMeshStruct.vertexBundles[b].view.length;
          }
          for (var _p = 0; _p < newMeshStruct.primitives.length; _p++) {
            var pm = newMeshStruct.primitives[_p];
            if (pm.indexView) {
              pm.indexView.offset = totalLength;
              totalLength += pm.indexView.length;
            }
          }
          var newMeshData = new Uint8Array(totalLength);
          var oldMeshData = mesh.data;
          var newDataView = new DataView(newMeshData.buffer);
          var oldDataView = new DataView(oldMeshData.buffer);
          var isLittleEndian = legacyCC.sys.isLittleEndian;
          for (var _b in modifiedBundles) {
            var _newBundle = newMeshStruct.vertexBundles[_b];
            var oldBundle = mesh.struct.vertexBundles[_b];
            var _modifiedBundles$_b = modifiedBundles[_b],
              _uvFormat = _modifiedBundles$_b[0],
              _uvOffset = _modifiedBundles$_b[1];
            var uvs = readBuffer(oldDataView, _uvFormat, _uvOffset, oldBundle.view.length, oldBundle.view.stride);
            var oldView = oldBundle.view;
            var newView = _newBundle.view;
            var oldStride = oldView.stride;
            var newStride = newView.stride;
            var oldOffset = oldView.offset;
            var newOffset = newView.offset;
            for (var j = 0; j < newView.count; j++) {
              var srcVertex = oldMeshData.subarray(oldOffset, oldOffset + oldStride);
              newMeshData.set(srcVertex, newOffset);
              newDataView.setFloat32(newOffset + oldStride, unitIdx);
              newDataView.setFloat32(newOffset + oldStride + 4, uvs[j * 2], isLittleEndian);
              newDataView.setFloat32(newOffset + oldStride + 8, uvs[j * 2 + 1], isLittleEndian);
              newOffset += newStride;
              oldOffset += oldStride;
            }
          }
          for (var k = 0; k < newMeshStruct.primitives.length; k++) {
            var oldPrimitive = mesh.struct.primitives[k];
            var newPrimitive = newMeshStruct.primitives[k];
            if (oldPrimitive.indexView && newPrimitive.indexView) {
              var _oldStride = oldPrimitive.indexView.stride;
              var _newStride = newPrimitive.indexView.stride;
              var _oldOffset = oldPrimitive.indexView.offset;
              var _newOffset = newPrimitive.indexView.offset;
              for (var _j3 = 0; _j3 < newPrimitive.indexView.count; _j3++) {
                var srcIndices = oldMeshData.subarray(_oldOffset, _oldOffset + _oldStride);
                newMeshData.set(srcIndices, _newOffset);
                _newOffset += _newStride;
                _oldOffset += _oldStride;
              }
            }
          }
          var newMesh = new Mesh();
          newMesh.reset({
            struct: newMeshStruct,
            data: newMeshData
          });
          return newMesh;
        };
        _createClass(SkinnedMeshBatchRenderer, [{
          key: "mesh",
          get: function get() {
            return _SkinnedMeshRenderer.prototype.mesh;
          },
          set: function set(val) {
            this.mesh = val;
          }
        }, {
          key: "skeleton",
          get: function get() {
            return _SkinnedMeshRenderer.prototype.skeleton;
          },
          set: function set(val) {
            this.skeleton = val;
          }
        }]);
        return SkinnedMeshBatchRenderer;
      }(SkinnedMeshRenderer), (_initializer7$y = applyDecoratedInitializer(_class5$r.prototype, "atlasSize", [serializable$p], function () {
        return 1024;
      }), _initializer8$u = applyDecoratedInitializer(_class5$r.prototype, "batchableTextureNames", [_dec8$m, serializable$p], function () {
        return [];
      }), _initializer9$q = applyDecoratedInitializer(_class5$r.prototype, "units", [_dec9$i, serializable$p], function () {
        return [];
      }), _applyDecoratedDescriptor(_class5$r.prototype, "mesh", [override$1], Object.getOwnPropertyDescriptor(_class5$r.prototype, "mesh"), _class5$r.prototype), _applyDecoratedDescriptor(_class5$r.prototype, "skeleton", [override$1], Object.getOwnPropertyDescriptor(_class5$r.prototype, "skeleton"), _class5$r.prototype)), _class5$r)) || _class4$q) || _class4$q));

      legacyCC.SkinningModelComponent = SkinnedMeshRenderer;
      setClassAlias(SkinnedMeshRenderer, 'cc.SkinningModelComponent');
      legacyCC.SkinningModelUnit = SkinnedMeshUnit;
      setClassAlias(SkinnedMeshUnit, 'cc.SkinningModelUnit');
      legacyCC.BatchedSkinningModelComponent = SkinnedMeshBatchRenderer;
      setClassAlias(SkinnedMeshBatchRenderer, 'cc.BatchedSkinningModelComponent');

      var _dec$2r, _dec2$1Q, _dec3$1i, _dec4$Y, _dec5$T, _class$2p, _class2$2b, _initializer$23, _initializer2$1J, _dec6$D, _dec7$u, _dec8$l, _class4$p, _class5$q, _initializer3$1f, _initializer4$14, _initializer5$R;
      var DEFAULT_SCREEN_OCCUPATION = [0.25, 0.125, 0.01];
      var LOD = exports('al', (_dec$2r = ccclass$M('cc.LOD'), _dec2$1Q = type$d([MeshRenderer]), _dec3$1i = type$d(CCFloat), _dec4$Y = type$d([MeshRenderer]), _dec5$T = type$d([CCInteger]), _dec$2r(_class$2p = (_class2$2b = function () {
        function LOD() {
          this._screenUsagePercentage = _initializer$23 && _initializer$23();
          this._renderers = _initializer2$1J && _initializer2$1J();
          this._LODData = new LODData();
          this._modelAddedCallback = void 0;
          this._LODData.screenUsagePercentage = this._screenUsagePercentage;
          this._modelAddedCallback = null;
        }
        var _proto = LOD.prototype;
        _proto.insertRenderer = function insertRenderer(index, renderer) {
          if (index < 0 || index > this._renderers.length) {
            index = this._renderers.length;
          }
          this._renderers.splice(index, 0, renderer);
          var modelAdded = false;
          if (renderer.model) {
            modelAdded = true;
            this._LODData.addModel(renderer.model);
          }
          if (this._modelAddedCallback && modelAdded) {
            this._modelAddedCallback();
          }
          return renderer;
        };
        _proto.deleteRenderer = function deleteRenderer(index) {
          var _renders$;
          var renders = this._renderers.splice(index, 1);
          var model = renders.length > 0 ? (_renders$ = renders[0]) === null || _renders$ === void 0 ? void 0 : _renders$.model : null;
          if (model) {
            this._LODData.eraseModel(model);
          }
          return renders[0];
        };
        _proto.getRenderer = function getRenderer(index) {
          return this._renderers[index] || null;
        };
        _proto.setRenderer = function setRenderer(index, renderer) {
          if (index < 0 || index >= this.rendererCount) {
            console.error('setRenderer to LOD error, index out of range');
            return;
          }
          this.deleteRenderer(index);
          this.insertRenderer(index, renderer);
        };
        _createClass(LOD, [{
          key: "screenUsagePercentage",
          get: function get() {
            return this._screenUsagePercentage;
          },
          set: function set(val) {
            this._screenUsagePercentage = val;
            this._LODData.screenUsagePercentage = val;
          }
        }, {
          key: "renderers",
          get: function get() {
            return this._renderers;
          },
          set: function set(meshList) {
            if (meshList === this._renderers) return;
            var modelAdded = false;
            this._renderers.length = 0;
            this._LODData.clearModels();
            for (var i = 0; i < meshList.length; i++) {
              var _meshList$i;
              this._renderers[i] = meshList[i];
              var model = (_meshList$i = meshList[i]) === null || _meshList$i === void 0 ? void 0 : _meshList$i.model;
              if (model) {
                modelAdded = true;
                this._LODData.addModel(model);
              }
            }
            if (this._modelAddedCallback && modelAdded) {
              this._modelAddedCallback();
            }
          }
        }, {
          key: "triangleCount",
          get: function get() {
            var tris = [];
            this._renderers.forEach(function (meshRenderer) {
              var count = 0;
              if (meshRenderer && meshRenderer.mesh) {
                var primitives = meshRenderer.mesh.struct.primitives;
                primitives === null || primitives === void 0 ? void 0 : primitives.forEach(function (subMesh) {
                  if (subMesh && subMesh.indexView) {
                    count += subMesh.indexView.count;
                  }
                });
              }
              tris.push(count / 3);
            });
            return tris;
          }
        }, {
          key: "rendererCount",
          get: function get() {
            return this._renderers.length;
          }
        }, {
          key: "lodData",
          get: function get() {
            return this._LODData;
          }
        }, {
          key: "modelAddedCallback",
          set: function set(callback) {
            this._modelAddedCallback = callback;
          }
        }]);
        return LOD;
      }(), (_initializer$23 = applyDecoratedInitializer(_class2$2b.prototype, "_screenUsagePercentage", [serializable$p], function () {
        return 1.0;
      }), _initializer2$1J = applyDecoratedInitializer(_class2$2b.prototype, "_renderers", [_dec2$1Q, serializable$p], function () {
        return [];
      }), _applyDecoratedDescriptor(_class2$2b.prototype, "screenUsagePercentage", [_dec3$1i], Object.getOwnPropertyDescriptor(_class2$2b.prototype, "screenUsagePercentage"), _class2$2b.prototype), _applyDecoratedDescriptor(_class2$2b.prototype, "renderers", [_dec4$Y], Object.getOwnPropertyDescriptor(_class2$2b.prototype, "renderers"), _class2$2b.prototype), _applyDecoratedDescriptor(_class2$2b.prototype, "triangleCount", [_dec5$T], Object.getOwnPropertyDescriptor(_class2$2b.prototype, "triangleCount"), _class2$2b.prototype)), _class2$2b)) || _class$2p));
      var LODGroup = exports('am', (_dec6$D = ccclass$M('cc.LODGroup'), _dec7$u = type$d(CCFloat), _dec8$l = type$d([LOD]), _dec6$D(_class4$p = (_class5$q = function (_Component) {
        _inheritsLoose(LODGroup, _Component);
        function LODGroup() {
          var _this;
          _this = _Component.call(this) || this;
          _this._localBoundaryCenter = _initializer3$1f && _initializer3$1f();
          _this._objectSize = _initializer4$14 && _initializer4$14();
          _this._LODs = _initializer5$R && _initializer5$R();
          _this._lodGroup = new LODGroup$1();
          _this._eventRegistered = false;
          _this._forceUsedLevels = [];
          return _this;
        }
        var _proto2 = LODGroup.prototype;
        _proto2.onLodModelAddedCallback = function onLodModelAddedCallback() {
          if (this.objectSize === 0) {
            this.recalculateBounds();
          }
        };
        _proto2.insertLOD = function insertLOD(index, screenUsagePercentage, lod) {
          if (index < 0 || index > this.lodCount) {
            index = this.lodCount;
          }
          if (!lod) {
            lod = new LOD();
          }
          lod.modelAddedCallback = this.onLodModelAddedCallback.bind(this);
          if (!screenUsagePercentage) {
            var preLod = this.getLOD(index - 1);
            var nextLod = this.getLOD(index);
            if (preLod && nextLod) {
              screenUsagePercentage = (preLod.screenUsagePercentage + nextLod.screenUsagePercentage) / 2;
            } else if (preLod && !nextLod) {
              screenUsagePercentage = preLod.screenUsagePercentage / 2;
              if (screenUsagePercentage > 0.01) {
                screenUsagePercentage = 0.01;
              }
            } else if (nextLod && !preLod) {
              screenUsagePercentage = nextLod.screenUsagePercentage;
              var curNextLOD = this.getLOD(index + 1);
              nextLod.screenUsagePercentage = (screenUsagePercentage + (curNextLOD ? curNextLOD.screenUsagePercentage : 0)) / 2;
            } else {
              screenUsagePercentage = DEFAULT_SCREEN_OCCUPATION[0];
            }
          }
          lod.screenUsagePercentage = screenUsagePercentage;
          this._LODs.splice(index, 0, lod);
          this._lodGroup.insertLOD(index, lod.lodData);
          this._updateDataToScene();
          if (this.node) {
            this._emitChangeNode(this.node);
          }
          return lod;
        };
        _proto2.eraseLOD = function eraseLOD(index) {
          if (index < 0 || index >= this.lodCount) {
            console.warn('eraseLOD error, index out of range');
            return null;
          }
          var lod = this._LODs[index];
          if (!lod) {
            console.warn('eraseLOD error, LOD not exist at specified index.');
            return null;
          }
          this._LODs.splice(index, 1);
          this._lodGroup.eraseLOD(index);
          this._updateDataToScene();
          this._emitChangeNode(this.node);
          return lod;
        };
        _proto2.getLOD = function getLOD(index) {
          if (index < 0 || index >= this.lodCount) {
            console.warn('getLOD error, index out of range');
            return null;
          }
          return this._LODs[index];
        };
        _proto2.setLOD = function setLOD(index, lod) {
          if (index < 0 || index >= this.lodCount) {
            console.warn('setLOD error, index out of range');
            return;
          }
          this._LODs[index] = lod;
          lod.modelAddedCallback = this.onLodModelAddedCallback.bind(this);
          this.lodGroup.updateLOD(index, lod.lodData);
          this._updateDataToScene();
        };
        _proto2.recalculateBounds = function recalculateBounds() {
          function getTransformedBoundary(c, e, transform) {
            var minPos;
            var maxPos;
            var pts = new Array(new Vec3(c.x - e.x, c.y - e.y, c.z - e.z), new Vec3(c.x - e.x, c.y + e.y, c.z - e.z), new Vec3(c.x + e.x, c.y + e.y, c.z - e.z), new Vec3(c.x + e.x, c.y - e.y, c.z - e.z), new Vec3(c.x - e.x, c.y - e.y, c.z + e.z), new Vec3(c.x - e.x, c.y + e.y, c.z + e.z), new Vec3(c.x + e.x, c.y + e.y, c.z + e.z), new Vec3(c.x + e.x, c.y - e.y, c.z + e.z));
            minPos = pts[0].transformMat4(transform);
            maxPos = minPos.clone();
            for (var i = 1; i < 8; ++i) {
              var pt = pts[i].transformMat4(transform);
              minPos = Vec3.min(minPos, minPos, pt);
              maxPos = Vec3.max(maxPos, maxPos, pt);
            }
            return [minPos, maxPos];
          }
          var minPos = new Vec3();
          var maxPos = new Vec3();
          var boundsMin = null;
          var boundsMax = new Vec3();
          for (var i = 0; i < this.lodCount; ++i) {
            var lod = this.getLOD(i);
            if (lod) {
              for (var j = 0; j < lod.rendererCount; ++j) {
                var _renderer$model, _renderer$model2;
                var renderer = lod.getRenderer(j);
                if (!renderer) {
                  continue;
                }
                (_renderer$model = renderer.model) === null || _renderer$model === void 0 ? void 0 : _renderer$model.updateWorldBound();
                var worldBounds = (_renderer$model2 = renderer.model) === null || _renderer$model2 === void 0 ? void 0 : _renderer$model2.worldBounds;
                if (worldBounds) {
                  worldBounds.getBoundary(minPos, maxPos);
                  if (boundsMin) {
                    Vec3.min(boundsMin, boundsMin, minPos);
                    Vec3.max(boundsMax, boundsMax, maxPos);
                  } else {
                    boundsMin = minPos.clone();
                    boundsMax = maxPos.clone();
                  }
                }
              }
            }
          }
          if (boundsMin) {
            var boundsMin2 = boundsMin;
            var c = new Vec3((boundsMax.x + boundsMin2.x) * 0.5, (boundsMax.y + boundsMin2.y) * 0.5, (boundsMax.z + boundsMin2.z) * 0.5);
            var e = new Vec3((boundsMax.x - boundsMin2.x) * 0.5, (boundsMax.y - boundsMin2.y) * 0.5, (boundsMax.z - boundsMin2.z) * 0.5);
            var _getTransformedBounda = getTransformedBoundary(c, e, this.node.worldMatrix.clone().invert()),
              _minPos = _getTransformedBounda[0],
              _maxPos = _getTransformedBounda[1];
            c.set((_maxPos.x + _minPos.x) * 0.5, (_maxPos.y + _minPos.y) * 0.5, (_maxPos.z + _minPos.z) * 0.5);
            e.set((_maxPos.x - _minPos.x) * 0.5, (_maxPos.y - _minPos.y) * 0.5, (_maxPos.z - _minPos.z) * 0.5);
            this.localBoundaryCenter = c;
            this.objectSize = Math.max(e.x, e.y, e.z) * 2.0;
          } else {
            this.localBoundaryCenter = new Vec3(0, 0, 0);
            this.objectSize = 0;
          }
          this._emitChangeNode(this.node);
        };
        _proto2.resetObjectSize = function resetObjectSize() {
          if (this.objectSize === 1.0) return;
          if (this.objectSize === 0) {
            this.objectSize = 1.0;
          }
          var scale = 1.0 / this.objectSize;
          this.objectSize = 1.0;
          for (var i = 0; i < this.lodCount; ++i) {
            var lod = this.getLOD(i);
            if (lod) {
              lod.screenUsagePercentage *= scale;
            }
          }
          this._emitChangeNode(this.node);
        };
        _proto2.forceLOD = function forceLOD(lodLevel) {
          this._forceUsedLevels = lodLevel < 0 ? [] : [lodLevel];
          this.lodGroup.lockLODLevels(this._forceUsedLevels);
        };
        _proto2.forceLODs = function forceLODs(lodIndexArray) {
        };
        _proto2.onLoad = function onLoad() {
          this._lodGroup.node = this.node;
          this._lodGroup.objectSize = this._objectSize;
          this._lodGroup.localBoundaryCenter = this._localBoundaryCenter;
          if (!this._eventRegistered) {
            this.node.on(NodeEventType.COMPONENT_REMOVED, this._onRemove, this);
            this._eventRegistered = true;
          }
          this._constructLOD();
        };
        _proto2._onRemove = function _onRemove(comp) {
          if (comp === this) {
            this.onDisable();
          }
        };
        _proto2._constructLOD = function _constructLOD() {
          if (this.lodCount < 1) {
            var size = DEFAULT_SCREEN_OCCUPATION.length;
            for (var i = 0; i < size; i++) {
              this.insertLOD(i, DEFAULT_SCREEN_OCCUPATION[i]);
            }
          }
        };
        _proto2.onRestore = function onRestore() {
          this._constructLOD();
          if (this.enabledInHierarchy) {
            this._attachToScene();
          }
        };
        _proto2.onEnable = function onEnable() {
          var _this2 = this;
          this._attachToScene();
          if (this.objectSize === 0) {
            this.recalculateBounds();
          }
          this.lodGroup.lockLODLevels(this._forceUsedLevels);
          if (this.lodCount > 0 && this._lodGroup.lodCount < 1) {
            this._LODs.forEach(function (lod, index) {
              lod.lodData.screenUsagePercentage = lod.screenUsagePercentage;
              var renderers = lod.renderers;
              if (renderers !== null && renderers.length > 0) {
                for (var i = 0; i < renderers.length; i++) {
                  var lodInstance = lod.lodData;
                  var renderer = renderers[i];
                  if (lodInstance && renderer && renderer.model) {
                    lodInstance.addModel(renderer.model);
                  }
                }
              }
              _this2._lodGroup.insertLOD(index, lod.lodData);
            });
          }
        };
        _proto2.onDisable = function onDisable() {
          this._detachFromScene();
          this.lodGroup.lockLODLevels([]);
        };
        _proto2._attachToScene = function _attachToScene() {
          if (this.node && this.node.scene) {
            var renderScene = this._getRenderScene();
            if (this._lodGroup.scene) {
              this._detachFromScene();
            }
            renderScene.addLODGroup(this._lodGroup);
          }
        };
        _proto2._detachFromScene = function _detachFromScene() {
          if (this._lodGroup.scene) {
            this._lodGroup.scene.removeLODGroup(this._lodGroup);
          }
        };
        _proto2._emitChangeNode = function _emitChangeNode(node) {
        };
        _proto2._updateDataToScene = function _updateDataToScene() {
          this._detachFromScene();
          this._attachToScene();
        };
        _createClass(LODGroup, [{
          key: "localBoundaryCenter",
          get: function get() {
            return this._localBoundaryCenter.clone();
          },
          set: function set(val) {
            this._localBoundaryCenter.set(val);
            this._lodGroup.localBoundaryCenter = val;
          }
        }, {
          key: "lodCount",
          get: function get() {
            return this._LODs.length;
          }
        }, {
          key: "objectSize",
          get: function get() {
            return this._objectSize;
          },
          set: function set(val) {
            this._objectSize = val;
            this._lodGroup.objectSize = val;
          }
        }, {
          key: "LODs",
          get: function get() {
            return this._LODs;
          },
          set: function set(valArray) {
            var _this3 = this;
            if (valArray === this._LODs) {
              this._updateDataToScene();
              return;
            }
            this._LODs.length = 0;
            this.lodGroup.clearLODs();
            valArray.forEach(function (lod, index) {
              _this3.lodGroup.insertLOD(index, lod.lodData);
              _this3._LODs[index] = lod;
              lod.modelAddedCallback = _this3.onLodModelAddedCallback.bind(_this3);
            });
            this._updateDataToScene();
          }
        }, {
          key: "lodGroup",
          get: function get() {
            return this._lodGroup;
          }
        }]);
        return LODGroup;
      }(Component), (_initializer3$1f = applyDecoratedInitializer(_class5$q.prototype, "_localBoundaryCenter", [serializable$p], function () {
        return new Vec3(0, 0, 0);
      }), _initializer4$14 = applyDecoratedInitializer(_class5$q.prototype, "_objectSize", [serializable$p], function () {
        return 0;
      }), _initializer5$R = applyDecoratedInitializer(_class5$q.prototype, "_LODs", [serializable$p], function () {
        return [];
      }), _applyDecoratedDescriptor(_class5$q.prototype, "objectSize", [_dec7$u], Object.getOwnPropertyDescriptor(_class5$q.prototype, "objectSize"), _class5$q.prototype), _applyDecoratedDescriptor(_class5$q.prototype, "LODs", [_dec8$l], Object.getOwnPropertyDescriptor(_class5$q.prototype, "LODs"), _class5$q.prototype)), _class5$q)) || _class4$p));

      var REFLECTION_PROBE_DEFAULT_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.UI_3D, Layers.BitMask.GIZMOS, Layers.BitMask.EDITOR, Layers.BitMask.SCENE_GIZMO, Layers.BitMask.PROFILER, Layers.Enum.IGNORE_RAYCAST]);
      var ReflectionProbeManager = exports('ao', function () {
        function ReflectionProbeManager() {
          this._probes = [];
          this._useCubeModels = new Map();
          this._usePlanarModels = new Map();
          this._updateForRuntime = true;
          this._dataTexture = null;
          this._registeredEvent = false;
        }
        var _proto = ReflectionProbeManager.prototype;
        _proto.registerEvent = function registerEvent() {
          if (!this._registeredEvent) {
            legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_UPDATE, this.onUpdateProbes, this);
            this._registeredEvent = true;
          }
        };
        _proto.onUpdateProbes = function onUpdateProbes() {
          if (this._probes.length === 0) return;
          var scene = legacyCC.director.getScene();
          if (!scene || !scene.renderScene) {
            return;
          }
          var models = scene.renderScene.models;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (!model.node) continue;
            if (model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) {
              if (model.reflectionProbeType === ReflectionProbeType.BAKED_CUBEMAP || this._isUsedBlending(model)) {
                this.selectReflectionProbe(model);
              } else if (model.reflectionProbeType === ReflectionProbeType.PLANAR_REFLECTION) {
                this.selectPlanarReflectionProbe(model);
              }
            }
          }
        };
        _proto.filterModelsForPlanarReflection = function filterModelsForPlanarReflection() {
          if (this._probes.length === 0) return;
          var scene = legacyCC.director.getScene();
          if (!scene || !scene.renderScene) {
            return;
          }
          var models = scene.renderScene.models;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (!model.node) continue;
            if (model.node.layer & REFLECTION_PROBE_DEFAULT_MASK && model.reflectionProbeType === ReflectionProbeType.PLANAR_REFLECTION) {
              this.selectPlanarReflectionProbe(model);
            }
          }
        };
        _proto.clearPlanarReflectionMap = function clearPlanarReflectionMap(probe) {
          for (var _iterator = _createForOfIteratorHelperLoose(this._usePlanarModels.entries()), _step; !(_step = _iterator()).done;) {
            var entry = _step.value;
            if (entry[1] === probe) {
              this._updatePlanarMapOfModel(entry[0], null, null);
            }
          }
        };
        _proto.register = function register(probe) {
          var index = this._probes.indexOf(probe);
          if (index === -1) {
            this._probes.push(probe);
            this.updateProbeData();
          }
        };
        _proto.unregister = function unregister(probe) {
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i] === probe) {
              var del = this._probes.splice(i, 1);
              if (del[0]) {
                this._removeDependentModels(del[0]);
              }
              break;
            }
          }
          this.updateProbeData();
        };
        _proto.exists = function exists(probeId) {
          if (this._probes.length === 0) return false;
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i].getProbeId() === probeId) {
              return true;
            }
          }
          return false;
        };
        _proto.getNewReflectionProbeId = function getNewReflectionProbeId() {
          var probeId = 0;
          while (true) {
            if (this.exists(probeId)) {
              probeId++;
            } else {
              return probeId;
            }
          }
        };
        _proto.getProbes = function getProbes() {
          return this._probes;
        };
        _proto.getProbeById = function getProbeById(probeId) {
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i].getProbeId() === probeId) {
              return this._probes[i];
            }
          }
          return null;
        };
        _proto.clearAll = function clearAll() {
          this._probes = [];
        };
        _proto.getProbeByCamera = function getProbeByCamera(camera) {
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i].camera === camera) {
              return this._probes[i];
            }
          }
          return null;
        };
        _proto.updateBakedCubemap = function updateBakedCubemap(probe) {
          var models = this._getModelsByProbe(probe);
          if (!probe.cubemap) return;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            this._updateCubemapOfModel(model, probe);
          }
          probe.needRefresh = false;
          if (models.length === 0) {
            for (var _iterator2 = _createForOfIteratorHelperLoose(this._useCubeModels.entries()), _step2; !(_step2 = _iterator2()).done;) {
              var entry = _step2.value;
              if (entry[0].reflectionProbeBlendId === probe.getProbeId()) {
                this._updateBlendCubemap(entry[0], probe);
              }
            }
          }
        };
        _proto.updatePlanarMap = function updatePlanarMap(probe, texture) {
          if (!probe.node || !probe.node.scene) return;
          var models = this._getModelsByProbe(probe);
          for (var i = 0; i < models.length; i++) {
            this._updatePlanarMapOfModel(models[i], texture, probe);
          }
          if (probe.previewPlane) {
            var meshRender = probe.previewPlane.getComponent(MeshRenderer);
            if (meshRender) {
              meshRender.updateProbePlanarMap(texture);
            }
          }
        };
        _proto.selectPlanarReflectionProbe = function selectPlanarReflectionProbe(model) {
          if (!model.node || !model.worldBounds || model.reflectionProbeType !== ReflectionProbeType.PLANAR_REFLECTION) return;
          for (var i = 0; i < this._probes.length; i++) {
            var probe = this._probes[i];
            if (probe.probeType !== ProbeType.PLANAR) continue;
            if (model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) {
              model.updateWorldBound();
              if (intersect.aabbWithAABB(model.worldBounds, probe.boundingBox)) {
                this._usePlanarModels.set(model, probe);
              } else if (this._usePlanarModels.has(model)) {
                var old = this._usePlanarModels.get(model);
                if (old === probe) {
                  this._usePlanarModels["delete"](model);
                  this._updatePlanarMapOfModel(model, null, null);
                }
              }
            }
          }
          for (var _i = 0; _i < this._probes.length; _i++) {
            if (this._probes[_i].probeType === ProbeType.PLANAR) {
              if (!this._probes[_i].realtimePlanarTexture) {
                this.updatePlanarMap(this._probes[_i], null);
              } else {
                this.updatePlanarMap(this._probes[_i], this._probes[_i].realtimePlanarTexture.getGFXTexture());
              }
            }
          }
        };
        _proto.selectReflectionProbe = function selectReflectionProbe(model) {
          if (model.node && model.worldBounds && model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) {
            model.updateWorldBound();
            var nearest = this._getNearestProbe(model);
            if (!nearest) {
              this._updateCubemapOfModel(model, null);
              this._useCubeModels["delete"](model);
            } else if (this._useCubeModels.has(model)) {
              var old = this._useCubeModels.get(model);
              if (old !== nearest) {
                this._useCubeModels.set(model, nearest);
              }
              nearest.needRefresh = true;
            } else {
              this._useCubeModels.set(model, nearest);
              nearest.needRefresh = true;
            }
          }
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i].needRefresh && this._probes[i].probeType === ProbeType.CUBE || this._isUsedBlending(model)) {
              this.updateBakedCubemap(this._probes[i]);
            }
          }
        };
        _proto.updatePreviewSphere = function updatePreviewSphere(probe) {
          if (!probe || !probe.previewSphere) return;
          var meshRender = probe.previewSphere.getComponent(MeshRenderer);
          if (meshRender) {
            meshRender.updateProbeCubemap(probe.cubemap);
            meshRender.updateReflectionProbeId(probe.getProbeId());
          }
        };
        _proto.updatePreviewPlane = function updatePreviewPlane(probe) {
          if (!probe || !probe.previewPlane) return;
          var meshRender = probe.previewPlane.getComponent(MeshRenderer);
          if (meshRender) {
            if (probe.realtimePlanarTexture) {
              this.updatePlanarMap(probe, probe.realtimePlanarTexture.getGFXTexture());
            }
          }
        };
        _proto.updateProbeData = function updateProbeData() {
          if (this._probes.length === 0) return;
          var maxId = this.getMaxProbeId();
          var height = maxId + 1;
          var dataWidth = 3;
          if (this._dataTexture) {
            this._dataTexture.destroy();
          }
          var buffer = new Float32Array(4 * dataWidth * height);
          var bufferOffset = 0;
          for (var i = 0; i <= maxId; i++) {
            var probe = this.getProbeById(i);
            if (!probe) {
              bufferOffset += 4 * dataWidth;
              continue;
            }
            if (probe.probeType === ProbeType.CUBE) {
              buffer[bufferOffset] = probe.node.worldPosition.x;
              buffer[bufferOffset + 1] = probe.node.worldPosition.y;
              buffer[bufferOffset + 2] = probe.node.worldPosition.z;
              buffer[bufferOffset + 3] = 0.0;
              buffer[bufferOffset + 4] = probe.size.x;
              buffer[bufferOffset + 5] = probe.size.y;
              buffer[bufferOffset + 6] = probe.size.z;
              buffer[bufferOffset + 7] = 0.0;
              var mipAndUseRGBE = probe.isRGBE() ? 1000 : 0;
              buffer[bufferOffset + 8] = probe.cubemap ? probe.cubemap.mipmapLevel + mipAndUseRGBE : 1.0 + mipAndUseRGBE;
            } else {
              buffer[bufferOffset] = probe.node.up.x;
              buffer[bufferOffset + 1] = probe.node.up.y;
              buffer[bufferOffset + 2] = probe.node.up.z;
              buffer[bufferOffset + 3] = 1.0;
              buffer[bufferOffset + 4] = 1.0;
              buffer[bufferOffset + 5] = 1.0;
              buffer[bufferOffset + 6] = 0.0;
              buffer[bufferOffset + 7] = 0.0;
              buffer[bufferOffset + 8] = 1.0;
            }
            bufferOffset += 4 * dataWidth;
          }
          var updateView = new Uint8Array(buffer.buffer);
          var image = new ImageAsset({
            _data: updateView,
            _compressed: false,
            width: dataWidth * 4,
            height: height,
            format: PixelFormat.RGBA8888
          });
          this._dataTexture = new Texture2D();
          this._dataTexture.setFilters(Texture2D.Filter.NONE, Texture2D.Filter.NONE);
          this._dataTexture.setMipFilter(Texture2D.Filter.NONE);
          this._dataTexture.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE);
          this._dataTexture.image = image;
          this._dataTexture.uploadData(updateView);
          for (var _i2 = 0; _i2 < this._probes.length; _i2++) {
            var _probe = this._probes[_i2];
            var models = this._getModelsByProbe(_probe);
            for (var j = 0; j < models.length; j++) {
              var meshRender = models[j].node.getComponent(MeshRenderer);
              if (meshRender) {
                meshRender.updateReflectionProbeDataMap(this._dataTexture);
              }
            }
          }
        };
        _proto.getMaxProbeId = function getMaxProbeId() {
          if (this._probes.length === 0) {
            return -1;
          }
          if (this._probes.length === 1) {
            return this._probes[0].getProbeId();
          }
          this._probes.sort(function (a, b) {
            return a.getProbeId() - b.getProbeId();
          });
          return this._probes[this._probes.length - 1].getProbeId();
        };
        _proto.getUsedReflectionProbe = function getUsedReflectionProbe(model, planarReflection) {
          if (planarReflection) {
            if (this._usePlanarModels.has(model)) {
              return this._usePlanarModels.get(model);
            }
          } else if (this._useCubeModels.has(model)) {
            return this._useCubeModels.get(model);
          }
          return null;
        };
        _proto.setReflectionProbe = function setReflectionProbe(model, probe, blendProbe) {
          if (blendProbe === void 0) {
            blendProbe = null;
          }
          if (!probe) return;
          this._useCubeModels.set(model, probe);
          this._updateCubemapOfModel(model, probe);
          if (blendProbe) {
            this._updateBlendProbeInfo(model, probe, blendProbe);
          }
        };
        _proto.updateProbeOfModels = function updateProbeOfModels() {
          if (this._probes.length === 0) return;
          var scene = legacyCC.director.getScene();
          if (!scene || !scene.renderScene) {
            return;
          }
          var models = scene.renderScene.models;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (!model.node) continue;
            if (model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) {
              if (model.reflectionProbeType === ReflectionProbeType.BAKED_CUBEMAP || model.reflectionProbeType === ReflectionProbeType.PLANAR_REFLECTION || this._isUsedBlending(model)) {
                model.updateReflectionProbeId();
              }
            }
          }
        };
        _proto._getNearestProbe = function _getNearestProbe(model) {
          if (!model.node || !model.worldBounds || this._probes.length === 0) return null;
          var nearestProbe = null;
          var minDistance = Infinity;
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._probes), _step3; !(_step3 = _iterator3()).done;) {
            var probe = _step3.value;
            if (probe.probeType !== ProbeType.CUBE || !probe.validate() || !intersect.aabbWithAABB(model.worldBounds, probe.boundingBox)) {
              continue;
            }
            var distance = Vec3.distance(model.node.worldPosition, probe.node.worldPosition);
            if (distance < minDistance) {
              minDistance = distance;
              nearestProbe = probe;
            }
          }
          return nearestProbe;
        };
        _proto._getBlendProbe = function _getBlendProbe(model) {
          if (!model || !model.node || !model.worldBounds || this._probes.length < 2) {
            return null;
          }
          var temp = [];
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i].probeType !== ProbeType.CUBE || !this._probes[i].validate() || !intersect.aabbWithAABB(model.worldBounds, this._probes[i].boundingBox)) {
              continue;
            }
            temp.push(this._probes[i]);
          }
          temp.sort(function (a, b) {
            var aDistance = Vec3.distance(model.node.worldPosition, a.node.worldPosition);
            var bDistance = Vec3.distance(model.node.worldPosition, b.node.worldPosition);
            return aDistance - bDistance;
          });
          return temp.length > 1 ? temp[1] : null;
        };
        _proto._getModelsByProbe = function _getModelsByProbe(probe) {
          var models = [];
          var useModels = this._useCubeModels;
          if (probe.probeType === ProbeType.PLANAR) {
            useModels = this._usePlanarModels;
          }
          for (var _iterator4 = _createForOfIteratorHelperLoose(useModels.entries()), _step4; !(_step4 = _iterator4()).done;) {
            var entry = _step4.value;
            if (entry[1] === probe) {
              models.push(entry[0]);
            }
          }
          return models;
        };
        _proto._removeDependentModels = function _removeDependentModels(probe) {
          for (var _iterator5 = _createForOfIteratorHelperLoose(this._useCubeModels.keys()), _step5; !(_step5 = _iterator5()).done;) {
            var key = _step5.value;
            var p = this._useCubeModels.get(key);
            if (p !== undefined && p === probe) {
              this._useCubeModels["delete"](key);
              this.selectReflectionProbe(key);
            }
          }
          for (var _iterator6 = _createForOfIteratorHelperLoose(this._usePlanarModels.keys()), _step6; !(_step6 = _iterator6()).done;) {
            var _key = _step6.value;
            var _p = this._usePlanarModels.get(_key);
            if (_p !== undefined && _p === probe) {
              this._usePlanarModels["delete"](_key);
              this.selectPlanarReflectionProbe(_key);
            }
          }
        };
        _proto._updateCubemapOfModel = function _updateCubemapOfModel(model, probe) {
          var node = model.node;
          if (!node) {
            return;
          }
          var meshRender = node.getComponent(MeshRenderer);
          if (!meshRender) {
            return;
          }
          meshRender.updateProbeCubemap(probe ? probe.cubemap : null);
          meshRender.updateReflectionProbeId(probe && probe.cubemap ? probe.getProbeId() : -1);
          if (probe) {
            meshRender.updateReflectionProbeDataMap(this._dataTexture);
            if (this._isUsedBlending(model)) {
              var blendProbe = this._getBlendProbe(model);
              this._updateBlendProbeInfo(model, probe, blendProbe);
            }
          }
        };
        _proto._updatePlanarMapOfModel = function _updatePlanarMapOfModel(model, texture, probe) {
          var meshRender = model.node.getComponent(MeshRenderer);
          if (meshRender) {
            meshRender.updateProbePlanarMap(texture);
            if (probe) {
              meshRender.updateReflectionProbeId(probe.getProbeId());
              meshRender.updateReflectionProbeDataMap(this._dataTexture);
            } else {
              meshRender.updateReflectionProbeId(-1);
            }
          }
        };
        _proto._isUsedBlending = function _isUsedBlending(model) {
          if (model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES || model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
            return true;
          }
          return false;
        };
        _proto._updateBlendProbeInfo = function _updateBlendProbeInfo(model, probe, blendProbe) {
          var node = model.node;
          if (!node) {
            return;
          }
          var meshRender = node.getComponent(MeshRenderer);
          if (!meshRender) {
            return;
          }
          if (blendProbe) {
            meshRender.updateReflectionProbeBlendId(blendProbe.getProbeId());
            meshRender.updateProbeBlendCubemap(blendProbe.cubemap);
            meshRender.updateReflectionProbeBlendWeight(this._calculateBlendWeight(model, probe, blendProbe));
          } else {
            meshRender.updateReflectionProbeBlendId(-1);
            if (model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
              meshRender.updateReflectionProbeBlendWeight(this._calculateBlendWeight(model, probe, blendProbe));
            }
          }
        };
        _proto._updateBlendCubemap = function _updateBlendCubemap(model, probe) {
          var node = model.node;
          if (!node) {
            return;
          }
          if (!this._isUsedBlending(model)) {
            return;
          }
          var meshRender = node.getComponent(MeshRenderer);
          if (meshRender) {
            meshRender.updateProbeBlendCubemap(probe.cubemap);
          }
        };
        _proto._calculateBlendWeight = function _calculateBlendWeight(model, probe, blendProbe) {
          if (blendProbe) {
            var d1 = Vec3.distance(model.node.worldPosition, probe.node.worldPosition);
            var d2 = Vec3.distance(model.node.worldPosition, blendProbe.node.worldPosition);
            return 1.0 - d2 / (d1 + d2);
          }
          if (model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES) {
            return 0.0;
          } else if (model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
            return this._calculateBlendOfSkybox(model.worldBounds, probe.boundingBox);
          }
          return 0.0;
        };
        _proto._calculateBlendOfSkybox = function _calculateBlendOfSkybox(aabb1, aabb2) {
          if (!aabb1) return 1.0;
          var aMin = new Vec3();
          var aMax = new Vec3();
          var bMin = new Vec3();
          var bMax = new Vec3();
          Vec3.subtract(aMin, aabb1.center, aabb1.halfExtents);
          Vec3.add(aMax, aabb1.center, aabb1.halfExtents);
          Vec3.subtract(bMin, aabb2.center, aabb2.halfExtents);
          Vec3.add(bMax, aabb2.center, aabb2.halfExtents);
          var inside = aMin.x <= bMax.x && aMax.x >= bMin.x && aMin.y <= bMax.y && aMax.y >= bMin.y && aMin.z <= bMax.z && aMax.z >= bMin.z;
          if (inside) {
            var fullSize = new Vec3();
            Vec3.multiplyScalar(fullSize, aabb1.halfExtents, 2.0);
            var boundaryXAdd = aMin.x + fullSize.x <= bMax.x && aMax.x + fullSize.x >= bMin.x;
            var boundaryXSub = aMin.x - fullSize.x <= bMax.x && aMax.x - fullSize.x >= bMin.x;
            var boundaryYAdd = aMin.y + fullSize.y <= bMax.y && aMax.y + fullSize.y >= bMin.y;
            var boundaryYSub = aMin.y - fullSize.y <= bMax.y && aMax.y - fullSize.y >= bMin.y;
            var boundaryZAdd = aMin.z + fullSize.z <= bMax.z && aMax.z + fullSize.z >= bMin.z;
            var boundaryZSub = aMin.z - fullSize.z <= bMax.z && aMax.z - fullSize.z >= bMin.z;
            var weights = [];
            if (!boundaryXAdd) {
              var offset = aMax.x - bMax.x;
              weights.push(offset / fullSize.x);
            }
            if (!boundaryXSub) {
              var _offset = Math.abs(aMin.x - bMin.x);
              weights.push(_offset / fullSize.x);
            }
            if (!boundaryYAdd) {
              var _offset2 = aMax.y - bMax.y;
              weights.push(_offset2 / fullSize.y);
            }
            if (!boundaryYSub) {
              var _offset3 = Math.abs(aMin.y - bMin.y);
              weights.push(_offset3 / fullSize.y);
            }
            if (!boundaryZAdd) {
              var _offset4 = aMax.z - bMax.z;
              weights.push(_offset4 / fullSize.z);
            }
            if (!boundaryZSub) {
              var _offset5 = Math.abs(aMin.z - bMin.z);
              weights.push(_offset5 / fullSize.z);
            }
            if (weights.length > 0) {
              weights.sort(function (a, b) {
                return b - a;
              });
              return weights[0];
            } else {
              return 0.0;
            }
          }
          return 1.0;
        };
        _createClass(ReflectionProbeManager, [{
          key: "updateForRuntime",
          get: function get() {
            return this._updateForRuntime;
          },
          set: function set(val) {
            this._updateForRuntime = val;
          }
        }]);
        return ReflectionProbeManager;
      }());
      ReflectionProbeManager.probeManager = void 0;
      ReflectionProbeManager.probeManager = new ReflectionProbeManager();
      legacyCC.internal.reflectionProbeManager = ReflectionProbeManager.probeManager;

      function wireframe(indices) {
        var offsets = [[0, 1], [1, 2], [2, 0]];
        var lines = [];
        var lineIDs = {};
        for (var i = 0; i < indices.length; i += 3) {
          for (var k = 0; k < 3; ++k) {
            var i1 = indices[i + offsets[k][0]];
            var i2 = indices[i + offsets[k][1]];
            var id = i1 > i2 ? i2 << 16 | i1 : i1 << 16 | i2;
            if (lineIDs[id] === undefined) {
              lineIDs[id] = 0;
              lines.push(i1, i2);
            }
          }
        }
        return lines;
      }
      function invWinding(indices) {
        var newIB = [];
        for (var i = 0; i < indices.length; i += 3) {
          newIB.push(indices[i], indices[i + 2], indices[i + 1]);
        }
        return newIB;
      }
      function toWavefrontOBJ(primitive, scale) {
        if (scale === void 0) {
          scale = 1;
        }
        if (!primitive.indices || !primitive.uvs || !primitive.normals || primitive.primitiveMode !== undefined && primitive.primitiveMode !== PrimitiveMode.TRIANGLE_LIST) {
          return '';
        }
        var v = primitive.positions;
        var t = primitive.uvs;
        var n = primitive.normals;
        var IB = primitive.indices;
        var V = function V(i) {
          return IB[i] + 1 + "/" + (IB[i] + 1) + "/" + (IB[i] + 1);
        };
        var content = '';
        for (var i = 0; i < v.length; i += 3) {
          content += "v " + v[i] * scale + " " + v[i + 1] * scale + " " + v[i + 2] * scale + "\n";
        }
        for (var _i = 0; _i < t.length; _i += 2) {
          content += "vt " + t[_i] + " " + t[_i + 1] + "\n";
        }
        for (var _i2 = 0; _i2 < n.length; _i2 += 3) {
          content += "vn " + n[_i2] + " " + n[_i2 + 1] + " " + n[_i2 + 2] + "\n";
        }
        for (var _i3 = 0; _i3 < IB.length; _i3 += 3) {
          content += "f " + V(_i3) + " " + V(_i3 + 1) + " " + V(_i3 + 2) + "\n";
        }
        return content;
      }
      function normals(positions, nms, length) {
        if (length === void 0) {
          length = 1;
        }
        var verts = new Array(2 * positions.length);
        for (var i = 0; i < positions.length / 3; ++i) {
          var i3 = 3 * i;
          var i6 = 6 * i;
          verts[i6 + 0] = positions[i3 + 0];
          verts[i6 + 1] = positions[i3 + 1];
          verts[i6 + 2] = positions[i3 + 2];
          verts[i6 + 3] = positions[i3 + 0] + nms[i3 + 0] * length;
          verts[i6 + 4] = positions[i3 + 1] + nms[i3 + 1] * length;
          verts[i6 + 5] = positions[i3 + 2] + nms[i3 + 2] * length;
        }
        return verts;
      }

      function applyDefaultGeometryOptions(options) {
        options = options || {};
        if (options.includeNormal === undefined) {
          options.includeNormal = true;
        }
        if (options.includeUV === undefined) {
          options.includeUV = true;
        }
        return options;
      }

      function box(options) {
        options = options || {};
        var ws = options.widthSegments || 1;
        var hs = options.heightSegments || 1;
        var ls = options.lengthSegments || 1;
        var hw = (options.width || 1) / 2;
        var hh = (options.height || 1) / 2;
        var hl = (options.length || 1) / 2;
        var corners = [Vec3.set(c0, -hw, -hh, hl), Vec3.set(c1, hw, -hh, hl), Vec3.set(c2, hw, hh, hl), Vec3.set(c3, -hw, hh, hl), Vec3.set(c4, hw, -hh, -hl), Vec3.set(c5, -hw, -hh, -hl), Vec3.set(c6, -hw, hh, -hl), Vec3.set(c7, hw, hh, -hl)];
        var faceAxes = [[2, 3, 1], [4, 5, 7], [7, 6, 2], [1, 0, 4], [1, 4, 2], [5, 0, 6]];
        var faceNormals = [[0, 0, 1], [0, 0, -1], [0, 1, 0], [0, -1, 0], [1, 0, 0], [-1, 0, 0]];
        var faceTangents = [[-1, 0, 0, 1], [-1, 0, 0, 1], [-1, 0, 0, 1], [-1, 0, 0, 1], [0, 0, -1, 1], [0, 0, 1, 1]];
        var positions = [];
        var normals = [];
        var uvs = [];
        var tangents = [];
        var indices = [];
        var minPos = new Vec3(-hw, -hh, -hl);
        var maxPos = new Vec3(hw, hh, hl);
        var boundingRadius = Math.sqrt(hw * hw + hh * hh + hl * hl);
        function _buildPlane(side, uSegments, vSegments) {
          var u;
          var v;
          var ix;
          var iy;
          var offset = positions.length / 3;
          var faceAxe = faceAxes[side];
          var faceNormal = faceNormals[side];
          var faceTangent = faceTangents[side];
          for (iy = 0; iy <= vSegments; iy++) {
            for (ix = 0; ix <= uSegments; ix++) {
              u = ix / uSegments;
              v = iy / vSegments;
              Vec3.lerp(temp1$3, corners[faceAxe[0]], corners[faceAxe[1]], u);
              Vec3.lerp(temp2$3, corners[faceAxe[0]], corners[faceAxe[2]], v);
              Vec3.subtract(temp3$1, temp2$3, corners[faceAxe[0]]);
              Vec3.add(r$1, temp1$3, temp3$1);
              positions.push(r$1.x, r$1.y, r$1.z);
              normals.push(faceNormal[0], faceNormal[1], faceNormal[2]);
              uvs.push(u, v);
              tangents.push(faceTangent[0], faceTangent[1], faceTangent[2], faceTangent[3]);
              if (ix < uSegments && iy < vSegments) {
                var useg1 = uSegments + 1;
                var a = ix + iy * useg1;
                var b = ix + (iy + 1) * useg1;
                var c = ix + 1 + (iy + 1) * useg1;
                var d = ix + 1 + iy * useg1;
                indices.push(offset + a, offset + d, offset + b);
                indices.push(offset + b, offset + d, offset + c);
              }
            }
          }
        }
        _buildPlane(0, ws, hs);
        _buildPlane(4, ls, hs);
        _buildPlane(1, ws, hs);
        _buildPlane(5, ls, hs);
        _buildPlane(3, ws, ls);
        _buildPlane(2, ws, ls);
        return {
          positions: positions,
          normals: normals,
          uvs: uvs,
          tangents: tangents,
          indices: indices,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
      }
      var temp1$3 = new Vec3();
      var temp2$3 = new Vec3();
      var temp3$1 = new Vec3();
      var r$1 = new Vec3();
      var c0 = new Vec3();
      var c1 = new Vec3();
      var c2 = new Vec3();
      var c3 = new Vec3();
      var c4 = new Vec3();
      var c5 = new Vec3();
      var c6 = new Vec3();
      var c7 = new Vec3();

      var temp1$2 = new Vec3(0, 0, 0);
      var temp2$2 = new Vec3(0, 0, 0);
      function cylinder(radiusTop, radiusBottom, height, opts) {
        if (radiusTop === void 0) {
          radiusTop = 0.5;
        }
        if (radiusBottom === void 0) {
          radiusBottom = 0.5;
        }
        if (height === void 0) {
          height = 2;
        }
        if (opts === void 0) {
          opts = {};
        }
        var halfHeight = height * 0.5;
        var radialSegments = opts.radialSegments || 32;
        var heightSegments = opts.heightSegments || 1;
        var capped = opts.capped !== undefined ? opts.capped : true;
        var arc = opts.arc || 2.0 * Math.PI;
        var cntCap = 0;
        if (capped) {
          if (radiusTop > 0) {
            cntCap++;
          }
          if (radiusBottom > 0) {
            cntCap++;
          }
        }
        var vertCount = (radialSegments + 1) * (heightSegments + 1);
        if (capped) {
          vertCount += (radialSegments + 1) * cntCap + radialSegments * cntCap;
        }
        var indexCount = radialSegments * heightSegments * 2 * 3;
        if (capped) {
          indexCount += radialSegments * cntCap * 3;
        }
        var indices = new Array(indexCount);
        var positions = new Array(vertCount * 3);
        var normals = new Array(vertCount * 3);
        var uvs = new Array(vertCount * 2);
        var maxRadius = Math.max(radiusTop, radiusBottom);
        var minPos = new Vec3(-maxRadius, -halfHeight, -maxRadius);
        var maxPos = new Vec3(maxRadius, halfHeight, maxRadius);
        var boundingRadius = Math.sqrt(maxRadius * maxRadius + halfHeight * halfHeight);
        var index = 0;
        var indexOffset = 0;
        generateTorso();
        if (capped) {
          if (radiusBottom > 0) {
            generateCap(false);
          }
          if (radiusTop > 0) {
            generateCap(true);
          }
        }
        return {
          positions: positions,
          normals: normals,
          uvs: uvs,
          indices: indices,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
        function generateTorso() {
          var indexArray = [];
          var r = radiusTop - radiusBottom;
          var slope = r * r / height * Math.sign(r);
          for (var y = 0; y <= heightSegments; y++) {
            var indexRow = [];
            var v = y / heightSegments;
            var radius = v * r + radiusBottom;
            for (var x = 0; x <= radialSegments; ++x) {
              var u = x / radialSegments;
              var theta = u * arc;
              var sinTheta = Math.sin(theta);
              var cosTheta = Math.cos(theta);
              positions[3 * index] = radius * sinTheta;
              positions[3 * index + 1] = v * height - halfHeight;
              positions[3 * index + 2] = radius * cosTheta;
              Vec3.normalize(temp1$2, Vec3.set(temp2$2, sinTheta, -slope, cosTheta));
              normals[3 * index] = temp1$2.x;
              normals[3 * index + 1] = temp1$2.y;
              normals[3 * index + 2] = temp1$2.z;
              uvs[2 * index] = (1 - u) * 2 % 1;
              uvs[2 * index + 1] = v;
              indexRow.push(index);
              ++index;
            }
            indexArray.push(indexRow);
          }
          for (var _y = 0; _y < heightSegments; ++_y) {
            for (var _x = 0; _x < radialSegments; ++_x) {
              var i1 = indexArray[_y][_x];
              var i2 = indexArray[_y + 1][_x];
              var i3 = indexArray[_y + 1][_x + 1];
              var i4 = indexArray[_y][_x + 1];
              indices[indexOffset] = i1;
              ++indexOffset;
              indices[indexOffset] = i4;
              ++indexOffset;
              indices[indexOffset] = i2;
              ++indexOffset;
              indices[indexOffset] = i4;
              ++indexOffset;
              indices[indexOffset] = i3;
              ++indexOffset;
              indices[indexOffset] = i2;
              ++indexOffset;
            }
          }
        }
        function generateCap(top) {
          var radius = top ? radiusTop : radiusBottom;
          var sign = top ? 1 : -1;
          var centerIndexStart = index;
          for (var x = 1; x <= radialSegments; ++x) {
            positions[3 * index] = 0;
            positions[3 * index + 1] = halfHeight * sign;
            positions[3 * index + 2] = 0;
            normals[3 * index] = 0;
            normals[3 * index + 1] = sign;
            normals[3 * index + 2] = 0;
            uvs[2 * index] = 0.5;
            uvs[2 * index + 1] = 0.5;
            ++index;
          }
          var centerIndexEnd = index;
          for (var _x2 = 0; _x2 <= radialSegments; ++_x2) {
            var u = _x2 / radialSegments;
            var theta = u * arc;
            var cosTheta = Math.cos(theta);
            var sinTheta = Math.sin(theta);
            positions[3 * index] = radius * sinTheta;
            positions[3 * index + 1] = halfHeight * sign;
            positions[3 * index + 2] = radius * cosTheta;
            normals[3 * index] = 0;
            normals[3 * index + 1] = sign;
            normals[3 * index + 2] = 0;
            uvs[2 * index] = 0.5 - sinTheta * 0.5 * sign;
            uvs[2 * index + 1] = 0.5 + cosTheta * 0.5;
            ++index;
          }
          for (var _x3 = 0; _x3 < radialSegments; ++_x3) {
            var c = centerIndexStart + _x3;
            var i = centerIndexEnd + _x3;
            if (top) {
              indices[indexOffset] = i + 1;
              ++indexOffset;
              indices[indexOffset] = c;
              ++indexOffset;
              indices[indexOffset] = i;
              ++indexOffset;
            } else {
              indices[indexOffset] = c;
              ++indexOffset;
              indices[indexOffset] = i + 1;
              ++indexOffset;
              indices[indexOffset] = i;
              ++indexOffset;
            }
          }
        }
      }

      function cone(radius, height, opts) {
        if (radius === void 0) {
          radius = 0.5;
        }
        if (height === void 0) {
          height = 1;
        }
        if (opts === void 0) {
          opts = {};
        }
        return cylinder(0, radius, height, opts);
      }

      function applyDefaultPlaneOptions(options) {
        options = applyDefaultGeometryOptions(options);
        options.width = options.width || 10;
        options.length = options.length || 10;
        options.widthSegments = options.widthSegments || 10;
        options.lengthSegments = options.lengthSegments || 10;
        return options;
      }
      var temp1$1 = new Vec3(0, 0, 0);
      var temp2$1 = new Vec3(0, 0, 0);
      var temp3 = new Vec3(0, 0, 0);
      var r = new Vec3(0, 0, 0);
      var c00 = new Vec3(0, 0, 0);
      var c10 = new Vec3(0, 0, 0);
      var c01 = new Vec3(0, 0, 0);
      function plane(options) {
        var normalizedOptions = applyDefaultPlaneOptions(options);
        var width = normalizedOptions.width,
          length = normalizedOptions.length,
          uSegments = normalizedOptions.widthSegments,
          vSegments = normalizedOptions.lengthSegments;
        var hw = width * 0.5;
        var hl = length * 0.5;
        var positions = [];
        var uvs = [];
        var indices = [];
        var minPos = new Vec3(-hw, 0, -hl);
        var maxPos = new Vec3(hw, 0, hl);
        var boundingRadius = Math.sqrt(width * width + length * length);
        Vec3.set(c00, -hw, 0, hl);
        Vec3.set(c10, hw, 0, hl);
        Vec3.set(c01, -hw, 0, -hl);
        for (var y = 0; y <= vSegments; y++) {
          for (var x = 0; x <= uSegments; x++) {
            var u = x / uSegments;
            var v = y / vSegments;
            Vec3.lerp(temp1$1, c00, c10, u);
            Vec3.lerp(temp2$1, c00, c01, v);
            Vec3.subtract(temp3, temp2$1, c00);
            Vec3.add(r, temp1$1, temp3);
            positions.push(r.x, r.y, r.z);
            if (normalizedOptions.includeUV) {
              uvs.push(u, v);
            }
            if (x < uSegments && y < vSegments) {
              var useg1 = uSegments + 1;
              var a = x + y * useg1;
              var b = x + (y + 1) * useg1;
              var c = x + 1 + (y + 1) * useg1;
              var d = x + 1 + y * useg1;
              indices.push(a, d, b);
              indices.push(d, c, b);
            }
          }
        }
        var result = {
          positions: positions,
          indices: indices,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
        if (normalizedOptions.includeNormal) {
          var nVertex = (vSegments + 1) * (uSegments + 1);
          var normals = new Array(3 * nVertex);
          result.normals = normals;
          for (var i = 0; i < nVertex; ++i) {
            normals[i * 3 + 0] = 0;
            normals[i * 3 + 1] = 1;
            normals[i * 3 + 2] = 0;
          }
        }
        if (normalizedOptions.includeUV) {
          result.uvs = uvs;
        }
        return result;
      }

      function quad(options) {
        var normalizedOptions = applyDefaultGeometryOptions(options);
        var result = {
          positions: [-0.5, -0.5, 0, -0.5, 0.5, 0, 0.5, 0.5, 0, 0.5, -0.5, 0],
          indices: [0, 3, 1, 3, 2, 1],
          minPos: {
            x: -0.5,
            y: -0.5,
            z: 0
          },
          maxPos: {
            x: 0.5,
            y: 0.5,
            z: 0
          },
          boundingRadius: Math.sqrt(0.5 * 0.5 + 0.5 * 0.5)
        };
        if (normalizedOptions.includeNormal !== false) {
          result.normals = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1];
        }
        if (normalizedOptions.includeUV !== false) {
          result.uvs = [0, 0, 0, 1, 1, 1, 1, 0];
        }
        return result;
      }

      function sphere(radius, opts) {
        if (radius === void 0) {
          radius = 0.5;
        }
        if (opts === void 0) {
          opts = {};
        }
        var segments = opts.segments !== undefined ? opts.segments : 32;
        var positions = [];
        var normals = [];
        var uvs = [];
        var indices = [];
        var minPos = new Vec3(-radius, -radius, -radius);
        var maxPos = new Vec3(radius, radius, radius);
        var boundingRadius = radius;
        for (var lat = 0; lat <= segments; ++lat) {
          var theta = lat * Math.PI / segments;
          var sinTheta = Math.sin(theta);
          var cosTheta = -Math.cos(theta);
          for (var lon = 0; lon <= segments; ++lon) {
            var phi = lon * 2 * Math.PI / segments - Math.PI / 2.0;
            var sinPhi = Math.sin(phi);
            var cosPhi = Math.cos(phi);
            var x = sinPhi * sinTheta;
            var y = cosTheta;
            var z = cosPhi * sinTheta;
            var u = lon / segments;
            var v = lat / segments;
            positions.push(x * radius, y * radius, z * radius);
            normals.push(x, y, z);
            uvs.push(u, v);
            if (lat < segments && lon < segments) {
              var seg1 = segments + 1;
              var a = seg1 * lat + lon;
              var b = seg1 * (lat + 1) + lon;
              var c = seg1 * (lat + 1) + lon + 1;
              var d = seg1 * lat + lon + 1;
              indices.push(a, d, b);
              indices.push(d, c, b);
            }
          }
        }
        return {
          positions: positions,
          indices: indices,
          normals: normals,
          uvs: uvs,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
      }

      function torus(radius, tube, opts) {
        if (radius === void 0) {
          radius = 0.4;
        }
        if (tube === void 0) {
          tube = 0.1;
        }
        if (opts === void 0) {
          opts = {};
        }
        var radialSegments = opts.radialSegments || 32;
        var tubularSegments = opts.tubularSegments || 32;
        var arc = opts.arc || 2.0 * Math.PI;
        var positions = [];
        var normals = [];
        var uvs = [];
        var indices = [];
        var minPos = new Vec3(-radius - tube, -tube, -radius - tube);
        var maxPos = new Vec3(radius + tube, tube, radius + tube);
        var boundingRadius = radius + tube;
        for (var j = 0; j <= radialSegments; j++) {
          for (var i = 0; i <= tubularSegments; i++) {
            var u = i / tubularSegments;
            var v = j / radialSegments;
            var u1 = u * arc;
            var v1 = v * Math.PI * 2;
            var x = (radius + tube * Math.cos(v1)) * Math.sin(u1);
            var y = tube * Math.sin(v1);
            var z = (radius + tube * Math.cos(v1)) * Math.cos(u1);
            var nx = Math.sin(u1) * Math.cos(v1);
            var ny = Math.sin(v1);
            var nz = Math.cos(u1) * Math.cos(v1);
            positions.push(x, y, z);
            normals.push(nx, ny, nz);
            uvs.push(u, v);
            if (i < tubularSegments && j < radialSegments) {
              var seg1 = tubularSegments + 1;
              var a = seg1 * j + i;
              var b = seg1 * (j + 1) + i;
              var c = seg1 * (j + 1) + i + 1;
              var d = seg1 * j + i + 1;
              indices.push(a, d, b);
              indices.push(d, c, b);
            }
          }
        }
        return {
          positions: positions,
          normals: normals,
          uvs: uvs,
          indices: indices,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
      }

      var temp1 = new Vec3(0, 0, 0);
      var temp2 = new Vec3(0, 0, 0);
      function capsule(radiusTop, radiusBottom, height, opts) {
        if (radiusTop === void 0) {
          radiusTop = 0.5;
        }
        if (radiusBottom === void 0) {
          radiusBottom = 0.5;
        }
        if (height === void 0) {
          height = 2;
        }
        if (opts === void 0) {
          opts = {};
        }
        var torsoHeight = height - radiusTop - radiusBottom;
        var sides = opts.sides || 32;
        var heightSegments = opts.heightSegments || 32;
        var bottomProp = radiusBottom / height;
        var torProp = torsoHeight / height;
        var topProp = radiusTop / height;
        var bottomSegments = Math.floor(heightSegments * bottomProp);
        var topSegments = Math.floor(heightSegments * topProp);
        var torSegments = Math.floor(heightSegments * torProp);
        var topOffset = torsoHeight + radiusBottom - height / 2;
        var torOffset = radiusBottom - height / 2;
        var bottomOffset = radiusBottom - height / 2;
        var arc = opts.arc || 2.0 * Math.PI;
        var positions = [];
        var normals = [];
        var uvs = [];
        var indices = [];
        var maxRadius = Math.max(radiusTop, radiusBottom);
        var minPos = new Vec3(-maxRadius, -height / 2, -maxRadius);
        var maxPos = new Vec3(maxRadius, height / 2, maxRadius);
        var boundingRadius = height / 2;
        var index = 0;
        var indexArray = [];
        generateBottom();
        generateTorso();
        generateTop();
        return {
          positions: positions,
          normals: normals,
          uvs: uvs,
          indices: indices,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
        function generateTorso() {
          var slope = (radiusTop - radiusBottom) / torsoHeight;
          for (var y = 0; y <= torSegments; y++) {
            var indexRow = [];
            var lat = y / torSegments;
            var radius = lat * (radiusTop - radiusBottom) + radiusBottom;
            for (var x = 0; x <= sides; ++x) {
              var u = x / sides;
              var v = lat * torProp + bottomProp;
              var theta = u * arc - arc / 4;
              var sinTheta = Math.sin(theta);
              var cosTheta = Math.cos(theta);
              positions.push(radius * sinTheta);
              positions.push(lat * torsoHeight + torOffset);
              positions.push(radius * cosTheta);
              Vec3.normalize(temp1, Vec3.set(temp2, sinTheta, -slope, cosTheta));
              normals.push(temp1.x);
              normals.push(temp1.y);
              normals.push(temp1.z);
              uvs.push(u, v);
              indexRow.push(index);
              ++index;
            }
            indexArray.push(indexRow);
          }
          for (var _y = 0; _y < torSegments; ++_y) {
            for (var _x = 0; _x < sides; ++_x) {
              var i1 = indexArray[_y][_x];
              var i2 = indexArray[_y + 1][_x];
              var i3 = indexArray[_y + 1][_x + 1];
              var i4 = indexArray[_y][_x + 1];
              indices.push(i1);
              indices.push(i4);
              indices.push(i2);
              indices.push(i4);
              indices.push(i3);
              indices.push(i2);
            }
          }
        }
        function generateBottom() {
          for (var lat = 0; lat <= bottomSegments; ++lat) {
            var theta = lat * Math.PI / bottomSegments / 2;
            var sinTheta = Math.sin(theta);
            var cosTheta = -Math.cos(theta);
            for (var lon = 0; lon <= sides; ++lon) {
              var phi = lon * 2 * Math.PI / sides - Math.PI / 2.0;
              var sinPhi = Math.sin(phi);
              var cosPhi = Math.cos(phi);
              var x = sinPhi * sinTheta;
              var y = cosTheta;
              var z = cosPhi * sinTheta;
              var u = lon / sides;
              var v = lat / heightSegments;
              positions.push(x * radiusBottom, y * radiusBottom + bottomOffset, z * radiusBottom);
              normals.push(x, y, z);
              uvs.push(u, v);
              if (lat < bottomSegments && lon < sides) {
                var seg1 = sides + 1;
                var a = seg1 * lat + lon;
                var b = seg1 * (lat + 1) + lon;
                var c = seg1 * (lat + 1) + lon + 1;
                var d = seg1 * lat + lon + 1;
                indices.push(a, d, b);
                indices.push(d, c, b);
              }
              ++index;
            }
          }
        }
        function generateTop() {
          for (var lat = 0; lat <= topSegments; ++lat) {
            var theta = lat * Math.PI / topSegments / 2 + Math.PI / 2;
            var sinTheta = Math.sin(theta);
            var cosTheta = -Math.cos(theta);
            for (var lon = 0; lon <= sides; ++lon) {
              var phi = lon * 2 * Math.PI / sides - Math.PI / 2.0;
              var sinPhi = Math.sin(phi);
              var cosPhi = Math.cos(phi);
              var x = sinPhi * sinTheta;
              var y = cosTheta;
              var z = cosPhi * sinTheta;
              var u = lon / sides;
              var v = lat / heightSegments + (1 - topProp);
              positions.push(x * radiusTop, y * radiusTop + topOffset, z * radiusTop);
              normals.push(x, y, z);
              uvs.push(u, v);
              if (lat < topSegments && lon < sides) {
                var seg1 = sides + 1;
                var a = seg1 * lat + lon + indexArray[torSegments][sides] + 1;
                var b = seg1 * (lat + 1) + lon + indexArray[torSegments][sides] + 1;
                var c = seg1 * (lat + 1) + lon + 1 + indexArray[torSegments][sides] + 1;
                var d = seg1 * lat + lon + 1 + indexArray[torSegments][sides] + 1;
                indices.push(a, d, b);
                indices.push(d, c, b);
              }
            }
          }
        }
      }

      function applyDefaultCircleOptions(options) {
        options = applyDefaultGeometryOptions(options);
        options.segments = 64;
        return options;
      }
      function circle(options) {
        var normalizedOptions = applyDefaultCircleOptions(options);
        var segments = normalizedOptions.segments;
        var positions = new Array(3 * (segments + 1));
        positions[0] = 0;
        positions[1] = 0;
        positions[2] = 0;
        var indices = new Array(1 + segments * 2);
        indices[0] = 0;
        var step = Math.PI * 2 / segments;
        for (var iSegment = 0; iSegment < segments; ++iSegment) {
          var angle = step * iSegment;
          var x = Math.cos(angle);
          var y = Math.sin(angle);
          var p = (iSegment + 1) * 3;
          positions[p + 0] = x;
          positions[p + 1] = y;
          positions[p + 2] = 0;
          var i = iSegment * 2;
          indices[1 + i] = iSegment + 1;
          indices[1 + (i + 1)] = iSegment + 2;
        }
        if (segments > 0) {
          indices[indices.length - 1] = 1;
        }
        var result = {
          positions: positions,
          indices: indices,
          minPos: {
            x: 1,
            y: 1,
            z: 0
          },
          maxPos: {
            x: -1,
            y: -1,
            z: 0
          },
          boundingRadius: 1,
          primitiveMode: PrimitiveMode.TRIANGLE_FAN
        };
        return result;
      }

      function translate(geometry, offset) {
        var x = offset.x || 0;
        var y = offset.y || 0;
        var z = offset.z || 0;
        var nVertex = Math.floor(geometry.positions.length / 3);
        for (var iVertex = 0; iVertex < nVertex; ++iVertex) {
          var iX = iVertex * 3;
          var iY = iVertex * 3 + 1;
          var iZ = iVertex * 3 + 2;
          geometry.positions[iX] += x;
          geometry.positions[iY] += y;
          geometry.positions[iZ] += z;
        }
        if (geometry.minPos) {
          geometry.minPos.x += x;
          geometry.minPos.y += y;
          geometry.minPos.z += z;
        }
        if (geometry.maxPos) {
          geometry.maxPos.x += x;
          geometry.maxPos.y += y;
          geometry.maxPos.z += z;
        }
        return geometry;
      }
      function scale(geometry, value) {
        var _value$x, _value$y, _value$z;
        var x = (_value$x = value.x) !== null && _value$x !== void 0 ? _value$x : 1.0;
        var y = (_value$y = value.y) !== null && _value$y !== void 0 ? _value$y : 1.0;
        var z = (_value$z = value.z) !== null && _value$z !== void 0 ? _value$z : 1.0;
        var nVertex = Math.floor(geometry.positions.length / 3);
        for (var iVertex = 0; iVertex < nVertex; ++iVertex) {
          var iX = iVertex * 3;
          var iY = iVertex * 3 + 1;
          var iZ = iVertex * 3 + 2;
          geometry.positions[iX] *= x;
          geometry.positions[iY] *= y;
          geometry.positions[iZ] *= z;
        }
        var minPos = geometry.minPos,
          maxPos = geometry.maxPos;
        if (minPos) {
          minPos.x *= x;
          minPos.y *= y;
          minPos.z *= z;
        }
        if (maxPos) {
          maxPos.x *= x;
          maxPos.y *= y;
          maxPos.z *= z;
        }
        if (minPos && maxPos) {
          if (x < 0) {
            var tmp = minPos.x;
            minPos.x = maxPos.x;
            maxPos.x = tmp;
          }
          if (y < 0) {
            var _tmp = minPos.y;
            minPos.y = maxPos.y;
            maxPos.y = _tmp;
          }
          if (z < 0) {
            var _tmp2 = minPos.z;
            minPos.z = maxPos.z;
            maxPos.z = _tmp2;
          }
        }
        if (typeof geometry.boundingRadius !== 'undefined') {
          geometry.boundingRadius *= Math.max(Math.max(Math.abs(x), Math.abs(y)), Math.abs(z));
        }
        return geometry;
      }
      function wireframed(geometry) {
        var indices = geometry.indices;
        if (!indices) {
          return geometry;
        }
        if (geometry.primitiveMode && geometry.primitiveMode !== PrimitiveMode.TRIANGLE_LIST) {
          return geometry;
        }
        var offsets = [[0, 1], [1, 2], [2, 0]];
        var lines = [];
        var lineIDs = {};
        for (var i = 0; i < indices.length; i += 3) {
          for (var k = 0; k < 3; ++k) {
            var i1 = indices[i + offsets[k][0]];
            var i2 = indices[i + offsets[k][1]];
            var id = i1 > i2 ? i2 << 16 | i1 : i1 << 16 | i2;
            if (lineIDs[id] === undefined) {
              lineIDs[id] = 0;
              lines.push(i1, i2);
            }
          }
        }
        geometry.indices = lines;
        geometry.primitiveMode = PrimitiveMode.LINE_LIST;
        return geometry;
      }

      var primitives = /*#__PURE__*/Object.freeze({
        __proto__: null,
        box: box,
        cone: cone,
        cylinder: cylinder,
        plane: plane,
        quad: quad,
        sphere: sphere,
        torus: torus,
        capsule: capsule,
        circle: circle,
        translate: translate,
        scale: scale,
        wireframed: wireframed,
        wireframe: wireframe,
        invWinding: invWinding,
        toWavefrontOBJ: toWavefrontOBJ,
        normals: normals,
        applyDefaultGeometryOptions: applyDefaultGeometryOptions
      });
      exports('g7', primitives);

      function setWrap(object, wrapper) {
        object.__cc_wrapper__ = wrapper;
      }
      function getWrap(object) {
        return object.__cc_wrapper__;
      }
      function maxComponent(v) {
        return Math.max(v.x, Math.max(v.y, v.z));
      }
      var VEC3_0 = new Vec3();
      var TriggerEventObject$1 = {
        type: 'onTriggerEnter',
        selfCollider: null,
        otherCollider: null,
        impl: null
      };
      var CharacterTriggerEventObject$1 = {
        type: 'onControllerTriggerEnter',
        collider: null,
        characterController: null,
        impl: null
      };
      var CollisionEventObject$1 = {
        type: 'onCollisionEnter',
        selfCollider: null,
        otherCollider: null,
        contacts: [],
        impl: null
      };
      function shrinkPositions(buffer) {
        var pos = [];
        var posHashMap = {};
        if (buffer.length >= 3) {
          pos[0] = buffer[0];
          pos[1] = buffer[1];
          pos[2] = buffer[2];
          var len = buffer.length;
          for (var i = 3; i < len; i += 3) {
            var p0 = buffer[i];
            var p1 = buffer[i + 1];
            var p2 = buffer[i + 2];
            var str = String(p0) + String(p1) + String(p2);
            var hash = murmurhash2_32_gc(str, 666);
            if (posHashMap[hash] !== str) {
              posHashMap[hash] = str;
              pos.push(p0);
              pos.push(p1);
              pos.push(p2);
            }
          }
        }
        return pos;
      }
      function absolute(v) {
        v.x = Math.abs(v.x);
        v.y = Math.abs(v.y);
        v.z = Math.abs(v.z);
        return v;
      }

      var util = /*#__PURE__*/Object.freeze({
        __proto__: null,
        setWrap: setWrap,
        getWrap: getWrap,
        maxComponent: maxComponent,
        VEC3_0: VEC3_0,
        TriggerEventObject: TriggerEventObject$1,
        CharacterTriggerEventObject: CharacterTriggerEventObject$1,
        CollisionEventObject: CollisionEventObject$1,
        shrinkPositions: shrinkPositions,
        absolute: absolute,
        cylinder: cylinder
      });

      var _dec$2q, _dec2$1P, _dec3$1h, _dec4$X, _dec5$S, _dec6$C, _dec7$t, _dec8$k, _dec9$h, _dec10$a, _class$2o, _class2$2a, _initializer$22, _initializer2$1I, _initializer3$1e, _initializer4$13, _initializer5$Q, _initializer6$H, _initializer7$x, _initializer8$t, _initializer9$p, _initializer10$n, _class3$B;
      var ProbeResolution;
      (function (ProbeResolution) {
        ProbeResolution[ProbeResolution["Low_256x256"] = 256] = "Low_256x256";
        ProbeResolution[ProbeResolution["Medium_512x512"] = 512] = "Medium_512x512";
        ProbeResolution[ProbeResolution["High_768x768"] = 768] = "High_768x768";
      })(ProbeResolution || (ProbeResolution = {}));
      var ReflectionProbe = exports('an', (_dec$2q = ccclass$M('cc.ReflectionProbe'), _dec2$1P = type$d(Vec3), _dec3$1h = type$d(Enum(ProbeType)), _dec4$X = type$d(Enum(ProbeResolution)), _dec5$S = type$d(Enum(ProbeClearFlag)), _dec6$C = type$d(Color$1), _dec7$t = type$d(Layers.BitMask), _dec8$k = type$d(Camera), _dec9$h = type$d(CCBoolean), _dec10$a = type$d(TextureCube), _dec$2q(_class$2o = (_class2$2a = (_class3$B = function (_Component) {
        _inheritsLoose(ReflectionProbe, _Component);
        function ReflectionProbe() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._lastSize = new Vec3();
          _this._resolution = _initializer$22 && _initializer$22();
          _this._clearFlag = _initializer2$1I && _initializer2$1I();
          _this._backgroundColor = _initializer3$1e && _initializer3$1e();
          _this._visibility = _initializer4$13 && _initializer4$13();
          _this._probeType = _initializer5$Q && _initializer5$Q();
          _this._cubemap = _initializer6$H && _initializer6$H();
          _this._size = _initializer7$x && _initializer7$x();
          _this._sourceCamera = _initializer8$t && _initializer8$t();
          _this._probeId = _initializer9$p && _initializer9$p();
          _this._fastBake = _initializer10$n && _initializer10$n();
          _this._probe = null;
          _this._previewSphere = null;
          _this._previewPlane = null;
          _this._sourceCameraPos = new Vec3(0, 0, 0);
          _this._position = new Vec3(0, 0, 0);
          return _this;
        }
        var _proto = ReflectionProbe.prototype;
        _proto.onLoad = function onLoad() {
          this._createProbe();
        };
        _proto.onEnable = function onEnable() {
          if (this._probe) {
            var probe = ReflectionProbeManager.probeManager.getProbeById(this._probeId);
            if (probe !== null && probe !== this._probe) {
              this._probeId = ReflectionProbeManager.probeManager.getNewReflectionProbeId();
              this._probe.updateProbeId(this._probeId);
            }
            ReflectionProbeManager.probeManager.register(this._probe);
            ReflectionProbeManager.probeManager.onUpdateProbes();
            this._probe.enable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._probe) {
            ReflectionProbeManager.probeManager.unregister(this._probe);
            this._probe.disable();
          }
        };
        _proto.start = function start() {
          if (this._sourceCamera && this.probeType === ProbeType.PLANAR) {
            this.probe.renderPlanarReflection(this.sourceCamera.camera);
            ReflectionProbeManager.probeManager.filterModelsForPlanarReflection();
          }
          ReflectionProbeManager.probeManager.updateProbeData();
          this._position = this.node.getWorldPosition().clone();
        };
        _proto.onDestroy = function onDestroy() {
          if (this.probe) {
            this.probe.destroy();
          }
        };
        _proto.update = function update(dt) {
          if (!this.probe) return;
          if (this.probeType === ProbeType.PLANAR && this.sourceCamera) {
            if (this.sourceCamera.node.hasChangedFlags & TransformBit.TRS || !this._sourceCameraPos.equals(this.sourceCamera.node.getWorldPosition())) {
              this._sourceCameraPos = this.sourceCamera.node.getWorldPosition();
              this.probe.renderPlanarReflection(this.sourceCamera.camera);
            }
          }
          if (this.node.hasChangedFlags & TransformBit.POSITION) {
            this.probe.updateBoundingBox();
            ReflectionProbeManager.probeManager.onUpdateProbes();
            ReflectionProbeManager.probeManager.updateProbeData();
          }
          {
            var worldPos = this.node.getWorldPosition();
            if (!this._position.equals(worldPos)) {
              this._position = worldPos;
              this.probe.updateBoundingBox();
              ReflectionProbeManager.probeManager.updateProbeData();
              ReflectionProbeManager.probeManager.updateProbeOfModels();
            }
          }
        };
        _proto.clearBakedCubemap = function clearBakedCubemap() {
          this.cubemap = null;
          ReflectionProbeManager.probeManager.updateBakedCubemap(this.probe);
          ReflectionProbeManager.probeManager.updatePreviewSphere(this.probe);
        };
        _proto._createProbe = function _createProbe() {
          if (this._probeId === -1 || ReflectionProbeManager.probeManager.exists(this._probeId)) {
            this._probeId = ReflectionProbeManager.probeManager.getNewReflectionProbeId();
          }
          this._probe = new ReflectionProbe$1(this._probeId);
          if (this._probe) {
            var cameraNode = new Node$1('ReflectionProbeCamera');
            cameraNode.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
            this.node.scene.addChild(cameraNode);
            this._probe.initialize(this.node, cameraNode);
            if (this.enabled) {
              ReflectionProbeManager.probeManager.register(this._probe);
            }
            this._probe.resolution = this._resolution;
            this._probe.clearFlag = this._clearFlag;
            this._probe.backgroundColor = this._backgroundColor;
            this._probe.visibility = this._visibility;
            this._probe.probeType = this._probeType;
            this._probe.size = this._size;
            this._probe.cubemap = this._cubemap;
          }
        };
        _createClass(ReflectionProbe, [{
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(value) {
            this._size.set(value);
            absolute(this._size);
            this.probe.size = this._size;
            if (this.probe) {
              this.probe.updateBoundingBox();
              ReflectionProbeManager.probeManager.onUpdateProbes();
              ReflectionProbeManager.probeManager.updateProbeData();
              ReflectionProbeManager.probeManager.updateProbeOfModels();
            }
          }
        }, {
          key: "probeType",
          get: function get() {
            return this._probeType;
          },
          set: function set(value) {
            this.probe.probeType = value;
            if (value !== this._probeType) {
              var lastSize = this._size.clone();
              var lastSizeIsNoExist = Vec3.equals(this._lastSize, Vec3.ZERO);
              this._probeType = value;
              if (this._probeType === ProbeType.CUBE) {
                if (lastSizeIsNoExist) {
                  this._size.set(ReflectionProbe.DEFAULT_CUBE_SIZE);
                }
                this.probe.switchProbeType(value, null);
                ReflectionProbeManager.probeManager.clearPlanarReflectionMap(this.probe);
              } else {
                if (lastSizeIsNoExist) {
                  this._size.set(ReflectionProbe.DEFAULT_PLANER_SIZE);
                }
                if (!this._sourceCamera) {
                  warn('the reflection camera is invalid, please set the reflection camera');
                } else {
                  this.probe.switchProbeType(value, this._sourceCamera.camera);
                }
              }
              if (!lastSizeIsNoExist) {
                this._size.set(this._lastSize);
              }
              this._lastSize.set(lastSize);
              this.size = this._size;
            }
          }
        }, {
          key: "resolution",
          get: function get() {
            return this._resolution;
          },
          set: function set(value) {
            this._resolution = value;
            this.probe.resolution = value;
          }
        }, {
          key: "clearFlag",
          get: function get() {
            return this._clearFlag;
          },
          set: function set(value) {
            this._clearFlag = value;
            this.probe.clearFlag = this._clearFlag;
          }
        }, {
          key: "backgroundColor",
          get: function get() {
            return this._backgroundColor;
          },
          set: function set(val) {
            this._backgroundColor = val;
            this.probe.backgroundColor = this._backgroundColor;
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(val) {
            this._visibility = val;
            this.probe.visibility = this._visibility;
          }
        }, {
          key: "sourceCamera",
          get: function get() {
            return this._sourceCamera;
          },
          set: function set(camera) {
            this._sourceCamera = camera;
            if (camera) {
              this.visibility = camera.visibility;
              this.clearFlag = camera.clearFlags;
              this.backgroundColor = camera.clearColor;
              if (this.probeType === ProbeType.PLANAR) {
                this.probe.switchProbeType(this.probeType, camera.camera);
              }
            }
          }
        }, {
          key: "fastBake",
          get: function get() {
            return this._fastBake;
          },
          set: function set(val) {
            this._fastBake = val;
          }
        }, {
          key: "cubemap",
          get: function get() {
            return this._cubemap;
          },
          set: function set(val) {
            this._cubemap = val;
            this.probe.cubemap = val;
            ReflectionProbeManager.probeManager.onUpdateProbes();
          }
        }, {
          key: "probe",
          get: function get() {
            return this._probe;
          }
        }, {
          key: "previewSphere",
          get: function get() {
            return this._previewSphere;
          },
          set: function set(val) {
            this._previewSphere = val;
            if (this.probe) {
              this.probe.previewSphere = val;
              if (this._previewSphere) {
                ReflectionProbeManager.probeManager.updatePreviewSphere(this.probe);
              }
            }
          }
        }, {
          key: "previewPlane",
          get: function get() {
            return this._previewPlane;
          },
          set: function set(val) {
            this._previewPlane = val;
            if (this.probe) {
              this.probe.previewPlane = val;
              if (this._previewPlane) {
                ReflectionProbeManager.probeManager.updatePreviewPlane(this.probe);
              }
            }
          }
        }]);
        return ReflectionProbe;
      }(Component), _class3$B.DEFAULT_CUBE_SIZE = new Vec3(1, 1, 1), _class3$B.DEFAULT_PLANER_SIZE = new Vec3(5, 0.5, 5), _class3$B), (_initializer$22 = applyDecoratedInitializer(_class2$2a.prototype, "_resolution", [serializable$p], function () {
        return 256;
      }), _initializer2$1I = applyDecoratedInitializer(_class2$2a.prototype, "_clearFlag", [serializable$p], function () {
        return ProbeClearFlag.SKYBOX;
      }), _initializer3$1e = applyDecoratedInitializer(_class2$2a.prototype, "_backgroundColor", [serializable$p], function () {
        return new Color$1(0, 0, 0, 255);
      }), _initializer4$13 = applyDecoratedInitializer(_class2$2a.prototype, "_visibility", [serializable$p], function () {
        return CAMERA_DEFAULT_MASK;
      }), _initializer5$Q = applyDecoratedInitializer(_class2$2a.prototype, "_probeType", [serializable$p], function () {
        return ProbeType.CUBE;
      }), _initializer6$H = applyDecoratedInitializer(_class2$2a.prototype, "_cubemap", [serializable$p], function () {
        return null;
      }), _initializer7$x = applyDecoratedInitializer(_class2$2a.prototype, "_size", [serializable$p], function () {
        return new Vec3(1, 1, 1);
      }), _initializer8$t = applyDecoratedInitializer(_class2$2a.prototype, "_sourceCamera", [serializable$p], function () {
        return null;
      }), _initializer9$p = applyDecoratedInitializer(_class2$2a.prototype, "_probeId", [serializable$p], function () {
        return -1;
      }), _initializer10$n = applyDecoratedInitializer(_class2$2a.prototype, "_fastBake", [serializable$p], function () {
        return false;
      }), _applyDecoratedDescriptor(_class2$2a.prototype, "size", [_dec2$1P], Object.getOwnPropertyDescriptor(_class2$2a.prototype, "size"), _class2$2a.prototype), _applyDecoratedDescriptor(_class2$2a.prototype, "probeType", [_dec3$1h], Object.getOwnPropertyDescriptor(_class2$2a.prototype, "probeType"), _class2$2a.prototype), _applyDecoratedDescriptor(_class2$2a.prototype, "resolution", [_dec4$X], Object.getOwnPropertyDescriptor(_class2$2a.prototype, "resolution"), _class2$2a.prototype), _applyDecoratedDescriptor(_class2$2a.prototype, "clearFlag", [_dec5$S], Object.getOwnPropertyDescriptor(_class2$2a.prototype, "clearFlag"), _class2$2a.prototype), _applyDecoratedDescriptor(_class2$2a.prototype, "backgroundColor", [_dec6$C], Object.getOwnPropertyDescriptor(_class2$2a.prototype, "backgroundColor"), _class2$2a.prototype), _applyDecoratedDescriptor(_class2$2a.prototype, "visibility", [_dec7$t], Object.getOwnPropertyDescriptor(_class2$2a.prototype, "visibility"), _class2$2a.prototype), _applyDecoratedDescriptor(_class2$2a.prototype, "sourceCamera", [_dec8$k], Object.getOwnPropertyDescriptor(_class2$2a.prototype, "sourceCamera"), _class2$2a.prototype), _applyDecoratedDescriptor(_class2$2a.prototype, "fastBake", [_dec9$h], Object.getOwnPropertyDescriptor(_class2$2a.prototype, "fastBake"), _class2$2a.prototype), _applyDecoratedDescriptor(_class2$2a.prototype, "cubemap", [_dec10$a], Object.getOwnPropertyDescriptor(_class2$2a.prototype, "cubemap"), _class2$2a.prototype)), _class2$2a)) || _class$2o));

      legacyCC.utils = utils;

      var CLASS_NAME_PREFIX_ANIM = 'cc.animation.';
      var createEvalSymbol = Symbol('CreateEval');

      var _dec$2p, _class$2n, _class2$29, _initializer$21, _initializer2$1H, _initializer3$1d, _initializer4$12;
      (_dec$2p = ccclass$M(CLASS_NAME_PREFIX_ANIM + "EmbeddedPlayer"), _dec$2p(_class$2n = (_class2$29 = function (_EditorExtendable) {
        _inheritsLoose(EmbeddedPlayer, _EditorExtendable);
        function EmbeddedPlayer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EditorExtendable.call.apply(_EditorExtendable, [this].concat(args)) || this;
          _this.begin = _initializer$21 && _initializer$21();
          _this.end = _initializer2$1H && _initializer2$1H();
          _this.reconciledSpeed = _initializer3$1d && _initializer3$1d();
          _this.playable = _initializer4$12 && _initializer4$12();
          return _this;
        }
        return EmbeddedPlayer;
      }(EditorExtendable), (_initializer$21 = applyDecoratedInitializer(_class2$29.prototype, "begin", [serializable$p], function () {
        return 0.0;
      }), _initializer2$1H = applyDecoratedInitializer(_class2$29.prototype, "end", [serializable$p], function () {
        return 0.0;
      }), _initializer3$1d = applyDecoratedInitializer(_class2$29.prototype, "reconciledSpeed", [serializable$p], function () {
        return false;
      }), _initializer4$12 = applyDecoratedInitializer(_class2$29.prototype, "playable", [serializable$p], function () {
        return null;
      })), _class2$29)) || _class$2n);
      var EmbeddedPlayable = function EmbeddedPlayable() {};
      var EmbeddedPlayableState = function () {
        function EmbeddedPlayableState(randomAccess) {
          this._randomAccess = randomAccess;
        }
        var _proto = EmbeddedPlayableState.prototype;
        _proto.setTime = function setTime(_time) {};
        _createClass(EmbeddedPlayableState, [{
          key: "randomAccess",
          get: function get() {
            return this._randomAccess;
          }
        }]);
        return EmbeddedPlayableState;
      }();

      var Playable = function () {
        function Playable() {
          this._isPlaying = false;
          this._isPaused = false;
          this._stepOnce = false;
        }
        var _proto = Playable.prototype;
        _proto.play = function play() {
          if (this._isPlaying) {
            if (this._isPaused) {
              this._isPaused = false;
              this.onResume();
            } else {
              this.onError(getError(3912));
            }
          } else {
            this._isPlaying = true;
            this.onPlay();
          }
        };
        _proto.stop = function stop() {
          if (this._isPlaying) {
            this._isPlaying = false;
            this.onStop();
            this._isPaused = false;
          }
        };
        _proto.pause = function pause() {
          if (this._isPlaying && !this._isPaused) {
            this._isPaused = true;
            this.onPause();
          }
        };
        _proto.resume = function resume() {
          if (this._isPlaying && this._isPaused) {
            this._isPaused = false;
            this.onResume();
          }
        };
        _proto.step = function step() {
          this.pause();
          this._stepOnce = true;
          if (!this._isPlaying) {
            this.play();
          }
        };
        _proto.update = function update(deltaTime) {};
        _proto.onPlay = function onPlay() {};
        _proto.onPause = function onPause() {};
        _proto.onResume = function onResume() {};
        _proto.onStop = function onStop() {};
        _proto.onError = function onError(message) {};
        _createClass(Playable, [{
          key: "isPlaying",
          get: function get() {
            return this._isPlaying;
          }
        }, {
          key: "isPaused",
          get: function get() {
            return this._isPaused;
          }
        }, {
          key: "isMotionless",
          get: function get() {
            return !this.isPlaying || this.isPaused;
          }
        }]);
        return Playable;
      }();

      var WrapMode;
      (function (WrapMode) {
        WrapMode[WrapMode["Default"] = WrapModeMask.Default] = "Default";
        WrapMode[WrapMode["Normal"] = WrapModeMask.Normal] = "Normal";
        WrapMode[WrapMode["Reverse"] = WrapModeMask.Reverse] = "Reverse";
        WrapMode[WrapMode["Loop"] = WrapModeMask.Loop] = "Loop";
        WrapMode[WrapMode["LoopReverse"] = WrapModeMask.Loop | WrapModeMask.Reverse] = "LoopReverse";
        WrapMode[WrapMode["PingPong"] = WrapModeMask.PingPong] = "PingPong";
        WrapMode[WrapMode["PingPongReverse"] = WrapModeMask.PingPong | WrapModeMask.Reverse] = "PingPongReverse";
      })(WrapMode || (WrapMode = {}));
      ccenum(WrapMode);
      var WrappedInfo = function () {
        function WrappedInfo(info) {
          this.ratio = 0;
          this.time = 0;
          this.direction = 1;
          this.stopped = true;
          this.iterations = 0;
          this.frameIndex = undefined;
          if (info) {
            this.set(info);
          }
        }
        var _proto = WrappedInfo.prototype;
        _proto.set = function set(info) {
          this.ratio = info.ratio;
          this.time = info.time;
          this.direction = info.direction;
          this.stopped = info.stopped;
          this.iterations = info.iterations;
          this.frameIndex = info.frameIndex;
        };
        return WrappedInfo;
      }();
      function isLerpable(object) {
        return typeof object.lerp === 'function';
      }

      var PoseOutput = function () {
        function PoseOutput(pose) {
          this.weight = 0.0;
          this._pose = void 0;
          this._blendStateWriters = [];
          this._pose = pose;
        }
        var _proto = PoseOutput.prototype;
        _proto.destroy = function destroy() {
          for (var iBlendStateWriter = 0; iBlendStateWriter < this._blendStateWriters.length; ++iBlendStateWriter) {
            this._pose.destroyWriter(this._blendStateWriters[iBlendStateWriter]);
          }
          this._blendStateWriters.length = 0;
        };
        _proto.createPoseWriter = function createPoseWriter(node, property, constants) {
          var writer = this._pose.createWriter(node, property, this, constants);
          this._blendStateWriters.push(writer);
          return writer;
        };
        return PoseOutput;
      }();

      function getGlobalAnimationManager() {
        var animationManager = legacyCC.director.getAnimationManager();
        return animationManager;
      }

      var EventType$8;
      (function (EventType) {
        EventType["PLAY"] = "play";
        EventType["STOP"] = "stop";
        EventType["PAUSE"] = "pause";
        EventType["RESUME"] = "resume";
        EventType["LASTFRAME"] = "lastframe";
        EventType["FINISHED"] = "finished";
      })(EventType$8 || (EventType$8 = {}));
      ccenum(EventType$8);
      var AnimationState$1 = exports('as', function (_Playable) {
        _inheritsLoose(AnimationState, _Playable);
        function AnimationState(clip, name) {
          var _this;
          if (name === void 0) {
            name = '';
          }
          _this = _Playable.call(this) || this;
          _this.duration = 1.0;
          _this.time = 0.0;
          _this.frameRate = 0;
          _this._targetNode = null;
          _this._curveLoaded = false;
          _this._clip = void 0;
          _this._speed = 1.0;
          _this._useSimpleProcess = false;
          _this._target = null;
          _this._wrapMode = WrapMode.Normal;
          _this._repeatCount = 1;
          _this._delay = 0.0;
          _this._delayTime = 0.0;
          _this._currentFramePlayed = false;
          _this._name = void 0;
          _this._lastIterations = NaN;
          _this._lastWrapInfo = null;
          _this._wrappedInfo = new WrappedInfo();
          _this._allowLastFrame = false;
          _this._blendStateWriterHost = {
            weight: 0.0
          };
          _this._playbackDuration = 0.0;
          _this._invDuration = 1.0;
          _this._poseOutput = null;
          _this._weight = 1.0;
          _this._clipEval = void 0;
          _this._clipEventEval = void 0;
          _this._clipEmbeddedPlayerEval = void 0;
          _this._doNotCreateEval = false;
          _this._clip = clip;
          _this._name = name || clip && clip.name;
          _this._playbackRange = {
            min: 0.0,
            max: clip.duration
          };
          _this._playbackDuration = clip.duration;
          if (!clip.duration) {
            debug("Clip " + clip.name + " has zero duration.");
          }
          return _this;
        }
        var _proto = AnimationState.prototype;
        _proto.initialize = function initialize(root, blendStateBuffer, mask) {
          if (this._curveLoaded) {
            return;
          }
          this._curveLoaded = true;
          if (this._poseOutput) {
            this._poseOutput.destroy();
            this._poseOutput = null;
          }
          if (this._clipEval) {
            this._clipEval = undefined;
          }
          if (this._clipEventEval) {
            this._clipEventEval = undefined;
          }
          if (this._clipEmbeddedPlayerEval) {
            this._clipEmbeddedPlayerEval.destroy();
            this._clipEmbeddedPlayerEval = undefined;
          }
          this._targetNode = root;
          var clip = this._clip;
          this.duration = clip.duration;
          this._invDuration = 1.0 / this.duration;
          this._speed = clip.speed;
          this.wrapMode = clip.wrapMode;
          this.frameRate = clip.sample;
          this._playbackRange.min = 0.0;
          this._playbackRange.max = clip.duration;
          this._playbackDuration = clip.duration;
          if ((this.wrapMode & WrapModeMask.Loop) === WrapModeMask.Loop) {
            this.repeatCount = Infinity;
          } else {
            this.repeatCount = 1;
          }
          if (!this._doNotCreateEval) {
            var _ref, _getGlobalAnimationMa, _this$_poseOutput;
            var pose = (_ref = blendStateBuffer !== null && blendStateBuffer !== void 0 ? blendStateBuffer : (_getGlobalAnimationMa = getGlobalAnimationManager()) === null || _getGlobalAnimationMa === void 0 ? void 0 : _getGlobalAnimationMa.blendState) !== null && _ref !== void 0 ? _ref : null;
            if (pose) {
              this._poseOutput = new PoseOutput(pose);
            }
            this._clipEval = clip.createEvaluator({
              target: root,
              pose: (_this$_poseOutput = this._poseOutput) !== null && _this$_poseOutput !== void 0 ? _this$_poseOutput : undefined,
              mask: mask
            });
          }
          {
            if (clip.containsAnyEvent()) {
              this._clipEventEval = clip.createEventEvaluator(this._targetNode);
            }
          }
          if (clip.containsAnyEmbeddedPlayer()) {
            this._clipEmbeddedPlayerEval = clip.createEmbeddedPlayerEvaluator(this._targetNode);
            this._clipEmbeddedPlayerEval.notifyHostSpeedChanged(this._speed);
          }
        };
        _proto.destroy = function destroy() {
          if (!this.isMotionless) {
            getGlobalAnimationManager().removeAnimation(this);
          }
          if (this._poseOutput) {
            this._poseOutput.destroy();
            this._poseOutput = null;
          }
          this._clipEval = undefined;
        };
        _proto.emit = function emit() {
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          getGlobalAnimationManager().pushDelayEvent(this._emit, this, args);
        };
        _proto.on = function on(type, callback, target) {
          if (this._target && this._target.isValid) {
            return this._target.on(type, callback, target);
          } else {
            return null;
          }
        };
        _proto.once = function once(type, callback, target) {
          if (this._target && this._target.isValid) {
            return this._target.once(type, callback, target);
          } else {
            return null;
          }
        };
        _proto.off = function off(type, callback, target) {
          if (this._target && this._target.isValid) {
            this._target.off(type, callback, target);
          }
        };
        _proto.allowLastFrameEvent = function allowLastFrameEvent(allowed) {
          this._allowLastFrame = allowed;
        };
        _proto._setEventTarget = function _setEventTarget(target) {
          this._target = target;
        };
        _proto.setTime = function setTime(time) {
          this._currentFramePlayed = false;
          this.time = time || 0.0;
          {
            var _this$_clipEventEval;
            var info = this.getWrappedInfo(time, this._wrappedInfo);
            (_this$_clipEventEval = this._clipEventEval) === null || _this$_clipEventEval === void 0 ? void 0 : _this$_clipEventEval.ignore(info.ratio, info.direction);
          }
        };
        _proto.update = function update(delta) {
          if (this._delayTime > 0.0) {
            this._delayTime -= delta;
            if (this._delayTime > 0.0) {
              return;
            }
          }
          if (this._currentFramePlayed) {
            this.time += delta * this._speed;
          } else {
            this._currentFramePlayed = true;
          }
          this._process();
        };
        _proto.sample = function sample() {
          var info = this.getWrappedInfo(this.time, this._wrappedInfo);
          this._sampleCurves(info.time);
          {
            this._sampleEvents(info);
          }
          this._sampleEmbeddedPlayers(info);
          return info;
        };
        _proto.onPlay = function onPlay() {
          var _this$_clipEmbeddedPl;
          this.setTime(this._getPlaybackStart());
          this._delayTime = this._delay;
          this._onReplayOrResume();
          this.emit(EventType$8.PLAY, this);
          (_this$_clipEmbeddedPl = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl === void 0 ? void 0 : _this$_clipEmbeddedPl.notifyHostPlay(this.current);
        };
        _proto.onStop = function onStop() {
          var _this$_clipEmbeddedPl2;
          if (!this.isPaused) {
            this._onPauseOrStop();
          }
          this.emit(EventType$8.STOP, this);
          (_this$_clipEmbeddedPl2 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl2 === void 0 ? void 0 : _this$_clipEmbeddedPl2.notifyHostStop();
        };
        _proto.onResume = function onResume() {
          var _this$_clipEmbeddedPl3;
          this._onReplayOrResume();
          this.emit(EventType$8.RESUME, this);
          (_this$_clipEmbeddedPl3 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl3 === void 0 ? void 0 : _this$_clipEmbeddedPl3.notifyHostPlay(this.current);
        };
        _proto.onPause = function onPause() {
          var _this$_clipEmbeddedPl4;
          this._onPauseOrStop();
          this.emit(EventType$8.PAUSE, this);
          (_this$_clipEmbeddedPl4 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl4 === void 0 ? void 0 : _this$_clipEmbeddedPl4.notifyHostPause(this.current);
        };
        _proto._sampleCurves = function _sampleCurves(time) {
          var poseOutput = this._poseOutput,
            clipEval = this._clipEval;
          if (poseOutput) {
            poseOutput.weight = this.weight;
          }
          if (clipEval) {
            clipEval.evaluate(time);
          }
        };
        _proto._process = function _process() {
          if (this._useSimpleProcess) {
            this.simpleProcess();
          } else {
            this.process();
          }
        };
        _proto.process = function process() {
          var info = this.sample();
          if (this._allowLastFrame) {
            var lastInfo;
            if (!this._lastWrapInfo) {
              lastInfo = this._lastWrapInfo = new WrappedInfo(info);
            } else {
              lastInfo = this._lastWrapInfo;
            }
            if (this.repeatCount > 1 && (info.iterations | 0) > (lastInfo.iterations | 0)) {
              this.emit(EventType$8.LASTFRAME, this);
            }
            lastInfo.set(info);
          }
          if (info.stopped) {
            this.stop();
            this.emit(EventType$8.FINISHED, this);
          }
        };
        _proto.simpleProcess = function simpleProcess() {
          var playbackStart = this._playbackRange.min;
          var playbackDuration = this._playbackDuration;
          var time = 0.0;
          var ratio = 0.0;
          if (playbackDuration !== 0.0) {
            time = this.time % playbackDuration;
            if (time < 0.0) {
              time += playbackDuration;
            }
            var realTime = playbackStart + time;
            ratio = realTime * this._invDuration;
          }
          this._sampleCurves(playbackStart + time);
          if (this._clipEventEval || this._clipEmbeddedPlayerEval) {
            var wrapInfo = this.getWrappedInfo(this.time, this._wrappedInfo);
            {
              this._sampleEvents(wrapInfo);
            }
            this._sampleEmbeddedPlayers(wrapInfo);
          }
          if (this._allowLastFrame) {
            if (Number.isNaN(this._lastIterations)) {
              this._lastIterations = ratio;
            }
            if (this.time > 0 && this._lastIterations > ratio || this.time < 0 && this._lastIterations < ratio) {
              this.emit(EventType$8.LASTFRAME, this);
            }
            this._lastIterations = ratio;
          }
        };
        _proto._needReverse = function _needReverse(currentIterations) {
          var wrapMode = this.wrapMode;
          var needReverse = false;
          if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
            var isEnd = currentIterations - (currentIterations | 0) === 0;
            if (isEnd && currentIterations > 0) {
              currentIterations -= 1;
            }
            var isOddIteration = currentIterations & 1;
            if (isOddIteration) {
              needReverse = !needReverse;
            }
          }
          if ((wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) {
            needReverse = !needReverse;
          }
          return needReverse;
        };
        _proto.getWrappedInfo = function getWrappedInfo(time, info) {
          info = info || new WrappedInfo();
          var playbackStart = this._playbackRange.min,
            playbackDuration = this._playbackDuration;
          var repeatCount = this.repeatCount;
          if (playbackDuration === 0.0) {
            info.time = 0.0;
            info.ratio = 0.0;
            info.direction = 1.0;
            info.stopped = !!Number.isFinite(repeatCount);
            info.iterations = 0.0;
            return info;
          }
          var stopped = false;
          time -= playbackStart;
          var currentIterations = time > 0 ? time / playbackDuration : -(time / playbackDuration);
          if (currentIterations >= repeatCount) {
            currentIterations = repeatCount;
            stopped = true;
            var tempRatio = repeatCount - (repeatCount | 0);
            if (tempRatio === 0) {
              tempRatio = 1;
            }
            time = tempRatio * playbackDuration * (time > 0 ? 1 : -1);
          }
          if (time > playbackDuration) {
            var tempTime = time % playbackDuration;
            time = tempTime === 0 ? playbackDuration : tempTime;
          } else if (time < 0) {
            time %= playbackDuration;
            if (time !== 0) {
              time += playbackDuration;
            }
          }
          var needReverse = false;
          var shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap;
          if (shouldWrap) {
            needReverse = this._needReverse(currentIterations);
          }
          var direction = needReverse ? -1 : 1;
          if (this.speed < 0) {
            direction *= -1;
          }
          if (shouldWrap && needReverse) {
            time = playbackDuration - time;
          }
          info.time = playbackStart + time;
          info.ratio = info.time / this.duration;
          info.direction = direction;
          info.stopped = stopped;
          info.iterations = currentIterations;
          return info;
        };
        _proto._getPlaybackStart = function _getPlaybackStart() {
          return this._playbackRange.min;
        };
        _proto._sampleEvents = function _sampleEvents(wrapInfo) {
          var _this$_clipEventEval2;
          (_this$_clipEventEval2 = this._clipEventEval) === null || _this$_clipEventEval2 === void 0 ? void 0 : _this$_clipEventEval2.sample(wrapInfo.ratio, wrapInfo.direction, wrapInfo.iterations);
        };
        _proto._sampleEmbeddedPlayers = function _sampleEmbeddedPlayers(wrapInfo) {
          var _this$_clipEmbeddedPl5;
          (_this$_clipEmbeddedPl5 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl5 === void 0 ? void 0 : _this$_clipEmbeddedPl5.evaluate(wrapInfo.time, Math.trunc(wrapInfo.iterations));
        };
        _proto._emit = function _emit(type, state) {
          if (this._target && this._target.isValid) {
            this._target.emit(type, type, state);
          }
        };
        _proto._onReplayOrResume = function _onReplayOrResume() {
          getGlobalAnimationManager().addAnimation(this);
        };
        _proto._onPauseOrStop = function _onPauseOrStop() {
          getGlobalAnimationManager().removeAnimation(this);
        };
        _createClass(AnimationState, [{
          key: "clip",
          get: function get() {
            return this._clip;
          }
        }, {
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "length",
          get: function get() {
            return this.duration;
          }
        }, {
          key: "wrapMode",
          get: function get() {
            return this._wrapMode;
          },
          set: function set(value) {
            var _this$_clipEventEval3;
            this._wrapMode = value;
            this.time = 0;
            if (value & WrapModeMask.Loop) {
              this.repeatCount = Infinity;
            } else {
              this.repeatCount = 1;
            }
            (_this$_clipEventEval3 = this._clipEventEval) === null || _this$_clipEventEval3 === void 0 ? void 0 : _this$_clipEventEval3.setWrapMode(value);
          }
        }, {
          key: "repeatCount",
          get: function get() {
            return this._repeatCount;
          },
          set: function set(value) {
            this._repeatCount = value;
            var shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap;
            var reverse = (this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse;
            if (value === Infinity && !shouldWrap && !reverse) {
              this._useSimpleProcess = true;
            } else {
              this._useSimpleProcess = false;
            }
          }
        }, {
          key: "delay",
          get: function get() {
            return this._delay;
          },
          set: function set(value) {
            this._delayTime = this._delay = value;
          }
        }, {
          key: "playbackRange",
          get: function get() {
            return this._playbackRange;
          },
          set: function set(value) {
            assertIsTrue(value.max >= value.min);
            this._playbackRange.min = Math.max(value.min, 0);
            this._playbackRange.max = Math.min(value.max, this.duration);
            this._playbackDuration = this._playbackRange.max - this._playbackRange.min;
            this.setTime(0.0);
          }
        }, {
          key: "speed",
          get: function get() {
            return this._speed;
          },
          set: function set(value) {
            var _this$_clipEmbeddedPl6;
            this._speed = value;
            (_this$_clipEmbeddedPl6 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl6 === void 0 ? void 0 : _this$_clipEmbeddedPl6.notifyHostSpeedChanged(value);
          }
        }, {
          key: "current",
          get: function get() {
            return this.getWrappedInfo(this.time).time;
          }
        }, {
          key: "ratio",
          get: function get() {
            return this.duration === 0.0 ? 0.0 : this.current / this.duration;
          }
        }, {
          key: "weight",
          get: function get() {
            return this._weight;
          },
          set: function set(value) {
            this._weight = value;
            if (this._poseOutput) {
              this._poseOutput.weight = value;
            }
          }
        }, {
          key: "curveLoaded",
          get: function get() {
            return this._curveLoaded;
          }
        }]);
        return AnimationState;
      }(Playable));
      legacyCC.AnimationState = AnimationState$1;

      var _dec$2o, _class$2m, _class2$28, _initializer$20, _initializer2$1G;
      (_dec$2o = ccclass$M(CLASS_NAME_PREFIX_ANIM + "EmbeddedAnimationClipPlayable"), _dec$2o(_class$2m = (_class2$28 = function (_EmbeddedPlayable) {
        _inheritsLoose(EmbeddedAnimationClipPlayable, _EmbeddedPlayable);
        function EmbeddedAnimationClipPlayable() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EmbeddedPlayable.call.apply(_EmbeddedPlayable, [this].concat(args)) || this;
          _this.path = _initializer$20 && _initializer$20();
          _this.clip = _initializer2$1G && _initializer2$1G();
          return _this;
        }
        var _proto = EmbeddedAnimationClipPlayable.prototype;
        _proto.instantiate = function instantiate(root) {
          var clip = this.clip,
            path = this.path;
          if (!clip) {
            return null;
          }
          var clipRoot = root.getChildByPath(path);
          if (!clipRoot) {
            errorID(3938, path, root.getPathInHierarchy(), clip.name);
            return null;
          }
          var state = new AnimationState$1(clip);
          state.initialize(clipRoot);
          return new EmbeddedAnimationClipPlayableState(state);
        };
        return EmbeddedAnimationClipPlayable;
      }(EmbeddedPlayable), (_initializer$20 = applyDecoratedInitializer(_class2$28.prototype, "path", [serializable$p], function () {
        return '';
      }), _initializer2$1G = applyDecoratedInitializer(_class2$28.prototype, "clip", [serializable$p], function () {
        return null;
      })), _class2$28)) || _class$2m);
      var EmbeddedAnimationClipPlayableState = function (_EmbeddedPlayableStat) {
        _inheritsLoose(EmbeddedAnimationClipPlayableState, _EmbeddedPlayableStat);
        function EmbeddedAnimationClipPlayableState(animationState) {
          var _this2;
          _this2 = _EmbeddedPlayableStat.call(this, true) || this;
          _this2._animationState = void 0;
          _this2._animationState = animationState;
          return _this2;
        }
        var _proto2 = EmbeddedAnimationClipPlayableState.prototype;
        _proto2.destroy = function destroy() {
          this._animationState.destroy();
        };
        _proto2.play = function play() {
          this._animationState.play();
        };
        _proto2.pause = function pause() {
          this._animationState.pause();
        };
        _proto2.stop = function stop() {
          this._animationState.stop();
        };
        _proto2.setSpeed = function setSpeed(speed) {
          this._animationState.speed = speed;
        };
        _proto2.setTime = function setTime(time) {
          this._animationState.time = time;
        };
        return EmbeddedAnimationClipPlayableState;
      }(EmbeddedPlayableState);

      var _dec$2n, _class$2l, _class2$27, _initializer$1$;
      (_dec$2n = ccclass$M(CLASS_NAME_PREFIX_ANIM + "EmbeddedParticleSystemPlayable"), _dec$2n(_class$2l = (_class2$27 = function (_EmbeddedPlayable) {
        _inheritsLoose(EmbeddedParticleSystemPlayable, _EmbeddedPlayable);
        function EmbeddedParticleSystemPlayable() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EmbeddedPlayable.call.apply(_EmbeddedPlayable, [this].concat(args)) || this;
          _this.path = _initializer$1$ && _initializer$1$();
          return _this;
        }
        var _proto = EmbeddedParticleSystemPlayable.prototype;
        _proto.instantiate = function instantiate(root) {
          var node = root.getChildByPath(this.path);
          if (!node) {
            warn("Hierarchy path " + this.path + " does not exists.");
            return null;
          }
          var ParticleSystemConstructor = getClassByName("cc.ParticleSystem");
          if (!ParticleSystemConstructor) {
            warn("Particle system is required for embedded particle system player.");
            return null;
          }
          var particleSystem = node.getComponent(ParticleSystemConstructor);
          if (!particleSystem) {
            warn(this.path + " does not includes a particle system component.");
            return null;
          }
          return new EmbeddedParticleSystemPlayableState(particleSystem);
        };
        return EmbeddedParticleSystemPlayable;
      }(EmbeddedPlayable), (_initializer$1$ = applyDecoratedInitializer(_class2$27.prototype, "path", [serializable$p], function () {
        return '';
      })), _class2$27)) || _class$2l);
      var EmbeddedParticleSystemPlayableState = function (_EmbeddedPlayableStat) {
        _inheritsLoose(EmbeddedParticleSystemPlayableState, _EmbeddedPlayableStat);
        function EmbeddedParticleSystemPlayableState(particleSystem) {
          var _this2;
          _this2 = _EmbeddedPlayableStat.call(this, false) || this;
          _this2._particleSystem = void 0;
          _this2._particleSystem = particleSystem;
          return _this2;
        }
        var _proto2 = EmbeddedParticleSystemPlayableState.prototype;
        _proto2.destroy = function destroy() {};
        _proto2.play = function play() {
          this._particleSystem.play();
        };
        _proto2.pause = function pause() {
          this._particleSystem.stopEmitting();
        };
        _proto2.stop = function stop() {
          this._particleSystem.stopEmitting();
        };
        _proto2.setSpeed = function setSpeed(speed) {
          this._particleSystem.simulationSpeed = speed;
        };
        return EmbeddedParticleSystemPlayableState;
      }(EmbeddedPlayableState);

      var _dec$2m, _class$2k, _class2$26, _initializer$1_, _dec2$1O, _class4$o, _class5$p, _initializer2$1F;
      function isPropertyPath(path) {
        return typeof path === 'string' || typeof path === 'number';
      }
      function isCustomPath(path, constructor) {
        return path instanceof constructor;
      }
      var HierarchyPath = (_dec$2m = ccclass$M('cc.animation.HierarchyPath'), _dec$2m(_class$2k = (_class2$26 = function () {
        function HierarchyPath(path) {
          this.path = _initializer$1_ && _initializer$1_();
          this.path = path || '';
        }
        var _proto = HierarchyPath.prototype;
        _proto.get = function get(target) {
          if (!(target instanceof Node$1)) {
            warnID(3925);
            return null;
          }
          var result = target.getChildByPath(this.path);
          if (!result) {
            warnID(3926, target.name, this.path);
            return null;
          }
          return result;
        };
        return HierarchyPath;
      }(), (_initializer$1_ = applyDecoratedInitializer(_class2$26.prototype, "path", [serializable$p], function () {
        return '';
      })), _class2$26)) || _class$2k);
      var ComponentPath = (_dec2$1O = ccclass$M('cc.animation.ComponentPath'), _dec2$1O(_class4$o = (_class5$p = function () {
        function ComponentPath(component) {
          this.component = _initializer2$1F && _initializer2$1F();
          this.component = component || '';
        }
        var _proto2 = ComponentPath.prototype;
        _proto2.get = function get(target) {
          if (!(target instanceof Node$1)) {
            warnID(3927);
            return null;
          }
          var result = target.getComponent(this.component);
          if (!result) {
            warnID(3928, target.name, this.component);
            return null;
          }
          return result;
        };
        return ComponentPath;
      }(), (_initializer2$1F = applyDecoratedInitializer(_class5$p.prototype, "component", [serializable$p], function () {
        return '';
      })), _class5$p)) || _class4$o);

      var _dec$2l, _class$2j, _class2$25, _initializer$1Z, _dec2$1N, _class4$n, _class5$o, _initializer2$1E, _initializer3$1c, _class6$7, _dec3$1g, _class7$7, _class8$8, _initializer4$11, _dec4$W, _class10$3, _class11$4, _initializer5$P, _dec5$R, _class13$3, _class14$2, _initializer6$G;
      var normalizedFollowTag = Symbol('NormalizedFollow');
      var parseTrsPathTag = Symbol('ConvertAsTrsPath');
      var trackBindingTag = Symbol('TrackBinding');
      var TrackPath = (_dec$2l = ccclass$M(CLASS_NAME_PREFIX_ANIM + "TrackPath"), _dec$2l(_class$2j = (_class2$25 = function () {
        function TrackPath() {
          this._paths = _initializer$1Z && _initializer$1Z();
        }
        var _proto = TrackPath.prototype;
        _proto.toProperty = function toProperty(name) {
          this._paths.push(name);
          return this;
        };
        _proto.toElement = function toElement(index) {
          this._paths.push(index);
          return this;
        };
        _proto.toHierarchy = function toHierarchy(nodePath) {
          this._paths.push(new HierarchyPath(nodePath));
          return this;
        };
        _proto.toComponent = function toComponent(constructor) {
          var path = new ComponentPath(typeof constructor === 'string' ? constructor : getClassName(constructor));
          this._paths.push(path);
          return this;
        };
        _proto.toCustomized = function toCustomized(resolver) {
          this._paths.push(resolver);
          return this;
        };
        _proto.append = function append() {
          var _this$_paths;
          for (var _len = arguments.length, trackPaths = new Array(_len), _key = 0; _key < _len; _key++) {
            trackPaths[_key] = arguments[_key];
          }
          var paths = (_this$_paths = this._paths).concat.apply(_this$_paths, trackPaths.map(function (trackPath) {
            return trackPath._paths;
          }));
          this._paths = paths;
          return this;
        };
        _proto.isPropertyAt = function isPropertyAt(index) {
          return typeof this._paths[index] === 'string';
        };
        _proto.parsePropertyAt = function parsePropertyAt(index) {
          return this._paths[index];
        };
        _proto.isElementAt = function isElementAt(index) {
          return typeof this._paths[index] === 'number';
        };
        _proto.parseElementAt = function parseElementAt(index) {
          return this._paths[index];
        };
        _proto.isHierarchyAt = function isHierarchyAt(index) {
          return this._paths[index] instanceof HierarchyPath;
        };
        _proto.parseHierarchyAt = function parseHierarchyAt(index) {
          assertIsTrue(this.isHierarchyAt(index));
          return this._paths[index].path;
        };
        _proto.isComponentAt = function isComponentAt(index) {
          return this._paths[index] instanceof ComponentPath;
        };
        _proto.parseComponentAt = function parseComponentAt(index) {
          assertIsTrue(this.isComponentAt(index));
          return this._paths[index].component;
        };
        _proto.slice = function slice(beginIndex, endIndex) {
          var trackPath = new TrackPath();
          trackPath._paths = this._paths.slice(beginIndex, endIndex);
          return trackPath;
        };
        _proto.trace = function trace(object, beginIndex, endIndex) {
          var _beginIndex, _endIndex;
          (_beginIndex = beginIndex) !== null && _beginIndex !== void 0 ? _beginIndex : beginIndex = 0;
          (_endIndex = endIndex) !== null && _endIndex !== void 0 ? _endIndex : endIndex = this._paths.length;
          return this[normalizedFollowTag](object, beginIndex, endIndex);
        };
        _proto[parseTrsPathTag] = function () {
          var paths = this._paths;
          var nPaths = paths.length;
          var iPath = 0;
          var nodePath = '';
          for (; iPath < nPaths; ++iPath) {
            var path = paths[iPath];
            if (!(path instanceof HierarchyPath)) {
              break;
            } else if (!path.path) {
              continue;
            } else if (nodePath) {
              nodePath += "/" + path.path;
            } else {
              nodePath = path.path;
            }
          }
          if (iPath === nPaths) {
            return null;
          }
          var prs;
          if (iPath !== nPaths - 1) {
            return null;
          }
          switch (paths[iPath]) {
            case 'position':
            case 'scale':
            case 'rotation':
            case 'eulerAngles':
              prs = paths[iPath];
              break;
            default:
              return null;
          }
          return {
            node: nodePath,
            property: prs
          };
        };
        _proto[normalizedFollowTag] = function (root, beginIndex, endIndex) {
          var paths = this._paths;
          var result = root;
          for (var iPath = beginIndex; iPath < endIndex; ++iPath) {
            var path = paths[iPath];
            if (isPropertyPath(path)) {
              if (!(path in result)) {
                warnID(3929, path);
                return null;
              } else {
                result = result[path];
              }
            } else {
              result = path.get(result);
            }
            if (result === null) {
              break;
            }
          }
          return result;
        };
        _createClass(TrackPath, [{
          key: "length",
          get: function get() {
            return this._paths.length;
          }
        }]);
        return TrackPath;
      }(), (_initializer$1Z = applyDecoratedInitializer(_class2$25.prototype, "_paths", [serializable$p], function () {
        return [];
      })), _class2$25)) || _class$2j);
      var TrackBinding = (_dec2$1N = ccclass$M(CLASS_NAME_PREFIX_ANIM + "TrackBinding"), _dec2$1N(_class4$n = uniquelyReferenced(_class4$n = (_class5$o = (_class6$7 = function () {
        function TrackBinding() {
          this.path = _initializer2$1E && _initializer2$1E();
          this.proxy = _initializer3$1c && _initializer3$1c();
        }
        var _proto2 = TrackBinding.prototype;
        _proto2.parseTrsPath = function parseTrsPath() {
          if (this.proxy) {
            return null;
          } else {
            return this.path[parseTrsPathTag]();
          }
        };
        _proto2.createRuntimeBinding = function createRuntimeBinding(target, poseOutput, isConstant) {
          var path = this.path,
            proxy = this.proxy;
          var nPaths = path.length;
          var iLastPath = nPaths - 1;
          if (nPaths !== 0 && (path.isPropertyAt(iLastPath) || path.isElementAt(iLastPath)) && !proxy) {
            var lastPropertyKey = path.isPropertyAt(iLastPath) ? path.parsePropertyAt(iLastPath) : path.parseElementAt(iLastPath);
            var resultTarget = path[normalizedFollowTag](target, 0, nPaths - 1);
            if (resultTarget === null) {
              return null;
            }
            if (poseOutput && resultTarget instanceof Node$1 && isTrsPropertyName(lastPropertyKey)) {
              var blendStateWriter = poseOutput.createPoseWriter(resultTarget, lastPropertyKey, isConstant);
              return blendStateWriter;
            }
            var _setValue;
            var _getValue;
            {
              var animationFunction = TrackBinding._animationFunctions.get(resultTarget.constructor);
              if (!animationFunction) {
                animationFunction = new Map();
                TrackBinding._animationFunctions.set(resultTarget.constructor, animationFunction);
              }
              var accessor = animationFunction.get(lastPropertyKey);
              if (!accessor) {
                accessor = {
                  setValue: Function('value', "this.target." + lastPropertyKey + " = value;"),
                  getValue: Function("return this.target." + lastPropertyKey + ";")
                };
                animationFunction.set(lastPropertyKey, accessor);
              }
              _setValue = accessor.setValue;
              _getValue = accessor.getValue;
            }
            return {
              target: resultTarget,
              setValue: _setValue,
              getValue: _getValue
            };
          } else if (!proxy) {
            errorID(3921);
            return null;
          } else {
            var _resultTarget = path[normalizedFollowTag](target, 0, nPaths);
            if (_resultTarget === null) {
              return null;
            }
            var runtimeProxy = proxy.forTarget(_resultTarget);
            if (!runtimeProxy) {
              return null;
            }
            var _binding = {
              setValue: function setValue(value) {
                runtimeProxy.set(value);
              }
            };
            var proxyGet = runtimeProxy.get;
            if (proxyGet) {
              _binding.getValue = function () {
                return proxyGet.call(runtimeProxy);
              };
            }
            return _binding;
          }
        };
        _proto2.isMaskedOff = function isMaskedOff(mask) {
          var trsPath = this.parseTrsPath();
          if (!trsPath) {
            return false;
          }
          var joints = mask.joints[Symbol.iterator]();
          for (var jointMaskInfoIter = joints.next(); !jointMaskInfoIter.done; jointMaskInfoIter = joints.next()) {
            var _jointMaskInfoIter = jointMaskInfoIter,
              jointMaskInfo = _jointMaskInfoIter.value;
            if (jointMaskInfo.path !== trsPath.node) {
              continue;
            }
            return !jointMaskInfo.enabled;
          }
          return false;
        };
        return TrackBinding;
      }(), _class6$7._animationFunctions = new WeakMap(), _class6$7), (_initializer2$1E = applyDecoratedInitializer(_class5$o.prototype, "path", [serializable$p], function () {
        return new TrackPath();
      }), _initializer3$1c = applyDecoratedInitializer(_class5$o.prototype, "proxy", [serializable$p], null)), _class5$o)) || _class4$n) || _class4$n);
      function isTrsPropertyName(name) {
        return name === 'position' || name === 'rotation' || name === 'scale' || name === 'eulerAngles';
      }
      var Track = (_dec3$1g = ccclass$M(CLASS_NAME_PREFIX_ANIM + "Track"), _dec3$1g(_class7$7 = (_class8$8 = function () {
        function Track() {
          this._binding = _initializer4$11 && _initializer4$11();
        }
        var _proto3 = Track.prototype;
        _proto3.channels = function channels() {
          return [];
        };
        _proto3.range = function range() {
          var range = {
            min: Infinity,
            max: -Infinity
          };
          for (var _iterator = _createForOfIteratorHelperLoose(this.channels()), _step; !(_step = _iterator()).done;) {
            var channel = _step.value;
            range.min = Math.min(range.min, channel.curve.rangeMin);
            range.max = Math.max(range.max, channel.curve.rangeMax);
          }
          return range;
        };
        _createClass(Track, [{
          key: "path",
          get: function get() {
            return this._binding.path;
          },
          set: function set(value) {
            this._binding.path = value;
          }
        }, {
          key: "proxy",
          get: function get() {
            return this._binding.proxy;
          },
          set: function set(value) {
            this._binding.proxy = value;
          }
        }, {
          key: trackBindingTag,
          get: function get() {
            return this._binding;
          }
        }]);
        return Track;
      }(), (_initializer4$11 = applyDecoratedInitializer(_class8$8.prototype, "_binding", [serializable$p], function () {
        return new TrackBinding();
      })), _class8$8)) || _class7$7);
      var Channel = (_dec4$W = ccclass$M(CLASS_NAME_PREFIX_ANIM + "Channel"), _dec4$W(_class10$3 = (_class11$4 = function () {
        function Channel(curve) {
          this.name = '';
          this._curve = _initializer5$P && _initializer5$P();
          this._curve = curve;
        }
        _createClass(Channel, [{
          key: "curve",
          get: function get() {
            return this._curve;
          }
        }]);
        return Channel;
      }(), (_initializer5$P = applyDecoratedInitializer(_class11$4.prototype, "_curve", [serializable$p], null)), _class11$4)) || _class10$3);
      var SingleChannelTrack = (_dec5$R = ccclass$M(CLASS_NAME_PREFIX_ANIM + "SingleChannelTrack"), _dec5$R(_class13$3 = (_class14$2 = function (_Track) {
        _inheritsLoose(SingleChannelTrack, _Track);
        function SingleChannelTrack() {
          var _this;
          _this = _Track.call(this) || this;
          _this._channel = _initializer6$G && _initializer6$G();
          _this._channel = new Channel(_this.createCurve());
          return _this;
        }
        var _proto4 = SingleChannelTrack.prototype;
        _proto4.channels = function channels() {
          return [this._channel];
        };
        _proto4.createCurve = function createCurve() {
          throw new Error("Not impl");
        };
        _proto4[createEvalSymbol] = function () {
          var curve = this._channel.curve;
          return new SingleChannelTrackEval(curve);
        };
        _createClass(SingleChannelTrack, [{
          key: "channel",
          get: function get() {
            return this._channel;
          }
        }]);
        return SingleChannelTrack;
      }(Track), (_initializer6$G = applyDecoratedInitializer(_class14$2.prototype, "_channel", [serializable$p], null)), _class14$2)) || _class13$3);
      var SingleChannelTrackEval = function () {
        function SingleChannelTrackEval(_curve) {
          this._curve = _curve;
        }
        var _proto5 = SingleChannelTrackEval.prototype;
        _proto5.evaluate = function evaluate(time) {
          return this._curve.evaluate(time);
        };
        _createClass(SingleChannelTrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return false;
          }
        }]);
        return SingleChannelTrackEval;
      }();

      var _dec$2k, _class$2i, _class2$24, _initializer$1Y;
      var ccclass$F = ccclass$M,
        serializable$j = serializable$p;
      (_dec$2k = ccclass$F(CLASS_NAME_PREFIX_ANIM + "RealArrayTrack"), _dec$2k(_class$2i = (_class2$24 = function (_Track) {
        _inheritsLoose(RealArrayTrack, _Track);
        function RealArrayTrack() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Track.call.apply(_Track, [this].concat(args)) || this;
          _this._channels = _initializer$1Y && _initializer$1Y();
          return _this;
        }
        var _proto = RealArrayTrack.prototype;
        _proto.channels = function channels() {
          return this._channels;
        };
        _proto[createEvalSymbol] = function () {
          return new RealArrayTrackEval(this._channels.map(function (_ref) {
            var curve = _ref.curve;
            return curve;
          }));
        };
        _createClass(RealArrayTrack, [{
          key: "elementCount",
          get: function get() {
            return this._channels.length;
          },
          set: function set(value) {
            var channels = this._channels;
            var nChannels = channels.length;
            if (value < nChannels) {
              this._channels.splice(value);
            } else if (value > nChannels) {
              var _this$_channels;
              (_this$_channels = this._channels).push.apply(_this$_channels, Array.from({
                length: value - nChannels
              }, function () {
                return new Channel(new RealCurve());
              }));
            }
          }
        }]);
        return RealArrayTrack;
      }(Track), (_initializer$1Y = applyDecoratedInitializer(_class2$24.prototype, "_channels", [serializable$j], function () {
        return [];
      })), _class2$24)) || _class$2i);
      var RealArrayTrackEval = function () {
        function RealArrayTrackEval(_curves) {
          this._curves = _curves;
          this._result = new Array(_curves.length).fill(0.0);
        }
        var _proto2 = RealArrayTrackEval.prototype;
        _proto2.evaluate = function evaluate(time) {
          var result = this._result;
          var nElements = result.length;
          for (var iElement = 0; iElement < nElements; ++iElement) {
            result[iElement] = this._curves[iElement].evaluate(time);
          }
          return this._result;
        };
        _createClass(RealArrayTrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return false;
          }
        }]);
        return RealArrayTrackEval;
      }();

      var _dec$2j, _class$2h, _class2$23, _initializer$1X, _initializer2$1D, _descriptor$2;
      var UniformProxyFactory = (_dec$2j = ccclass$M('cc.animation.UniformProxyFactory'), _dec$2j(_class$2h = (_class2$23 = function () {
        function UniformProxyFactory(uniformName, passIndex) {
          this.passIndex = _initializer$1X && _initializer$1X();
          this.uniformName = _initializer2$1D && _initializer2$1D();
          _initializerDefineProperty(this, "channelIndex", _descriptor$2, this);
          this.passIndex = passIndex || 0;
          this.uniformName = uniformName || '';
        }
        var _proto = UniformProxyFactory.prototype;
        _proto.forTarget = function forTarget(target) {
          if (!(target instanceof Material)) {
            warnID(3940, target);
            return undefined;
          }
          var passIndex = this.passIndex,
            uniformName = this.uniformName,
            channelIndex = this.channelIndex;
          if (passIndex < 0 || passIndex >= target.passes.length) {
            warnID(3941, target.name, passIndex);
            return undefined;
          }
          var pass = target.passes[passIndex];
          var handle = pass.getHandle(uniformName);
          if (!handle) {
            warnID(3942, target.name, passIndex, uniformName);
            return undefined;
          }
          var type = Pass.getTypeFromHandle(handle);
          if (type < Type$1.SAMPLER1D) {
            var realHandle = channelIndex === undefined ? handle : pass.getHandle(uniformName, channelIndex, Type$1.FLOAT);
            if (!realHandle) {
              warnID(3943, target.name, passIndex, uniformName, channelIndex);
              return undefined;
            }
            if (isUniformArray(pass, uniformName)) {
              return {
                set: function set(value) {
                  pass.setUniformArray(realHandle, value);
                }
              };
            }
            return {
              set: function set(value) {
                pass.setUniform(realHandle, value);
              }
            };
          } else {
            var binding = Pass.getBindingFromHandle(handle);
            var prop = pass.properties[uniformName];
            var texName = prop && prop.value ? "" + prop.value + getStringFromType(prop.type) : getDefaultFromType(prop.type);
            var dftTex = builtinResMgr.get(texName);
            if (!dftTex) {
              warn("Illegal texture default value: " + texName + ".");
              dftTex = builtinResMgr.get('default-texture');
            }
            return {
              set: function set(value) {
                if (!value) {
                  value = dftTex;
                }
                var texture = value.getGFXTexture();
                if (!texture || !texture.width || !texture.height) {
                  return;
                }
                pass.bindTexture(binding, texture);
                if (value instanceof TextureBase) {
                  pass.bindSampler(binding, deviceManager.gfxDevice.getSampler(value.getSamplerInfo()));
                }
              }
            };
          }
        };
        return UniformProxyFactory;
      }(), (_initializer$1X = applyDecoratedInitializer(_class2$23.prototype, "passIndex", [serializable$p], function () {
        return 0;
      }), _initializer2$1D = applyDecoratedInitializer(_class2$23.prototype, "uniformName", [serializable$p], function () {
        return '';
      }), _descriptor$2 = _applyDecoratedDescriptor(_class2$23.prototype, "channelIndex", [_float], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return undefined;
        }
      })), _class2$23)) || _class$2h);
      function isUniformArray(pass, name) {
        for (var _iterator = _createForOfIteratorHelperLoose(pass.shaderInfo.blocks), _step; !(_step = _iterator()).done;) {
          var block = _step.value;
          for (var _iterator2 = _createForOfIteratorHelperLoose(block.members), _step2; !(_step2 = _iterator2()).done;) {
            var uniform = _step2.value;
            if (uniform.name === name) {
              return uniform.count > 1;
            }
          }
        }
        return false;
      }

      var _dec$2i, _class$2g, _class2$22, _initializer$1W, _initializer2$1C, _dec2$1M, _class4$m, _class5$n, _initializer3$1b, _dec3$1f, _class7$6;
      var MorphWeightValueProxy = (_dec$2i = ccclass$M('cc.animation.MorphWeightValueProxy'), _dec$2i(_class$2g = (_class2$22 = function () {
        function MorphWeightValueProxy() {
          this.subMeshIndex = _initializer$1W && _initializer$1W();
          this.shapeIndex = _initializer2$1C && _initializer2$1C();
        }
        var _proto = MorphWeightValueProxy.prototype;
        _proto.forTarget = function forTarget(target) {
          var _this = this;
          return {
            set: function set(value) {
              target.setWeight(value, _this.subMeshIndex, _this.shapeIndex);
            }
          };
        };
        return MorphWeightValueProxy;
      }(), (_initializer$1W = applyDecoratedInitializer(_class2$22.prototype, "subMeshIndex", [serializable$p], function () {
        return 0;
      }), _initializer2$1C = applyDecoratedInitializer(_class2$22.prototype, "shapeIndex", [serializable$p], function () {
        return 0;
      })), _class2$22)) || _class$2g);
      var MorphWeightsValueProxy = (_dec2$1M = ccclass$M('cc.animation.MorphWeightsValueProxy'), _dec2$1M(_class4$m = (_class5$n = function () {
        function MorphWeightsValueProxy() {
          this.subMeshIndex = _initializer3$1b && _initializer3$1b();
        }
        var _proto2 = MorphWeightsValueProxy.prototype;
        _proto2.forTarget = function forTarget(target) {
          var _this2 = this;
          return {
            set: function set(value) {
              target.setWeights(value, _this2.subMeshIndex);
            }
          };
        };
        return MorphWeightsValueProxy;
      }(), (_initializer3$1b = applyDecoratedInitializer(_class5$n.prototype, "subMeshIndex", [serializable$p], function () {
        return 0;
      })), _class5$n)) || _class4$m);
      var MorphWeightsAllValueProxy = (_dec3$1f = ccclass$M('cc.animation.MorphWeightsAllValueProxy'), _dec3$1f(_class7$6 = function () {
        function MorphWeightsAllValueProxy() {}
        var _proto3 = MorphWeightsAllValueProxy.prototype;
        _proto3.forTarget = function forTarget(target) {
          return {
            set: function set(value) {
              var _target$mesh$struct$p, _target$mesh;
              var nSubMeshes = (_target$mesh$struct$p = (_target$mesh = target.mesh) === null || _target$mesh === void 0 ? void 0 : _target$mesh.struct.primitives.length) !== null && _target$mesh$struct$p !== void 0 ? _target$mesh$struct$p : 0;
              for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
                target.setWeights(value, iSubMesh);
              }
            }
          };
        };
        return MorphWeightsAllValueProxy;
      }()) || _class7$6);

      var _dec2$1L, _class4$l, _class5$m, _initializer4$10, _initializer5$O, _initializer6$F;
      function makeCubicSplineValueConstructor(name, ConstructorX, scaleFx, scaleAndAdd) {
        var _dec, _class, _class2, _initializer, _initializer2, _initializer3;
        var tempValue = new ConstructorX();
        var m0 = new ConstructorX();
        var m1 = new ConstructorX();
        var CubicSplineValueClass = (_dec = ccclass$M(name), _dec(_class = (_class2 = function () {
          function CubicSplineValueClass(dataPoint, inTangent, outTangent) {
            this.dataPoint = _initializer && _initializer();
            this.inTangent = _initializer2 && _initializer2();
            this.outTangent = _initializer3 && _initializer3();
            this.dataPoint = dataPoint || new ConstructorX();
            this.inTangent = inTangent || new ConstructorX();
            this.outTangent = outTangent || new ConstructorX();
          }
          var _proto = CubicSplineValueClass.prototype;
          _proto.lerp = function lerp(to, t, dt) {
            var p0 = this.dataPoint;
            var p1 = to.dataPoint;
            m0 = scaleFx(m0, this.inTangent, dt);
            m1 = scaleFx(m1, to.outTangent, dt);
            var t_3 = t * t * t;
            var t_2 = t * t;
            var f_0 = 2 * t_3 - 3 * t_2 + 1;
            var f_1 = t_3 - 2 * t_2 + t;
            var f_2 = -2 * t_3 + 3 * t_2;
            var f_3 = t_3 - t_2;
            tempValue = scaleFx(tempValue, p0, f_0);
            tempValue = scaleAndAdd(tempValue, tempValue, m0, f_1);
            tempValue = scaleAndAdd(tempValue, tempValue, p1, f_2);
            tempValue = scaleAndAdd(tempValue, tempValue, m1, f_3);
            return tempValue;
          };
          _proto.getNoLerp = function getNoLerp() {
            return this.dataPoint;
          };
          return CubicSplineValueClass;
        }(), (_initializer = applyDecoratedInitializer(_class2.prototype, "dataPoint", [serializable$p], function () {
          return new ConstructorX();
        }), _initializer2 = applyDecoratedInitializer(_class2.prototype, "inTangent", [serializable$p], function () {
          return new ConstructorX();
        }), _initializer3 = applyDecoratedInitializer(_class2.prototype, "outTangent", [serializable$p], function () {
          return new ConstructorX();
        })), _class2)) || _class);
        if (ConstructorX === Quat) {
          var _lerp = CubicSplineValueClass.prototype.lerp;
          CubicSplineValueClass.prototype.lerp = function (to, t, dt) {
            var result = _lerp.call(this, to, t, dt);
            Quat.normalize(result, result);
            return result;
          };
        }
        return CubicSplineValueClass;
      }
      var CubicSplineVec2Value = makeCubicSplineValueConstructor('cc.CubicSplineVec2Value', Vec2, Vec2.multiplyScalar, Vec2.scaleAndAdd);
      var CubicSplineVec3Value = makeCubicSplineValueConstructor('cc.CubicSplineVec3Value', Vec3, Vec3.multiplyScalar, Vec3.scaleAndAdd);
      var CubicSplineVec4Value = makeCubicSplineValueConstructor('cc.CubicSplineVec4Value', Vec4, Vec4.multiplyScalar, Vec4.scaleAndAdd);
      var CubicSplineQuatValue = makeCubicSplineValueConstructor('cc.CubicSplineQuatValue', Quat, Quat.multiplyScalar, Quat.scaleAndAdd);
      var CubicSplineNumberValue = (_dec2$1L = ccclass$M('cc.CubicSplineNumberValue'), _dec2$1L(_class4$l = (_class5$m = function () {
        function CubicSplineNumberValue(dataPoint, inTangent, outTangent) {
          this.dataPoint = _initializer4$10 && _initializer4$10();
          this.inTangent = _initializer5$O && _initializer5$O();
          this.outTangent = _initializer6$F && _initializer6$F();
          this.dataPoint = dataPoint;
          this.inTangent = inTangent;
          this.outTangent = outTangent;
        }
        var _proto2 = CubicSplineNumberValue.prototype;
        _proto2.lerp = function lerp(to, t, dt) {
          var p0 = this.dataPoint;
          var p1 = to.dataPoint;
          var m0 = this.outTangent * dt;
          var m1 = to.inTangent * dt;
          var t_3 = t * t * t;
          var t_2 = t * t;
          var f_0 = 2 * t_3 - 3 * t_2 + 1;
          var f_1 = t_3 - 2 * t_2 + t;
          var f_2 = -2 * t_3 + 3 * t_2;
          var f_3 = t_3 - t_2;
          return p0 * f_0 + m0 * f_1 + p1 * f_2 + m1 * f_3;
        };
        _proto2.getNoLerp = function getNoLerp() {
          return this.dataPoint;
        };
        return CubicSplineNumberValue;
      }(), (_initializer4$10 = applyDecoratedInitializer(_class5$m.prototype, "dataPoint", [serializable$p], function () {
        return 0;
      }), _initializer5$O = applyDecoratedInitializer(_class5$m.prototype, "inTangent", [serializable$p], function () {
        return 0;
      }), _initializer6$F = applyDecoratedInitializer(_class5$m.prototype, "outTangent", [serializable$p], function () {
        return 0;
      })), _class5$m)) || _class4$l);

      var _dec$2h, _class$2f;
      var RealTrack = (_dec$2h = ccclass$M(CLASS_NAME_PREFIX_ANIM + "RealTrack"), _dec$2h(_class$2f = function (_SingleChannelTrack) {
        _inheritsLoose(RealTrack, _SingleChannelTrack);
        function RealTrack() {
          return _SingleChannelTrack.apply(this, arguments) || this;
        }
        var _proto = RealTrack.prototype;
        _proto.createCurve = function createCurve() {
          return new RealCurve();
        };
        return RealTrack;
      }(SingleChannelTrack)) || _class$2f);

      function maskIfEmpty(curve) {
        return curve.keyFramesCount === 0 ? undefined : curve;
      }

      var _dec$2g, _class$2e, _class2$21, _initializer$1V, _initializer2$1B;
      var CHANNEL_NAMES$2 = ['X', 'Y', 'Z', 'W'];
      var VectorTrack = (_dec$2g = ccclass$M(CLASS_NAME_PREFIX_ANIM + "VectorTrack"), _dec$2g(_class$2e = (_class2$21 = function (_Track) {
        _inheritsLoose(VectorTrack, _Track);
        function VectorTrack() {
          var _this;
          _this = _Track.call(this) || this;
          _this._channels = _initializer$1V && _initializer$1V();
          _this._nComponents = _initializer2$1B && _initializer2$1B();
          _this._channels = new Array(4);
          for (var i = 0; i < _this._channels.length; ++i) {
            var channel = new Channel(new RealCurve());
            channel.name = CHANNEL_NAMES$2[i];
            _this._channels[i] = channel;
          }
          return _this;
        }
        var _proto = VectorTrack.prototype;
        _proto.channels = function channels() {
          return this._channels;
        };
        _proto[createEvalSymbol] = function () {
          switch (this._nComponents) {
            default:
            case 2:
              return new Vec2TrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve));
            case 3:
              return new Vec3TrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve), maskIfEmpty(this._channels[2].curve));
            case 4:
              return new Vec4TrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve), maskIfEmpty(this._channels[2].curve), maskIfEmpty(this._channels[3].curve));
          }
        };
        _createClass(VectorTrack, [{
          key: "componentsCount",
          get: function get() {
            return this._nComponents;
          },
          set: function set(value) {
            this._nComponents = value;
          }
        }]);
        return VectorTrack;
      }(Track), (_initializer$1V = applyDecoratedInitializer(_class2$21.prototype, "_channels", [serializable$p], null), _initializer2$1B = applyDecoratedInitializer(_class2$21.prototype, "_nComponents", [serializable$p], function () {
        return 4;
      })), _class2$21)) || _class$2e);
      var Vec2TrackEval = function () {
        function Vec2TrackEval(_x, _y) {
          this._result = new Vec2();
          this._x = _x;
          this._y = _y;
        }
        var _proto2 = Vec2TrackEval.prototype;
        _proto2.evaluate = function evaluate(time, defaultValue) {
          if (defaultValue) {
            Vec2.copy(this._result, defaultValue);
          }
          if (this._x) {
            this._result.x = this._x.evaluate(time);
          }
          if (this._y) {
            this._result.y = this._y.evaluate(time);
          }
          return this._result;
        };
        _createClass(Vec2TrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return !this._x || !this._y;
          }
        }]);
        return Vec2TrackEval;
      }();
      var Vec3TrackEval = function () {
        function Vec3TrackEval(_x, _y, _z) {
          this._result = new Vec3();
          this._x = _x;
          this._y = _y;
          this._z = _z;
        }
        var _proto3 = Vec3TrackEval.prototype;
        _proto3.evaluate = function evaluate(time, defaultValue) {
          var _x = this._x,
            _y = this._y,
            _z = this._z,
            _result = this._result;
          if (defaultValue) {
            Vec3.copy(_result, defaultValue);
          }
          if (_x) {
            _result.x = _x.evaluate(time);
          }
          if (_y) {
            _result.y = _y.evaluate(time);
          }
          if (_z) {
            _result.z = _z.evaluate(time);
          }
          return _result;
        };
        _createClass(Vec3TrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return !this._x || !this._y || !this._z;
          }
        }]);
        return Vec3TrackEval;
      }();
      var Vec4TrackEval = function () {
        function Vec4TrackEval(_x, _y, _z, _w) {
          this._result = new Vec4();
          this._x = _x;
          this._y = _y;
          this._z = _z;
          this._w = _w;
        }
        var _proto4 = Vec4TrackEval.prototype;
        _proto4.evaluate = function evaluate(time, defaultValue) {
          if (defaultValue) {
            Vec4.copy(this._result, defaultValue);
          }
          if (this._x) {
            this._result.x = this._x.evaluate(time);
          }
          if (this._y) {
            this._result.y = this._y.evaluate(time);
          }
          if (this._z) {
            this._result.z = this._z.evaluate(time);
          }
          if (this._w) {
            this._result.w = this._w.evaluate(time);
          }
          return this._result;
        };
        _createClass(Vec4TrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return !this._x || !this._y || !this._z || !this._w;
          }
        }]);
        return Vec4TrackEval;
      }();

      var _dec$2f, _class$2d;
      var QuatTrack = (_dec$2f = ccclass$M(CLASS_NAME_PREFIX_ANIM + "QuatTrack"), _dec$2f(_class$2d = function (_SingleChannelTrack) {
        _inheritsLoose(QuatTrack, _SingleChannelTrack);
        function QuatTrack() {
          return _SingleChannelTrack.apply(this, arguments) || this;
        }
        var _proto = QuatTrack.prototype;
        _proto.createCurve = function createCurve() {
          return new QuatCurve();
        };
        _proto[createEvalSymbol] = function () {
          return new QuatTrackEval(this.channels()[0].curve);
        };
        return QuatTrack;
      }(SingleChannelTrack)) || _class$2d);
      var QuatTrackEval = function () {
        function QuatTrackEval(_curve) {
          this._result = new Quat();
          this._curve = _curve;
        }
        var _proto2 = QuatTrackEval.prototype;
        _proto2.evaluate = function evaluate(time) {
          this._curve.evaluate(time, this._result);
          return this._result;
        };
        _createClass(QuatTrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return false;
          }
        }]);
        return QuatTrackEval;
      }();

      var _dec$2e, _class$2c, _class2$20, _initializer$1U;
      var CHANNEL_NAMES$1 = ['Red', 'Green', 'Blue', 'Alpha'];
      var ColorTrack = (_dec$2e = ccclass$M(CLASS_NAME_PREFIX_ANIM + "ColorTrack"), _dec$2e(_class$2c = (_class2$20 = function (_Track) {
        _inheritsLoose(ColorTrack, _Track);
        function ColorTrack() {
          var _this;
          _this = _Track.call(this) || this;
          _this._channels = _initializer$1U && _initializer$1U();
          _this._channels = new Array(4);
          for (var i = 0; i < _this._channels.length; ++i) {
            var channel = new Channel(new RealCurve());
            channel.name = CHANNEL_NAMES$1[i];
            _this._channels[i] = channel;
          }
          return _this;
        }
        var _proto = ColorTrack.prototype;
        _proto.channels = function channels() {
          return this._channels;
        };
        _proto[createEvalSymbol] = function () {
          return new ColorTrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve), maskIfEmpty(this._channels[2].curve), maskIfEmpty(this._channels[3].curve));
        };
        return ColorTrack;
      }(Track), (_initializer$1U = applyDecoratedInitializer(_class2$20.prototype, "_channels", [serializable$p], null)), _class2$20)) || _class$2c);
      var ColorTrackEval = function () {
        function ColorTrackEval(_x, _y, _z, _w) {
          this._result = new Color$1();
          this._x = _x;
          this._y = _y;
          this._z = _z;
          this._w = _w;
        }
        var _proto2 = ColorTrackEval.prototype;
        _proto2.evaluate = function evaluate(time, defaultValue) {
          if (defaultValue) {
            Color$1.copy(this._result, defaultValue);
          }
          if (this._x) {
            this._result.r = this._x.evaluate(time);
          }
          if (this._y) {
            this._result.g = this._y.evaluate(time);
          }
          if (this._z) {
            this._result.b = this._z.evaluate(time);
          }
          if (this._w) {
            this._result.a = this._w.evaluate(time);
          }
          return this._result;
        };
        _createClass(ColorTrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return !this._x || !this._y || !this._z || !this._w;
          }
        }]);
        return ColorTrackEval;
      }();

      var _dec$2d, _class$2b, _class2$1$, _initializer$1T;
      var CHANNEL_NAMES = ['Width', 'Height'];
      var SizeTrack = (_dec$2d = ccclass$M(CLASS_NAME_PREFIX_ANIM + "SizeTrack"), _dec$2d(_class$2b = (_class2$1$ = function (_Track) {
        _inheritsLoose(SizeTrack, _Track);
        function SizeTrack() {
          var _this;
          _this = _Track.call(this) || this;
          _this._channels = _initializer$1T && _initializer$1T();
          _this._channels = new Array(2);
          for (var i = 0; i < _this._channels.length; ++i) {
            var channel = new Channel(new RealCurve());
            channel.name = CHANNEL_NAMES[i];
            _this._channels[i] = channel;
          }
          return _this;
        }
        var _proto = SizeTrack.prototype;
        _proto.channels = function channels() {
          return this._channels;
        };
        _proto[createEvalSymbol] = function () {
          return new SizeTrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve));
        };
        return SizeTrack;
      }(Track), (_initializer$1T = applyDecoratedInitializer(_class2$1$.prototype, "_channels", [serializable$p], null)), _class2$1$)) || _class$2b);
      var SizeTrackEval = function () {
        function SizeTrackEval(_width, _height) {
          this._result = new Size$1();
          this._width = _width;
          this._height = _height;
        }
        var _proto2 = SizeTrackEval.prototype;
        _proto2.evaluate = function evaluate(time, defaultValue) {
          if (defaultValue) {
            this._result.x = defaultValue.x;
            this._result.y = defaultValue.y;
          }
          if (this._width) {
            this._result.width = this._width.evaluate(time);
          }
          if (this._height) {
            this._result.height = this._height.evaluate(time);
          }
          return this._result;
        };
        _createClass(SizeTrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return !this._width || !this._height;
          }
        }]);
        return SizeTrackEval;
      }();

      var _dec$2c, _class$2a;
      var ObjectTrack = (_dec$2c = ccclass$M(CLASS_NAME_PREFIX_ANIM + "ObjectTrack"), _dec$2c(_class$2a = function (_SingleChannelTrack) {
        _inheritsLoose(ObjectTrack, _SingleChannelTrack);
        function ObjectTrack() {
          return _SingleChannelTrack.apply(this, arguments) || this;
        }
        var _proto = ObjectTrack.prototype;
        _proto.createCurve = function createCurve() {
          return new ObjectCurve();
        };
        return ObjectTrack;
      }(SingleChannelTrack)) || _class$2a);

      var ownerSymbol = Symbol('[[Owner]]');
      function assertsOwnedBy(mastered, owner) {
        assertIsTrue(mastered[ownerSymbol] === owner);
      }
      function own(mastered, owner) {
        {
          mastered[ownerSymbol] = owner;
        }
      }
      function markAsDangling(mastered) {
        {
          mastered[ownerSymbol] = undefined;
        }
      }

      var VariableType;
      (function (VariableType) {
        VariableType[VariableType["FLOAT"] = 0] = "FLOAT";
        VariableType[VariableType["BOOLEAN"] = 1] = "BOOLEAN";
        VariableType[VariableType["TRIGGER"] = 2] = "TRIGGER";
        VariableType[VariableType["INTEGER"] = 3] = "INTEGER";
        VariableType[VariableType["VEC3_experimental"] = 4] = "VEC3_experimental";
        VariableType[VariableType["QUAT_experimental"] = 5] = "QUAT_experimental";
      })(VariableType || (VariableType = {}));
      var createInstanceTag = Symbol('CreateInstance');
      var VarInstanceBase = function () {
        function VarInstanceBase(type) {
          this._refs = [];
          this.type = type;
        }
        var _proto = VarInstanceBase.prototype;
        _proto.bind = function bind(fn, thisArg) {
          for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
            args[_key - 2] = arguments[_key];
          }
          this._refs.push({
            fn: fn,
            thisArg: thisArg,
            args: args
          });
          return this.getValue();
        };
        _createClass(VarInstanceBase, [{
          key: "value",
          get: function get() {
            return this.getValue();
          },
          set: function set(value) {
            this.setValue(value);
            for (var _iterator = _createForOfIteratorHelperLoose(this._refs), _step; !(_step = _iterator()).done;) {
              var _step$value = _step.value,
                fn = _step$value.fn,
                thisArg = _step$value.thisArg,
                args = _step$value.args;
              fn.call.apply(fn, [thisArg, value].concat(args));
            }
          }
        }]);
        return VarInstanceBase;
      }();

      var _dec$2b, _class$29, _class2$1_, _initializer$1S, _initializer2$1A;
      var PlainVariable = (_dec$2b = ccclass$M('cc.animation.PlainVariable'), _dec$2b(_class$29 = (_class2$1_ = function () {
        function PlainVariable(type) {
          this._type = _initializer$1S && _initializer$1S();
          this._value = _initializer2$1A && _initializer2$1A();
          if (typeof type === 'undefined') {
            return;
          }
          this._type = type;
          switch (type) {
            default:
              break;
            case VariableType.FLOAT:
              this._value = 0.0;
              break;
            case VariableType.INTEGER:
              this._value = 0;
              break;
            case VariableType.BOOLEAN:
              this._value = false;
              break;
          }
        }
        var _proto = PlainVariable.prototype;
        _proto[createInstanceTag] = function () {
          return new VarInstancePrimitive(this._type, this._value);
        };
        _createClass(PlainVariable, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "value",
          get: function get() {
            return this._value;
          },
          set: function set(value) {
            {
              switch (this._type) {
                default:
                  break;
                case VariableType.FLOAT:
                  assertIsTrue(typeof value === 'number');
                  break;
                case VariableType.INTEGER:
                  assertIsTrue(Number.isInteger(value));
                  break;
                case VariableType.BOOLEAN:
                  assertIsTrue(typeof value === 'boolean');
                  break;
              }
            }
            this._value = value;
          }
        }]);
        return PlainVariable;
      }(), (_initializer$1S = applyDecoratedInitializer(_class2$1_.prototype, "_type", [serializable$p], function () {
        return VariableType.FLOAT;
      }), _initializer2$1A = applyDecoratedInitializer(_class2$1_.prototype, "_value", [serializable$p], function () {
        return 0.0;
      })), _class2$1_)) || _class$29);
      var VarInstancePrimitive = function (_VarInstanceBase) {
        _inheritsLoose(VarInstancePrimitive, _VarInstanceBase);
        function VarInstancePrimitive(type, value) {
          var _this;
          _this = _VarInstanceBase.call(this, type) || this;
          _this._value = void 0;
          _this._value = value;
          return _this;
        }
        var _proto2 = VarInstancePrimitive.prototype;
        _proto2.getValue = function getValue() {
          return this._value;
        };
        _proto2.setValue = function setValue(value) {
          this._value = value;
        };
        return VarInstancePrimitive;
      }(VarInstanceBase);

      var _dec$2a, _class$28, _class2$1Z, _initializer$1R;
      var TriggerResetMode;
      (function (TriggerResetMode) {
        TriggerResetMode[TriggerResetMode["AFTER_CONSUMED"] = 0] = "AFTER_CONSUMED";
        TriggerResetMode[TriggerResetMode["NEXT_FRAME_OR_AFTER_CONSUMED"] = 1] = "NEXT_FRAME_OR_AFTER_CONSUMED";
      })(TriggerResetMode || (TriggerResetMode = {}));
      var TRIGGER_VARIABLE_FLAG_VALUE_START = 0;
      var TRIGGER_VARIABLE_FLAG_VALUE_MASK = 1;
      var TRIGGER_VARIABLE_FLAG_RESET_MODE_START = 1;
      var TRIGGER_VARIABLE_FLAG_RESET_MODE_MASK = 6;
      var TRIGGER_VARIABLE_DEFAULT_FLAGS = 0;
      assertIsTrue((0 << TRIGGER_VARIABLE_FLAG_VALUE_START | TriggerResetMode.AFTER_CONSUMED << TRIGGER_VARIABLE_FLAG_RESET_MODE_START) === TRIGGER_VARIABLE_DEFAULT_FLAGS);
      var TriggerVariable = (_dec$2a = ccclass$M('cc.animation.TriggerVariable'), _dec$2a(_class$28 = (_class2$1Z = function () {
        function TriggerVariable() {
          this._flags = _initializer$1R && _initializer$1R();
        }
        var _proto = TriggerVariable.prototype;
        _proto[createInstanceTag] = function () {
          return new VarInstanceTrigger(this.value, this.resetMode);
        };
        _createClass(TriggerVariable, [{
          key: "type",
          get: function get() {
            return VariableType.TRIGGER;
          }
        }, {
          key: "value",
          get: function get() {
            return !!((this._flags & TRIGGER_VARIABLE_FLAG_VALUE_MASK) >> TRIGGER_VARIABLE_FLAG_VALUE_START);
          },
          set: function set(value) {
            if (value) {
              this._flags |= 1 << TRIGGER_VARIABLE_FLAG_VALUE_START;
            } else {
              this._flags &= ~(1 << TRIGGER_VARIABLE_FLAG_VALUE_START);
            }
          }
        }, {
          key: "resetMode",
          get: function get() {
            return (this._flags & TRIGGER_VARIABLE_FLAG_RESET_MODE_MASK) >> TRIGGER_VARIABLE_FLAG_RESET_MODE_START;
          },
          set: function set(value) {
            this._flags &= ~TRIGGER_VARIABLE_FLAG_RESET_MODE_MASK;
            this._flags |= value << TRIGGER_VARIABLE_FLAG_RESET_MODE_START;
          }
        }]);
        return TriggerVariable;
      }(), (_initializer$1R = applyDecoratedInitializer(_class2$1Z.prototype, "_flags", [serializable$p], function () {
        return TRIGGER_VARIABLE_DEFAULT_FLAGS;
      })), _class2$1Z)) || _class$28);
      var VarInstanceTrigger = function (_VarInstanceBase) {
        _inheritsLoose(VarInstanceTrigger, _VarInstanceBase);
        function VarInstanceTrigger(value, resetMode) {
          var _this;
          _this = _VarInstanceBase.call(this, VariableType.TRIGGER) || this;
          _this.resetMode = TriggerResetMode.AFTER_CONSUMED;
          _this._value = void 0;
          _this.resetMode = resetMode;
          _this._value = value;
          return _this;
        }
        var _proto2 = VarInstanceTrigger.prototype;
        _proto2.getValue = function getValue() {
          return this._value;
        };
        _proto2.setValue = function setValue(value) {
          this._value = value;
        };
        return VarInstanceTrigger;
      }(VarInstanceBase);

      var _dec$29, _class$27, _class2$1Y, _initializer$1Q;
      var Vec3Variable = (_dec$29 = ccclass$M('cc.animation.Vec3Variable'), _dec$29(_class$27 = (_class2$1Y = function () {
        function Vec3Variable() {
          this._value = _initializer$1Q && _initializer$1Q();
        }
        var _proto = Vec3Variable.prototype;
        _proto[createInstanceTag] = function () {
          return new VarInstanceVec3(this.value);
        };
        _createClass(Vec3Variable, [{
          key: "type",
          get: function get() {
            return VariableType.VEC3_experimental;
          }
        }, {
          key: "value",
          get: function get() {
            return this._value;
          },
          set: function set(value) {
            Vec3.copy(this._value, value);
          }
        }]);
        return Vec3Variable;
      }(), (_initializer$1Q = applyDecoratedInitializer(_class2$1Y.prototype, "_value", [serializable$p], function () {
        return new Vec3();
      })), _class2$1Y)) || _class$27);
      var VarInstanceVec3 = function (_VarInstanceBase) {
        _inheritsLoose(VarInstanceVec3, _VarInstanceBase);
        function VarInstanceVec3(value) {
          var _this;
          _this = _VarInstanceBase.call(this, VariableType.VEC3_experimental) || this;
          _this._value = new Vec3();
          Vec3.copy(_this._value, value);
          return _this;
        }
        var _proto2 = VarInstanceVec3.prototype;
        _proto2.getValue = function getValue() {
          return this._value;
        };
        _proto2.setValue = function setValue(value) {
          assertIsTrue(value instanceof Vec3);
          Vec3.copy(this._value, value);
        };
        return VarInstanceVec3;
      }(VarInstanceBase);

      var _dec$28, _class$26, _class2$1X, _initializer$1P;
      var QuatVariable = (_dec$28 = ccclass$M('cc.animation.QuatVariable'), _dec$28(_class$26 = (_class2$1X = function () {
        function QuatVariable() {
          this._value = _initializer$1P && _initializer$1P();
        }
        var _proto = QuatVariable.prototype;
        _proto[createInstanceTag] = function () {
          return new VarInstanceQuat(this._value);
        };
        _createClass(QuatVariable, [{
          key: "type",
          get: function get() {
            return VariableType.QUAT_experimental;
          }
        }, {
          key: "value",
          get: function get() {
            return this._value;
          },
          set: function set(value) {
            Quat.copy(this._value, value);
          }
        }]);
        return QuatVariable;
      }(), (_initializer$1P = applyDecoratedInitializer(_class2$1X.prototype, "_value", [serializable$p], function () {
        return new Quat();
      })), _class2$1X)) || _class$26);
      var VarInstanceQuat = function (_VarInstanceBase) {
        _inheritsLoose(VarInstanceQuat, _VarInstanceBase);
        function VarInstanceQuat(value) {
          var _this;
          _this = _VarInstanceBase.call(this, VariableType.QUAT_experimental) || this;
          _this._value = new Quat();
          Quat.copy(_this._value, value);
          return _this;
        }
        var _proto2 = VarInstanceQuat.prototype;
        _proto2.getValue = function getValue() {
          return this._value;
        };
        _proto2.setValue = function setValue(value) {
          assertIsTrue(value instanceof Quat);
          Quat.copy(this._value, value);
        };
        return VarInstanceQuat;
      }(VarInstanceBase);

      function createVariable(type, initialValue) {
        var variable;
        switch (type) {
          case VariableType.FLOAT:
          case VariableType.INTEGER:
          case VariableType.BOOLEAN:
            variable = new PlainVariable(type);
            break;
          case VariableType.TRIGGER:
            variable = new TriggerVariable();
            break;
          case VariableType.VEC3_experimental:
            variable = new Vec3Variable();
            break;
          case VariableType.QUAT_experimental:
            variable = new QuatVariable();
            break;
          default:
            throw new Error("Unknown variable type " + type);
        }
        if (typeof initialValue !== 'undefined') {
          variable.value = initialValue;
        }
        return variable;
      }

      var InvalidTransitionError = function (_Error) {
        _inheritsLoose(InvalidTransitionError, _Error);
        function InvalidTransitionError(type) {
          var _this;
          _this = _Error.call(this, type + " transition is invalid") || this;
          _this.name = 'TransitionRejectError';
          return _this;
        }
        return InvalidTransitionError;
      }(_wrapNativeSuper(Error));
      var VariableNotDefinedError = function (_Error2) {
        _inheritsLoose(VariableNotDefinedError, _Error2);
        function VariableNotDefinedError(name) {
          return _Error2.call(this, "Graph variable " + name + " is not defined") || this;
        }
        return VariableNotDefinedError;
      }(_wrapNativeSuper(Error));
      var VariableTypeMismatchedError = function (_Error3) {
        _inheritsLoose(VariableTypeMismatchedError, _Error3);
        function VariableTypeMismatchedError(name, expected, received) {
          return _Error3.call(this, "Expect graph variable " + name + " to have type '" + expected + "' instead of received '" + (received !== null && received !== void 0 ? received : typeof received) + "'") || this;
        }
        return VariableTypeMismatchedError;
      }(_wrapNativeSuper(Error));

      var Destroyed = CCObject.Flags.Destroyed;
      var PersistentMask = CCObject.Flags.PersistentMask;
      var objsToClearTmpVar = [];
      function hasImplementedInstantiate(original) {
        return typeof original._instantiate === 'function';
      }
      function instantiate(original, internalForce) {
        var clone;
        if (isCCObject(original)) {
          if (hasImplementedInstantiate(original)) {
            legacyCC.game._isCloning = true;
            clone = original._instantiate(null, true);
            legacyCC.game._isCloning = false;
            return clone;
          } else if (original instanceof legacyCC.Asset) {
            throw new TypeError(getError(6903));
          }
        }
        legacyCC.game._isCloning = true;
        clone = doInstantiate(original);
        legacyCC.game._isCloning = false;
        return clone;
      }
      function doInstantiate(obj, parent) {
        var clone;
        if (obj._iN$t) {
          clone = obj._iN$t;
        } else if (obj.constructor) {
          var Klass = obj.constructor;
          clone = new Klass();
        } else {
          clone = Object.create(null);
        }
        enumerateObject(obj, clone, parent);
        for (var i = 0, len = objsToClearTmpVar.length; i < len; ++i) {
          objsToClearTmpVar[i]._iN$t = null;
        }
        objsToClearTmpVar.length = 0;
        return clone;
      }
      function enumerateCCClass(klass, obj, clone, parent) {
        var props = klass.__values__;
        for (var p = 0; p < props.length; p++) {
          var key = props[p];
          var value = obj[key];
          if (typeof value === 'object' && value) {
            var initValue = clone[key];
            if (initValue instanceof ValueType && initValue.constructor === value.constructor) {
              initValue.set(value);
            } else {
              clone[key] = value._iN$t || instantiateObj(value, parent);
            }
          } else {
            clone[key] = value;
          }
        }
      }
      function enumerateObject(obj, clone, parent) {
        value(obj, '_iN$t', clone, true);
        objsToClearTmpVar.push(obj);
        var klass = obj.constructor;
        if (isCCClassOrFastDefined(klass)) {
          enumerateCCClass(klass, obj, clone, parent);
        } else {
          for (var key in obj) {
            if (!obj.hasOwnProperty(key) || key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && key !== '__type__' && key !== '__prefab') {
              continue;
            }
            var value$1 = obj[key];
            if (typeof value$1 === 'object' && value$1) {
              if (value$1 === clone) {
                continue;
              }
              clone[key] = value$1._iN$t || instantiateObj(value$1, parent);
            } else {
              clone[key] = value$1;
            }
          }
        }
        if (isCCObject(obj)) {
          clone._objFlags &= PersistentMask;
        }
      }
      function instantiateObj(obj, parent) {
        if (obj instanceof ValueType) {
          return obj.clone();
        }
        if (obj instanceof legacyCC.Asset) {
          return obj;
        }
        var clone;
        if (ArrayBuffer.isView(obj)) {
          var len = obj.length;
          clone = new obj.constructor(len);
          obj._iN$t = clone;
          objsToClearTmpVar.push(obj);
          for (var i = 0; i < len; ++i) {
            clone[i] = obj[i];
          }
          return clone;
        }
        if (Array.isArray(obj)) {
          var _len = obj.length;
          clone = new Array(_len);
          obj._iN$t = clone;
          objsToClearTmpVar.push(obj);
          for (var _i = 0; _i < _len; ++_i) {
            var value = obj[_i];
            if (typeof value === 'object' && value) {
              clone[_i] = value._iN$t || instantiateObj(value, parent);
            } else {
              clone[_i] = value;
            }
          }
          return clone;
        } else if (obj._objFlags & Destroyed) {
          return null;
        }
        var ctor = obj.constructor;
        if (isCCClassOrFastDefined(ctor)) {
          if (parent) {
            if (parent instanceof Component) {
              if (obj instanceof Node$1 || obj instanceof Component) {
                return obj;
              }
            } else if (parent instanceof Node$1) {
              if (obj instanceof Node$1) {
                if (!obj.isChildOf(parent)) {
                  return obj;
                }
              } else if (obj instanceof Component) {
                if (obj.node && !obj.node.isChildOf(parent)) {
                  return obj;
                }
              }
            }
          }
          clone = new ctor();
        } else if (ctor === Object) {
          clone = {};
        } else if (!ctor) {
          clone = Object.create(null);
        } else {
          return obj;
        }
        enumerateObject(obj, clone, parent);
        return clone;
      }
      instantiate._clone = doInstantiate;
      legacyCC.instantiate = instantiate;

      function cloneAnimationGraphEditorExtrasFrom(object) {
        var editorExtras = object[editorExtrasTag];
        if (typeof editorExtras === 'object' && editorExtras) {
          var _maybeCloneableEditor;
          var maybeCloneableEditorExtras = editorExtras;
          return (_maybeCloneableEditor = maybeCloneableEditorExtras.clone) === null || _maybeCloneableEditor === void 0 ? void 0 : _maybeCloneableEditor.call(maybeCloneableEditorExtras, object);
        }
        return undefined;
      }

      var _dec$27, _class$25, _class2$1W, _initializer$1O, _dec2$1K, _class4$k, _class5$l, _initializer2$1z;
      var outgoingsSymbol = Symbol('[[Outgoing transitions]]');
      var incomingsSymbol = Symbol('[[Incoming transitions]]');
      var ccclass$E = ccclass$M,
        serializable$i = serializable$p;
      var State$1 = (_dec$27 = ccclass$E('cc.animation.State'), _dec$27(_class$25 = (_class2$1W = function (_EditorExtendable) {
        _inheritsLoose(State, _EditorExtendable);
        function State() {
          var _this;
          _this = _EditorExtendable.call(this) || this;
          _this.name = _initializer$1O && _initializer$1O();
          _this[outgoingsSymbol] = [];
          _this[incomingsSymbol] = [];
          return _this;
        }
        var _proto = State.prototype;
        _proto.copyTo = function copyTo(that) {
          that.name = this.name;
          that[editorExtrasTag] = cloneAnimationGraphEditorExtrasFrom(this);
        };
        return State;
      }(EditorExtendable), (_initializer$1O = applyDecoratedInitializer(_class2$1W.prototype, "name", [serializable$i], function () {
        return '';
      })), _class2$1W)) || _class$25);
      var InteractiveState = (_dec2$1K = ccclass$E(CLASS_NAME_PREFIX_ANIM + "InteractiveState"), _dec2$1K(_class4$k = (_class5$l = function (_State) {
        _inheritsLoose(InteractiveState, _State);
        function InteractiveState() {
          var _this2;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this2 = _State.call.apply(_State, [this].concat(args)) || this;
          _this2._components = _initializer2$1z && _initializer2$1z();
          return _this2;
        }
        var _proto2 = InteractiveState.prototype;
        _proto2.addComponent = function addComponent(constructor) {
          var component = new constructor();
          this._components.push(component);
          return component;
        };
        _proto2.removeComponent = function removeComponent(component) {
          remove(this._components, component);
        };
        _proto2.instantiateComponents = function instantiateComponents() {
          var instantiatedComponents = this._components.map(function (component) {
            var instantiated = instantiate(component);
            return instantiated;
          });
          return instantiatedComponents;
        };
        _proto2.copyTo = function copyTo(that) {
          _State.prototype.copyTo.call(this, that);
          that._components = this.instantiateComponents();
        };
        _createClass(InteractiveState, [{
          key: "components",
          get: function get() {
            return this._components;
          }
        }]);
        return InteractiveState;
      }(State$1), (_initializer2$1z = applyDecoratedInitializer(_class5$l.prototype, "_components", [serializable$i], function () {
        return [];
      })), _class5$l)) || _class4$k);

      function invokeComponentMethodsEngagedInAnimationEvent(node, methodName, args) {
        var components = node.components;
        var nComponents = components.length;
        for (var iComponent = 0; iComponent < nComponents; ++iComponent) {
          var component = components[iComponent];
          var fx = component[methodName];
          if (typeof fx === 'function') {
            fx.apply(component, args);
          }
        }
      }

      var _dec$26, _class$24, _class2$1V, _initializer$1N;
      var AnimationGraphEventBinding = (_dec$26 = ccclass$M(CLASS_NAME_PREFIX_ANIM + "AnimationGraphEventBinding"), _dec$26(_class$24 = (_class2$1V = function () {
        function AnimationGraphEventBinding() {
          this.methodName = _initializer$1N && _initializer$1N();
        }
        var _proto = AnimationGraphEventBinding.prototype;
        _proto.emit = function emit(origin) {
          if (!this.methodName) {
            return;
          }
          invokeComponentMethodsEngagedInAnimationEvent(origin, this.methodName, []);
        };
        _proto.copyTo = function copyTo(that) {
          that.methodName = this.methodName;
          return this;
        };
        _createClass(AnimationGraphEventBinding, [{
          key: "isBound",
          get: function get() {
            return !!this.methodName;
          }
        }]);
        return AnimationGraphEventBinding;
      }(), (_initializer$1N = applyDecoratedInitializer(_class2$1V.prototype, "methodName", [serializable$p], function () {
        return '';
      })), _class2$1V)) || _class$24);

      var _dec$25, _class$23, _class2$1U, _initializer$1M, _initializer2$1y, _initializer3$1a, _initializer4$$, _initializer5$N, _initializer6$E;
      var MotionState = (_dec$25 = ccclass$M('cc.animation.Motion'), _dec$25(_class$23 = (_class2$1U = function (_InteractiveState) {
        _inheritsLoose(MotionState, _InteractiveState);
        function MotionState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _InteractiveState.call.apply(_InteractiveState, [this].concat(args)) || this;
          _this.motion = _initializer$1M && _initializer$1M();
          _this.speed = _initializer2$1y && _initializer2$1y();
          _this.speedMultiplier = _initializer3$1a && _initializer3$1a();
          _this.speedMultiplierEnabled = _initializer4$$ && _initializer4$$();
          _this.transitionInEventBinding = _initializer5$N && _initializer5$N();
          _this.transitionOutEventBinding = _initializer6$E && _initializer6$E();
          return _this;
        }
        var _proto = MotionState.prototype;
        _proto.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          var _this$motion;
          (_this$motion = this.motion) === null || _this$motion === void 0 ? void 0 : _this$motion.__callOnAfterDeserializeRecursive();
        };
        _proto.copyTo = function copyTo(that) {
          var _this$motion$clone, _this$motion2;
          _InteractiveState.prototype.copyTo.call(this, that);
          that.motion = (_this$motion$clone = (_this$motion2 = this.motion) === null || _this$motion2 === void 0 ? void 0 : _this$motion2.clone()) !== null && _this$motion$clone !== void 0 ? _this$motion$clone : null;
          that.speed = this.speed;
          that.speedMultiplier = this.speedMultiplier;
          that.speedMultiplierEnabled = this.speedMultiplierEnabled;
          this.transitionInEventBinding.copyTo(that.transitionInEventBinding);
          this.transitionOutEventBinding.copyTo(that.transitionOutEventBinding);
          return this;
        };
        return MotionState;
      }(InteractiveState), (_initializer$1M = applyDecoratedInitializer(_class2$1U.prototype, "motion", [serializable$p], function () {
        return null;
      }), _initializer2$1y = applyDecoratedInitializer(_class2$1U.prototype, "speed", [serializable$p], function () {
        return 1.0;
      }), _initializer3$1a = applyDecoratedInitializer(_class2$1U.prototype, "speedMultiplier", [serializable$p], function () {
        return '';
      }), _initializer4$$ = applyDecoratedInitializer(_class2$1U.prototype, "speedMultiplierEnabled", [serializable$p], function () {
        return false;
      }), _initializer5$N = applyDecoratedInitializer(_class2$1U.prototype, "transitionInEventBinding", [serializable$p], function () {
        return new AnimationGraphEventBinding();
      }), _initializer6$E = applyDecoratedInitializer(_class2$1U.prototype, "transitionOutEventBinding", [serializable$p], function () {
        return new AnimationGraphEventBinding();
      })), _class2$1U)) || _class$23);

      var onAfterDeserializedTag = Symbol('[[OnAfterDeserialized]]');

      var _dec$24, _class$22;
      var AnimationGraphLike = (_dec$24 = ccclass$M(CLASS_NAME_PREFIX_ANIM + "AnimationGraphLike"), _dec$24(_class$22 = function (_Asset) {
        _inheritsLoose(AnimationGraphLike, _Asset);
        function AnimationGraphLike() {
          return _Asset.apply(this, arguments) || this;
        }
        return AnimationGraphLike;
      }(Asset)) || _class$22);

      function renameObjectProperty(object, originalPropertyKey, newPropertyKey) {
        var propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
        if (!propertyIsEnumerable.call(object, originalPropertyKey)) {
          return object;
        }
        if (newPropertyKey in object) {
          return object;
        }
        var result = {};
        if (typeof originalPropertyKey === 'symbol') {
          Object.entries(object).forEach(function (_ref) {
            var k = _ref[0],
              v = _ref[1];
            result[k] = v;
          });
          Object.getOwnPropertySymbols(object).forEach(function (k) {
            if (!propertyIsEnumerable.call(object, k)) {
              return;
            }
            result[k === originalPropertyKey ? newPropertyKey : k] = object[k];
          });
        } else {
          Object.entries(object).forEach(function (_ref2) {
            var k = _ref2[0],
              v = _ref2[1];
            result[k === originalPropertyKey ? newPropertyKey : k] = v;
          });
          Object.getOwnPropertySymbols(object).forEach(function (k) {
            if (!propertyIsEnumerable.call(object, k)) {
              return;
            }
            result[k] = object[k];
          });
        }
        return result;
      }
      var createInstanceofProxy = function () {
        var isSymbolHasInstanceAvailable = false;
        try {
          var Array1 = function (_Symbol$hasInstance) {
            function Array1() {}
            Array1[_Symbol$hasInstance] = function (instance) {
              return Array.isArray(instance);
            };
            return Array1;
          }(Symbol.hasInstance);
          isSymbolHasInstanceAvailable = [] instanceof Array1;
        } catch (_unused) {
          isSymbolHasInstanceAvailable = false;
        }
        if (!isSymbolHasInstanceAvailable) {
          return function (constructor) {
            return constructor;
          };
        }
        return function (constructor) {
          function InstanceOfProxy() {
            throw new Error("This function can not be called as a constructor.");
          }
          Object.defineProperty(InstanceOfProxy, Symbol.hasInstance, {
            value: function value(instance) {
              return instance instanceof constructor;
            }
          });
          return InstanceOfProxy;
        };
      }();

      var _dec$23, _class$21, _class2$1T, _initializer$1L, _dec2$1J, _class4$j, _class5$k, _initializer2$1x, _initializer3$19, _initializer4$_;
      var PoseGraphNodeShell = (_dec$23 = ccclass$M(CLASS_NAME_PREFIX_ANIM + "PoseGraphNodeShell"), _dec$23(_class$21 = (_class2$1T = function (_EditorExtendable) {
        _inheritsLoose(PoseGraphNodeShell, _EditorExtendable);
        function PoseGraphNodeShell() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EditorExtendable.call.apply(_EditorExtendable, [this].concat(args)) || this;
          _this._bindings = _initializer$1L && _initializer$1L();
          return _this;
        }
        var _proto = PoseGraphNodeShell.prototype;
        _proto.getBindings = function getBindings() {
          return this._bindings;
        };
        _proto.addBinding = function addBinding(inputPath, producer, outputIndex) {
          this._emplaceBinding(new PoseGraphNodeInputBinding(inputPath, producer, outputIndex));
        };
        _proto.deleteBinding = function deleteBinding(inputPath) {
          var index = this._findBindingIndex(inputPath);
          if (index >= 0) {
            this._bindings.splice(index, 1);
          }
        };
        _proto.moveArrayElementBindingForward = function moveArrayElementBindingForward(propertyKey, firstIndex, forward) {
          var bindings = this._bindings;
          var oldBindings = [];
          for (var iBinding = 0; iBinding < bindings.length; ++iBinding) {
            var binding = bindings[iBinding];
            var _binding$inputPath = binding.inputPath,
              consumerPropertyKey = _binding$inputPath[0],
              _binding$inputPath$ = _binding$inputPath[1],
              consumerElementIndex = _binding$inputPath$ === void 0 ? -1 : _binding$inputPath$;
            if (consumerPropertyKey === propertyKey && consumerElementIndex >= firstIndex) {
              oldBindings.push(binding);
              bindings.splice(iBinding, 1);
            }
          }
          for (var _i = 0, _oldBindings = oldBindings; _i < _oldBindings.length; _i++) {
            var oldBinding = _oldBindings[_i];
            var _oldBinding$inputPath = oldBinding.inputPath,
              _consumerPropertyKey = _oldBinding$inputPath[0],
              _oldBinding$inputPath2 = _oldBinding$inputPath[1],
              _consumerElementIndex = _oldBinding$inputPath2 === void 0 ? -1 : _oldBinding$inputPath2;
            this.addBinding([_consumerPropertyKey, _consumerElementIndex + (forward ? -1 : 1)], oldBinding.producer, oldBinding.outputIndex);
          }
        };
        _proto.deleteBindingTo = function deleteBindingTo(producer) {
          var bindings = this._bindings;
          for (var iBinding = 0; iBinding < bindings.length; ++iBinding) {
            var binding = bindings[iBinding];
            if (binding.producer === producer) {
              bindings.splice(iBinding, 1);
            }
          }
        };
        _proto.findBinding = function findBinding(inputPath) {
          var bindingIndex = this._findBindingIndex(inputPath);
          return bindingIndex >= 0 ? this._bindings[bindingIndex] : undefined;
        };
        _proto._findBindingIndex = function _findBindingIndex(inputPath) {
          return this._bindings.findIndex(function (searchElement) {
            return isEqualNodeInputPath(searchElement.inputPath, inputPath);
          });
        };
        _proto._emplaceBinding = function _emplaceBinding(binding) {
          var index = this._bindings.findIndex(function (searchElement) {
            return isEqualNodeInputPath(searchElement.inputPath, binding.inputPath);
          });
          if (index >= 0) {
            this._bindings[index] = binding;
          } else {
            this._bindings.push(binding);
          }
        };
        return PoseGraphNodeShell;
      }(EditorExtendable), (_initializer$1L = applyDecoratedInitializer(_class2$1T.prototype, "_bindings", [serializable$p], function () {
        return [];
      })), _class2$1T)) || _class$21);
      function isEqualNodeInputPath(lhs, rhs) {
        var lhsPropertyKey = lhs[0],
          lhsElementIndex = lhs[1];
        var rhsPropertyKey = rhs[0],
          rhsElementIndex = rhs[1];
        return lhsPropertyKey === rhsPropertyKey && lhsElementIndex === rhsElementIndex;
      }
      var PoseGraphNodeInputBinding = (_dec2$1J = ccclass$M(CLASS_NAME_PREFIX_ANIM + "PoseGraphNodeInputBinding"), _dec2$1J(_class4$j = (_class5$k = function () {
        function PoseGraphNodeInputBinding(inputPath, producer, outputIndex) {
          this._inputPath = _initializer2$1x && _initializer2$1x();
          this._producer = _initializer3$19 && _initializer3$19();
          this._outputIndex = _initializer4$_ && _initializer4$_();
          this._inputPath = inputPath;
          this._producer = producer;
          if (typeof outputIndex !== 'undefined') {
            this._outputIndex = outputIndex;
          }
        }
        _createClass(PoseGraphNodeInputBinding, [{
          key: "inputPath",
          get: function get() {
            return this._inputPath;
          }
        }, {
          key: "producer",
          get: function get() {
            return this._producer;
          }
        }, {
          key: "outputIndex",
          get: function get() {
            return this._outputIndex;
          }
        }]);
        return PoseGraphNodeInputBinding;
      }(), (_initializer2$1x = applyDecoratedInitializer(_class5$k.prototype, "_inputPath", [serializable$p], null), _initializer3$19 = applyDecoratedInitializer(_class5$k.prototype, "_producer", [serializable$p], null), _initializer4$_ = applyDecoratedInitializer(_class5$k.prototype, "_outputIndex", [serializable$p], function () {
        return 0;
      })), _class5$k)) || _class4$j);

      var AddNonFreestandingNodeError = function (_Error) {
        _inheritsLoose(AddNonFreestandingNodeError, _Error);
        function AddNonFreestandingNodeError(node) {
          return _Error.call(this, "Can not add the specified " + node.toString() + " since it has already been added into another graph.") || this;
        }
        return AddNonFreestandingNodeError;
      }(_wrapNativeSuper(Error));
      var OperationOnFreestandingNodeError = function (_Error2) {
        _inheritsLoose(OperationOnFreestandingNodeError, _Error2);
        function OperationOnFreestandingNodeError(node) {
          return _Error2.call(this, "Can not perform specified operation on " + node.toString() + " since it has not been added in to graph.") || this;
        }
        return OperationOnFreestandingNodeError;
      }(_wrapNativeSuper(Error));

      var PoseGraphType;
      (function (PoseGraphType) {
        PoseGraphType[PoseGraphType["FLOAT"] = 0] = "FLOAT";
        PoseGraphType[PoseGraphType["INTEGER"] = 1] = "INTEGER";
        PoseGraphType[PoseGraphType["BOOLEAN"] = 2] = "BOOLEAN";
        PoseGraphType[PoseGraphType["VEC3"] = 3] = "VEC3";
        PoseGraphType[PoseGraphType["QUAT"] = 4] = "QUAT";
        PoseGraphType[PoseGraphType["POSE"] = 5] = "POSE";
      })(PoseGraphType || (PoseGraphType = {}));

      var PoseGraphNode = function (_EditorExtendable) {
        _inheritsLoose(PoseGraphNode, _EditorExtendable);
        function PoseGraphNode() {
          return _EditorExtendable.apply(this, arguments) || this;
        }
        return PoseGraphNode;
      }(EditorExtendable);

      var nodeEditorMetadataMap = new WeakMap();
      function getOrCreateNodeEditorMetadata(constructor) {
        var existing = nodeEditorMetadataMap.get(constructor);
        if (existing) {
          return existing;
        } else {
          var metadata = {};
          nodeEditorMetadataMap.set(constructor, metadata);
          return metadata;
        }
      }

      function makeNodeEditorMetadataModifier(edit) {
        return function (target) {
          if (!checkDecoratingClass(target)) {
            return;
          }
          var metadata = getOrCreateNodeEditorMetadata(target);
          edit(metadata);
        };
      }
      var poseGraphNodeCategory = function poseGraphNodeCategory(category) {
        return makeNodeEditorMetadataModifier(function (metadata) {
          metadata.category = category;
        });
      };
      var poseGraphCreateNodeFactory = function poseGraphCreateNodeFactory(factory) {
        return makeNodeEditorMetadataModifier(function (metadata) {
          metadata.factory = factory;
        });
      };
      var poseGraphNodeAppearance = function poseGraphNodeAppearance(appearance) {
        return makeNodeEditorMetadataModifier(function (metadata) {
          var _metadata$appearance;
          Object.assign((_metadata$appearance = metadata.appearance) !== null && _metadata$appearance !== void 0 ? _metadata$appearance : metadata.appearance = {}, appearance);
        });
      };
      function checkDecoratingClass(fn) {
        if (!isChildClassOf(fn, PoseGraphNode)) {
          error("This kind of decorator should only be applied to pose graph node classes.");
          return false;
        }
        return true;
      }

      var _excluded = ["arraySyncGroup"];
      var PoseGraphNodeInputManager = function () {
        function PoseGraphNodeInputManager() {
          this._classInputMap = new WeakMap();
        }
        var _proto = PoseGraphNodeInputManager.prototype;
        _proto.setPropertyNodeInputRecord = function setPropertyNodeInputRecord(constructor, propertyKey, options) {
          var classInputRecord = this._classInputMap.get(constructor);
          if (!classInputRecord) {
            classInputRecord = {
              properties: {}
            };
            this._classInputMap.set(constructor, classInputRecord);
          }
          options.arraySyncGroup;
            var unchanged = _objectWithoutPropertiesLoose(options, _excluded);
          var record = unchanged;
          var arraySyncGroupName = options.arraySyncGroup;
          if (arraySyncGroupName) {
            var _classInputRecord$arr, _classInputRecord$arr2;
            if (!classInputRecord.arraySyncGroups) {
              classInputRecord.arraySyncGroups = {};
            }
            var group = (_classInputRecord$arr2 = (_classInputRecord$arr = classInputRecord.arraySyncGroups)[arraySyncGroupName]) !== null && _classInputRecord$arr2 !== void 0 ? _classInputRecord$arr2 : _classInputRecord$arr[arraySyncGroupName] = {
              members: []
            };
            if (!group.members.includes(propertyKey)) {
              group.members.push(propertyKey);
            }
            record.arraySyncGroup = group;
          }
          classInputRecord.properties[propertyKey] = Object.freeze(record);
        };
        _proto.getInputKeys = function getInputKeys(object) {
          var _this = this;
          var result = [];
          var getInputKeysRecurse = function getInputKeysRecurse(constructor) {
            if (!constructor) {
              return;
            }
            getInputKeysRecurse(getSuper(constructor));
            var record = _this._classInputMap.get(constructor);
            if (!record) {
              return;
            }
            var _loop = function _loop() {
              var _Object$entries$_i = _Object$entries[_i],
                propertyKey = _Object$entries$_i[0];
              if (result.findIndex(function (_ref) {
                var subClassPropertyKey = _ref[0];
                return propertyKey === subClassPropertyKey;
              }) >= 0) {
                return 1;
              }
              var field = object[propertyKey];
              if (Array.isArray(field)) {
                for (var iElement = 0; iElement < field.length; ++iElement) {
                  result.push([propertyKey, iElement]);
                }
              } else {
                result.push([propertyKey]);
              }
            };
            for (var _i = 0, _Object$entries = Object.entries(record.properties); _i < _Object$entries.length; _i++) {
              if (_loop()) continue;
            }
          };
          getInputKeysRecurse(object.constructor);
          return result;
        };
        _proto.isPoseInput = function isPoseInput(object, key) {
          var propertyKey = key[0];
          var propertyInputRecord = this._getPropertyNodeInputRecord(object.constructor, propertyKey);
          if (!propertyInputRecord) {
            return false;
          }
          return propertyInputRecord.type === PoseGraphType.POSE;
        };
        _proto.getInputMetadata = function getInputMetadata(object, key) {
          var propertyKey = key[0],
            _key$ = key[1],
            elementIndex = _key$ === void 0 ? -1 : _key$;
          var propertyInputRecord = this._getPropertyNodeInputRecord(object.constructor, propertyKey);
          if (!propertyInputRecord) {
            return undefined;
          }
          var field = object[propertyKey];
          if (Array.isArray(field)) {
            if (elementIndex < 0 || elementIndex >= field.length) {
              return undefined;
            } else {
              var _propertyInputRecord$, _propertyInputRecord$2;
              var displayName = (_propertyInputRecord$ = (_propertyInputRecord$2 = propertyInputRecord.getArrayElementDisplayName) === null || _propertyInputRecord$2 === void 0 ? void 0 : _propertyInputRecord$2.call(object, elementIndex)) !== null && _propertyInputRecord$ !== void 0 ? _propertyInputRecord$ : propertyInputRecord.displayName;
              return {
                type: propertyInputRecord.type,
                displayName: displayName,
                deletable: !(propertyInputRecord.arraySyncGroup && propertyInputRecord.arraySyncGroupFollower),
                insertPoint: true
              };
            }
          }
          return {
            type: propertyInputRecord.type,
            displayName: propertyInputRecord.displayName
          };
        };
        _proto.hasInput = function hasInput(object, key) {
          var propertyKey = key[0],
            _key$2 = key[1],
            elementIndex = _key$2 === void 0 ? -1 : _key$2;
          var record = this._getPropertyNodeInputRecord(object.constructor, propertyKey);
          if (!record) {
            return false;
          }
          var field = object[propertyKey];
          if (Array.isArray(field)) {
            if (elementIndex < 0 || elementIndex >= field.length) {
              return false;
            }
          }
          return true;
        };
        _proto.getInputInsertInfos = function getInputInsertInfos(object) {
          var result = {};
          for (var _constructor = object.constructor; _constructor; _constructor = getSuper(_constructor)) {
            var classInputRecord = this._classInputMap.get(_constructor);
            if (!classInputRecord) {
              continue;
            }
            for (var propertyKey in classInputRecord.properties) {
              var propertyInputRecord = classInputRecord.properties[propertyKey];
              var property = object[propertyKey];
              if (Array.isArray(property)) {
                if (propertyInputRecord.arraySyncGroup && propertyInputRecord.arraySyncGroupFollower) {
                  continue;
                }
                result[propertyKey] = {
                  displayName: propertyKey
                };
              }
            }
          }
          return result;
        };
        _proto.deleteInput = function deleteInput(graph, node, key) {
          var propertyKey = key[0],
            _key$3 = key[1],
            elementIndex = _key$3 === void 0 ? -1 : _key$3;
          var propertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, propertyKey);
          if (!propertyInputRecord) {
            return;
          }
          var property = node[propertyKey];
          if (!Array.isArray(property)) {
            return;
          }
          if (elementIndex < 0 || elementIndex >= property.length) {
            return;
          }
          {
            var arraySyncGroup = propertyInputRecord.arraySyncGroup;
            if (arraySyncGroup) {
              this._deleteInputInArraySyncGroup(graph, node, arraySyncGroup, property.length, elementIndex);
              return;
            }
          }
          deletePoseGraphNodeArrayElement(graph, node, key);
        };
        _proto.insertInput = function insertInput(graph, node, insertId) {
          var propertyKey = insertId;
          var propertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, propertyKey);
          if (!propertyInputRecord) {
            return;
          }
          var property = node[propertyKey];
          if (!Array.isArray(property)) {
            return;
          }
          var hint = property.length;
          {
            var arraySyncGroup = propertyInputRecord.arraySyncGroup;
            if (arraySyncGroup) {
              this._insertInputInArraySyncGroup(graph, node, arraySyncGroup, property.length, hint);
              return;
            }
          }
          insertPoseGraphNodeArrayElement(graph, node, [propertyKey, hint], createDefaultInputValueByType(propertyInputRecord.type));
        };
        _proto._getPropertyNodeInputRecord = function _getPropertyNodeInputRecord(constructor, propertyKey) {
          if (!constructor) {
            return undefined;
          }
          var classInputRecord = this._classInputMap.get(constructor);
          if (classInputRecord) {
            var record = classInputRecord.properties[propertyKey];
            if (record) {
              return record;
            }
          }
          return this._getPropertyNodeInputRecord(getSuper(constructor), propertyKey);
        };
        _proto._insertInputInArraySyncGroup = function _insertInputInArraySyncGroup(graph, node, syncGroup, expectedOriginalSyncLength, insertHint) {
          for (var iGroupMember = 0; iGroupMember < syncGroup.members.length; ++iGroupMember) {
            var syncedPropertyKey = syncGroup.members[iGroupMember];
            var syncedPropertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, syncedPropertyKey);
            assertIsTrue(syncedPropertyInputRecord);
            var syncedProperty = node[syncedPropertyKey];
            if (!Array.isArray(syncedProperty) || syncedProperty.length !== expectedOriginalSyncLength) {
              continue;
            }
            insertPoseGraphNodeArrayElement(graph, node, [syncedPropertyKey, insertHint], createDefaultInputValueByType(syncedPropertyInputRecord.type));
          }
        };
        _proto._deleteInputInArraySyncGroup = function _deleteInputInArraySyncGroup(graph, node, syncGroup, expectedOriginalSyncLength, index) {
          for (var iGroupMember = 0; iGroupMember < syncGroup.members.length; ++iGroupMember) {
            var syncedPropertyKey = syncGroup.members[iGroupMember];
            var syncedPropertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, syncedPropertyKey);
            assertIsTrue(syncedPropertyInputRecord);
            var syncedProperty = node[syncedPropertyKey];
            if (!Array.isArray(syncedProperty) || syncedProperty.length !== expectedOriginalSyncLength) {
              continue;
            }
            deletePoseGraphNodeArrayElement(graph, node, [syncedPropertyKey, index]);
          }
        };
        return PoseGraphNodeInputManager;
      }();
      function insertPoseGraphNodeArrayElement(graph, node, inputKey, value) {
        var shell = graph.getShell(node);
        if (!shell) {
          throw new OperationOnFreestandingNodeError(node);
        }
        var propertyKey = inputKey[0],
          _inputKey$ = inputKey[1],
          elementIndex = _inputKey$ === void 0 ? -1 : _inputKey$;
        var property = node[propertyKey];
        if (!Array.isArray(property)) {
          return;
        }
        property.splice(elementIndex, 0, value);
        shell.moveArrayElementBindingForward(propertyKey, elementIndex + 1, false);
      }
      function deletePoseGraphNodeArrayElement(graph, node, inputKey) {
        var shell = graph.getShell(node);
        if (!shell) {
          throw new OperationOnFreestandingNodeError(node);
        }
        var propertyKey = inputKey[0],
          _inputKey$2 = inputKey[1],
          elementIndex = _inputKey$2 === void 0 ? -1 : _inputKey$2;
        var property = node[propertyKey];
        if (!Array.isArray(property)) {
          return;
        }
        if (elementIndex < 0 || elementIndex >= property.length) {
          return;
        }
        shell.deleteBinding(inputKey);
        property.splice(elementIndex, 1);
        shell.moveArrayElementBindingForward(propertyKey, elementIndex + 1, true);
      }
      function createDefaultInputValueByType(type) {
        switch (type) {
          default:
            assertIsTrue(false);
          case PoseGraphType.FLOAT:
          case PoseGraphType.INTEGER:
            return 0;
          case PoseGraphType.BOOLEAN:
            return false;
          case PoseGraphType.POSE:
            return null;
          case PoseGraphType.VEC3:
            return new Vec3();
          case PoseGraphType.QUAT:
            return new Quat();
        }
      }
      var globalPoseGraphNodeInputManager = new PoseGraphNodeInputManager();

      var _class$20;
      var CACHE_VECTOR_A = new Vec3();
      var CACHE_VECTOR_B = new Vec3();
      var CACHE_QUAT_A = new Quat();
      new Quat();
      var Transform$1 = function () {
        function Transform() {
          this._position = new Vec3();
          this._rotation = new Quat();
          this._scale = Vec3.clone(Vec3.ONE);
        }
        Transform.clone = function clone(src) {
          var transform = new Transform();
          Transform.copy(transform, src);
          return transform;
        };
        Transform.setIdentity = function setIdentity(out) {
          Vec3.copy(out._position, Vec3.ZERO);
          Quat.copy(out._rotation, Quat.IDENTITY);
          Vec3.copy(out._scale, Vec3.ONE);
          return out;
        };
        Transform.copy = function copy(out, src) {
          Vec3.copy(out._position, src._position);
          Quat.copy(out._rotation, src._rotation);
          Vec3.copy(out._scale, src._scale);
          return out;
        };
        Transform.equals = function equals(a, b, epsilon) {
          return Vec3.equals(a._position, b._position, epsilon) && Quat.equals(a._rotation, b._rotation, epsilon) && Vec3.equals(a._scale, b._scale, epsilon);
        };
        Transform.strictEquals = function strictEquals(a, b) {
          return Vec3.strictEquals(a._position, b._position) && Quat.strictEquals(a._rotation, b._rotation) && Vec3.strictEquals(a._scale, b._scale);
        };
        Transform.lerp = function lerp(out, from, to, t) {
          if (t === 0.0) {
            return Transform.copy(out, from);
          }
          if (t === 1.0) {
            return Transform.copy(out, to);
          }
          Vec3.lerp(out._position, from._position, to._position, t);
          Quat.slerp(out._rotation, from._rotation, to._rotation, t);
          Vec3.lerp(out._scale, from._scale, to._scale, t);
          return out;
        };
        Transform.multiply = function multiply(out, second, first) {
          var cacheRotation = Quat.multiply(CACHE_QUAT_A, second._rotation, first._rotation);
          var cacheScale = Vec3.multiply(CACHE_VECTOR_A, first._scale, second._scale);
          var cachePosition = Vec3.multiply(CACHE_VECTOR_B, first._position, second._scale);
          Vec3.transformQuat(cachePosition, cachePosition, second._rotation);
          Vec3.add(cachePosition, cachePosition, second._position);
          Vec3.copy(out._position, cachePosition);
          Quat.copy(out._rotation, cacheRotation);
          Vec3.copy(out._scale, cacheScale);
          return out;
        };
        Transform.invert = function invert(out, transform) {
          var invRotation = out._rotation,
            invScale = out._scale,
            invPosition = out._position;
          Quat.invert(invRotation, transform._rotation);
          invScaleOrZero(invScale, transform._scale, EPSILON$3);
          Vec3.negate(invPosition, transform._position);
          Vec3.multiply(invPosition, invPosition, invScale);
          Vec3.transformQuat(invPosition, invPosition, invRotation);
          return out;
        };
        Transform.fromMatrix = function fromMatrix(out, matrix) {
          Mat4.toSRT(matrix, out._rotation, out._position, out._scale);
          return out;
        };
        Transform.toMatrix = function toMatrix(out, transform) {
          return Mat4.fromSRT(out, transform._rotation, transform._position, transform._scale);
        };
        _createClass(Transform, [{
          key: "position",
          get: function get() {
            return this._position;
          },
          set: function set(value) {
            Vec3.copy(this._position, value);
          }
        }, {
          key: "rotation",
          get: function get() {
            return this._rotation;
          },
          set: function set(value) {
            Quat.copy(this._rotation, value);
          }
        }, {
          key: "scale",
          get: function get() {
            return this._scale;
          },
          set: function set(value) {
            Vec3.copy(this._scale, value);
          }
        }]);
        return Transform;
      }();
      _class$20 = Transform$1;
      Transform$1.IDENTITY = Object.freeze(new _class$20());
      Transform$1.ZERO = Object.freeze(function () {
        var transform = new _class$20();
        Vec3.copy(transform._position, Vec3.ZERO);
        Quat.set(transform._rotation, 0.0, 0.0, 0.0, 0.0);
        Vec3.copy(transform._scale, Vec3.ZERO);
        return transform;
      }());
      Transform$1.calculateRelative = function () {
        var cacheInvRotation = new Quat();
        var cacheInvScale = new Vec3();
        return function (out, first, second) {
          var invSecondRotation = Quat.invert(cacheInvRotation, second._rotation);
          var invScale = invScaleOrZero(cacheInvScale, second._scale, EPSILON$3);
          var cachePosition = Vec3.subtract(CACHE_VECTOR_B, first._position, second._position);
          Vec3.transformQuat(cachePosition, cachePosition, invSecondRotation);
          Vec3.multiply(cachePosition, cachePosition, invScale);
          Vec3.copy(out._position, cachePosition);
          Quat.multiply(out._rotation, invSecondRotation, first._rotation);
          Vec3.multiply(out._scale, first._scale, invScale);
          return out;
        };
      }();
      function invScaleOrZero(out, scale, epsilon) {
        var x = scale.x,
          y = scale.y,
          z = scale.z;
        return Vec3.set(out, Math.abs(x) <= epsilon ? 0.0 : 1.0 / x, Math.abs(y) <= epsilon ? 0.0 : 1.0 / y, Math.abs(z) <= epsilon ? 0.0 : 1.0 / z);
      }
      function __calculateDeltaTransform(out, target, base) {
        Vec3.subtract(out.position, target.position, base.position);
        deltaQuat(out.rotation, base.rotation, target.rotation);
        Vec3.subtract(out.scale, target.scale, base.scale);
        return out;
      }
      var __applyDeltaTransform = function () {
        var cacheQuat = new Quat();
        return function (out, base, delta, alpha) {
          Vec3.scaleAndAdd(out.position, base.position, delta.position, alpha);
          var weightedDeltaRotation = Quat.slerp(cacheQuat, Quat.IDENTITY, delta.rotation, alpha);
          Quat.multiply(out.rotation, weightedDeltaRotation, base.rotation);
          Vec3.scaleAndAdd(out.scale, base.scale, delta.scale, alpha);
          return out;
        };
      }();
      var deltaQuat = function () {
        var quatMultiInvInverseCache = new Quat();
        return function (out, from, to) {
          var fromInv = Quat.invert(quatMultiInvInverseCache, from);
          return Quat.multiply(out, to, fromInv);
        };
      }();
      var ZERO_DELTA_TRANSFORM = Object.freeze(function () {
        var transform = new Transform$1();
        transform.position = Vec3.ZERO;
        transform.rotation = Quat.IDENTITY;
        transform.scale = Vec3.ZERO;
        return transform;
      }());

      var Pose = function () {
        function Pose(transforms, auxiliaryCurves) {
          this.transforms = void 0;
          this.auxiliaryCurves = void 0;
          this._poseTransformSpace = PoseTransformSpace.LOCAL;
          this.transforms = transforms;
          this.auxiliaryCurves = auxiliaryCurves;
        }
        Pose._create = function _create(transforms, auxiliaryCurves) {
          return new Pose(transforms, auxiliaryCurves);
        };
        return Pose;
      }();
      var PoseTransformSpace;
      (function (PoseTransformSpace) {
        PoseTransformSpace[PoseTransformSpace["LOCAL"] = 0] = "LOCAL";
        PoseTransformSpace[PoseTransformSpace["COMPONENT"] = 1] = "COMPONENT";
      })(PoseTransformSpace || (PoseTransformSpace = {}));
      var TransformFilter = function () {
        function TransformFilter(involvedTransforms) {
          {
            assertIsTrue(involvedTransforms.every(function (transformIndex) {
              return transformIndex < Math.pow(2, 16);
            }), 'The number of transforms exceeds the max allowed(2 ** 16)');
          }
          this._involvedTransforms = new Uint16Array(involvedTransforms);
        }
        _createClass(TransformFilter, [{
          key: "involvedTransforms",
          get: function get() {
            return this._involvedTransforms;
          }
        }]);
        return TransformFilter;
      }();
      function blendPoseInto(target, source, alpha, transformFilter) {
        if (transformFilter === void 0) {
          transformFilter = undefined;
        }
        blendTransformsInto(target.transforms, source.transforms, alpha, transformFilter);
        blendAuxiliaryCurvesInto(target.auxiliaryCurves, source.auxiliaryCurves, alpha);
      }
      function blendTransformsInto(target, source, alpha, transformFilter) {
        if (transformFilter === void 0) {
          transformFilter = undefined;
        }
        var nTransforms = target.length;
        assertIsTrue(nTransforms === target.length);
        if (alpha === 0) {
          return;
        } else if (alpha === 1) {
          if (!transformFilter) {
            target.set(source);
          } else {
            copyTransformsWithFilter(target, source, transformFilter);
          }
          return;
        }
        if (!transformFilter) {
          for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
            blendIntoTransformArrayAt(target, source, alpha, iTransform);
          }
        } else {
          for (var index = 0; index < transformFilter.involvedTransforms.length; ++index) {
            var involvedTransformIndex = transformFilter.involvedTransforms[index];
            blendIntoTransformArrayAt(target, source, alpha, involvedTransformIndex);
          }
        }
      }
      function copyTransformsWithFilter(target, source, filter) {
        var nTransforms = target.length;
        assertIsTrue(nTransforms === target.length);
        for (var index = 0; index < filter.involvedTransforms.length; ++index) {
          var involvedTransformIndex = filter.involvedTransforms[index];
          target.copyRange(involvedTransformIndex, source, involvedTransformIndex, 1);
        }
      }
      var blendIntoTransformArrayAt = function () {
        var cacheTransformSource = new Transform$1();
        var cacheTransformTarget = new Transform$1();
        return function (target, source, alpha, transformIndex) {
          var transformTarget = target.getTransform(transformIndex, cacheTransformTarget);
          var transformSource = source.getTransform(transformIndex, cacheTransformSource);
          Transform$1.lerp(transformTarget, transformTarget, transformSource, alpha);
          target.setTransform(transformIndex, transformTarget);
        };
      }();
      function blendAuxiliaryCurvesInto(target, source, alpha) {
        var nValues = source.length;
        assertIsTrue(nValues === target.length);
        for (var iValue = 0; iValue < nValues; ++iValue) {
          target[iValue] = lerp(target[iValue], source[iValue], alpha);
        }
      }
      function calculateDeltaPose(target, base) {
        calculateDeltaTransforms(target.transforms, base.transforms);
        calculateDeltaAuxiliaryCurves(target.auxiliaryCurves, base.auxiliaryCurves);
      }
      var calculateDeltaTransformArrayAt = function () {
        var cacheTransformBase = new Transform$1();
        var cacheTransformTarget = new Transform$1();
        return function (target, base, transformIndex) {
          var baseTransform = base.getTransform(transformIndex, cacheTransformBase);
          var targetTransform = target.getTransform(transformIndex, cacheTransformTarget);
          __calculateDeltaTransform(targetTransform, targetTransform, baseTransform);
          target.setTransform(transformIndex, targetTransform);
        };
      }();
      function calculateDeltaTransforms(target, base) {
        var nTransforms = target.length;
        assertIsTrue(nTransforms === base.length);
        for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
          calculateDeltaTransformArrayAt(target, base, iTransform);
        }
      }
      function calculateDeltaAuxiliaryCurves(target, base) {
        var nAuxiliaryCurves = target.length;
        assertIsTrue(nAuxiliaryCurves === base.length);
        for (var i = 0; i < target.length; ++i) {
          target[i] -= base[i];
        }
      }
      function applyDeltaPose(target, base, alpha, transformFilter) {
        if (transformFilter === void 0) {
          transformFilter = undefined;
        }
        applyDeltaTransforms(target.transforms, base.transforms, alpha, transformFilter);
        applyDeltaAuxiliaryCurves(target.auxiliaryCurves, base.auxiliaryCurves, alpha);
      }
      var applyDeltaTransformArrayAt = function () {
        var cacheTransformDelta = new Transform$1();
        var cacheTransformTarget = new Transform$1();
        return function (target, delta, alpha, transformIndex) {
          var deltaTransform = delta.getTransform(transformIndex, cacheTransformDelta);
          var targetTransform = target.getTransform(transformIndex, cacheTransformTarget);
          __applyDeltaTransform(targetTransform, targetTransform, deltaTransform, alpha);
          target.setTransform(transformIndex, targetTransform);
        };
      }();
      function applyDeltaTransforms(target, delta, alpha, transformFilter) {
        if (transformFilter === void 0) {
          transformFilter = undefined;
        }
        var nTransforms = target.length;
        assertIsTrue(nTransforms === delta.length);
        if (!transformFilter) {
          for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
            applyDeltaTransformArrayAt(target, delta, alpha, iTransform);
          }
        } else {
          for (var index = 0; index < transformFilter.involvedTransforms.length; ++index) {
            var _transformIndex = transformFilter.involvedTransforms[index];
            applyDeltaTransformArrayAt(target, delta, alpha, _transformIndex);
          }
        }
      }
      function applyDeltaAuxiliaryCurves(target, delta, alpha) {
        var nAuxiliaryCurves = target.length;
        assertIsTrue(nAuxiliaryCurves === delta.length);
        for (var i = 0; i < target.length; ++i) {
          target[i] += delta[i] * alpha;
        }
      }

      var _dec$22, _class$1$;
      var PoseTransformSpaceRequirement;
      (function (PoseTransformSpaceRequirement) {
        PoseTransformSpaceRequirement[PoseTransformSpaceRequirement["NO"] = 0] = "NO";
        PoseTransformSpaceRequirement[PoseTransformSpaceRequirement["LOCAL"] = 1] = "LOCAL";
        PoseTransformSpaceRequirement[PoseTransformSpaceRequirement["COMPONENT"] = 2] = "COMPONENT";
      })(PoseTransformSpaceRequirement || (PoseTransformSpaceRequirement = {}));
      ccenum(PoseTransformSpaceRequirement);
      var PoseNode = (_dec$22 = ccclass$M(CLASS_NAME_PREFIX_ANIM + "PoseNode"), _dec$22(_class$1$ = function (_PoseGraphNode) {
        _inheritsLoose(PoseNode, _PoseGraphNode);
        function PoseNode() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseGraphNode.call.apply(_PoseGraphNode, [this].concat(args)) || this;
          _this._dependencyEvaluation = undefined;
          return _this;
        }
        var _proto = PoseNode.prototype;
        _proto.update = function update(context) {
          var _this$_dependencyEval;
          (_this$_dependencyEval = this._dependencyEvaluation) === null || _this$_dependencyEval === void 0 ? void 0 : _this$_dependencyEval.evaluate();
          this.doUpdate(context);
        };
        _proto.evaluate = function evaluate(context, poseTransformSpaceRequirement) {
          var pose = this.doEvaluate(context);
          var currentSpace = pose._poseTransformSpace;
          switch (poseTransformSpaceRequirement) {
            default:
              assertIsTrue(false);
            case PoseTransformSpaceRequirement.NO:
              break;
            case PoseTransformSpaceRequirement.LOCAL:
              {
                if (currentSpace === PoseTransformSpace.COMPONENT) {
                  context._poseTransformsSpaceComponentToLocal(pose);
                }
                assertIsTrue(pose._poseTransformSpace === PoseTransformSpace.LOCAL);
                break;
              }
            case PoseTransformSpaceRequirement.COMPONENT:
              {
                if (currentSpace === PoseTransformSpace.LOCAL) {
                  context._poseTransformsSpaceLocalToComponent(pose);
                }
                assertIsTrue(pose._poseTransformSpace === PoseTransformSpace.COMPONENT);
                break;
              }
          }
          return pose;
        };
        PoseNode.evaluateDefaultPose = function evaluateDefaultPose(context, poseTransformSpaceRequirement) {
          switch (poseTransformSpaceRequirement) {
            default:
              assertIsTrue(false);
            case PoseTransformSpaceRequirement.NO:
            case PoseTransformSpaceRequirement.LOCAL:
              return context.pushDefaultedPose();
            case PoseTransformSpaceRequirement.COMPONENT:
              return context.pushDefaultedPoseInComponentSpace();
          }
        };
        _proto._setDependencyEvaluation = function _setDependencyEvaluation(dependency) {
          this._dependencyEvaluation = dependency;
        };
        _proto._forceEvaluateEvaluation = function _forceEvaluateEvaluation() {
          var _this$_dependencyEval2;
          (_this$_dependencyEval2 = this._dependencyEvaluation) === null || _this$_dependencyEval2 === void 0 ? void 0 : _this$_dependencyEval2.evaluate();
        };
        return PoseNode;
      }(PoseGraphNode)) || _class$1$);

      var PureValueNode = function (_PoseGraphNode) {
        _inheritsLoose(PureValueNode, _PoseGraphNode);
        function PureValueNode(outputTypes) {
          var _this;
          _this = _PoseGraphNode.call(this) || this;
          _this._outputTypes = [];
          _this._outputTypes = outputTypes;
          return _this;
        }
        var _proto = PureValueNode.prototype;
        _proto.getOutputType = function getOutputType(outputIndex) {
          return this._outputTypes[outputIndex];
        };
        _proto.link = function link(context) {};
        _createClass(PureValueNode, [{
          key: "outputCount",
          get: function get() {
            return this._outputTypes.length;
          }
        }]);
        return PureValueNode;
      }(PoseGraphNode);
      (function (_PureValueNode) {
        _inheritsLoose(SingleOutputPVNode, _PureValueNode);
        function SingleOutputPVNode(outputType) {
          return _PureValueNode.call(this, [outputType]) || this;
        }
        var _proto2 = SingleOutputPVNode.prototype;
        _proto2.selfEvaluate = function selfEvaluate(outputs) {
          outputs[0] = this.selfEvaluateDefaultOutput();
        };
        return SingleOutputPVNode;
      })(PureValueNode);

      function input(options) {
        return function (target, propertyKey) {
          var targetConstructor = target.constructor;
          if (options.type === PoseGraphType.POSE) {
            if (!isChildClassOf(targetConstructor, PoseNode)) {
              error("@input specifying pose input can be only applied to fields of subclasses of PoseNode.");
              return;
            }
          }
          if (!isChildClassOf(targetConstructor, PoseNode) && !isChildClassOf(targetConstructor, PureValueNode)) {
            error("@input can be only applied to fields of subclasses of PoseNode or PureValueNode.");
            return;
          }
          inputUnchecked(options)(target, propertyKey);
        };
      }
      function inputUnchecked(options) {
        return function (target, propertyKey) {
          if (typeof propertyKey !== 'string') {
            error("@input can be only applied to string-named fields.");
            return;
          }
          var targetConstructor = target.constructor;
          globalPoseGraphNodeInputManager.setPropertyNodeInputRecord(targetConstructor, propertyKey, options);
          var propertyStash = getOrCreatePropertyStash(target, propertyKey);
          propertyStash.__internalFlags |= PropertyStashInternalFlag.STANDALONE | PropertyStashInternalFlag.IMPLICIT_VISIBLE;
        };
      }

      var _dec$21, _dec2$1I, _dec3$1e, _class$1_, _class2$1S, _descriptor$1;
      var PoseGraphOutputNode = (_dec$21 = ccclass$M(CLASS_NAME_PREFIX_ANIM + "PoseGraphOutputNode"), _dec2$1I = poseGraphNodeAppearance({
        themeColor: '#CD3A58',
        inline: true
      }), _dec3$1e = inputUnchecked({
        type: PoseGraphType.POSE
      }), _dec$21(_class$1_ = _dec2$1I(_class$1_ = (_class2$1S = function (_PoseGraphNode) {
        _inheritsLoose(PoseGraphOutputNode, _PoseGraphNode);
        function PoseGraphOutputNode() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseGraphNode.call.apply(_PoseGraphNode, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "pose", _descriptor$1, _assertThisInitialized(_this));
          return _this;
        }
        return PoseGraphOutputNode;
      }(PoseGraphNode), (_descriptor$1 = _applyDecoratedDescriptor(_class2$1S.prototype, "pose", [serializable$p, _dec3$1e], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      })), _class2$1S)) || _class$1_) || _class$1_);

      var _dec$20, _class$1Z, _class2$1R, _initializer$1K, _initializer2$1w, _initializer3$18, _initializer4$Z;
      var PoseGraph = (_dec$20 = ccclass$M(CLASS_NAME_PREFIX_ANIM + "PoseGraph"), _dec$20(_class$1Z = (_class2$1R = function (_EditorExtendable) {
        _inheritsLoose(PoseGraph, _EditorExtendable);
        function PoseGraph() {
          var _this;
          _this = _EditorExtendable.call(this) || this;
          _this._outputNode = _initializer$1K && _initializer$1K();
          _this._nodes = _initializer2$1w && _initializer2$1w();
          _this._shells = _initializer3$18 && _initializer3$18();
          _this._shellMap = _initializer4$Z && _initializer4$Z();
          _this.addNode(_this._outputNode);
          return _this;
        }
        var _proto = PoseGraph.prototype;
        _proto.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          assertIsTrue(this._nodes.length === this._shells.length);
          for (var iNode = 0; iNode < this._nodes.length; ++iNode) {
            var _node$__callOnAfterDe;
            var node = this._nodes[iNode];
            var shell = this._shells[iNode];
            this._shellMap.set(node, shell);
            (_node$__callOnAfterDe = node.__callOnAfterDeserializeRecursive) === null || _node$__callOnAfterDe === void 0 ? void 0 : _node$__callOnAfterDe.call(node);
          }
        };
        _proto.nodes = function nodes() {
          return this._nodes.values();
        };
        _proto.addNode = function addNode(node) {
          if (this._shellMap.has(node)) {
            throw new AddNonFreestandingNodeError(node);
          }
          var shell = new PoseGraphNodeShell();
          this._shells.push(shell);
          this._nodes.push(node);
          this._shellMap.set(node, shell);
          return node;
        };
        _proto.removeNode = function removeNode(removal) {
          if (removal === this._outputNode) {
            error("Can not remove the output node.");
            return;
          }
          var nodeIndex = this._nodes.indexOf(removal);
          if (nodeIndex < 0) {
            return;
          }
          assertIsTrue(this._shellMap.has(removal));
          for (var _iterator = _createForOfIteratorHelperLoose(this._shells), _step; !(_step = _iterator()).done;) {
            var shell = _step.value;
            shell.deleteBindingTo(removal);
          }
          removeAt(this._shells, nodeIndex);
          removeAt(this._nodes, nodeIndex);
          this._shellMap["delete"](removal);
        };
        _proto.getShell = function getShell(node) {
          return this._shellMap.get(node);
        };
        _createClass(PoseGraph, [{
          key: "outputNode",
          get: function get() {
            return this._outputNode;
          }
        }]);
        return PoseGraph;
      }(EditorExtendable), (_initializer$1K = applyDecoratedInitializer(_class2$1R.prototype, "_outputNode", [serializable$p], function () {
        return new PoseGraphOutputNode();
      }), _initializer2$1w = applyDecoratedInitializer(_class2$1R.prototype, "_nodes", [serializable$p], function () {
        return [];
      }), _initializer3$18 = applyDecoratedInitializer(_class2$1R.prototype, "_shells", [serializable$p], function () {
        return [];
      }), _initializer4$Z = applyDecoratedInitializer(_class2$1R.prototype, "_shellMap", [serializable$p], function () {
        return new Map();
      })), _class2$1R)) || _class$1Z);

      var _dec$1$, _class$1Y, _class2$1Q, _initializer$1J, _initializer2$1v, _initializer3$17, _dec2$1H, _class4$i, _class5$j, _initializer4$Y, _initializer5$M, _initializer6$D, _initializer7$w, _dec3$1d, _class7$5, _class8$7, _initializer8$s, _initializer9$o, _initializer10$m, _initializer11$m, _dec4$V, _class10$2, _dec5$Q, _class11$3, _class12$3, _initializer12$k, _dec6$B, _class14$1, _class15, _initializer13$h, _initializer14$d, _initializer15$a, _dec7$s, _class17, _class18, _initializer16$a, _dec8$j, _class20$1, _class21$1, _initializer17$7, _initializer18$7, _initializer19$6, _initializer20$5, _initializer21$5, _dec9$g, _class23, _class24, _initializer22$5, _dec10$9, _class26, _class27, _initializer23$4, _dec11$6, _class29, _class30, _initializer24$4, _initializer25$4, _initializer26$4, _initializer27$3, _initializer28$3, _initializer29$3, _dec12$5, _class32, _class33, _initializer30$3, _initializer31$3;
      var Transition$1 = (_dec$1$ = ccclass$M(CLASS_NAME_PREFIX_ANIM + "Transition"), _dec$1$(_class$1Y = (_class2$1Q = function (_EditorExtendable) {
        _inheritsLoose(Transition, _EditorExtendable);
        function Transition(from, to, conditions) {
          var _this;
          _this = _EditorExtendable.call(this) || this;
          _this.from = _initializer$1J && _initializer$1J();
          _this.to = _initializer2$1v && _initializer2$1v();
          _this.conditions = _initializer3$17 && _initializer3$17();
          _this[ownerSymbol] = void 0;
          _this.from = from;
          _this.to = to;
          if (conditions) {
            _this.conditions = conditions;
          }
          return _this;
        }
        var _proto = Transition.prototype;
        _proto.copyTo = function copyTo(that) {
          that.conditions = this.conditions.map(function (condition) {
            return condition.clone();
          });
        };
        return Transition;
      }(EditorExtendable), (_initializer$1J = applyDecoratedInitializer(_class2$1Q.prototype, "from", [serializable$p], null), _initializer2$1v = applyDecoratedInitializer(_class2$1Q.prototype, "to", [serializable$p], null), _initializer3$17 = applyDecoratedInitializer(_class2$1Q.prototype, "conditions", [serializable$p], function () {
        return [];
      })), _class2$1Q)) || _class$1Y);
      var DurationalTransition = (_dec2$1H = ccclass$M(CLASS_NAME_PREFIX_ANIM + "DurationalTransition"), _dec2$1H(_class4$i = (_class5$j = function (_Transition) {
        _inheritsLoose(DurationalTransition, _Transition);
        function DurationalTransition() {
          var _this2;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this2 = _Transition.call.apply(_Transition, [this].concat(args)) || this;
          _this2.destinationStart = _initializer4$Y && _initializer4$Y();
          _this2.relativeDestinationStart = _initializer5$M && _initializer5$M();
          _this2.startEventBinding = _initializer6$D && _initializer6$D();
          _this2.endEventBinding = _initializer7$w && _initializer7$w();
          _this2[ownerSymbol] = void 0;
          return _this2;
        }
        var _proto2 = DurationalTransition.prototype;
        _proto2.copyTo = function copyTo(that) {
          _Transition.prototype.copyTo.call(this, that);
          that.destinationStart = this.destinationStart;
          that.relativeDestinationStart = this.relativeDestinationStart;
          this.startEventBinding.copyTo(that.startEventBinding);
          this.endEventBinding.copyTo(that.endEventBinding);
        };
        return DurationalTransition;
      }(Transition$1), (_initializer4$Y = applyDecoratedInitializer(_class5$j.prototype, "destinationStart", [serializable$p], function () {
        return 0.0;
      }), _initializer5$M = applyDecoratedInitializer(_class5$j.prototype, "relativeDestinationStart", [serializable$p], function () {
        return false;
      }), _initializer6$D = applyDecoratedInitializer(_class5$j.prototype, "startEventBinding", [serializable$p], function () {
        return new AnimationGraphEventBinding();
      }), _initializer7$w = applyDecoratedInitializer(_class5$j.prototype, "endEventBinding", [serializable$p], function () {
        return new AnimationGraphEventBinding();
      })), _class5$j)) || _class4$i);
      var AnimationTransition = (_dec3$1d = ccclass$M(CLASS_NAME_PREFIX_ANIM + "AnimationTransition"), _dec3$1d(_class7$5 = (_class8$7 = function (_DurationalTransition) {
        _inheritsLoose(AnimationTransition, _DurationalTransition);
        function AnimationTransition() {
          var _this3;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this3 = _DurationalTransition.call.apply(_DurationalTransition, [this].concat(args)) || this;
          _this3.duration = _initializer8$s && _initializer8$s();
          _this3.relativeDuration = _initializer9$o && _initializer9$o();
          _this3.exitConditionEnabled = _initializer10$m && _initializer10$m();
          _this3._exitCondition = _initializer11$m && _initializer11$m();
          return _this3;
        }
        var _proto3 = AnimationTransition.prototype;
        _proto3.copyTo = function copyTo(that) {
          _DurationalTransition.prototype.copyTo.call(this, that);
          that.duration = this.duration;
          that.relativeDuration = this.relativeDuration;
          that.exitConditionEnabled = this.exitConditionEnabled;
          that.exitCondition = this.exitCondition;
        };
        _createClass(AnimationTransition, [{
          key: "exitCondition",
          get: function get() {
            return this._exitCondition;
          },
          set: function set(value) {
            assertIsTrue(value >= 0.0);
            this._exitCondition = value;
          }
        }]);
        return AnimationTransition;
      }(DurationalTransition), (_initializer8$s = applyDecoratedInitializer(_class8$7.prototype, "duration", [serializable$p], function () {
        return 0.3;
      }), _initializer9$o = applyDecoratedInitializer(_class8$7.prototype, "relativeDuration", [serializable$p], function () {
        return false;
      }), _initializer10$m = applyDecoratedInitializer(_class8$7.prototype, "exitConditionEnabled", [serializable$p], function () {
        return true;
      }), _initializer11$m = applyDecoratedInitializer(_class8$7.prototype, "_exitCondition", [serializable$p], function () {
        return 1.0;
      })), _class8$7)) || _class7$5);
      function isAnimationTransition(transition) {
        return transition instanceof AnimationTransition;
      }
      var EmptyState = (_dec4$V = ccclass$M(CLASS_NAME_PREFIX_ANIM + "EmptyState"), _dec4$V(_class10$2 = function (_State) {
        _inheritsLoose(EmptyState, _State);
        function EmptyState() {
          return _State.apply(this, arguments) || this;
        }
        return EmptyState;
      }(State$1)) || _class10$2);
      var EmptyStateTransition = (_dec5$Q = ccclass$M(CLASS_NAME_PREFIX_ANIM + "EmptyStateTransition"), _dec5$Q(_class11$3 = (_class12$3 = function (_DurationalTransition2) {
        _inheritsLoose(EmptyStateTransition, _DurationalTransition2);
        function EmptyStateTransition() {
          var _this4;
          for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
            args[_key3] = arguments[_key3];
          }
          _this4 = _DurationalTransition2.call.apply(_DurationalTransition2, [this].concat(args)) || this;
          _this4.duration = _initializer12$k && _initializer12$k();
          return _this4;
        }
        var _proto4 = EmptyStateTransition.prototype;
        _proto4.copyTo = function copyTo(that) {
          _DurationalTransition2.prototype.copyTo.call(this, that);
          that.duration = this.duration;
        };
        return EmptyStateTransition;
      }(DurationalTransition), (_initializer12$k = applyDecoratedInitializer(_class12$3.prototype, "duration", [serializable$p], function () {
        return 0.3;
      })), _class12$3)) || _class11$3);
      var ProceduralPoseState = (_dec6$B = ccclass$M(CLASS_NAME_PREFIX_ANIM + "ProceduralPoseState"), _dec6$B(_class14$1 = (_class15 = function (_State2) {
        _inheritsLoose(ProceduralPoseState, _State2);
        function ProceduralPoseState() {
          var _this5;
          for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
            args[_key4] = arguments[_key4];
          }
          _this5 = _State2.call.apply(_State2, [this].concat(args)) || this;
          _this5.graph = _initializer13$h && _initializer13$h();
          _this5.transitionInEventBinding = _initializer14$d && _initializer14$d();
          _this5.transitionOutEventBinding = _initializer15$a && _initializer15$a();
          return _this5;
        }
        var _proto5 = ProceduralPoseState.prototype;
        _proto5.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          this.graph.__callOnAfterDeserializeRecursive();
        };
        _proto5.copyTo = function copyTo(that) {
          _State2.prototype.copyTo.call(this, that);
          this.transitionInEventBinding.copyTo(that.transitionInEventBinding);
          this.transitionOutEventBinding.copyTo(that.transitionOutEventBinding);
          return this;
        };
        return ProceduralPoseState;
      }(State$1), (_initializer13$h = applyDecoratedInitializer(_class15.prototype, "graph", [serializable$p], function () {
        return new PoseGraph();
      }), _initializer14$d = applyDecoratedInitializer(_class15.prototype, "transitionInEventBinding", [serializable$p], function () {
        return new AnimationGraphEventBinding();
      }), _initializer15$a = applyDecoratedInitializer(_class15.prototype, "transitionOutEventBinding", [serializable$p], function () {
        return new AnimationGraphEventBinding();
      })), _class15)) || _class14$1);
      var ProceduralPoseState_ = createInstanceofProxy(ProceduralPoseState);
      var ProceduralPoseTransition = (_dec7$s = ccclass$M(CLASS_NAME_PREFIX_ANIM + "ProceduralPoseTransition"), _dec7$s(_class17 = (_class18 = function (_DurationalTransition3) {
        _inheritsLoose(ProceduralPoseTransition, _DurationalTransition3);
        function ProceduralPoseTransition() {
          var _this6;
          for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
            args[_key5] = arguments[_key5];
          }
          _this6 = _DurationalTransition3.call.apply(_DurationalTransition3, [this].concat(args)) || this;
          _this6.duration = _initializer16$a && _initializer16$a();
          return _this6;
        }
        var _proto6 = ProceduralPoseTransition.prototype;
        _proto6.copyTo = function copyTo(that) {
          _DurationalTransition3.prototype.copyTo.call(this, that);
          that.duration = this.duration;
        };
        return ProceduralPoseTransition;
      }(DurationalTransition), (_initializer16$a = applyDecoratedInitializer(_class18.prototype, "duration", [serializable$p], function () {
        return 0.3;
      })), _class18)) || _class17);
      var ProceduralPoseTransition_ = createInstanceofProxy(ProceduralPoseTransition);
      var StateMachine = (_dec8$j = ccclass$M('cc.animation.StateMachine'), _dec8$j(_class20$1 = (_class21$1 = function (_EditorExtendable2) {
        _inheritsLoose(StateMachine, _EditorExtendable2);
        var _proto7 = StateMachine.prototype;
        _proto7.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          this[onAfterDeserializedTag]();
          var nStates = this._states.length;
          for (var iState = 0; iState < nStates; ++iState) {
            var state = this._states[iState];
            if (state instanceof SubStateMachine) {
              state.stateMachine.__callOnAfterDeserializeRecursive();
            } else if (state instanceof ProceduralPoseState) {
              state.__callOnAfterDeserializeRecursive();
            } else if (state instanceof MotionState) {
              state.__callOnAfterDeserializeRecursive();
            }
          }
        };
        function StateMachine(allowEmptyStates) {
          var _this7;
          _this7 = _EditorExtendable2.call(this) || this;
          _this7._states = _initializer17$7 && _initializer17$7();
          _this7._transitions = _initializer18$7 && _initializer18$7();
          _this7._entryState = _initializer19$6 && _initializer19$6();
          _this7._exitState = _initializer20$5 && _initializer20$5();
          _this7._anyState = _initializer21$5 && _initializer21$5();
          _this7._allowEmptyStates = true;
          _this7._allowEmptyStates = allowEmptyStates !== null && allowEmptyStates !== void 0 ? allowEmptyStates : false;
          _this7._entryState = _this7._addState(new State$1());
          _this7._entryState.name = 'Entry';
          _this7._exitState = _this7._addState(new State$1());
          _this7._exitState.name = 'Exit';
          _this7._anyState = _this7._addState(new State$1());
          _this7._anyState.name = 'Any';
          return _this7;
        }
        _proto7[onAfterDeserializedTag] = function () {
          var _this8 = this;
          this._states.forEach(function (state) {
            return own(state, _this8);
          });
          this._transitions.forEach(function (transition) {
            transition.from[outgoingsSymbol].push(transition);
            transition.to[incomingsSymbol].push(transition);
          });
        };
        _proto7.states = function states() {
          return this._states;
        };
        _proto7.transitions = function transitions() {
          return this._transitions;
        };
        _proto7.getTransitionsBetween = function getTransitionsBetween(from, to) {
          assertsOwnedBy(from, this);
          assertsOwnedBy(to, this);
          return from[outgoingsSymbol].filter(function (transition) {
            return transition.to === to;
          });
        };
        _proto7.getOutgoings = function getOutgoings(from) {
          assertsOwnedBy(from, this);
          return from[outgoingsSymbol];
        };
        _proto7.getIncomings = function getIncomings(to) {
          assertsOwnedBy(to, this);
          return to[incomingsSymbol];
        };
        _proto7.addMotion = function addMotion() {
          return this._addState(new MotionState());
        };
        _proto7.addSubStateMachine = function addSubStateMachine() {
          return this._addState(new SubStateMachine(this._allowEmptyStates));
        };
        _proto7.addEmpty = function addEmpty() {
          if (!this._allowEmptyStates) {
            throw new Error("Empty states are now allowed in this state machine.");
          }
          return this._addState(new EmptyState());
        };
        _proto7.addProceduralPoseState = function addProceduralPoseState() {
          return this._addState(new ProceduralPoseState());
        };
        _proto7.remove = function remove$1(state) {
          assertsOwnedBy(state, this);
          if (state === this.entryState || state === this.exitState || state === this.anyState) {
            return;
          }
          this.eraseTransitionsIncludes(state);
          remove(this._states, state);
          markAsDangling(state);
        };
        _proto7.connect = function connect(from, to, conditions) {
          assertsOwnedBy(from, this);
          assertsOwnedBy(to, this);
          if (to === this.entryState) {
            throw new InvalidTransitionError('to-entry');
          }
          if (to === this.anyState) {
            throw new InvalidTransitionError('to-any');
          }
          if (from === this.exitState) {
            throw new InvalidTransitionError('from-exit');
          }
          var transition = from instanceof MotionState || from === this._anyState ? new AnimationTransition(from, to, conditions) : from instanceof EmptyState ? new EmptyStateTransition(from, to, conditions) : from instanceof ProceduralPoseState ? new ProceduralPoseTransition(from, to, conditions) : new Transition$1(from, to, conditions);
          own(transition, this);
          this._transitions.push(transition);
          from[outgoingsSymbol].push(transition);
          to[incomingsSymbol].push(transition);
          return transition;
        };
        _proto7.disconnect = function disconnect(from, to) {
          assertsOwnedBy(from, this);
          assertsOwnedBy(to, this);
          var oTransitions = from[outgoingsSymbol];
          var iTransitions = to[incomingsSymbol];
          var transitions = this._transitions;
          var oTransitionsToRemove = oTransitions.filter(function (oTransition) {
            return oTransition.to === to;
          });
          var nOTransitionToRemove = oTransitionsToRemove.length;
          var _loop = function _loop() {
            var oTransition = oTransitionsToRemove[iOTransitionToRemove];
            remove(oTransitions, oTransition);
            assertIsTrue(remove(transitions, oTransition));
            assertIsNonNullable(removeIf(iTransitions, function (transition) {
              return transition === oTransition;
            }));
            markAsDangling(oTransition);
          };
          for (var iOTransitionToRemove = 0; iOTransitionToRemove < nOTransitionToRemove; ++iOTransitionToRemove) {
            _loop();
          }
        };
        _proto7.removeTransition = function removeTransition(removal) {
          assertIsTrue(remove(this._transitions, removal));
          assertIsNonNullable(removeIf(removal.from[outgoingsSymbol], function (transition) {
            return transition === removal;
          }));
          assertIsNonNullable(removeIf(removal.to[incomingsSymbol], function (transition) {
            return transition === removal;
          }));
          markAsDangling(removal);
        };
        _proto7.eraseOutgoings = function eraseOutgoings(from) {
          var _this9 = this;
          assertsOwnedBy(from, this);
          var oTransitions = from[outgoingsSymbol];
          var _loop2 = function _loop2() {
            var oTransition = oTransitions[iOTransition];
            var to = oTransition.to;
            assertIsTrue(remove(_this9._transitions, oTransition));
            assertIsNonNullable(removeIf(to[incomingsSymbol], function (transition) {
              return transition === oTransition;
            }));
            markAsDangling(oTransition);
          };
          for (var iOTransition = 0; iOTransition < oTransitions.length; ++iOTransition) {
            _loop2();
          }
          oTransitions.length = 0;
        };
        _proto7.eraseIncomings = function eraseIncomings(to) {
          var _this10 = this;
          assertsOwnedBy(to, this);
          var iTransitions = to[incomingsSymbol];
          var _loop3 = function _loop3() {
            var iTransition = iTransitions[iITransition];
            var from = iTransition.from;
            assertIsTrue(remove(_this10._transitions, iTransition));
            assertIsNonNullable(removeIf(from[outgoingsSymbol], function (transition) {
              return transition === iTransition;
            }));
            markAsDangling(iTransition);
          };
          for (var iITransition = 0; iITransition < iTransitions.length; ++iITransition) {
            _loop3();
          }
          iTransitions.length = 0;
        };
        _proto7.eraseTransitionsIncludes = function eraseTransitionsIncludes(state) {
          this.eraseIncomings(state);
          this.eraseOutgoings(state);
        };
        _proto7.adjustTransitionPriority = function adjustTransitionPriority(adjusting, diff) {
          var from = adjusting.from;
          if (diff === 0) {
            return;
          }
          var outgoings = from[outgoingsSymbol];
          var iAdjusting = outgoings.indexOf(adjusting);
          assertIsTrue(iAdjusting >= 0);
          var iNew = clamp$1(iAdjusting + diff, 0, outgoings.length - 1);
          {
            var globalTransitions = this._transitions;
            var adjustingIndexInGlobal = globalTransitions.indexOf(adjusting);
            assertIsTrue(adjustingIndexInGlobal >= 0);
            var lastPlaceholder = adjustingIndexInGlobal;
            if (iNew > iAdjusting) {
              for (var iOutgoing = iAdjusting + 1; iOutgoing <= iNew; ++iOutgoing) {
                var outgoing = outgoings[iOutgoing];
                var indexInGlobal = globalTransitions.indexOf(outgoing);
                assertIsTrue(indexInGlobal >= 0);
                globalTransitions[lastPlaceholder] = outgoing;
                lastPlaceholder = indexInGlobal;
              }
            } else if (iAdjusting > iNew) {
              for (var _iOutgoing = iAdjusting - 1; _iOutgoing >= iNew; --_iOutgoing) {
                var _outgoing = outgoings[_iOutgoing];
                var _indexInGlobal = globalTransitions.indexOf(_outgoing);
                assertIsTrue(_indexInGlobal >= 0);
                globalTransitions[lastPlaceholder] = _outgoing;
                lastPlaceholder = _indexInGlobal;
              }
            }
            globalTransitions[lastPlaceholder] = adjusting;
          }
          {
            shift(outgoings, iAdjusting, iNew);
          }
        };
        _proto7.copyTo = function copyTo(that) {
          var thatStatesOld = that._states.filter(function (state) {
            switch (state) {
              case that._entryState:
              case that._exitState:
              case that._anyState:
                return true;
              default:
                return false;
            }
          });
          for (var _iterator = _createForOfIteratorHelperLoose(thatStatesOld), _step; !(_step = _iterator()).done;) {
            var thatStateOld = _step.value;
            that.remove(thatStateOld);
          }
          var stateMap = new Map();
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._states), _step2; !(_step2 = _iterator2()).done;) {
            var state = _step2.value;
            switch (state) {
              case this._entryState:
                stateMap.set(state, that._entryState);
                break;
              case this._exitState:
                stateMap.set(state, that._exitState);
                break;
              case this._anyState:
                stateMap.set(state, that._anyState);
                break;
              default:
                if (state instanceof MotionState || state instanceof SubStateMachine || state instanceof EmptyState || state instanceof ProceduralPoseState) {
                  if (state instanceof EmptyState && !that._allowEmptyStates) {
                    continue;
                  }
                  var thatState = instantiate(state);
                  that._addState(thatState);
                  stateMap.set(state, thatState);
                } else {
                  assertIsTrue(false);
                }
                break;
            }
          }
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._transitions), _step3; !(_step3 = _iterator3()).done;) {
            var transition = _step3.value;
            if (!that._allowEmptyStates) {
              if (transition.from instanceof EmptyState || transition.to instanceof EmptyState) {
                continue;
              }
            }
            var thatFrom = stateMap.get(transition.from);
            var thatTo = stateMap.get(transition.to);
            assertIsTrue(thatFrom && thatTo);
            var thatTransition = that.connect(thatFrom, thatTo);
            thatTransition.conditions = transition.conditions.map(function (condition) {
              return condition.clone();
            });
            if (thatTransition instanceof AnimationTransition) {
              assertIsTrue(transition instanceof AnimationTransition);
              transition.copyTo(thatTransition);
            } else if (thatTransition instanceof EmptyStateTransition) {
              assertIsTrue(transition instanceof EmptyStateTransition);
              transition.copyTo(thatTransition);
            } else if (thatTransition instanceof ProceduralPoseState) {
              assertIsTrue(transition instanceof ProceduralPoseState);
              transition.copyTo(thatTransition);
            } else {
              transition.copyTo(thatTransition);
            }
          }
        };
        _proto7.clone = function clone() {
          var that = new StateMachine(this._allowEmptyStates);
          this.copyTo(that);
          return that;
        };
        _proto7._addState = function _addState(state) {
          own(state, this);
          this._states.push(state);
          return state;
        };
        _createClass(StateMachine, [{
          key: "allowEmptyStates",
          get: function get() {
            return this._allowEmptyStates;
          }
        }, {
          key: "entryState",
          get: function get() {
            return this._entryState;
          }
        }, {
          key: "exitState",
          get: function get() {
            return this._exitState;
          }
        }, {
          key: "anyState",
          get: function get() {
            return this._anyState;
          }
        }]);
        return StateMachine;
      }(EditorExtendable), (_initializer17$7 = applyDecoratedInitializer(_class21$1.prototype, "_states", [serializable$p], function () {
        return [];
      }), _initializer18$7 = applyDecoratedInitializer(_class21$1.prototype, "_transitions", [serializable$p], function () {
        return [];
      }), _initializer19$6 = applyDecoratedInitializer(_class21$1.prototype, "_entryState", [serializable$p], null), _initializer20$5 = applyDecoratedInitializer(_class21$1.prototype, "_exitState", [serializable$p], null), _initializer21$5 = applyDecoratedInitializer(_class21$1.prototype, "_anyState", [serializable$p], null)), _class21$1)) || _class20$1);
      var SubStateMachine = (_dec9$g = ccclass$M('cc.animation.SubStateMachine'), _dec9$g(_class23 = (_class24 = function (_InteractiveState) {
        _inheritsLoose(SubStateMachine, _InteractiveState);
        function SubStateMachine(allowEmptyStates) {
          var _this11;
          _this11 = _InteractiveState.call(this) || this;
          _this11._stateMachine = _initializer22$5 && _initializer22$5();
          _this11._stateMachine = new StateMachine(allowEmptyStates);
          return _this11;
        }
        var _proto8 = SubStateMachine.prototype;
        _proto8.copyTo = function copyTo(that) {
          _InteractiveState.prototype.copyTo.call(this, that);
          this._stateMachine.copyTo(that._stateMachine);
        };
        _createClass(SubStateMachine, [{
          key: "stateMachine",
          get: function get() {
            return this._stateMachine;
          }
        }]);
        return SubStateMachine;
      }(InteractiveState), (_initializer22$5 = applyDecoratedInitializer(_class24.prototype, "_stateMachine", [serializable$p], null)), _class24)) || _class23);
      var PoseGraphStash = (_dec10$9 = ccclass$M(CLASS_NAME_PREFIX_ANIM + "PoseGraphStash"), _dec10$9(_class26 = (_class27 = function (_EditorExtendable3) {
        _inheritsLoose(PoseGraphStash, _EditorExtendable3);
        function PoseGraphStash() {
          var _this12;
          for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
            args[_key6] = arguments[_key6];
          }
          _this12 = _EditorExtendable3.call.apply(_EditorExtendable3, [this].concat(args)) || this;
          _this12.graph = _initializer23$4 && _initializer23$4();
          return _this12;
        }
        return PoseGraphStash;
      }(EditorExtendable), (_initializer23$4 = applyDecoratedInitializer(_class27.prototype, "graph", [serializable$p], function () {
        return new PoseGraph();
      })), _class27)) || _class26);
      var Layer = (_dec11$6 = ccclass$M('cc.animation.Layer'), _dec11$6(_class29 = (_class30 = function () {
        var _proto9 = Layer.prototype;
        _proto9.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          this.stateMachine._allowEmptyStates = true;
          this.stateMachine.__callOnAfterDeserializeRecursive();
          for (var stashId in this._stashes) {
            var stash = this._stashes[stashId];
            stash.graph.__callOnAfterDeserializeRecursive();
          }
        };
        _proto9.stashes = function stashes() {
          return Object.entries(this._stashes);
        };
        _proto9.getStash = function getStash(id) {
          return this._stashes[id];
        };
        _proto9.addStash = function addStash(id) {
          return this._stashes[id] = new PoseGraphStash();
        };
        _proto9.removeStash = function removeStash(id) {
          delete this._stashes[id];
        };
        _proto9.renameStash = function renameStash(id, newId) {
          this._stashes = renameObjectProperty(this._stashes, id, newId);
        };
        function Layer() {
          this[ownerSymbol] = void 0;
          this._stateMachine = _initializer24$4 && _initializer24$4();
          this.name = _initializer25$4 && _initializer25$4();
          this.weight = _initializer26$4 && _initializer26$4();
          this.mask = _initializer27$3 && _initializer27$3();
          this.additive = _initializer28$3 && _initializer28$3();
          this._stashes = _initializer29$3 && _initializer29$3();
          this._stateMachine = new StateMachine(true);
        }
        _createClass(Layer, [{
          key: "stateMachine",
          get: function get() {
            return this._stateMachine;
          }
        }]);
        return Layer;
      }(), (_initializer24$4 = applyDecoratedInitializer(_class30.prototype, "_stateMachine", [serializable$p], null), _initializer25$4 = applyDecoratedInitializer(_class30.prototype, "name", [serializable$p], function () {
        return '';
      }), _initializer26$4 = applyDecoratedInitializer(_class30.prototype, "weight", [serializable$p], function () {
        return 1.0;
      }), _initializer27$3 = applyDecoratedInitializer(_class30.prototype, "mask", [serializable$p], function () {
        return null;
      }), _initializer28$3 = applyDecoratedInitializer(_class30.prototype, "additive", [serializable$p], function () {
        return false;
      }), _initializer29$3 = applyDecoratedInitializer(_class30.prototype, "_stashes", [serializable$p], function () {
        return {};
      })), _class30)) || _class29);
      var LayerBlending;
      (function (LayerBlending) {
        LayerBlending[LayerBlending["override"] = 0] = "override";
        LayerBlending[LayerBlending["additive"] = 1] = "additive";
      })(LayerBlending || (LayerBlending = {}));
      var AnimationGraph = (_dec12$5 = ccclass$M('cc.animation.AnimationGraph'), _dec12$5(_class32 = (_class33 = function (_AnimationGraphLike) {
        _inheritsLoose(AnimationGraph, _AnimationGraphLike);
        function AnimationGraph() {
          var _this13;
          _this13 = _AnimationGraphLike.call(this) || this;
          _this13._layers = _initializer30$3 && _initializer30$3();
          _this13._variables = _initializer31$3 && _initializer31$3();
          return _this13;
        }
        var _proto10 = AnimationGraph.prototype;
        _proto10.onLoaded = function onLoaded() {
          var layers = this._layers;
          var nLayers = layers.length;
          for (var iLayer = 0; iLayer < nLayers; ++iLayer) {
            layers[iLayer].__callOnAfterDeserializeRecursive();
          }
        };
        _proto10.addLayer = function addLayer() {
          var layer = new Layer();
          this._layers.push(layer);
          return layer;
        };
        _proto10.removeLayer = function removeLayer(index) {
          removeAt(this._layers, index);
        };
        _proto10.moveLayer = function moveLayer(index, newIndex) {
          shift(this._layers, index, newIndex);
        };
        _proto10.addVariable = function addVariable(name, type, initialValue) {
          var variable = createVariable(type, initialValue);
          this._variables[name] = variable;
          return variable;
        };
        _proto10.removeVariable = function removeVariable(name) {
          delete this._variables[name];
        };
        _proto10.getVariable = function getVariable(name) {
          return this._variables[name];
        };
        _proto10.renameVariable = function renameVariable(name, newName) {
          this._variables = renameObjectProperty(this._variables, name, newName);
        };
        _createClass(AnimationGraph, [{
          key: "layers",
          get: function get() {
            return this._layers;
          }
        }, {
          key: "variables",
          get: function get() {
            return Object.entries(this._variables);
          }
        }]);
        return AnimationGraph;
      }(AnimationGraphLike), (_initializer30$3 = applyDecoratedInitializer(_class33.prototype, "_layers", [serializable$p], function () {
        return [];
      }), _initializer31$3 = applyDecoratedInitializer(_class33.prototype, "_variables", [serializable$p], function () {
        return {};
      })), _class33)) || _class32);

      var createEval = Symbol('[[createEval]]');

      var _dec$1_, _class$1X;
      var Motion = (_dec$1_ = ccclass$M(CLASS_NAME_PREFIX_ANIM + "MotionBase"), _dec$1_(_class$1X = function (_EditorExtendable) {
        _inheritsLoose(Motion, _EditorExtendable);
        function Motion() {
          return _EditorExtendable.apply(this, arguments) || this;
        }
        var _proto = Motion.prototype;
        _proto.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {};
        return Motion;
      }(EditorExtendable)) || _class$1X);

      var RatioSampler = exports('au', function () {
        function RatioSampler(ratios) {
          this.ratios = void 0;
          this._findRatio = void 0;
          this.ratios = ratios;
          var currRatioDif;
          var lastRatioDif;
          var canOptimize = true;
          var EPSILON = 1e-6;
          for (var i = 1, l = ratios.length; i < l; i++) {
            currRatioDif = ratios[i] - ratios[i - 1];
            if (i === 1) {
              lastRatioDif = currRatioDif;
            } else if (Math.abs(currRatioDif - lastRatioDif) > EPSILON) {
              canOptimize = false;
              break;
            }
          }
          this._findRatio = canOptimize ? quickFindIndex : binarySearchEpsilon;
        }
        var _proto = RatioSampler.prototype;
        _proto.sample = function sample(ratio) {
          return this._findRatio(this.ratios, ratio);
        };
        return RatioSampler;
      }());
      legacyCC.RatioSampler = RatioSampler;
      var AnimCurve = exports('av', function () {
        AnimCurve.Bezier = function Bezier(controlPoints) {
          return controlPoints;
        };
        function AnimCurve(propertyCurveData, duration) {
          this.types = undefined;
          this.type = null;
          this._values = [];
          this._lerp = undefined;
          this._duration = void 0;
          this._array = void 0;
          this._duration = duration;
          this._values = propertyCurveData.values;
          var getCurveType = function getCurveType(easingMethod) {
            if (typeof easingMethod === 'string') {
              return easingMethod;
            } else if (Array.isArray(easingMethod)) {
              if (easingMethod[0] === easingMethod[1] && easingMethod[2] === easingMethod[3]) {
                return AnimCurve.Linear;
              } else {
                return AnimCurve.Bezier(easingMethod);
              }
            } else {
              return AnimCurve.Linear;
            }
          };
          if (propertyCurveData.easingMethod !== undefined) {
            this.type = getCurveType(propertyCurveData.easingMethod);
          } else if (Array.isArray(propertyCurveData.easingMethods)) {
            this.types = propertyCurveData.easingMethods.map(getCurveType);
          } else if (propertyCurveData.easingMethods !== undefined) {
            this.types = new Array(this._values.length).fill(null);
            for (var _i = 0, _Object$keys = Object.keys(propertyCurveData.easingMethods); _i < _Object$keys.length; _i++) {
              var index = _Object$keys[_i];
              this.types[index] = getCurveType(propertyCurveData.easingMethods[index]);
            }
          } else {
            this.type = null;
          }
          var firstValue = propertyCurveData.values[0];
          var interpolate = propertyCurveData.interpolate === undefined ? true : propertyCurveData.interpolate;
          if (interpolate) {
            this._lerp = selectLerpFx(firstValue);
          }
          if (propertyCurveData._arrayLength !== undefined) {
            this._array = new Array(propertyCurveData._arrayLength);
          }
        }
        var _proto2 = AnimCurve.prototype;
        _proto2.hasLerp = function hasLerp() {
          return !!this._lerp;
        };
        _proto2.valueAt = function valueAt(index) {
          if (this._array === undefined) {
            var _value = this._values[index];
            if (_value && _value.getNoLerp) {
              return _value.getNoLerp();
            } else {
              return _value;
            }
          } else {
            for (var i = 0; i < this._array.length; ++i) {
              this._array[i] = this._values[this._array.length * index + i];
            }
            return this._array;
          }
        };
        _proto2.valueBetween = function valueBetween(ratio, from, fromRatio, to, toRatio) {
          if (this._lerp) {
            var type = this.types ? this.types[from] : this.type;
            var dRatio = toRatio - fromRatio;
            var ratioBetweenFrames = (ratio - fromRatio) / dRatio;
            if (type) {
              ratioBetweenFrames = computeRatioByType(ratioBetweenFrames, type);
            }
            if (this._array === undefined) {
              var fromVal = this._values[from];
              var toVal = this._values[to];
              var _value2 = this._lerp(fromVal, toVal, ratioBetweenFrames, dRatio * this._duration);
              return _value2;
            } else {
              for (var i = 0; i < this._array.length; ++i) {
                var _fromVal = this._values[this._array.length * from + i];
                var _toVal = this._values[this._array.length * to + i];
                this._array[i] = this._lerp(_fromVal, _toVal, ratioBetweenFrames, dRatio * this._duration);
              }
              return this._array;
            }
          } else if (this._array === undefined) {
            return this.valueAt(from);
          } else {
            for (var _i2 = 0; _i2 < this._array.length; ++_i2) {
              this._array[_i2] = this._values[this._array.length * from + _i2];
            }
            return this._array;
          }
        };
        _proto2.empty = function empty() {
          return this._values.length === 0;
        };
        _proto2.constant = function constant() {
          return this._values.length === 1;
        };
        return AnimCurve;
      }());
      AnimCurve.Linear = null;
      legacyCC.AnimCurve = AnimCurve;
      var EventInfo = exports('aw', function () {
        function EventInfo() {
          this.events = [];
        }
        var _proto3 = EventInfo.prototype;
        _proto3.add = function add(func, params) {
          this.events.push({
            func: func || '',
            params: params || []
          });
        };
        return EventInfo;
      }());
      function sampleAnimationCurve(curve, sampler, ratio) {
        var index = sampler.sample(ratio);
        if (index < 0) {
          index = ~index;
          if (index <= 0) {
            index = 0;
          } else if (index >= sampler.ratios.length) {
            index = sampler.ratios.length - 1;
          } else {
            return curve.valueBetween(ratio, index - 1, sampler.ratios[index - 1], index, sampler.ratios[index]);
          }
        }
        return curve.valueAt(index);
      }
      legacyCC.sampleAnimationCurve = sampleAnimationCurve;
      function computeRatioByType(ratio, type) {
        if (typeof type === 'string') {
          var func = easing[type];
          if (func) {
            ratio = func(ratio);
          } else {
            errorID(3906, type);
          }
        } else if (Array.isArray(type)) {
          ratio = bezierByTime(type, ratio);
        }
        return ratio;
      }
      function quickFindIndex(ratios, ratio) {
        var length = ratios.length - 1;
        if (length === 0) {
          return 0;
        }
        var start = ratios[0];
        if (ratio < start) {
          return 0;
        }
        var end = ratios[length];
        if (ratio > end) {
          return length;
        }
        ratio = (ratio - start) / (end - start);
        var eachLength = 1 / length;
        var index = ratio / eachLength;
        var floorIndex = index | 0;
        var EPSILON = 1e-6;
        if (index - floorIndex < EPSILON) {
          return floorIndex;
        } else if (floorIndex + 1 - index < EPSILON) {
          return floorIndex + 1;
        }
        return ~(floorIndex + 1);
      }
      var selectLerpFx = function () {
        function makeValueTypeLerpFx(constructor) {
          var tempValue = new constructor();
          return function (from, to, ratio) {
            constructor.lerp(tempValue, from, to, ratio);
            return tempValue;
          };
        }
        function callLerpable(from, to, t, dt) {
          return from.lerp(to, t, dt);
        }
        function makeQuatSlerpFx() {
          var tempValue = new Quat();
          return function (from, to, t, dt) {
            return Quat.slerp(tempValue, from, to, t);
          };
        }
        return function (value) {
          if (value === null) {
            return undefined;
          }
          if (typeof value === 'number') {
            return lerp;
          } else if (typeof value === 'object' && value.constructor) {
            if (value instanceof Quat) {
              return makeQuatSlerpFx();
            } else if (value instanceof ValueType) {
              return makeValueTypeLerpFx(value.constructor);
            } else if (value.constructor === Number) {
              return lerp;
            } else if (isLerpable(value)) {
              return callLerpable;
            }
          }
          return undefined;
        };
      }();

      var _dec$1Z, _class$1W, _class2$1P, _initializer$1I, _dec2$1G, _class4$h, _class5$i, _initializer2$1u;
      var UntypedTrackChannel = (_dec$1Z = ccclass$M(CLASS_NAME_PREFIX_ANIM + "UntypedTrackChannel"), _dec$1Z(_class$1W = (_class2$1P = function (_Channel) {
        _inheritsLoose(UntypedTrackChannel, _Channel);
        function UntypedTrackChannel() {
          var _this;
          _this = _Channel.call(this, new RealCurve()) || this;
          _this.property = _initializer$1I && _initializer$1I();
          return _this;
        }
        return UntypedTrackChannel;
      }(Channel), (_initializer$1I = applyDecoratedInitializer(_class2$1P.prototype, "property", [serializable$p], function () {
        return '';
      })), _class2$1P)) || _class$1W);
      var UntypedTrack = (_dec2$1G = ccclass$M(CLASS_NAME_PREFIX_ANIM + "UntypedTrack"), _dec2$1G(_class4$h = (_class5$i = function (_Track) {
        _inheritsLoose(UntypedTrack, _Track);
        function UntypedTrack() {
          var _this2;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this2 = _Track.call.apply(_Track, [this].concat(args)) || this;
          _this2._channels = _initializer2$1u && _initializer2$1u();
          return _this2;
        }
        var _proto = UntypedTrack.prototype;
        _proto.channels = function channels() {
          return this._channels;
        };
        _proto[createEvalSymbol] = function () {
          throw new Error("UntypedTrack should be handled specially. Please file an issue.");
        };
        _proto.createLegacyEval = function createLegacyEval(hintValue) {
          var _this3 = this;
          var trySearchCurve = function trySearchCurve(property) {
            var _this3$_channels$find;
            return (_this3$_channels$find = _this3._channels.find(function (channel) {
              return channel.property === property;
            })) === null || _this3$_channels$find === void 0 ? void 0 : _this3$_channels$find.curve;
          };
          switch (true) {
            default:
              throw new Error(getError(3931));
            case hintValue instanceof Vec2:
              return new Vec2TrackEval(trySearchCurve('x'), trySearchCurve('y'));
            case hintValue instanceof Vec3:
              return new Vec3TrackEval(trySearchCurve('x'), trySearchCurve('y'), trySearchCurve('z'));
            case hintValue instanceof Vec4:
              return new Vec4TrackEval(trySearchCurve('x'), trySearchCurve('y'), trySearchCurve('z'), trySearchCurve('w'));
            case hintValue instanceof Color$1:
              return new ColorTrackEval(trySearchCurve('r'), trySearchCurve('g'), trySearchCurve('b'), trySearchCurve('a'));
            case hintValue instanceof Size$1:
              return new SizeTrackEval(trySearchCurve('width'), trySearchCurve('height'));
          }
        };
        _proto.addChannel = function addChannel(property) {
          var channel = new UntypedTrackChannel();
          channel.property = property;
          this._channels.push(channel);
          return channel;
        };
        _proto.upgrade = function upgrade(refine) {
          var _this4 = this;
          var trySearchChannel = function trySearchChannel(property, outChannel) {
            var untypedChannel = _this4.channels().find(function (channel) {
              return channel.property === property;
            });
            if (untypedChannel) {
              outChannel.name = untypedChannel.name;
              outChannel.curve.assignSorted(Array.from(untypedChannel.curve.times()), Array.from(untypedChannel.curve.values()));
            }
          };
          var kind = refine(this.path, this.proxy);
          switch (kind) {
            default:
              break;
            case 'vec2':
            case 'vec3':
            case 'vec4':
              {
                var track = new VectorTrack();
                track.path = this.path;
                track.proxy = this.proxy;
                track.componentsCount = kind === 'vec2' ? 2 : kind === 'vec3' ? 3 : 4;
                var _track$channels = track.channels(),
                  x = _track$channels[0],
                  y = _track$channels[1],
                  z = _track$channels[2],
                  w = _track$channels[3];
                switch (kind) {
                  case 'vec4':
                    trySearchChannel('w', w);
                  case 'vec3':
                    trySearchChannel('z', z);
                  default:
                  case 'vec2':
                    trySearchChannel('x', x);
                    trySearchChannel('y', y);
                }
                return track;
              }
            case 'color':
              {
                var _track = new ColorTrack();
                var _track$channels2 = _track.channels(),
                  r = _track$channels2[0],
                  g = _track$channels2[1],
                  b = _track$channels2[2],
                  a = _track$channels2[3];
                trySearchChannel('r', r);
                trySearchChannel('g', g);
                trySearchChannel('b', b);
                trySearchChannel('a', a);
                trySearchChannel('x', r);
                trySearchChannel('y', g);
                trySearchChannel('z', b);
                trySearchChannel('w', a);
                return _track;
              }
            case 'size':
              break;
          }
          return null;
        };
        return UntypedTrack;
      }(Track), (_initializer2$1u = applyDecoratedInitializer(_class5$i.prototype, "_channels", [serializable$p], function () {
        return [];
      })), _class5$i)) || _class4$h);

      var AnimationClipLegacyData = function () {
        function AnimationClipLegacyData(duration) {
          this._keys = [];
          this._curves = [];
          this._commonTargets = [];
          this._ratioSamplers = [];
          this._runtimeCurves = void 0;
          this._data = null;
          this._duration = void 0;
          this._duration = duration;
        }
        var _proto = AnimationClipLegacyData.prototype;
        _proto.getPropertyCurves = function getPropertyCurves() {
          if (!this._runtimeCurves) {
            this._createPropertyCurves();
          }
          return this._runtimeCurves;
        };
        _proto.toTracks = function toTracks() {
          var newTracks = [];
          var legacyKeys = this.keys,
            legacyCurves = this.curves,
            legacyCommonTargets = this.commonTargets;
          var convertTrackPath = function convertTrackPath(track, modifiers, valueAdapter) {
            var trackPath = new TrackPath();
            for (var _iterator = _createForOfIteratorHelperLoose(modifiers), _step; !(_step = _iterator()).done;) {
              var modifier = _step.value;
              if (typeof modifier === 'string') {
                trackPath.toProperty(modifier);
              } else if (typeof modifier === 'number') {
                trackPath.toElement(modifier);
              } else if (modifier instanceof HierarchyPath) {
                trackPath.toHierarchy(modifier.path);
              } else if (modifier instanceof ComponentPath) {
                trackPath.toComponent(modifier.component);
              } else {
                trackPath.toCustomized(modifier);
              }
            }
            track.path = trackPath;
            track.proxy = valueAdapter;
          };
          var untypedTracks = legacyCommonTargets.map(function (legacyCommonTarget) {
            var track = new UntypedTrack();
            convertTrackPath(track, legacyCommonTarget.modifiers, legacyCommonTarget.valueAdapter);
            newTracks.push(track);
            return track;
          });
          var _loop = function _loop() {
              var _legacyCurveData$inte;
              var legacyCurve = _step2.value;
              var legacyCurveData = legacyCurve.data;
              var legacyValues = legacyCurveData.values;
              if (legacyValues.length === 0) {
                return 0;
              }
              var legacyKeysIndex = legacyCurveData.keys;
              var times = legacyKeysIndex < 0 ? [0.0] : legacyKeys[legacyCurveData.keys];
              var firstValue = legacyValues[0];
              var interpolate = (_legacyCurveData$inte = legacyCurveData.interpolate) !== null && _legacyCurveData$inte !== void 0 ? _legacyCurveData$inte : true;
              assertIsTrue(typeof legacyCurveData._arrayLength !== 'number' || typeof firstValue === 'number');
              var legacyEasingMethodConverter = new LegacyEasingMethodConverter(legacyCurveData, times.length);
              var installPathAndSetter = function installPathAndSetter(track) {
                convertTrackPath(track, legacyCurve.modifiers, legacyCurve.valueAdapter);
              };
              var legacyCommonTargetCurve;
              if (typeof legacyCurve.commonTarget === 'number') {
                if (!legacyValues.every(function (value) {
                  return typeof value === 'number';
                })) {
                  warnID(3932);
                  return 0;
                }
                if (legacyCurve.valueAdapter || legacyCurve.modifiers.length !== 1 || typeof legacyCurve.modifiers[0] !== 'string') {
                  warnID(3933);
                  return 0;
                }
                var _propertyName = legacyCurve.modifiers[0];
                var untypedTrack = untypedTracks[legacyCurve.commonTarget];
                var _untypedTrack$addChan = untypedTrack.addChannel(_propertyName),
                  curve = _untypedTrack$addChan.curve;
                legacyCommonTargetCurve = curve;
              }
              var convertCurve = function convertCurve() {
                if (typeof firstValue === 'number') {
                  if (!legacyValues.every(function (value) {
                    return typeof value === 'number';
                  })) {
                    warnID(3934);
                    return;
                  }
                  var realCurve;
                  if (legacyCommonTargetCurve) {
                    realCurve = legacyCommonTargetCurve;
                  } else {
                    var track = new RealTrack();
                    installPathAndSetter(track);
                    newTracks.push(track);
                    realCurve = track.channel.curve;
                  }
                  var interpolationMethod = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
                  realCurve.assignSorted(times, legacyValues.map(function (value) {
                    return {
                      value: value,
                      interpolationMode: interpolationMethod
                    };
                  }));
                  legacyEasingMethodConverter.convert(realCurve);
                  return;
                } else if (typeof firstValue === 'object') {
                  switch (true) {
                    default:
                      break;
                    case everyInstanceOf(legacyValues, Vec2):
                    case everyInstanceOf(legacyValues, Vec3):
                    case everyInstanceOf(legacyValues, Vec4):
                      {
                        var components = firstValue instanceof Vec2 ? 2 : firstValue instanceof Vec3 ? 3 : 4;
                        var _track = new VectorTrack();
                        installPathAndSetter(_track);
                        _track.componentsCount = components;
                        var _track$channels = _track.channels(),
                          x = _track$channels[0].curve,
                          y = _track$channels[1].curve,
                          z = _track$channels[2].curve,
                          w = _track$channels[3].curve;
                        var interpolationMode = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
                        var valueToFrame = function valueToFrame(value) {
                          return {
                            value: value,
                            interpolationMode: interpolationMode
                          };
                        };
                        switch (components) {
                          case 4:
                            w.assignSorted(times, legacyValues.map(function (value) {
                              return valueToFrame(value.w);
                            }));
                            legacyEasingMethodConverter.convert(w);
                          case 3:
                            z.assignSorted(times, legacyValues.map(function (value) {
                              return valueToFrame(value.z);
                            }));
                            legacyEasingMethodConverter.convert(z);
                          default:
                            x.assignSorted(times, legacyValues.map(function (value) {
                              return valueToFrame(value.x);
                            }));
                            legacyEasingMethodConverter.convert(x);
                            y.assignSorted(times, legacyValues.map(function (value) {
                              return valueToFrame(value.y);
                            }));
                            legacyEasingMethodConverter.convert(y);
                            break;
                        }
                        newTracks.push(_track);
                        return;
                      }
                    case everyInstanceOf(legacyValues, Quat):
                      {
                        var _track2 = new QuatTrack();
                        installPathAndSetter(_track2);
                        var _interpolationMode = interpolate ? QuatInterpolationMode.SLERP : QuatInterpolationMode.CONSTANT;
                        _track2.channel.curve.assignSorted(times, legacyValues.map(function (value) {
                          return {
                            value: Quat.clone(value),
                            interpolationMode: _interpolationMode
                          };
                        }));
                        legacyEasingMethodConverter.convertQuatCurve(_track2.channel.curve);
                        newTracks.push(_track2);
                        return;
                      }
                    case everyInstanceOf(legacyValues, Color$1):
                      {
                        var _track3 = new ColorTrack();
                        installPathAndSetter(_track3);
                        var _track3$channels = _track3.channels(),
                          r = _track3$channels[0].curve,
                          g = _track3$channels[1].curve,
                          b = _track3$channels[2].curve,
                          a = _track3$channels[3].curve;
                        var _interpolationMode2 = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
                        var _valueToFrame = function _valueToFrame(value) {
                          return {
                            value: value,
                            interpolationMode: _interpolationMode2
                          };
                        };
                        r.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame(value.r);
                        }));
                        legacyEasingMethodConverter.convert(r);
                        g.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame(value.g);
                        }));
                        legacyEasingMethodConverter.convert(g);
                        b.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame(value.b);
                        }));
                        legacyEasingMethodConverter.convert(b);
                        a.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame(value.a);
                        }));
                        legacyEasingMethodConverter.convert(a);
                        newTracks.push(_track3);
                        return;
                      }
                    case everyInstanceOf(legacyValues, Size$1):
                      {
                        var _track4 = new SizeTrack();
                        installPathAndSetter(_track4);
                        var _track4$channels = _track4.channels(),
                          width = _track4$channels[0].curve,
                          height = _track4$channels[1].curve;
                        var _interpolationMode3 = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
                        var _valueToFrame2 = function _valueToFrame2(value) {
                          return {
                            value: value,
                            interpolationMode: _interpolationMode3
                          };
                        };
                        width.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame2(value.width);
                        }));
                        legacyEasingMethodConverter.convert(width);
                        height.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame2(value.height);
                        }));
                        legacyEasingMethodConverter.convert(height);
                        newTracks.push(_track4);
                        return;
                      }
                    case everyInstanceOf(legacyValues, CubicSplineNumberValue):
                      {
                        assertIsTrue(legacyEasingMethodConverter.nil);
                        var _track5 = new RealTrack();
                        installPathAndSetter(_track5);
                        var _interpolationMode4 = interpolate ? RealInterpolationMode.CUBIC : RealInterpolationMode.CONSTANT;
                        _track5.channel.curve.assignSorted(times, legacyValues.map(function (value) {
                          return {
                            value: value.dataPoint,
                            leftTangent: value.inTangent,
                            rightTangent: value.outTangent,
                            interpolationMode: _interpolationMode4
                          };
                        }));
                        newTracks.push(_track5);
                        return;
                      }
                    case everyInstanceOf(legacyValues, CubicSplineVec2Value):
                    case everyInstanceOf(legacyValues, CubicSplineVec3Value):
                    case everyInstanceOf(legacyValues, CubicSplineVec4Value):
                      {
                        assertIsTrue(legacyEasingMethodConverter.nil);
                        var _components = firstValue instanceof CubicSplineVec2Value ? 2 : firstValue instanceof CubicSplineVec3Value ? 3 : 4;
                        var _track6 = new VectorTrack();
                        installPathAndSetter(_track6);
                        _track6.componentsCount = _components;
                        var _track6$channels = _track6.channels(),
                          _x = _track6$channels[0],
                          _y = _track6$channels[1],
                          _z = _track6$channels[2],
                          _w = _track6$channels[3];
                        var _interpolationMode5 = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
                        var _valueToFrame3 = function _valueToFrame3(value, inTangent, outTangent) {
                          return {
                            value: value,
                            leftTangent: inTangent,
                            rightTangent: outTangent,
                            interpolationMode: _interpolationMode5
                          };
                        };
                        switch (_components) {
                          case 4:
                            _w.curve.assignSorted(times, legacyValues.map(function (value) {
                              return _valueToFrame3(value.dataPoint.w, value.inTangent.w, value.outTangent.w);
                            }));
                          case 3:
                            _z.curve.assignSorted(times, legacyValues.map(function (value) {
                              return _valueToFrame3(value.dataPoint.z, value.inTangent.z, value.outTangent.z);
                            }));
                          default:
                            _x.curve.assignSorted(times, legacyValues.map(function (value) {
                              return _valueToFrame3(value.dataPoint.y, value.inTangent.y, value.outTangent.y);
                            }));
                            _y.curve.assignSorted(times, legacyValues.map(function (value) {
                              return _valueToFrame3(value.dataPoint.x, value.inTangent.x, value.outTangent.x);
                            }));
                            break;
                        }
                        newTracks.push(_track6);
                        return;
                      }
                    case legacyValues.every(function (value) {
                      return value instanceof CubicSplineQuatValue;
                    }):
                      {
                        warnID(3935);
                        break;
                      }
                  }
                }
                var objectTrack = new ObjectTrack();
                installPathAndSetter(objectTrack);
                objectTrack.channel.curve.assignSorted(times, legacyValues);
                newTracks.push(objectTrack);
              };
              convertCurve();
            },
            _ret;
          for (var _iterator2 = _createForOfIteratorHelperLoose(legacyCurves), _step2; !(_step2 = _iterator2()).done;) {
            _ret = _loop();
            if (_ret === 0) continue;
          }
          return newTracks;
        };
        _proto._createPropertyCurves = function _createPropertyCurves() {
          var _this = this;
          this._ratioSamplers = this._keys.map(function (keys) {
            return new RatioSampler(keys.map(function (key) {
              return key / _this._duration;
            }));
          });
          this._runtimeCurves = this._curves.map(function (targetCurve) {
            return {
              curve: new AnimCurve(targetCurve.data, _this._duration),
              modifiers: targetCurve.modifiers,
              valueAdapter: targetCurve.valueAdapter,
              sampler: _this._ratioSamplers[targetCurve.data.keys],
              commonTarget: targetCurve.commonTarget
            };
          });
        };
        _createClass(AnimationClipLegacyData, [{
          key: "keys",
          get: function get() {
            return this._keys;
          },
          set: function set(value) {
            this._keys = value;
          }
        }, {
          key: "curves",
          get: function get() {
            return this._curves;
          },
          set: function set(value) {
            this._curves = value;
            delete this._runtimeCurves;
          }
        }, {
          key: "commonTargets",
          get: function get() {
            return this._commonTargets;
          },
          set: function set(value) {
            this._commonTargets = value;
          }
        }, {
          key: "data",
          get: function get() {
            return this._data;
          }
        }]);
        return AnimationClipLegacyData;
      }();
      function everyInstanceOf(array, constructor) {
        return array.every(function (element) {
          return element instanceof constructor;
        });
      }
      var LegacyEasingMethodConverter = function () {
        function LegacyEasingMethodConverter(legacyCurveData, keyframesCount) {
          this._easingMethods = void 0;
          var easingMethods = legacyCurveData.easingMethods;
          if (Array.isArray(easingMethods)) {
            if (easingMethods.length === 0 && keyframesCount !== 0) {
              this._easingMethods = new Array(keyframesCount).fill(null);
            } else {
              this._easingMethods = easingMethods;
            }
          } else if (easingMethods === undefined) {
            this._easingMethods = new Array(keyframesCount).fill(legacyCurveData.easingMethod);
          } else {
            this._easingMethods = Array.from({
              length: keyframesCount
            }, function (_, index) {
              var _easingMethods$index;
              return (_easingMethods$index = easingMethods[index]) !== null && _easingMethods$index !== void 0 ? _easingMethods$index : null;
            });
          }
        }
        var _proto2 = LegacyEasingMethodConverter.prototype;
        _proto2.convert = function convert(curve) {
          var easingMethods = this._easingMethods;
          if (!easingMethods) {
            return;
          }
          var nKeyframes = curve.keyFramesCount;
          if (curve.keyFramesCount < 2) {
            return;
          }
          if (Array.isArray(easingMethods)) {
            assertIsTrue(nKeyframes === easingMethods.length);
          }
          var iLastKeyframe = nKeyframes - 1;
          for (var iKeyframe = 0; iKeyframe < iLastKeyframe; ++iKeyframe) {
            var easingMethod = easingMethods[iKeyframe];
            if (!easingMethod) {
              continue;
            }
            if (Array.isArray(easingMethod)) {
              timeBezierToTangents(easingMethod, curve.getKeyframeTime(iKeyframe), curve.getKeyframeValue(iKeyframe), curve.getKeyframeTime(iKeyframe + 1), curve.getKeyframeValue(iKeyframe + 1));
            } else {
              applyLegacyEasingMethodName(easingMethod, curve, iKeyframe);
            }
          }
        };
        _proto2.convertQuatCurve = function convertQuatCurve(curve) {
          var easingMethods = this._easingMethods;
          if (!easingMethods) {
            return;
          }
          var nKeyframes = curve.keyFramesCount;
          if (curve.keyFramesCount < 2) {
            return;
          }
          if (Array.isArray(easingMethods)) {
            assertIsTrue(nKeyframes === easingMethods.length);
          }
          var iLastKeyframe = nKeyframes - 1;
          for (var iKeyframe = 0; iKeyframe < iLastKeyframe; ++iKeyframe) {
            var easingMethod = easingMethods[iKeyframe];
            if (!easingMethod) {
              continue;
            }
            if (Array.isArray(easingMethod)) {
              curve.getKeyframeValue(iKeyframe).easingMethod = easingMethod.slice();
            } else {
              applyLegacyEasingMethodNameIntoQuatCurve(easingMethod, curve, iKeyframe);
            }
          }
        };
        _createClass(LegacyEasingMethodConverter, [{
          key: "nil",
          get: function get() {
            return !this._easingMethods || this._easingMethods.every(function (easingMethod) {
              return easingMethod === null || easingMethod === undefined;
            });
          }
        }]);
        return LegacyEasingMethodConverter;
      }();
      function applyLegacyEasingMethodName(easingMethodName, curve, keyframeIndex) {
        assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
        assertIsTrue(easingMethodName in easingMethodNameMap);
        var keyframeValue = curve.getKeyframeValue(keyframeIndex);
        var easingMethod = easingMethodNameMap[easingMethodName];
        if (easingMethod === EasingMethod.CONSTANT) {
          keyframeValue.interpolationMode = RealInterpolationMode.CONSTANT;
        } else {
          keyframeValue.interpolationMode = RealInterpolationMode.LINEAR;
          keyframeValue.easingMethod = easingMethod;
        }
      }
      function applyLegacyEasingMethodNameIntoQuatCurve(easingMethodName, curve, keyframeIndex) {
        assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
        assertIsTrue(easingMethodName in easingMethodNameMap);
        var keyframeValue = curve.getKeyframeValue(keyframeIndex);
        var easingMethod = easingMethodNameMap[easingMethodName];
        keyframeValue.easingMethod = easingMethod;
      }
      var easingMethodNameMap = {
        constant: EasingMethod.CONSTANT,
        linear: EasingMethod.LINEAR,
        quadIn: EasingMethod.QUAD_IN,
        quadOut: EasingMethod.QUAD_OUT,
        quadInOut: EasingMethod.QUAD_IN_OUT,
        quadOutIn: EasingMethod.QUAD_OUT_IN,
        cubicIn: EasingMethod.CUBIC_IN,
        cubicOut: EasingMethod.CUBIC_OUT,
        cubicInOut: EasingMethod.CUBIC_IN_OUT,
        cubicOutIn: EasingMethod.CUBIC_OUT_IN,
        quartIn: EasingMethod.QUART_IN,
        quartOut: EasingMethod.QUART_OUT,
        quartInOut: EasingMethod.QUART_IN_OUT,
        quartOutIn: EasingMethod.QUART_OUT_IN,
        quintIn: EasingMethod.QUINT_IN,
        quintOut: EasingMethod.QUINT_OUT,
        quintInOut: EasingMethod.QUINT_IN_OUT,
        quintOutIn: EasingMethod.QUINT_OUT_IN,
        sineIn: EasingMethod.SINE_IN,
        sineOut: EasingMethod.SINE_OUT,
        sineInOut: EasingMethod.SINE_IN_OUT,
        sineOutIn: EasingMethod.SINE_OUT_IN,
        expoIn: EasingMethod.EXPO_IN,
        expoOut: EasingMethod.EXPO_OUT,
        expoInOut: EasingMethod.EXPO_IN_OUT,
        expoOutIn: EasingMethod.EXPO_OUT_IN,
        circIn: EasingMethod.CIRC_IN,
        circOut: EasingMethod.CIRC_OUT,
        circInOut: EasingMethod.CIRC_IN_OUT,
        circOutIn: EasingMethod.CIRC_OUT_IN,
        elasticIn: EasingMethod.ELASTIC_IN,
        elasticOut: EasingMethod.ELASTIC_OUT,
        elasticInOut: EasingMethod.ELASTIC_IN_OUT,
        elasticOutIn: EasingMethod.ELASTIC_OUT_IN,
        backIn: EasingMethod.BACK_IN,
        backOut: EasingMethod.BACK_OUT,
        backInOut: EasingMethod.BACK_IN_OUT,
        backOutIn: EasingMethod.BACK_OUT_IN,
        bounceIn: EasingMethod.BOUNCE_IN,
        bounceOut: EasingMethod.BOUNCE_OUT,
        bounceInOut: EasingMethod.BOUNCE_IN_OUT,
        bounceOutIn: EasingMethod.BOUNCE_OUT_IN,
        smooth: EasingMethod.SMOOTH,
        fade: EasingMethod.FADE
      };
      function timeBezierToTangents(timeBezierPoints, previousTime, previousKeyframe, nextTime, nextKeyframe) {
        var p1X = timeBezierPoints[0],
          p1Y = timeBezierPoints[1],
          p2X = timeBezierPoints[2],
          p2Y = timeBezierPoints[3];
        var previousValue = previousKeyframe.value;
        var nextValue = nextKeyframe.value;
        var dValue = nextValue - previousValue;
        var dTime = nextTime - previousTime;
        var fx = 3 * dTime;
        var fy = 3 * dValue;
        var t1x = p1X * fx;
        var t1y = p1Y * fy;
        var t2x = (1.0 - p2X) * fx;
        var t2y = (1.0 - p2Y) * fy;
        var ONE_THIRD = 1.0 / 3.0;
        var previousTangent = t1y / t1x;
        var previousTangentWeight = Math.sqrt(t1x * t1x + t1y * t1y) * ONE_THIRD;
        var nextTangent = t2y / t2x;
        var nextTangentWeight = Math.sqrt(t2x * t2x + t2y * t2y) * ONE_THIRD;
        previousKeyframe.interpolationMode = RealInterpolationMode.CUBIC;
        previousKeyframe.tangentWeightMode = ensureRightTangentWeightMode(previousKeyframe.tangentWeightMode);
        previousKeyframe.rightTangent = previousTangent;
        previousKeyframe.rightTangentWeight = previousTangentWeight;
        nextKeyframe.tangentWeightMode = ensureLeftTangentWeightMode(nextKeyframe.tangentWeightMode);
        nextKeyframe.leftTangent = nextTangent;
        nextKeyframe.leftTangentWeight = nextTangentWeight;
      }
      function ensureLeftTangentWeightMode(tangentWeightMode) {
        if (tangentWeightMode === TangentWeightMode.NONE) {
          return TangentWeightMode.LEFT;
        } else if (tangentWeightMode === TangentWeightMode.RIGHT) {
          return TangentWeightMode.BOTH;
        } else {
          return tangentWeightMode;
        }
      }
      function ensureRightTangentWeightMode(tangentWeightMode) {
        if (tangentWeightMode === TangentWeightMode.NONE) {
          return TangentWeightMode.RIGHT;
        } else if (tangentWeightMode === TangentWeightMode.LEFT) {
          return TangentWeightMode.BOTH;
        } else {
          return tangentWeightMode;
        }
      }

      var _dec$1Y, _class$1V, _class2$1O, _initializer$1H, _dec2$1F, _class4$g, _class5$h, _initializer2$1t, _initializer3$16, _initializer4$X, _initializer5$L, _dec3$1c, _class7$4, _class8$6, _initializer6$C, _initializer7$v, _dec4$U, _class10$1, _dec5$P, _class11$2, _dec6$A, _class12$2, _class13$2, _initializer8$r, _initializer9$n, _dec7$r, _class20, _class21, _initializer10$l, _initializer11$l, _initializer12$j, _initializer13$g;
      var ccclass$D = ccclass$M,
        serializable$h = serializable$p;
      function throwIfSplitMethodIsNotValid() {
        throw new Error("split() only valid in Editor.");
      }
      (_dec$1Y = ccclass$D(CLASS_NAME_PREFIX_ANIM + "ExoticAnimation"), _dec$1Y(_class$1V = (_class2$1O = function () {
        function ExoticAnimation() {
          this._nodeAnimations = _initializer$1H && _initializer$1H();
        }
        var _proto = ExoticAnimation.prototype;
        _proto.createEvaluator = function createEvaluator(binder) {
          return new ExoticTrsAnimationEvaluator(this._nodeAnimations, binder);
        };
        _proto.createEvaluatorForAnimationGraph = function createEvaluatorForAnimationGraph(context) {
          return new ExoticTrsAGEvaluation(this._nodeAnimations, context);
        };
        _proto.addNodeAnimation = function addNodeAnimation(path) {
          var nodeAnimation = new ExoticNodeAnimation(path);
          this._nodeAnimations.push(nodeAnimation);
          return nodeAnimation;
        };
        _proto.collectAnimatedJoints = function collectAnimatedJoints() {
          return Array.from(new Set(this._nodeAnimations.map(function (_ref) {
            var path = _ref.path;
            return path;
          })));
        };
        _proto.split = function split(from, to) {
          {
            return throwIfSplitMethodIsNotValid();
          }
        };
        _proto.toHashString = function toHashString() {
          return this._nodeAnimations.map(function (nodeAnimation) {
            return nodeAnimation.toHashString();
          }).join('\n');
        };
        return ExoticAnimation;
      }(), (_initializer$1H = applyDecoratedInitializer(_class2$1O.prototype, "_nodeAnimations", [serializable$h], function () {
        return [];
      })), _class2$1O)) || _class$1V);
      var ExoticNodeAnimation = (_dec2$1F = ccclass$D(CLASS_NAME_PREFIX_ANIM + "ExoticNodeAnimation"), _dec2$1F(_class4$g = (_class5$h = function () {
        function ExoticNodeAnimation(path) {
          this._path = _initializer2$1t && _initializer2$1t();
          this._position = _initializer3$16 && _initializer3$16();
          this._rotation = _initializer4$X && _initializer4$X();
          this._scale = _initializer5$L && _initializer5$L();
          this._path = path;
        }
        var _proto2 = ExoticNodeAnimation.prototype;
        _proto2.createPosition = function createPosition(times, values) {
          this._position = new ExoticTrack(times, new ExoticVec3TrackValues(values));
        };
        _proto2.createRotation = function createRotation(times, values) {
          this._rotation = new ExoticTrack(times, new ExoticQuatTrackValues(values));
        };
        _proto2.createScale = function createScale(times, values) {
          this._scale = new ExoticTrack(times, new ExoticVec3TrackValues(values));
        };
        _proto2.createEvaluator = function createEvaluator(binder) {
          return new ExoticNodeAnimationEvaluator(this._path, this._position, this._rotation, this._scale, binder);
        };
        _proto2.createEvaluatorForAnimationGraph = function createEvaluatorForAnimationGraph(context) {
          var transformHandle = context.bindTransform(this._path);
          if (!transformHandle) {
            return null;
          }
          return new ExoticNodeAnimationAGEvaluation(transformHandle, this._position, this._rotation, this._scale);
        };
        _proto2.split = function split(from, to, splitInfoCache) {
          {
            return throwIfSplitMethodIsNotValid();
          }
        };
        _proto2.toHashString = function toHashString() {
          var _this$_position$toHas, _this$_position, _this$_scale$toHashSt, _this$_scale, _this$_rotation$toHas, _this$_rotation;
          return this._path + "\n" + ((_this$_position$toHas = (_this$_position = this._position) === null || _this$_position === void 0 ? void 0 : _this$_position.toHashString()) !== null && _this$_position$toHas !== void 0 ? _this$_position$toHas : '') + ((_this$_scale$toHashSt = (_this$_scale = this._scale) === null || _this$_scale === void 0 ? void 0 : _this$_scale.toHashString()) !== null && _this$_scale$toHashSt !== void 0 ? _this$_scale$toHashSt : '') + ((_this$_rotation$toHas = (_this$_rotation = this._rotation) === null || _this$_rotation === void 0 ? void 0 : _this$_rotation.toHashString()) !== null && _this$_rotation$toHas !== void 0 ? _this$_rotation$toHas : '');
        };
        _createClass(ExoticNodeAnimation, [{
          key: "path",
          get: function get() {
            return this._path;
          }
        }]);
        return ExoticNodeAnimation;
      }(), (_initializer2$1t = applyDecoratedInitializer(_class5$h.prototype, "_path", [serializable$h], function () {
        return '';
      }), _initializer3$16 = applyDecoratedInitializer(_class5$h.prototype, "_position", [serializable$h], function () {
        return null;
      }), _initializer4$X = applyDecoratedInitializer(_class5$h.prototype, "_rotation", [serializable$h], function () {
        return null;
      }), _initializer5$L = applyDecoratedInitializer(_class5$h.prototype, "_scale", [serializable$h], function () {
        return null;
      })), _class5$h)) || _class4$g);
      function floatToHashString(value) {
        return value.toPrecision(2);
      }
      function floatArrayToHashString(values) {
        return values.map(function (v) {
          return Number.parseFloat(floatToHashString(v));
        }).join(' ');
      }
      var ExoticVectorLikeTrackValues = (_dec3$1c = ccclass$D(CLASS_NAME_PREFIX_ANIM + "ExoticVectorLikeTrackValues"), _dec3$1c(_class7$4 = (_class8$6 = function () {
        function ExoticVectorLikeTrackValues(values) {
          this._values = _initializer6$C && _initializer6$C();
          this._isQuantized = _initializer7$v && _initializer7$v();
          this._values = values;
        }
        var _proto3 = ExoticVectorLikeTrackValues.prototype;
        _proto3.quantize = function quantize(type) {
          assertIsTrue(!this._isQuantized);
          this._values = _quantize(this._values, type);
          this._isQuantized = true;
        };
        _proto3.toHashString = function toHashString() {
          var isQuantized = this._isQuantized,
            values = this._values;
          return isQuantized + " " + (isQuantized ? values.toHashString() : floatArrayToHashString(values));
        };
        _createClass(ExoticVectorLikeTrackValues, [{
          key: "precision",
          get: function get() {
            return this._isQuantized ? this._values.originalPrecision : getFloatArrayPrecision(this._values);
          }
        }]);
        return ExoticVectorLikeTrackValues;
      }(), (_initializer6$C = applyDecoratedInitializer(_class8$6.prototype, "_values", [serializable$h], null), _initializer7$v = applyDecoratedInitializer(_class8$6.prototype, "_isQuantized", [serializable$h], function () {
        return false;
      })), _class8$6)) || _class7$4);
      var ExoticVec3TrackValues = (_dec4$U = ccclass$D(CLASS_NAME_PREFIX_ANIM + "ExoticVec3TrackValues"), _dec4$U(_class10$1 = function (_ExoticVectorLikeTrac) {
        _inheritsLoose(ExoticVec3TrackValues, _ExoticVectorLikeTrac);
        function ExoticVec3TrackValues() {
          return _ExoticVectorLikeTrac.apply(this, arguments) || this;
        }
        ExoticVec3TrackValues.imitate = function imitate(values, model) {
          var trackValues = new ExoticVec3TrackValues(values);
          if (model._isQuantized) {
            trackValues.quantize(model._values.quantizationType);
          }
          return trackValues;
        };
        var _proto4 = ExoticVec3TrackValues.prototype;
        _proto4.get = function get(index, resultValue) {
          var values = this._values,
            isQuantized = this._isQuantized;
          if (isQuantized) {
            loadVec3FromQuantized(values, index, resultValue);
          } else {
            Vec3.fromArray(resultValue, values, index * 3);
          }
        };
        _proto4.lerp = function lerp(prevIndex, nextIndex, ratio, prevValue, nextValue, resultValue) {
          var values = this._values,
            isQuantized = this._isQuantized;
          if (isQuantized) {
            loadVec3FromQuantized(values, prevIndex, prevValue);
            loadVec3FromQuantized(values, nextIndex, nextValue);
          } else {
            Vec3.fromArray(prevValue, values, prevIndex * 3);
            Vec3.fromArray(nextValue, values, nextIndex * 3);
          }
          Vec3.lerp(resultValue, prevValue, nextValue, ratio);
        };
        return ExoticVec3TrackValues;
      }(ExoticVectorLikeTrackValues)) || _class10$1);
      var ExoticQuatTrackValues = (_dec5$P = ccclass$D(CLASS_NAME_PREFIX_ANIM + "ExoticQuatTrackValues"), _dec5$P(_class11$2 = function (_ExoticVectorLikeTrac2) {
        _inheritsLoose(ExoticQuatTrackValues, _ExoticVectorLikeTrac2);
        function ExoticQuatTrackValues() {
          return _ExoticVectorLikeTrac2.apply(this, arguments) || this;
        }
        ExoticQuatTrackValues.imitate = function imitate(values, model) {
          var trackValues = new ExoticQuatTrackValues(values);
          if (model._isQuantized) {
            trackValues.quantize(model._values.quantizationType);
          }
          return trackValues;
        };
        var _proto5 = ExoticQuatTrackValues.prototype;
        _proto5.get = function get(index, resultValue) {
          var values = this._values,
            isQuantized = this._isQuantized;
          if (isQuantized) {
            loadQuatFromQuantized(values, index, resultValue);
          } else {
            Quat.fromArray(resultValue, values, index * 4);
          }
        };
        _proto5.lerp = function lerp(prevIndex, nextIndex, ratio, prevValue, nextValue, resultValue) {
          var values = this._values,
            isQuantized = this._isQuantized;
          if (isQuantized) {
            loadQuatFromQuantized(values, prevIndex, prevValue);
            loadQuatFromQuantized(values, nextIndex, nextValue);
          } else {
            Quat.fromArray(prevValue, values, prevIndex * 4);
            Quat.fromArray(nextValue, values, nextIndex * 4);
          }
          Quat.slerp(resultValue, prevValue, nextValue, ratio);
        };
        return ExoticQuatTrackValues;
      }(ExoticVectorLikeTrackValues)) || _class11$2);
      var ExoticTrack = (_dec6$A = ccclass$D(CLASS_NAME_PREFIX_ANIM + "ExoticTrack"), _dec6$A(_class12$2 = (_class13$2 = function () {
        function ExoticTrack(times, values) {
          this.times = _initializer8$r && _initializer8$r();
          this.values = _initializer9$n && _initializer9$n();
          this.times = times;
          this.values = values;
        }
        var _proto6 = ExoticTrack.prototype;
        _proto6.toHashString = function toHashString() {
          var times = this.times,
            values = this.values;
          return "times: " + floatArrayToHashString(times) + "; values: " + values.toHashString();
        };
        return ExoticTrack;
      }(), (_initializer8$r = applyDecoratedInitializer(_class13$2.prototype, "times", [serializable$h], null), _initializer9$n = applyDecoratedInitializer(_class13$2.prototype, "values", [serializable$h], null)), _class13$2)) || _class12$2);
      (function () {
        function SplitInfo() {
          this._reset();
        }
        var _proto7 = SplitInfo.prototype;
        _proto7.calculate = function calculate(times, from, to) {
          this._reset();
          if (from > to) {
            return;
          }
          var nKeyframes = times.length;
          if (!nKeyframes) {
            return;
          }
          var firstTime = times[0];
          var lastTime = times[nKeyframes - 1];
          var fromIndex = 0;
          var fromRatio = 0.0;
          if (from < firstTime) ; else if (from >= lastTime) {
            fromIndex = nKeyframes - 1;
            fromRatio = 0.0;
          } else {
            var _binarySearchRatio = binarySearchRatio(times, from);
            fromIndex = _binarySearchRatio.index;
            fromRatio = _binarySearchRatio.ratio;
          }
          var toIndex = 0;
          var toRatio = 0.0;
          if (to < firstTime) ; else if (to >= lastTime) {
            toIndex = nKeyframes - 1;
            toRatio = 0.0;
          } else {
            var _binarySearchRatio2 = binarySearchRatio(times, to);
            toIndex = _binarySearchRatio2.index;
            toRatio = _binarySearchRatio2.ratio;
          }
          assertIsTrue(toIndex >= fromIndex);
          var fromJust = !fromRatio;
          var toJust = !toRatio;
          if (fromIndex === toIndex && fromRatio === toRatio) {
            if (!fromJust) {
              this.preLerpIndex = fromIndex;
              this.preLerpRatio = fromRatio;
            } else {
              this.directKeyframesBegin = fromIndex;
              this.directKeyframesEnd = fromIndex + 1;
            }
            return;
          }
          if (!fromJust) {
            this.preLerpIndex = fromIndex;
            this.preLerpRatio = fromRatio;
          }
          this.directKeyframesBegin = fromJust ? fromIndex : fromIndex + 1;
          this.directKeyframesEnd = toIndex + 1;
          if (!toJust) {
            this.postLerpIndex = toIndex;
            this.postLerpRatio = toRatio;
          }
        };
        _proto7._reset = function _reset() {
          this.preLerpIndex = -1;
          this.preLerpRatio = 0.0;
          this.directKeyframesBegin = 0;
          this.directKeyframesEnd = 0;
          this.postLerpIndex = -1;
          this.postLerpRatio = 0.0;
        };
        _createClass(SplitInfo, [{
          key: "keyframesCount",
          get: function get() {
            var preLerpIndex = this.preLerpIndex,
              directKeyframesBegin = this.directKeyframesBegin,
              directKeyframesEnd = this.directKeyframesEnd,
              postLerpIndex = this.postLerpIndex;
            return 0 + (preLerpIndex < 0 ? 0 : 1) + (directKeyframesEnd - directKeyframesBegin) + (postLerpIndex < 0 ? 0 : 1);
          }
        }]);
        return SplitInfo;
      })();
      function binarySearchRatio(values, value) {
        var nValues = values.length;
        assertIsTrue(values.length !== 0);
        var resultIndex = 0;
        var resultRatio = 0.0;
        var index0 = binarySearchEpsilon(values, value);
        if (index0 >= 0) {
          resultIndex = index0;
        } else {
          var iNext = ~index0;
          assertIsTrue(iNext !== 0 && iNext !== nValues && nValues > 1);
          var iPrev = iNext - 1;
          resultIndex = iPrev;
          var next = values[iNext];
          var prev = values[iPrev];
          resultRatio = (value - prev) / (next - prev);
        }
        return {
          index: resultIndex,
          ratio: resultRatio
        };
      }
      var ExoticTrsAnimationEvaluator = function () {
        function ExoticTrsAnimationEvaluator(nodeAnimations, binder) {
          this._nodeEvaluations = void 0;
          this._nodeEvaluations = nodeAnimations.map(function (nodeAnimation) {
            return nodeAnimation.createEvaluator(binder);
          });
        }
        var _proto8 = ExoticTrsAnimationEvaluator.prototype;
        _proto8.evaluate = function evaluate(time) {
          this._nodeEvaluations.forEach(function (nodeEvaluator) {
            nodeEvaluator.evaluate(time);
          });
        };
        return ExoticTrsAnimationEvaluator;
      }();
      var ExoticNodeAnimationEvaluator = function () {
        function ExoticNodeAnimationEvaluator(path, position, rotation, scale, binder) {
          this._position = null;
          this._rotation = null;
          this._scale = null;
          if (position) {
            this._position = createExoticTrackEvaluationRecord(position.times, position.values, Vec3, path, 'position', binder);
          }
          if (rotation) {
            this._rotation = createExoticTrackEvaluationRecord(rotation.times, rotation.values, Quat, path, 'rotation', binder);
          }
          if (scale) {
            this._scale = createExoticTrackEvaluationRecord(scale.times, scale.values, Vec3, path, 'scale', binder);
          }
        }
        var _proto9 = ExoticNodeAnimationEvaluator.prototype;
        _proto9.evaluate = function evaluate(time) {
          if (this._position) {
            var _value = this._position.evaluator.evaluate(time);
            this._position.runtimeBinding.setValue(_value);
          }
          if (this._rotation) {
            var _value2 = this._rotation.evaluator.evaluate(time);
            this._rotation.runtimeBinding.setValue(_value2);
          }
          if (this._scale) {
            var _value3 = this._scale.evaluator.evaluate(time);
            this._scale.runtimeBinding.setValue(_value3);
          }
        };
        return ExoticNodeAnimationEvaluator;
      }();
      var ExoticTrackEvaluator = function () {
        function ExoticTrackEvaluator(times, values, ValueConstructor) {
          this._times = void 0;
          this._inputSampleResultCache = {
            just: false,
            index: -1,
            nextIndex: -1,
            ratio: 0.0
          };
          this._values = void 0;
          this._prevValue = void 0;
          this._nextValue = void 0;
          this._resultValue = void 0;
          this._times = times;
          this._values = values;
          this._prevValue = new ValueConstructor();
          this._nextValue = new ValueConstructor();
          this._resultValue = new ValueConstructor();
        }
        var _proto10 = ExoticTrackEvaluator.prototype;
        _proto10.evaluate = function evaluate(time) {
          var times = this._times,
            values = this._values,
            resultValue = this._resultValue;
          var nFrames = times.length;
          if (nFrames === 0) {
            return resultValue;
          }
          var inputSampleResult = sampleInput(times, time, this._inputSampleResultCache);
          if (inputSampleResult.just) {
            values.get(inputSampleResult.index, resultValue);
          } else {
            values.lerp(inputSampleResult.index, inputSampleResult.nextIndex, inputSampleResult.ratio, this._prevValue, this._nextValue, resultValue);
          }
          return resultValue;
        };
        return ExoticTrackEvaluator;
      }();
      var ExoticTrsAGEvaluation = function () {
        function ExoticTrsAGEvaluation(nodeAnimations, context) {
          this._nodeEvaluations = void 0;
          this._nodeEvaluations = nodeAnimations.map(function (nodeAnimation) {
            return nodeAnimation.createEvaluatorForAnimationGraph(context);
          }).filter(function (x) {
            return !!x;
          });
        }
        var _proto11 = ExoticTrsAGEvaluation.prototype;
        _proto11.destroy = function destroy() {
          var nodeEvaluations = this._nodeEvaluations;
          var nNodeEvaluations = nodeEvaluations.length;
          for (var iNodeEvaluation = 0; iNodeEvaluation < nNodeEvaluations; ++iNodeEvaluation) {
            nodeEvaluations[iNodeEvaluation].destroy();
          }
        };
        _proto11.evaluate = function evaluate(time, pose) {
          var nodeEvaluations = this._nodeEvaluations;
          var nNodeEvaluations = nodeEvaluations.length;
          for (var iNodeEvaluation = 0; iNodeEvaluation < nNodeEvaluations; ++iNodeEvaluation) {
            nodeEvaluations[iNodeEvaluation].evaluate(time, pose);
          }
        };
        return ExoticTrsAGEvaluation;
      }();
      var ExoticNodeAnimationAGEvaluation = function () {
        function ExoticNodeAnimationAGEvaluation(transformHandle, position, rotation, scale) {
          this._position = null;
          this._rotation = null;
          this._scale = null;
          this._transformHandle = void 0;
          this._transformHandle = transformHandle;
          if (position) {
            this._position = new ExoticTrackEvaluator(position.times, position.values, Vec3);
          }
          if (rotation) {
            this._rotation = new ExoticTrackEvaluator(rotation.times, rotation.values, Quat);
          }
          if (scale) {
            this._scale = new ExoticTrackEvaluator(scale.times, scale.values, Vec3);
          }
        }
        var _proto12 = ExoticNodeAnimationAGEvaluation.prototype;
        _proto12.destroy = function destroy() {
          this._transformHandle.destroy();
        };
        _proto12.evaluate = function evaluate(time, pose) {
          var transformIndex = this._transformHandle.index,
            position = this._position,
            rotation = this._rotation,
            scale = this._scale;
          var poseTransforms = pose.transforms;
          if (position) {
            var _value4 = position.evaluate(time);
            poseTransforms.setPosition(transformIndex, _value4);
          }
          if (rotation) {
            var rotationAbs = rotation.evaluate(time);
            poseTransforms.setRotation(transformIndex, rotationAbs);
          }
          if (scale) {
            var _value5 = scale.evaluate(time);
            poseTransforms.setScale(transformIndex, _value5);
          }
        };
        return ExoticNodeAnimationAGEvaluation;
      }();
      function sampleInput(values, time, result) {
        var nFrames = values.length;
        assertIsTrue(nFrames !== 0);
        var firstTime = values[0];
        var lastTime = values[nFrames - 1];
        if (time < firstTime) {
          result.just = true;
          result.index = 0;
        } else if (time > lastTime) {
          result.just = true;
          result.index = nFrames - 1;
        } else {
          var _index2 = binarySearchEpsilon(values, time);
          if (_index2 >= 0) {
            result.just = true;
            result.index = _index2;
          } else {
            var _nextIndex = ~_index2;
            assertIsTrue(_nextIndex !== 0 && _nextIndex !== nFrames && nFrames > 1);
            var _prevIndex = _nextIndex - 1;
            var prevTime = values[_prevIndex];
            var nextTime = values[_nextIndex];
            var _ratio = (time - values[_prevIndex]) / (nextTime - prevTime);
            result.just = false;
            result.index = _prevIndex;
            result.nextIndex = _nextIndex;
            result.ratio = _ratio;
          }
        }
        return result;
      }
      var QUANTIZATION_TYPE_TO_ARRAY_VIEW_CONSTRUCTOR_MAP = {
        uint8: Uint8Array,
        uint16: Uint16Array
      };
      var FloatPrecision;
      (function (FloatPrecision) {
        FloatPrecision[FloatPrecision["FLOAT_32"] = 0] = "FLOAT_32";
        FloatPrecision[FloatPrecision["FLOAT_64"] = 1] = "FLOAT_64";
      })(FloatPrecision || (FloatPrecision = {}));
      function getFloatArrayPrecision(array) {
        switch (array.BYTES_PER_ELEMENT) {
          default:
            assertIsTrue(false);
          case 4:
            return FloatPrecision.FLOAT_32;
          case 8:
            return FloatPrecision.FLOAT_64;
        }
      }
      var QuantizedFloatArray = (_dec7$r = ccclass$D(CLASS_NAME_PREFIX_ANIM + "QuantizedFloatArray"), _dec7$r(_class20 = (_class21 = function () {
        function QuantizedFloatArray(originalPrecision, values, extent, min) {
          if (min === void 0) {
            min = 0.0;
          }
          this.originalPrecision = _initializer10$l && _initializer10$l();
          this.min = _initializer11$l && _initializer11$l();
          this.extent = _initializer12$j && _initializer12$j();
          this.values = _initializer13$g && _initializer13$g();
          this.originalPrecision = originalPrecision;
          this.values = values;
          this.extent = extent;
          this.min = min;
        }
        var _proto13 = QuantizedFloatArray.prototype;
        _proto13.toHashString = function toHashString() {
          var originalPrecision = this.originalPrecision,
            min = this.min,
            extent = this.extent,
            values = this.values;
          return originalPrecision + " " + floatToHashString(min) + " " + floatToHashString(extent) + " " + values.join(' ');
        };
        _createClass(QuantizedFloatArray, [{
          key: "quantizationType",
          get: function get() {
            switch (this.values.BYTES_PER_ELEMENT) {
              default:
              case 1:
                return 'uint8';
              case 2:
                return 'uint16';
            }
          }
        }]);
        return QuantizedFloatArray;
      }(), (_initializer10$l = applyDecoratedInitializer(_class21.prototype, "originalPrecision", [serializable$h], null), _initializer11$l = applyDecoratedInitializer(_class21.prototype, "min", [serializable$h], null), _initializer12$j = applyDecoratedInitializer(_class21.prototype, "extent", [serializable$h], null), _initializer13$g = applyDecoratedInitializer(_class21.prototype, "values", [serializable$h], null)), _class21)) || _class20);
      function _quantize(values, type) {
        var TypedArrayViewConstructor = QUANTIZATION_TYPE_TO_ARRAY_VIEW_CONSTRUCTOR_MAP[type];
        var MAX = 1 << TypedArrayViewConstructor.BYTES_PER_ELEMENT;
        var min = Number.POSITIVE_INFINITY;
        var max = Number.NEGATIVE_INFINITY;
        values.forEach(function (value) {
          min = Math.min(value, min);
          max = Math.max(value, max);
        });
        var extent = max - min;
        var normalized = TypedArrayViewConstructor.from(values, function (value) {
          return (value - min) / extent * MAX;
        });
        return new QuantizedFloatArray(getFloatArrayPrecision(values), normalized, extent, min);
      }
      function indexQuantized(quantized, index) {
        var quantizedValue = quantized.values[index];
        var MAX_VALUE = 1 << quantized.values.BYTES_PER_ELEMENT;
        return quantizedValue / MAX_VALUE * quantized.extent + quantized.min;
      }
      function createExoticTrackEvaluationRecord(times, values, ValueConstructor, path, property, binder) {
        var trackBinding = new TrackBinding();
        trackBinding.path = new TrackPath().toHierarchy(path).toProperty(property);
        var runtimeBinding = binder(trackBinding);
        if (!runtimeBinding) {
          return null;
        }
        var evaluator = new ExoticTrackEvaluator(times, values, ValueConstructor);
        return {
          runtimeBinding: runtimeBinding,
          evaluator: evaluator
        };
      }
      function loadVec3FromQuantized(values, index, out) {
        Vec3.set(out, indexQuantized(values, 3 * index + 0), indexQuantized(values, 3 * index + 1), indexQuantized(values, 3 * index + 2));
      }
      function loadQuatFromQuantized(values, index, out) {
        Quat.set(out, indexQuantized(values, 4 * index + 0), indexQuantized(values, 4 * index + 1), indexQuantized(values, 4 * index + 2), indexQuantized(values, 4 * index + 3));
      }

      var _dec$1X, _class$1U, _class2$1N, _initializer$1G, _initializer2$1s;
      var AuxiliaryCurveEntry = (_dec$1X = ccclass$M(CLASS_NAME_PREFIX_ANIM + "AuxiliaryCurveEntry"), _dec$1X(_class$1U = (_class2$1N = function AuxiliaryCurveEntry() {
        this.name = _initializer$1G && _initializer$1G();
        this.curve = _initializer2$1s && _initializer2$1s();
      }, (_initializer$1G = applyDecoratedInitializer(_class2$1N.prototype, "name", [serializable$p], function () {
        return '';
      }), _initializer2$1s = applyDecoratedInitializer(_class2$1N.prototype, "curve", [serializable$p], function () {
        return new RealCurve();
      })), _class2$1N)) || _class$1U);

      var _dec$1W, _class$1T, _class2$1M, _initializer$1F, _initializer2$1r, _initializer3$15, _initializer4$W, _initializer5$K, _initializer6$B, _initializer7$u, _initializer8$q, _initializer9$m, _initializer10$k, _initializer11$k, _initializer12$i, _class3$A, _dec2$1E, _class4$f, _class5$g, _initializer13$f, _initializer14$c;
      var searchForRootBonePathSymbol = Symbol('SearchForRootBonePath');
      var exoticAnimationTag = Symbol('ExoticAnimation');
      var embeddedPlayerCountTag = Symbol('[[EmbeddedPlayerCount]]');
      var getEmbeddedPlayersTag = Symbol('[[GetEmbeddedPlayers]]');
      var addEmbeddedPlayerTag = Symbol('[[AddEmbeddedPlayer]]');
      var removeEmbeddedPlayerTag = Symbol('[[RemoveEmbeddedPlayer]]');
      var clearEmbeddedPlayersTag = Symbol('[[ClearEmbeddedPlayers]]');
      var additiveSettingsTag = Symbol('[[Additive Settings]]');
      var AnimationClip = exports('ar', (_dec$1W = ccclass$M('cc.AnimationClip'), _dec$1W(_class$1T = (_class2$1M = (_class3$A = function (_Asset) {
        _inheritsLoose(AnimationClip, _Asset);
        function AnimationClip() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.sample = _initializer$1F && _initializer$1F();
          _this.speed = _initializer2$1r && _initializer2$1r();
          _this.wrapMode = _initializer3$15 && _initializer3$15();
          _this.enableTrsBlending = _initializer4$W && _initializer4$W();
          _this._duration = _initializer5$K && _initializer5$K();
          _this._hash = _initializer6$B && _initializer6$B();
          _this.frameRate = 0;
          _this._tracks = _initializer7$u && _initializer7$u();
          _this._exoticAnimation = _initializer8$q && _initializer8$q();
          _this._legacyData = undefined;
          _this._legacyDataDirty = false;
          _this._events = _initializer9$m && _initializer9$m();
          _this._embeddedPlayers = _initializer10$k && _initializer10$k();
          _this._additiveSettings = _initializer11$k && _initializer11$k();
          _this._auxiliaryCurveEntries = _initializer12$i && _initializer12$i();
          _this._runtimeEvents = {
            ratios: [],
            eventGroups: []
          };
          return _this;
        }
        AnimationClip.createWithSpriteFrames = function createWithSpriteFrames(spriteFrames, sample) {
          var clip = new AnimationClip();
          clip.sample = sample || clip.sample;
          clip.duration = spriteFrames.length / clip.sample;
          var step = 1 / clip.sample;
          var track = new ObjectTrack();
          track.path = new TrackPath().toComponent('cc.Sprite').toProperty('spriteFrame');
          var curve = track.channels()[0].curve;
          curve.assignSorted(spriteFrames.map(function (spriteFrame, index) {
            return [step * index, spriteFrame];
          }));
          clip.addTrack(track);
          return clip;
        };
        var _proto = AnimationClip.prototype;
        _proto.onLoaded = function onLoaded() {
          this.frameRate = this.sample;
          this.events = this._events;
        };
        _proto.range = function range() {
          var range = {
            min: Infinity,
            max: -Infinity
          };
          var tracks = this._tracks;
          var nTracks = tracks.length;
          for (var iTrack = 0; iTrack < nTracks; ++iTrack) {
            var track = tracks[iTrack];
            var trackRange = track.range();
            range.min = Math.min(range.min, trackRange.min);
            range.max = Math.max(range.max, trackRange.max);
          }
          return range;
        };
        _proto.getTrack = function getTrack(index) {
          return this._tracks[index];
        };
        _proto.addTrack = function addTrack(track) {
          var index = this._tracks.length;
          this._tracks.push(track);
          return index;
        };
        _proto.removeTrack = function removeTrack(index) {
          this._tracks.splice(index, 1);
        };
        _proto.clearTracks = function clearTracks() {
          this._tracks.length = 0;
        };
        _proto.containsAnyEvent = function containsAnyEvent() {
          return this._events.length !== 0;
        };
        _proto.createEventEvaluator = function createEventEvaluator(targetNode) {
          return new EventEvaluator(targetNode, this._runtimeEvents.ratios, this._runtimeEvents.eventGroups, this.wrapMode);
        };
        _proto.containsAnyEmbeddedPlayer = function containsAnyEmbeddedPlayer() {
          return this._embeddedPlayers.length !== 0;
        };
        _proto.createEmbeddedPlayerEvaluator = function createEmbeddedPlayerEvaluator(targetNode) {
          return new EmbeddedPlayerEvaluation(this._embeddedPlayers, targetNode);
        };
        _proto.createEvaluator = function createEvaluator(context) {
          var _this2 = this;
          var target = context.target;
          var binder = function binder(binding) {
            if (context.mask && binding.isMaskedOff(context.mask)) {
              return undefined;
            }
            var trackTarget = binding.createRuntimeBinding(target, _this2.enableTrsBlending ? context.pose : undefined, false);
            if (!trackTarget) {
              warnID(3937, _this2.name, context.target instanceof Node$1 ? context.target.name : context.target);
            }
            return trackTarget !== null && trackTarget !== void 0 ? trackTarget : undefined;
          };
          return this._createEvalWithBinder(target, binder, context.rootMotion);
        };
        _proto.destroy = function destroy() {
          var _cclegacy$director$ro;
          if ((_cclegacy$director$ro = legacyCC.director.root) !== null && _cclegacy$director$ro !== void 0 && _cclegacy$director$ro.dataPoolManager) {
            legacyCC.director.root.dataPoolManager.releaseAnimationClip(this);
          }
          SkelAnimDataHub.destroy(this);
          return _Asset.prototype.destroy.call(this);
        };
        _proto[BAKE_SKELETON_CURVE_SYMBOL] = function (start, samples, frames) {
          var step = 1.0 / samples;
          var animatedJoints = this._collectAnimatedJoints();
          var nAnimatedJoints = animatedJoints.length;
          var jointsBakeInfo = {};
          for (var iAnimatedJoint = 0; iAnimatedJoint < nAnimatedJoints; ++iAnimatedJoint) {
            var joint = animatedJoints[iAnimatedJoint];
            jointsBakeInfo[joint] = {
              transforms: Array.from({
                length: frames
              }, function () {
                return new Mat4();
              })
            };
          }
          var skeletonFrames = animatedJoints.reduce(function (result, joint) {
            result[joint] = new BoneGlobalTransform();
            return result;
          }, {});
          for (var _joint in skeletonFrames) {
            var skeletonFrame = skeletonFrames[_joint];
            var parentJoint = _joint.lastIndexOf('/');
            if (parentJoint >= 0) {
              var parentJointName = _joint.substring(0, parentJoint);
              var parentJointFrame = skeletonFrames[parentJointName];
              if (parentJointFrame) {
                skeletonFrame.parent = parentJointFrame;
              }
            }
          }
          var binder = function binder(binding) {
            var trsPath = binding.parseTrsPath();
            if (!trsPath) {
              return undefined;
            }
            var jointFrame = skeletonFrames[trsPath.node];
            if (!jointFrame) {
              return undefined;
            }
            return createBoneTransformBinding(jointFrame, trsPath.property);
          };
          var evaluator = this._createEvalWithBinder(undefined, binder, undefined);
          for (var iFrame = 0; iFrame < frames; ++iFrame) {
            var time = start + step * iFrame;
            evaluator.evaluate(time);
            for (var _iAnimatedJoint = 0; _iAnimatedJoint < nAnimatedJoints; ++_iAnimatedJoint) {
              var _joint2 = animatedJoints[_iAnimatedJoint];
              Mat4.copy(jointsBakeInfo[_joint2].transforms[iFrame], skeletonFrames[_joint2].globalTransform);
            }
            for (var _iAnimatedJoint2 = 0; _iAnimatedJoint2 < nAnimatedJoints; ++_iAnimatedJoint2) {
              var _joint3 = animatedJoints[_iAnimatedJoint2];
              skeletonFrames[_joint3].invalidate();
            }
          }
          return {
            samples: samples,
            frames: frames,
            joints: jointsBakeInfo
          };
        };
        _proto.upgradeUntypedTracks = function upgradeUntypedTracks(refine) {
          var newTracks = [];
          var removals = [];
          var tracks = this._tracks;
          var nTracks = tracks.length;
          for (var iTrack = 0; iTrack < nTracks; ++iTrack) {
            var track = tracks[iTrack];
            if (!(track instanceof UntypedTrack)) {
              continue;
            }
            var newTrack = track.upgrade(refine);
            if (newTrack) {
              newTracks.push(newTrack);
              removals.push(track);
            }
          }
          var nRemovalTracks = removals.length;
          for (var iRemovalTrack = 0; iRemovalTrack < nRemovalTracks; ++iRemovalTrack) {
            remove(tracks, removals[iRemovalTrack]);
          }
          tracks.push.apply(tracks, newTracks);
        };
        _proto[searchForRootBonePathSymbol] = function () {
          return this._searchForRootBonePath();
        };
        _proto.getPropertyCurves = function getPropertyCurves() {
          return this._getLegacyData().getPropertyCurves();
        };
        _proto.updateEventDatas = function updateEventDatas() {
          this.events = this._events;
        };
        _proto.hasEvents = function hasEvents() {
          return this.events.length !== 0;
        };
        _proto.syncLegacyData = function syncLegacyData() {
          if (this._legacyData) {
            this._fromLegacy(this._legacyData);
            this._legacyData = undefined;
          }
        };
        _proto[getEmbeddedPlayersTag] = function () {
          return this._embeddedPlayers;
        };
        _proto[addEmbeddedPlayerTag] = function (embeddedPlayer) {
          this._embeddedPlayers.push(embeddedPlayer);
        };
        _proto[removeEmbeddedPlayerTag] = function (embeddedPlayer) {
          var iEmbeddedPlayer = this._embeddedPlayers.indexOf(embeddedPlayer);
          if (iEmbeddedPlayer >= 0) {
            this._embeddedPlayers.splice(iEmbeddedPlayer, 1);
          }
        };
        _proto[clearEmbeddedPlayersTag] = function () {
          this._embeddedPlayers.length = 0;
        };
        _proto.getAuxiliaryCurveNames_experimental = function getAuxiliaryCurveNames_experimental() {
          return this._auxiliaryCurveEntries.map(function (entry) {
            return entry.name;
          });
        };
        _proto.hasAuxiliaryCurve_experimental = function hasAuxiliaryCurve_experimental(name) {
          return !!this._findAuxiliaryCurveEntry(name);
        };
        _proto.addAuxiliaryCurve_experimental = function addAuxiliaryCurve_experimental(name) {
          var entry = this._findAuxiliaryCurveEntry(name);
          if (!entry) {
            entry = new AuxiliaryCurveEntry();
            entry.name = name;
            this._auxiliaryCurveEntries.push(entry);
          }
          return entry.curve;
        };
        _proto.getAuxiliaryCurve_experimental = function getAuxiliaryCurve_experimental(name) {
          var entry = this._findAuxiliaryCurveEntry(name);
          assertIsTrue(entry);
          return entry.curve;
        };
        _proto.renameAuxiliaryCurve_experimental = function renameAuxiliaryCurve_experimental(name, newName) {
          var entry = this._findAuxiliaryCurveEntry(name);
          if (entry) {
            entry.name = newName;
          }
        };
        _proto.removeAuxiliaryCurve_experimental = function removeAuxiliaryCurve_experimental(name) {
          removeIf(this._auxiliaryCurveEntries, function (entry) {
            return entry.name === name;
          });
        };
        _proto._trySyncLegacyData = function _trySyncLegacyData() {
          if (this._legacyDataDirty) {
            this._legacyDataDirty = false;
            this.syncLegacyData();
          }
        };
        _proto._createEvalWithBinder = function _createEvalWithBinder(target, binder, rootMotionOptions) {
          if (this._legacyDataDirty) {
            this._legacyDataDirty = false;
            this.syncLegacyData();
          }
          var rootMotionTrackExcludes = [];
          var rootMotionEvaluation;
          if (rootMotionOptions) {
            rootMotionEvaluation = this._createRootMotionEvaluation(target, rootMotionOptions, rootMotionTrackExcludes);
          }
          var trackEvalStatues = [];
          var exoticAnimationEvaluator;
          var tracks = this._tracks;
          var nTracks = tracks.length;
          for (var iTrack = 0; iTrack < nTracks; ++iTrack) {
            var track = tracks[iTrack];
            if (rootMotionTrackExcludes.includes(track)) {
              continue;
            }
            if (Array.from(track.channels()).every(function (_ref) {
              var curve = _ref.curve;
              return curve.keyFramesCount === 0;
            })) {
              continue;
            }
            var runtimeBinding = binder(track[trackBindingTag]);
            if (!runtimeBinding) {
              continue;
            }
            var trackEval = void 0;
            if (!(track instanceof UntypedTrack)) {
              trackEval = track[createEvalSymbol]();
            } else {
              if (!runtimeBinding.getValue) {
                errorID(3930);
                continue;
              }
              var hintValue = runtimeBinding.getValue();
              trackEval = track.createLegacyEval(hintValue);
            }
            trackEvalStatues.push(new TrackEvalStatus(runtimeBinding, trackEval));
          }
          if (this._exoticAnimation) {
            exoticAnimationEvaluator = this._exoticAnimation.createEvaluator(binder);
          }
          var evaluation = new AnimationClipEvaluation(trackEvalStatues, exoticAnimationEvaluator, rootMotionEvaluation);
          return evaluation;
        };
        _proto._createRootMotionEvaluation = function _createRootMotionEvaluation(target, rootMotionOptions, rootMotionTrackExcludes) {
          if (!(target instanceof Node$1)) {
            errorID(3920);
            return undefined;
          }
          var rootBonePath = this._searchForRootBonePath();
          if (!rootBonePath) {
            warnID(3923);
            return undefined;
          }
          var rootBone = target.getChildByPath(rootBonePath);
          if (!rootBone) {
            warnID(3924);
            return undefined;
          }
          var boneTransform = new BoneTransform();
          var rootMotionsTrackEvaluations = [];
          var tracks = this._tracks;
          var nTracks = tracks.length;
          for (var iTrack = 0; iTrack < nTracks; ++iTrack) {
            var track = tracks[iTrack];
            var trackBinding = track[trackBindingTag];
            var trsPath = trackBinding.parseTrsPath();
            if (!trsPath) {
              continue;
            }
            var bonePath = trsPath.node;
            if (bonePath !== rootBonePath) {
              continue;
            }
            rootMotionTrackExcludes.push(track);
            var property = trsPath.property;
            var runtimeBinding = createBoneTransformBinding(boneTransform, property);
            if (!runtimeBinding) {
              continue;
            }
            var trackEval = track[createEvalSymbol]();
            rootMotionsTrackEvaluations.push(new TrackEvalStatus(runtimeBinding, trackEval));
          }
          var rootMotionEvaluation = new RootMotionEvaluation(rootBone, this._duration, boneTransform, rootMotionsTrackEvaluations);
          return rootMotionEvaluation;
        };
        _proto._searchForRootBonePath = function _searchForRootBonePath() {
          var paths = this._tracks.map(function (track) {
            var trsPath = track[trackBindingTag].parseTrsPath();
            if (trsPath) {
              var nodePath = trsPath.node;
              return {
                path: nodePath,
                rank: nodePath.split('/').length
              };
            } else {
              return {
                path: '',
                rank: 0
              };
            }
          });
          paths.sort(function (a, b) {
            return a.rank - b.rank;
          });
          var iNonEmptyPath = paths.findIndex(function (p) {
            return p.rank !== 0;
          });
          if (iNonEmptyPath < 0) {
            return '';
          }
          var nPaths = paths.length;
          var firstPath = paths[iNonEmptyPath];
          var highestPathsAreSame = true;
          for (var iPath = iNonEmptyPath + 1; iPath < nPaths; ++iPath) {
            var path = paths[iPath];
            if (path.rank !== firstPath.rank) {
              break;
            }
            if (path.path !== firstPath.path) {
              highestPathsAreSame = false;
              break;
            }
          }
          return highestPathsAreSame ? firstPath.path : '';
        };
        _proto._getLegacyData = function _getLegacyData() {
          if (!this._legacyData) {
            this._legacyData = this._toLegacy();
          }
          return this._legacyData;
        };
        _proto._toLegacy = function _toLegacy() {
          var keys = [];
          var legacyCurves = [];
          var commonTargets = [];
          var legacyClipData = new AnimationClipLegacyData(this._duration);
          legacyClipData.keys = keys;
          legacyClipData.curves = legacyCurves;
          legacyClipData.commonTargets = commonTargets;
          return legacyClipData;
        };
        _proto._fromLegacy = function _fromLegacy(legacyData) {
          var newTracks = legacyData.toTracks();
          var nNewTracks = newTracks.length;
          for (var iNewTrack = 0; iNewTrack < nNewTracks; ++iNewTrack) {
            this.addTrack(newTracks[iNewTrack]);
          }
        };
        _proto._collectAnimatedJoints = function _collectAnimatedJoints() {
          var joints = new Set();
          var tracks = this._tracks;
          var nTracks = tracks.length;
          for (var iTrack = 0; iTrack < nTracks; ++iTrack) {
            var track = tracks[iTrack];
            var trsPath = track[trackBindingTag].parseTrsPath();
            if (trsPath) {
              joints.add(trsPath.node);
            }
          }
          if (this._exoticAnimation) {
            var animatedJoints = this._exoticAnimation.collectAnimatedJoints();
            var nAnimatedJoints = animatedJoints.length;
            for (var iAnimatedJoint = 0; iAnimatedJoint < nAnimatedJoints; ++iAnimatedJoint) {
              joints.add(animatedJoints[iAnimatedJoint]);
            }
          }
          return Array.from(joints);
        };
        _proto._findAuxiliaryCurveEntry = function _findAuxiliaryCurveEntry(name) {
          return this._auxiliaryCurveEntries.find(function (entry) {
            return entry.name === name;
          });
        };
        _createClass(AnimationClip, [{
          key: "duration",
          get: function get() {
            return this._duration;
          },
          set: function set(value) {
            this._duration = value;
          }
        }, {
          key: "tracksCount",
          get: function get() {
            return this._tracks.length;
          }
        }, {
          key: "tracks",
          get: function get() {
            return this._tracks;
          }
        }, {
          key: "hash",
          get: function get() {
            var _this$_exoticAnimatio, _this$_exoticAnimatio2;
            if (this._hash) {
              return this._hash;
            }
            var hashString = "Exotic:" + ((_this$_exoticAnimatio = (_this$_exoticAnimatio2 = this._exoticAnimation) === null || _this$_exoticAnimatio2 === void 0 ? void 0 : _this$_exoticAnimatio2.toHashString()) !== null && _this$_exoticAnimatio !== void 0 ? _this$_exoticAnimatio : '');
            return this._hash = murmurhash2_32_gc(hashString, 666);
          }
        }, {
          key: "events",
          get: function get() {
            return this._events;
          },
          set: function set(value) {
            var _this3 = this;
            this._events = value;
            var ratios = [];
            var eventGroups = [];
            var events = this.events.sort(function (a, b) {
              return a.frame - b.frame;
            });
            var nEvents = events.length;
            var _loop = function _loop() {
              var eventData = events[iEvent];
              var ratio = eventData.frame / _this3._duration;
              var i = ratios.findIndex(function (r) {
                return r === ratio;
              });
              if (i < 0) {
                i = ratios.length;
                ratios.push(ratio);
                eventGroups.push({
                  events: []
                });
              }
              eventGroups[i].events.push({
                functionName: eventData.func,
                parameters: eventData.params
              });
            };
            for (var iEvent = 0; iEvent < nEvents; ++iEvent) {
              _loop();
            }
            this._runtimeEvents = {
              ratios: ratios,
              eventGroups: eventGroups
            };
          }
        }, {
          key: exoticAnimationTag,
          get: function get() {
            return this._exoticAnimation;
          }
        }, {
          key: exoticAnimationTag,
          set: function set(value) {
            this._exoticAnimation = value;
          }
        }, {
          key: "isAdditive_experimental",
          get: function get() {
            return this._additiveSettings.enabled;
          }
        }, {
          key: additiveSettingsTag,
          get: function get() {
            return this._additiveSettings;
          }
        }, {
          key: "keys",
          get: function get() {
            return this._getLegacyData().keys;
          }
        }, {
          key: "keys",
          set: function set(value) {
            this._legacyDataDirty = true;
            this._getLegacyData().keys = value;
          }
        }, {
          key: "curves",
          get: function get() {
            this._legacyDataDirty = true;
            return this._getLegacyData().curves;
          }
        }, {
          key: "curves",
          set: function set(value) {
            this._getLegacyData().curves = value;
          }
        }, {
          key: "commonTargets",
          get: function get() {
            return this._getLegacyData().commonTargets;
          }
        }, {
          key: "commonTargets",
          set: function set(value) {
            this._legacyDataDirty = true;
            this._getLegacyData().commonTargets = value;
          }
        }, {
          key: "data",
          get: function get() {
            return this._getLegacyData().data;
          }
        }, {
          key: "eventGroups",
          get: function get() {
            return this._runtimeEvents.eventGroups;
          }
        }, {
          key: embeddedPlayerCountTag,
          get: function get() {
            return this._embeddedPlayers.length;
          }
        }, {
          key: "auxiliaryCurveCount_experimental",
          get: function get() {
            return this._auxiliaryCurveEntries.length;
          }
        }]);
        return AnimationClip;
      }(Asset), _class3$A.WrapMode = WrapMode, _class3$A), (_initializer$1F = applyDecoratedInitializer(_class2$1M.prototype, "sample", [serializable$p], function () {
        return 60;
      }), _initializer2$1r = applyDecoratedInitializer(_class2$1M.prototype, "speed", [serializable$p], function () {
        return 1;
      }), _initializer3$15 = applyDecoratedInitializer(_class2$1M.prototype, "wrapMode", [serializable$p], function () {
        return WrapMode.Normal;
      }), _initializer4$W = applyDecoratedInitializer(_class2$1M.prototype, "enableTrsBlending", [serializable$p], function () {
        return false;
      }), _initializer5$K = applyDecoratedInitializer(_class2$1M.prototype, "_duration", [serializable$p], function () {
        return 0;
      }), _initializer6$B = applyDecoratedInitializer(_class2$1M.prototype, "_hash", [serializable$p], function () {
        return 0;
      }), _initializer7$u = applyDecoratedInitializer(_class2$1M.prototype, "_tracks", [serializable$p], function () {
        return [];
      }), _initializer8$q = applyDecoratedInitializer(_class2$1M.prototype, "_exoticAnimation", [serializable$p], function () {
        return null;
      }), _initializer9$m = applyDecoratedInitializer(_class2$1M.prototype, "_events", [serializable$p], function () {
        return [];
      }), _initializer10$k = applyDecoratedInitializer(_class2$1M.prototype, "_embeddedPlayers", [serializable$p], function () {
        return [];
      }), _initializer11$k = applyDecoratedInitializer(_class2$1M.prototype, "_additiveSettings", [serializable$p], function () {
        return new AdditiveSettings();
      }), _initializer12$i = applyDecoratedInitializer(_class2$1M.prototype, "_auxiliaryCurveEntries", [serializable$p], function () {
        return [];
      })), _class2$1M)) || _class$1T));
      var AdditiveSettings = (_dec2$1E = ccclass$M('cc.AnimationClipAdditiveSettings'), _dec2$1E(_class4$f = (_class5$g = function AdditiveSettings() {
        this.enabled = _initializer13$f && _initializer13$f();
        this.refClip = _initializer14$c && _initializer14$c();
      }, (_initializer13$f = applyDecoratedInitializer(_class5$g.prototype, "enabled", [serializable$p], function () {
        return false;
      }), _initializer14$c = applyDecoratedInitializer(_class5$g.prototype, "refClip", [serializable$p], function () {
        return null;
      })), _class5$g)) || _class4$f);
      legacyCC.AnimationClip = AnimationClip;
      var TrackEvalStatus = function () {
        function TrackEvalStatus(binding, trackEval) {
          this._binding = void 0;
          this._trackEval = void 0;
          this._shouldEvaluateDefault = true;
          this._binding = binding;
          this._trackEval = trackEval;
          this._shouldEvaluateDefault = !!binding.getValue && trackEval.requiresDefault;
        }
        var _proto2 = TrackEvalStatus.prototype;
        _proto2.evaluate = function evaluate(time) {
          var binding = this._binding,
            trackEval = this._trackEval;
          var defaultValue = this._shouldEvaluateDefault ? binding.getValue() : undefined;
          var value = trackEval.evaluate(time, defaultValue);
          binding.setValue(value);
        };
        return TrackEvalStatus;
      }();
      var EmbeddedPlayerEvaluation = function () {
        function EmbeddedPlayerEvaluation(embeddedPlayers, rootNode) {
          this._embeddedPlayers = embeddedPlayers;
          this._embeddedPlayerEvaluationInfos = embeddedPlayers.map(function (embeddedPlayer) {
            var player = embeddedPlayer.playable;
            if (!player) {
              return null;
            }
            var instantiatedPlayer = player.instantiate(rootNode);
            if (!instantiatedPlayer) {
              return null;
            }
            return {
              instantiatedPlayer: instantiatedPlayer,
              entered: false,
              hostPauseTime: 0.0,
              lastIterations: 0
            };
          });
        }
        var _proto3 = EmbeddedPlayerEvaluation.prototype;
        _proto3.destroy = function destroy() {
          var embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayerEvaluationInfos.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var _embeddedPlayerEvalua;
            (_embeddedPlayerEvalua = embeddedPlayerEvaluationInfos[iEmbeddedPlayer]) === null || _embeddedPlayerEvalua === void 0 ? void 0 : _embeddedPlayerEvalua.instantiatedPlayer.destroy();
          }
          this._embeddedPlayerEvaluationInfos.length = 0;
        };
        _proto3.evaluate = function evaluate(time, iterations) {
          assertIsTrue(Number.isInteger(iterations));
          var embeddedPlayers = this._embeddedPlayers,
            embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayers.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer];
            if (!embeddedPlayerEvaluationInfo) {
              continue;
            }
            var entered = embeddedPlayerEvaluationInfo.entered,
              instantiatedPlayer = embeddedPlayerEvaluationInfo.instantiatedPlayer,
              lastIterations = embeddedPlayerEvaluationInfo.lastIterations;
            var _embeddedPlayers$iEmb = embeddedPlayers[iEmbeddedPlayer],
              begin = _embeddedPlayers$iEmb.begin,
              end = _embeddedPlayers$iEmb.end;
            var withinEmbeddedPlayer = time >= begin && time <= end;
            if (withinEmbeddedPlayer) {
              if (!entered) {
                instantiatedPlayer.play();
                embeddedPlayerEvaluationInfo.entered = true;
              } else if (iterations !== lastIterations) {
                instantiatedPlayer.stop();
                instantiatedPlayer.play();
                embeddedPlayerEvaluationInfo.entered = true;
              }
            } else if (entered) {
              instantiatedPlayer.stop();
              embeddedPlayerEvaluationInfo.entered = false;
            }
            embeddedPlayerEvaluationInfo.lastIterations = iterations;
            if (embeddedPlayerEvaluationInfo.entered) {
              var playerTime = time - begin;
              embeddedPlayerEvaluationInfo.instantiatedPlayer.setTime(playerTime);
            }
          }
        };
        _proto3.notifyHostSpeedChanged = function notifyHostSpeedChanged(speed) {
          var embeddedPlayers = this._embeddedPlayers,
            embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayers.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer];
            if (!embeddedPlayerEvaluationInfo) {
              continue;
            }
            var instantiatedPlayer = embeddedPlayerEvaluationInfo.instantiatedPlayer;
            var reconciledSpeed = embeddedPlayers[iEmbeddedPlayer].reconciledSpeed;
            if (reconciledSpeed) {
              instantiatedPlayer.setSpeed(speed);
            }
          }
        };
        _proto3.notifyHostPlay = function notifyHostPlay(time) {
          var embeddedPlayers = this._embeddedPlayers,
            embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayers.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer];
            if (!embeddedPlayerEvaluationInfo) {
              continue;
            }
            var _embeddedPlayers$iEmb2 = embeddedPlayers[iEmbeddedPlayer],
              begin = _embeddedPlayers$iEmb2.begin,
              end = _embeddedPlayers$iEmb2.end;
            var instantiatedPlayer = embeddedPlayerEvaluationInfo.instantiatedPlayer,
              entered = embeddedPlayerEvaluationInfo.entered;
            if (entered) {
              var hostPauseTime = embeddedPlayerEvaluationInfo.hostPauseTime;
              if (instantiatedPlayer.randomAccess || approx(hostPauseTime, time, 1e-5)) {
                var startTime = clamp$1(time, begin, end);
                instantiatedPlayer.play();
                instantiatedPlayer.setTime(startTime - begin);
              } else {
                instantiatedPlayer.stop();
              }
            }
          }
        };
        _proto3.notifyHostPause = function notifyHostPause(time) {
          var embeddedPlayers = this._embeddedPlayers,
            embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayers.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer];
            if (!embeddedPlayerEvaluationInfo) {
              continue;
            }
            var instantiatedPlayer = embeddedPlayerEvaluationInfo.instantiatedPlayer,
              entered = embeddedPlayerEvaluationInfo.entered;
            if (entered) {
              instantiatedPlayer.pause();
              embeddedPlayerEvaluationInfo.hostPauseTime = time;
            }
          }
        };
        _proto3.notifyHostStop = function notifyHostStop() {
          var embeddedPlayers = this._embeddedPlayers,
            embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayers.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer];
            if (!embeddedPlayerEvaluationInfo) {
              continue;
            }
            var instantiatedPlayer = embeddedPlayerEvaluationInfo.instantiatedPlayer,
              entered = embeddedPlayerEvaluationInfo.entered;
            if (entered) {
              embeddedPlayerEvaluationInfo.entered = false;
              instantiatedPlayer.stop();
            }
          }
        };
        return EmbeddedPlayerEvaluation;
      }();
      var AnimationClipEvaluation = function () {
        function AnimationClipEvaluation(trackEvalStatuses, exoticAnimationEvaluator, rootMotionEvaluation) {
          this._exoticAnimationEvaluator = void 0;
          this._trackEvalStatues = [];
          this._rootMotionEvaluation = undefined;
          this._trackEvalStatues = trackEvalStatuses;
          this._exoticAnimationEvaluator = exoticAnimationEvaluator;
          this._rootMotionEvaluation = rootMotionEvaluation;
        }
        var _proto4 = AnimationClipEvaluation.prototype;
        _proto4.evaluate = function evaluate(time) {
          var trackEvalStatuses = this._trackEvalStatues,
            exoticAnimationEvaluator = this._exoticAnimationEvaluator;
          var nTrackEvalStatuses = trackEvalStatuses.length;
          for (var iTrackEvalStatus = 0; iTrackEvalStatus < nTrackEvalStatuses; ++iTrackEvalStatus) {
            trackEvalStatuses[iTrackEvalStatus].evaluate(time);
          }
          if (exoticAnimationEvaluator) {
            exoticAnimationEvaluator.evaluate(time);
          }
        };
        _proto4.evaluateRootMotion = function evaluateRootMotion(time, motionLength) {
          var rootMotionEvaluation = this._rootMotionEvaluation;
          if (rootMotionEvaluation) {
            rootMotionEvaluation.evaluate(time, motionLength);
          }
        };
        return AnimationClipEvaluation;
      }();
      var BoneTransform = function () {
        function BoneTransform() {
          this.position = new Vec3();
          this.scale = new Vec3(1.0, 1.0, 1.0);
          this.rotation = new Quat();
          this.eulerAngles = new Vec3();
        }
        var _proto5 = BoneTransform.prototype;
        _proto5.getTransform = function getTransform(out) {
          Mat4.fromRTS(out, this.rotation, this.position, this.scale);
        };
        return BoneTransform;
      }();
      var BoneGlobalTransform = function (_BoneTransform) {
        _inheritsLoose(BoneGlobalTransform, _BoneTransform);
        function BoneGlobalTransform() {
          var _this4;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this4 = _BoneTransform.call.apply(_BoneTransform, [this].concat(args)) || this;
          _this4.parent = null;
          _this4._dirty = true;
          _this4._transform = new Mat4();
          return _this4;
        }
        var _proto6 = BoneGlobalTransform.prototype;
        _proto6.invalidate = function invalidate() {
          this._dirty = true;
        };
        _createClass(BoneGlobalTransform, [{
          key: "globalTransform",
          get: function get() {
            var transform = this._transform;
            if (this._dirty) {
              this._dirty = false;
              Mat4.fromRTS(transform, this.rotation, this.position, this.scale);
              if (this.parent) {
                Mat4.multiply(transform, this.parent.globalTransform, transform);
              }
            }
            return this._transform;
          }
        }]);
        return BoneGlobalTransform;
      }(BoneTransform);
      var motionTransformCache = new Mat4();
      var RootMotionEvaluation = function () {
        function RootMotionEvaluation(_rootBone, _duration, _boneTransform, _trackEvalStatuses) {
          this._initialTransformCache = new Mat4();
          this._clipEndTransformCache = new Mat4();
          this._startTransformCache = new Mat4();
          this._endTransformCache = new Mat4();
          this._motionTransformCache = new Mat4();
          this._translationMotionCache = new Vec3();
          this._rotationMotionCache = new Quat();
          this._scaleMotionCache = new Vec3();
          this._rootBone = _rootBone;
          this._duration = _duration;
          this._boneTransform = _boneTransform;
          this._trackEvalStatuses = _trackEvalStatuses;
        }
        var _proto7 = RootMotionEvaluation.prototype;
        _proto7.evaluate = function evaluate(time, motionLength) {
          var motionTransform = this._calcMotionTransform(time, motionLength, this._motionTransformCache);
          var translationMotion = this._translationMotionCache,
            rotationMotion = this._rotationMotionCache,
            scaleMotion = this._scaleMotionCache,
            rootBone = this._rootBone;
          Mat4.toRTS(motionTransform, rotationMotion, translationMotion, scaleMotion);
          Vec3.add(translationMotion, translationMotion, rootBone.position);
          rootBone.setPosition(translationMotion);
          Quat.multiply(rotationMotion, rotationMotion, rootBone.rotation);
          rootBone.setRotation(rotationMotion);
          Vec3.multiply(scaleMotion, scaleMotion, rootBone.scale);
          rootBone.setScale(scaleMotion);
        };
        _proto7._calcMotionTransform = function _calcMotionTransform(time, motionLength, outTransform) {
          var duration = this._duration;
          var remainLength = duration - time;
          assertIsTrue(remainLength >= 0);
          var startTransform = this._evaluateAt(time, this._startTransformCache);
          if (motionLength < remainLength) {
            var endTransform = this._evaluateAt(time + motionLength, this._endTransformCache);
            relativeTransform(outTransform, startTransform, endTransform);
          } else {
            Mat4.identity(outTransform);
            var accumulateMotionTransform = function accumulateMotionTransform(from, to) {
              relativeTransform(motionTransformCache, from, to);
              Mat4.multiply(outTransform, outTransform, motionTransformCache);
            };
            var diff = motionLength - remainLength;
            var repeatCount = Math.floor(diff / duration);
            var lastRemainTime = diff - repeatCount * duration;
            var clipStartTransform = this._evaluateAt(0, this._initialTransformCache);
            var clipEndTransform = this._evaluateAt(duration, this._clipEndTransformCache);
            var _endTransform = this._evaluateAt(lastRemainTime, this._endTransformCache);
            accumulateMotionTransform(startTransform, clipEndTransform);
            relativeTransform(motionTransformCache, clipStartTransform, clipEndTransform);
            for (var i = 0; i < repeatCount; ++i) {
              Mat4.multiply(outTransform, outTransform, motionTransformCache);
            }
            accumulateMotionTransform(clipStartTransform, _endTransform);
          }
          return outTransform;
        };
        _proto7._evaluateAt = function _evaluateAt(time, outTransform) {
          var trackEvalStatuses = this._trackEvalStatuses;
          var nTrackEvalStatuses = trackEvalStatuses.length;
          for (var iTrackEvalStatus = 0; iTrackEvalStatus < nTrackEvalStatuses; ++iTrackEvalStatus) {
            trackEvalStatuses[iTrackEvalStatus].evaluate(time);
          }
          this._boneTransform.getTransform(outTransform);
          return outTransform;
        };
        return RootMotionEvaluation;
      }();
      function relativeTransform(out, from, to) {
        Mat4.invert(out, from);
        Mat4.multiply(out, to, out);
      }
      function createBoneTransformBinding(boneTransform, property) {
        switch (property) {
          default:
            return undefined;
          case 'position':
            return {
              setValue: function setValue(value) {
                Vec3.copy(boneTransform.position, value);
              }
            };
          case 'rotation':
            return {
              setValue: function setValue(value) {
                Quat.copy(boneTransform.rotation, value);
              }
            };
          case 'scale':
            return {
              setValue: function setValue(value) {
                Vec3.copy(boneTransform.scale, value);
              }
            };
          case 'eulerAngles':
            return {
              setValue: function setValue(value) {
                Vec3.copy(boneTransform.eulerAngles, value);
              }
            };
        }
      }
      var InvalidIndex = -1;
      var EventEvaluator = function () {
        function EventEvaluator(_targetNode, _ratios, _eventGroups, _wrapMode) {
          this._lastFrameIndex = -1;
          this._lastIterations = 0.0;
          this._lastDirection = 0;
          this._ignoreIndex = InvalidIndex;
          this._sampled = false;
          this._targetNode = _targetNode;
          this._ratios = _ratios;
          this._eventGroups = _eventGroups;
          this._wrapMode = _wrapMode;
        }
        var _proto8 = EventEvaluator.prototype;
        _proto8.setWrapMode = function setWrapMode(wrapMode) {
          this._wrapMode = wrapMode;
        };
        _proto8.ignore = function ignore(ratio, direction) {
          this._ignoreIndex = InvalidIndex;
          this._sampled = false;
          var frameIndex = getEventGroupIndexAtRatio(ratio, this._ratios);
          if (frameIndex < 0) {
            frameIndex = ~frameIndex - 1;
            if (direction < 0) {
              frameIndex += 1;
            }
            this._ignoreIndex = frameIndex;
          }
        };
        _proto8.reset = function reset() {
          this._lastFrameIndex = -1;
          this._lastIterations = 0.0;
          this._lastDirection = 0;
          this._ignoreIndex = InvalidIndex;
          this._sampled = false;
        };
        _proto8.sample = function sample(ratio, direction, iterations) {
          if (this._eventGroups.length === 0) {
            return;
          }
          var length = this._eventGroups.length;
          var eventIndex = getEventGroupIndexAtRatio(ratio, this._ratios);
          if (eventIndex < 0) {
            eventIndex = ~eventIndex - 1;
            if (direction < 0) {
              eventIndex += 1;
            }
          }
          if (this._ignoreIndex !== eventIndex) {
            this._ignoreIndex = InvalidIndex;
          }
          if (!this._sampled) {
            this._sampled = true;
            this._doFire(eventIndex, false);
            this._lastFrameIndex = eventIndex;
            this._lastIterations = iterations;
            this._lastDirection = direction;
            return;
          }
          var wrapMode = this._wrapMode;
          var currentIterations = wrapIterations(iterations);
          var lastIterations = wrapIterations(this._lastIterations);
          var lastIndex = this._lastFrameIndex;
          var lastDirection = this._lastDirection;
          var iterationsChanged = lastIterations !== -1 && currentIterations !== lastIterations;
          if (lastIndex === eventIndex && iterationsChanged && length === 1) {
            this._doFire(0, false);
          } else if (lastIndex !== eventIndex || iterationsChanged) {
            direction = lastDirection;
            do {
              if (lastIndex !== eventIndex) {
                if (direction === -1 && lastIndex === 0 && eventIndex > 0) {
                  if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
                    direction *= -1;
                  } else {
                    lastIndex = length;
                  }
                  lastIterations++;
                } else if (direction === 1 && lastIndex === length - 1 && eventIndex < length - 1) {
                  if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
                    direction *= -1;
                  } else {
                    lastIndex = -1;
                  }
                  lastIterations++;
                }
                if (lastIndex === eventIndex) {
                  break;
                }
                if (lastIterations > currentIterations) {
                  break;
                }
              }
              lastIndex += direction;
              this._doFire(lastIndex, true);
            } while (lastIndex !== eventIndex && lastIndex > -1 && lastIndex < length);
          }
          this._lastFrameIndex = eventIndex;
          this._lastIterations = iterations;
          this._lastDirection = direction;
        };
        _proto8._doFire = function _doFire(eventIndex, delay) {
          if (delay) {
            getGlobalAnimationManager().pushDelayEvent(this._checkAndFire, this, [eventIndex]);
          } else {
            this._checkAndFire(eventIndex);
          }
        };
        _proto8._checkAndFire = function _checkAndFire(eventIndex) {
          if (!this._targetNode || !this._targetNode.isValid) {
            return;
          }
          var eventGroups = this._eventGroups;
          if (eventIndex < 0 || eventIndex >= eventGroups.length || this._ignoreIndex === eventIndex) {
            return;
          }
          var eventGroup = eventGroups[eventIndex];
          var nEvents = eventGroup.events.length;
          for (var iEvent = 0; iEvent < nEvents; ++iEvent) {
            var event = eventGroup.events[iEvent];
            invokeComponentMethodsEngagedInAnimationEvent(this._targetNode, event.functionName, event.parameters);
          }
        };
        return EventEvaluator;
      }();
      function wrapIterations(iterations) {
        if (iterations - (iterations | 0) === 0) {
          iterations -= 1;
        }
        return iterations | 0;
      }
      function getEventGroupIndexAtRatio(ratio, ratios) {
        var result = binarySearchEpsilon(ratios, ratio);
        return result;
      }

      function wrap(elapsedTime, duration, wrapMode, repeatCount, negativeSpeed, info) {
        if (duration === 0.0) {
          info.time = 0.0;
          info.ratio = 0.0;
          info.direction = 1.0;
          info.stopped = !!Number.isFinite(repeatCount);
          info.iterations = 0.0;
          return info;
        }
        var stopped = false;
        var currentIterations = elapsedTime > 0 ? elapsedTime / duration : -(elapsedTime / duration);
        if (currentIterations >= repeatCount) {
          currentIterations = repeatCount;
          stopped = true;
          var tempRatio = repeatCount - (repeatCount | 0);
          if (tempRatio === 0) {
            tempRatio = 1;
          }
          elapsedTime = tempRatio * duration * (elapsedTime > 0 ? 1 : -1);
        }
        if (elapsedTime > duration) {
          var tempTime = elapsedTime % duration;
          elapsedTime = tempTime === 0 ? duration : tempTime;
        } else if (elapsedTime < 0) {
          elapsedTime %= duration;
          if (elapsedTime !== 0) {
            elapsedTime += duration;
          }
        }
        var needReverse = false;
        var shouldWrap = wrapMode & WrapModeMask.ShouldWrap;
        if (shouldWrap) {
          needReverse = isReverseIteration(wrapMode, currentIterations);
        }
        var direction = needReverse ? -1 : 1;
        if (negativeSpeed) {
          direction *= -1;
        }
        if (shouldWrap && needReverse) {
          elapsedTime = duration - elapsedTime;
        }
        info.time = elapsedTime;
        info.ratio = info.time / duration;
        info.direction = direction;
        info.stopped = stopped;
        info.iterations = currentIterations;
        return info;
      }
      function isReverseIteration(wrapMode, currentIterations) {
        var needReverse = false;
        if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
          var isEnd = currentIterations - (currentIterations | 0) === 0;
          if (isEnd && currentIterations > 0) {
            currentIterations -= 1;
          }
          var isOddIteration = currentIterations & 1;
          if (isOddIteration) {
            needReverse = !needReverse;
          }
        }
        if ((wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) {
          needReverse = !needReverse;
        }
        return needReverse;
      }

      var CACHE_VEC3_GET_VALUE = new Vec3();
      var CACHE_QUAT_GET_VALUE = new Quat();
      var PoseBindingBase = function () {
        function PoseBindingBase(transformHandle) {
          this._transformHandle = transformHandle;
        }
        var _proto = PoseBindingBase.prototype;
        _proto.destroy = function destroy() {
          this._transformHandle.destroy();
        };
        return PoseBindingBase;
      }();
      var PosePositionBinding = function (_PoseBindingBase) {
        _inheritsLoose(PosePositionBinding, _PoseBindingBase);
        function PosePositionBinding() {
          return _PoseBindingBase.apply(this, arguments) || this;
        }
        var _proto2 = PosePositionBinding.prototype;
        _proto2.setValue = function setValue(value, pose) {
          pose.transforms.setPosition(this._transformHandle.index, value);
        };
        _proto2.getValue = function getValue(pose) {
          return pose.transforms.getPosition(this._transformHandle.index, CACHE_VEC3_GET_VALUE);
        };
        return PosePositionBinding;
      }(PoseBindingBase);
      var PoseRotationBinding = function (_PoseBindingBase2) {
        _inheritsLoose(PoseRotationBinding, _PoseBindingBase2);
        function PoseRotationBinding() {
          return _PoseBindingBase2.apply(this, arguments) || this;
        }
        var _proto3 = PoseRotationBinding.prototype;
        _proto3.setValue = function setValue(value, pose) {
          pose.transforms.setRotation(this._transformHandle.index, value);
        };
        _proto3.getValue = function getValue(pose) {
          return pose.transforms.getRotation(this._transformHandle.index, CACHE_QUAT_GET_VALUE);
        };
        return PoseRotationBinding;
      }(PoseBindingBase);
      var PoseEulerAnglesBinding = function (_PoseBindingBase3) {
        _inheritsLoose(PoseEulerAnglesBinding, _PoseBindingBase3);
        function PoseEulerAnglesBinding() {
          return _PoseBindingBase3.apply(this, arguments) || this;
        }
        var _proto4 = PoseEulerAnglesBinding.prototype;
        _proto4.setValue = function setValue(value, pose) {
          var quat = Quat.fromEuler(PoseEulerAnglesBinding._EULER_TO_QUAT_CACHE, value.x, value.y, value.z);
          pose.transforms.setRotation(this._transformHandle.index, quat);
        };
        _proto4.getValue = function getValue(pose) {
          var q = pose.transforms.getRotation(this._transformHandle.index, CACHE_QUAT_GET_VALUE);
          return Quat.toEuler(CACHE_VEC3_GET_VALUE, q);
        };
        return PoseEulerAnglesBinding;
      }(PoseBindingBase);
      PoseEulerAnglesBinding._EULER_TO_QUAT_CACHE = new Quat();
      var PoseScaleBinding = function (_PoseBindingBase4) {
        _inheritsLoose(PoseScaleBinding, _PoseBindingBase4);
        function PoseScaleBinding() {
          return _PoseBindingBase4.apply(this, arguments) || this;
        }
        var _proto5 = PoseScaleBinding.prototype;
        _proto5.setValue = function setValue(value, pose) {
          pose.transforms.setScale(this._transformHandle.index, value);
        };
        _proto5.getValue = function getValue(pose) {
          return pose.transforms.getScale(this._transformHandle.index, CACHE_VEC3_GET_VALUE);
        };
        return PoseScaleBinding;
      }(PoseBindingBase);
      var AuxiliaryCurveBinding = function () {
        function AuxiliaryCurveBinding(_handle) {
          this._handle = _handle;
        }
        var _proto6 = AuxiliaryCurveBinding.prototype;
        _proto6.destroy = function destroy() {
          this._handle.destroy();
        };
        _proto6.setValue = function setValue(value, pose) {
          pose.auxiliaryCurves[this._handle.index] = value;
        };
        _proto6.getValue = function getValue(pose) {
          return pose.auxiliaryCurves[this._handle.index];
        };
        return AuxiliaryCurveBinding;
      }();
      function bindPoseTransform(transformHandle, propertyKey) {
        switch (propertyKey) {
          case 'position':
            return new PosePositionBinding(transformHandle);
          case 'rotation':
            return new PoseRotationBinding(transformHandle);
          case 'eulerAngles':
            return new PoseEulerAnglesBinding(transformHandle);
          case 'scale':
            return new PoseScaleBinding(transformHandle);
          default:
            assertIsTrue(false);
        }
      }
      var NonTransformPoseBinding = function () {
        function NonTransformPoseBinding(binding) {
          this.binding = binding;
        }
        var _proto7 = NonTransformPoseBinding.prototype;
        _proto7.destroy = function destroy() {};
        _proto7.setValue = function setValue(value, _pose) {
          this.binding.setValue(value);
        };
        _proto7.getValue = function getValue(pose) {
          var _this$binding$getValu, _this$binding$getValu2, _this$binding;
          return (_this$binding$getValu = (_this$binding$getValu2 = (_this$binding = this.binding).getValue) === null || _this$binding$getValu2 === void 0 ? void 0 : _this$binding$getValu2.call(_this$binding)) !== null && _this$binding$getValu !== void 0 ? _this$binding$getValu : undefined;
        };
        return NonTransformPoseBinding;
      }();
      var AGTrackEvaluation = function () {
        function AGTrackEvaluation(binding, trackEvaluation) {
          this._binding = void 0;
          this._trackSampler = void 0;
          this._binding = binding;
          this._trackSampler = trackEvaluation;
        }
        var _proto8 = AGTrackEvaluation.prototype;
        _proto8.destroy = function destroy() {
          this._binding.destroy();
        };
        _proto8.evaluate = function evaluate(time, pose) {
          var trackSampler = this._trackSampler,
            binding = this._binding;
          var defaultValue = trackSampler.requiresDefault ? binding.getValue(pose) : undefined;
          var value = trackSampler.evaluate(time, defaultValue);
          binding.setValue(value, pose);
        };
        return AGTrackEvaluation;
      }();
      function bindTrackAG(animationClip, track, bindContext) {
        var trackBinding = track[trackBindingTag];
        var trackTarget = createRuntimeBindingAG(trackBinding, bindContext);
        if (!trackTarget) {
          warnID(3937, animationClip.name, bindContext.origin.name);
        }
        return trackTarget !== null && trackTarget !== void 0 ? trackTarget : undefined;
      }
      function createRuntimeBindingAG(track, bindContext) {
        var origin = bindContext.origin;
        var path = track.path,
          proxy = track.proxy;
        var nPaths = path.length;
        var iLastPath = nPaths - 1;
        if (nPaths !== 0 && (path.isPropertyAt(iLastPath) || path.isElementAt(iLastPath)) && !proxy) {
          var lastPropertyKey = path.isPropertyAt(iLastPath) ? path.parsePropertyAt(iLastPath) : path.parseElementAt(iLastPath);
          var resultTarget = path[normalizedFollowTag](origin, 0, nPaths - 1);
          if (resultTarget === null) {
            return null;
          }
          if (resultTarget instanceof Node$1 && isTrsPropertyName(lastPropertyKey)) {
            var transformPath = function () {
              var segments = [];
              var node = resultTarget;
              for (; node && node !== origin; node = node.parent) {
                segments.unshift(node.name);
              }
              if (node === origin) {
                return segments.join('/');
              } else {
                return undefined;
              }
            }();
            if (typeof transformPath === 'string') {
              var transformHandle = bindContext.bindTransform(transformPath);
              if (!transformHandle) {
                return undefined;
              }
              return bindPoseTransform(transformHandle, lastPropertyKey);
            }
          }
        }
        {
          var nonTransformBinding = track.createRuntimeBinding(bindContext.origin, undefined, false);
          if (!nonTransformBinding) {
            return null;
          }
          return new NonTransformPoseBinding(nonTransformBinding);
        }
      }
      var AuxiliaryCurveEvaluation = function () {
        function AuxiliaryCurveEvaluation(_binding, _curve) {
          this._binding = _binding;
          this._curve = _curve;
        }
        var _proto9 = AuxiliaryCurveEvaluation.prototype;
        _proto9.evaluate = function evaluate(time, context) {
          var curve = this._curve,
            binding = this._binding;
          var pose = context;
          var value = curve.evaluate(time);
          binding.setValue(value, pose);
        };
        return AuxiliaryCurveEvaluation;
      }();
      function createAnimationAGEvaluation(clip, context) {
        if (clip.isAdditive_experimental) {
          return new AnimationClipAGEvaluationAdditive(clip, context);
        } else {
          return new AnimationClipAGEvaluationRegular(clip, context);
        }
      }
      var AnimationClipAGEvaluationRegular = function () {
        function AnimationClipAGEvaluationRegular(clip, context) {
          this._trackEvaluations = [];
          this._exoticAnimationEvaluation = void 0;
          this._auxiliaryCurveEvaluations = [];
          clip._trySyncLegacyData();
          var trackEvaluations = [];
          var exoticAnimationEvaluation;
          var auxiliaryCurveEvaluations = [];
          var tracks = clip.tracks;
          var exoticAnimation = clip[exoticAnimationTag];
          for (var _iterator = _createForOfIteratorHelperLoose(tracks), _step; !(_step = _iterator()).done;) {
            var track = _step.value;
            if (track instanceof UntypedTrack) {
              continue;
            }
            if (Array.from(track.channels()).every(function (_ref) {
              var curve = _ref.curve;
              return curve.keyFramesCount === 0;
            })) {
              continue;
            }
            var trackRuntimeBinding = bindTrackAG(clip, track, context);
            if (!trackRuntimeBinding) {
              continue;
            }
            var trackSampler = track[createEvalSymbol]();
            var trackEvaluation = new AGTrackEvaluation(trackRuntimeBinding, trackSampler);
            trackEvaluations.push(trackEvaluation);
          }
          if (exoticAnimation) {
            exoticAnimationEvaluation = exoticAnimation.createEvaluatorForAnimationGraph(context);
          }
          var auxiliaryCurveNames = clip.getAuxiliaryCurveNames_experimental();
          var nAuxiliaryCurves = auxiliaryCurveNames.length;
          for (var iAuxiliaryCurve = 0; iAuxiliaryCurve < nAuxiliaryCurves; ++iAuxiliaryCurve) {
            var _curveName = auxiliaryCurveNames[iAuxiliaryCurve];
            var curve = clip.getAuxiliaryCurve_experimental(_curveName);
            var handle = context.bindAuxiliaryCurve(_curveName);
            var _binding2 = new AuxiliaryCurveBinding(handle);
            auxiliaryCurveEvaluations.push(new AuxiliaryCurveEvaluation(_binding2, curve));
          }
          this._trackEvaluations = trackEvaluations;
          this._exoticAnimationEvaluation = exoticAnimationEvaluation;
          this._auxiliaryCurveEvaluations = auxiliaryCurveEvaluations;
        }
        var _proto10 = AnimationClipAGEvaluationRegular.prototype;
        _proto10.destroy = function destroy() {
          var _this$_exoticAnimatio;
          (_this$_exoticAnimatio = this._exoticAnimationEvaluation) === null || _this$_exoticAnimatio === void 0 ? void 0 : _this$_exoticAnimatio.destroy();
          var trackEvaluations = this._trackEvaluations;
          var nTrackEvaluations = trackEvaluations.length;
          for (var iNodeEvaluation = 0; iNodeEvaluation < nTrackEvaluations; ++iNodeEvaluation) {
            trackEvaluations[iNodeEvaluation].destroy();
          }
        };
        _proto10.evaluate = function evaluate(time, context) {
          var trackEvaluations = this._trackEvaluations,
            exoticAnimationEvaluation = this._exoticAnimationEvaluation,
            auxiliaryCurveEvaluations = this._auxiliaryCurveEvaluations;
          var pose = context.pushDefaultedPose();
          var nTrackEvaluations = trackEvaluations.length;
          for (var iNodeEvaluation = 0; iNodeEvaluation < nTrackEvaluations; ++iNodeEvaluation) {
            trackEvaluations[iNodeEvaluation].evaluate(time, pose);
          }
          if (exoticAnimationEvaluation) {
            exoticAnimationEvaluation.evaluate(time, pose);
          }
          var nAuxiliaryCurveEvaluations = auxiliaryCurveEvaluations.length;
          for (var iAuxiliaryCurveEvaluation = 0; iAuxiliaryCurveEvaluation < nAuxiliaryCurveEvaluations; ++iAuxiliaryCurveEvaluation) {
            auxiliaryCurveEvaluations[iAuxiliaryCurveEvaluation].evaluate(time, pose);
          }
          return pose;
        };
        return AnimationClipAGEvaluationRegular;
      }();
      var AnimationClipAGEvaluationAdditive = function () {
        function AnimationClipAGEvaluationAdditive(clip, context) {
          this._clipEval = void 0;
          this._refClipEval = void 0;
          this._clipEval = new AnimationClipAGEvaluationRegular(clip, context);
          var refClip = clip[additiveSettingsTag].refClip;
          if (refClip && refClip !== clip) {
            this._refClipEval = new AnimationClipAGEvaluationRegular(refClip, context);
          }
        }
        var _proto11 = AnimationClipAGEvaluationAdditive.prototype;
        _proto11.destroy = function destroy() {
          var _this$_refClipEval;
          this._clipEval.destroy();
          (_this$_refClipEval = this._refClipEval) === null || _this$_refClipEval === void 0 ? void 0 : _this$_refClipEval.destroy();
        };
        _proto11.evaluate = function evaluate(time, context) {
          var pose = this._clipEval.evaluate(time, context);
          var refPose;
          if (this._refClipEval) {
            var refClipTime = 0.0;
            refPose = this._refClipEval.evaluate(refClipTime, context);
          } else {
            refPose = this._clipEval.evaluate(0.0, context);
          }
          calculateDeltaPose(pose, refPose);
          context.popPose();
          return pose;
        };
        return AnimationClipAGEvaluationAdditive;
      }();

      var _dec$1V, _dec2$1D, _class$1S, _class2$1L, _initializer$1E;
      var ccclass$C = ccclass$M,
        type$7 = type$d;
      var ClipMotion = (_dec$1V = ccclass$C('cc.animation.ClipMotion'), _dec2$1D = type$7(AnimationClip), _dec$1V(_class$1S = (_class2$1L = function (_Motion) {
        _inheritsLoose(ClipMotion, _Motion);
        function ClipMotion() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Motion.call.apply(_Motion, [this].concat(args)) || this;
          _this.clip = _initializer$1E && _initializer$1E();
          return _this;
        }
        var _proto = ClipMotion.prototype;
        _proto[createEval] = function (context, ignoreEmbeddedPlayers) {
          if (!this.clip) {
            return null;
          }
          var clipMotionEval = new ClipMotionEval(context, this.clip, ignoreEmbeddedPlayers);
          return clipMotionEval;
        };
        _proto.clone = function clone() {
          var that = new ClipMotion();
          that.clip = this.clip;
          that[editorExtrasTag] = cloneAnimationGraphEditorExtrasFrom(this);
          return that;
        };
        return ClipMotion;
      }(Motion), (_initializer$1E = applyDecoratedInitializer(_class2$1L.prototype, "clip", [_dec2$1D, serializable$p], function () {
        return null;
      })), _class2$1L)) || _class$1S);
      var evaluatePortTag = Symbol('EvaluatePort');
      var ClipMotionEval = function () {
        function ClipMotionEval(context, clip, ignoreEmbeddedPlayers) {
          var _context$clipOverride, _context$clipOverride2;
          this._clipEmbeddedPlayerEval = null;
          this._frameEventEval = null;
          this._wrapInfo = new WrappedInfo();
          this._duration = 0.0;
          this._ignoreEmbeddedPlayers = void 0;
          this._originalClip = clip;
          this._ignoreEmbeddedPlayers = ignoreEmbeddedPlayers;
          var overriding = (_context$clipOverride = (_context$clipOverride2 = context.clipOverrides) === null || _context$clipOverride2 === void 0 ? void 0 : _context$clipOverride2.get(clip)) !== null && _context$clipOverride !== void 0 ? _context$clipOverride : clip;
          this._setClip(overriding, context);
        }
        var _proto2 = ClipMotionEval.prototype;
        _proto2.createPort = function createPort() {
          return new ClipMotionPort(this);
        };
        _proto2.getClipStatuses = function getClipStatuses(baseWeight) {
          var _this2 = this;
          var got = false;
          return {
            next: function next() {
              if (got) {
                return {
                  done: true,
                  value: undefined
                };
              } else {
                got = true;
                return {
                  done: false,
                  value: {
                    __DEBUG_ID__: _this2.__DEBUG__ID__,
                    clip: _this2._clip,
                    weight: baseWeight
                  }
                };
              }
            }
          };
        };
        _proto2[evaluatePortTag] = function (progress, context) {
          var _this$_frameEventEval, _this$_clipEmbeddedPl;
          var duration = this._duration,
            clipDuration = this._clip.duration,
            clipEval = this._clipEval;
          var elapsedTime = duration * progress;
          var wrapMode = this._clip.wrapMode;
          var repeatCount = (wrapMode & WrapModeMask.Loop) === WrapModeMask.Loop ? Infinity : 1;
          var wrapInfo = wrap(elapsedTime, duration, wrapMode, repeatCount, false, this._wrapInfo);
          var clipTime = wrapInfo.ratio * clipDuration;
          var pose = clipEval.evaluate(clipTime, context);
          (_this$_frameEventEval = this._frameEventEval) === null || _this$_frameEventEval === void 0 ? void 0 : _this$_frameEventEval.sample(wrapInfo.ratio, wrapInfo.direction, wrapInfo.iterations);
          (_this$_clipEmbeddedPl = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl === void 0 ? void 0 : _this$_clipEmbeddedPl.evaluate(clipTime, Math.trunc(wrapInfo.iterations));
          return pose;
        };
        _proto2.overrideClips = function overrideClips(context) {
          var _context$clipOverride3;
          var originalClip = this._originalClip;
          var overriding = (_context$clipOverride3 = context.clipOverrides) === null || _context$clipOverride3 === void 0 ? void 0 : _context$clipOverride3.get(originalClip);
          if (overriding) {
            this._setClip(overriding, context);
          }
        };
        _proto2.reenter = function reenter() {
          var _this$_frameEventEval2;
          (_this$_frameEventEval2 = this._frameEventEval) === null || _this$_frameEventEval2 === void 0 ? void 0 : _this$_frameEventEval2.reset();
        };
        _proto2._setClip = function _setClip(clip, context) {
          var _this$_clipEval;
          (_this$_clipEval = this._clipEval) === null || _this$_clipEval === void 0 ? void 0 : _this$_clipEval.destroy();
          this._frameEventEval = null;
          if (this._clipEmbeddedPlayerEval) {
            this._clipEmbeddedPlayerEval.destroy();
            this._clipEmbeddedPlayerEval = null;
          }
          this._clip = clip;
          this._duration = clip.speed === 0.0 ? 0.0 : clip.duration / clip.speed;
          this._clipEval = createAnimationAGEvaluation(clip, context);
          this._frameEventEval = clip.createEventEvaluator(context.origin);
          if (!this._ignoreEmbeddedPlayers && clip.containsAnyEmbeddedPlayer()) {
            this._clipEmbeddedPlayerEval = clip.createEmbeddedPlayerEvaluator(context.origin);
          }
        };
        _createClass(ClipMotionEval, [{
          key: "duration",
          get: function get() {
            return this._duration;
          }
        }]);
        return ClipMotionEval;
      }();
      var ClipMotionPort = function () {
        function ClipMotionPort(host) {
          this._eval = void 0;
          this._eval = host;
        }
        var _proto3 = ClipMotionPort.prototype;
        _proto3.evaluate = function evaluate(progress, context) {
          return this._eval[evaluatePortTag](progress, context);
        };
        _proto3.reenter = function reenter() {
          this._eval.reenter();
        };
        return ClipMotionPort;
      }();

      var _dec$1U, _class$1R, _class2$1K, _initializer$1D, _dec2$1C, _class4$e, _class5$f, _initializer2$1q;
      var ccclass$B = ccclass$M,
        serializable$g = serializable$p;
      var AnimationBlendItem = (_dec$1U = ccclass$B(CLASS_NAME_PREFIX_ANIM + "AnimationBlendItem"), _dec$1U(_class$1R = (_class2$1K = function () {
        function AnimationBlendItem() {
          this.motion = _initializer$1D && _initializer$1D();
        }
        var _proto = AnimationBlendItem.prototype;
        _proto.clone = function clone() {
          var that = new AnimationBlendItem();
          this._copyTo(that);
          return that;
        };
        _proto._copyTo = function _copyTo(that) {
          var _this$motion$clone, _this$motion;
          that.motion = (_this$motion$clone = (_this$motion = this.motion) === null || _this$motion === void 0 ? void 0 : _this$motion.clone()) !== null && _this$motion$clone !== void 0 ? _this$motion$clone : null;
          return that;
        };
        return AnimationBlendItem;
      }(), (_initializer$1D = applyDecoratedInitializer(_class2$1K.prototype, "motion", [serializable$g], function () {
        return null;
      })), _class2$1K)) || _class$1R);
      var AnimationBlend = (_dec2$1C = ccclass$B(CLASS_NAME_PREFIX_ANIM + "AnimationBlend"), _dec2$1C(_class4$e = (_class5$f = function (_Motion) {
        _inheritsLoose(AnimationBlend, _Motion);
        function AnimationBlend() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Motion.call.apply(_Motion, [this].concat(args)) || this;
          _this.name = _initializer2$1q && _initializer2$1q();
          return _this;
        }
        var _proto2 = AnimationBlend.prototype;
        _proto2.copyTo = function copyTo(that) {
          that.name = this.name;
          that[editorExtrasTag] = cloneAnimationGraphEditorExtrasFrom(this);
        };
        return AnimationBlend;
      }(Motion), (_initializer2$1q = applyDecoratedInitializer(_class5$f.prototype, "name", [serializable$g], function () {
        return '';
      })), _class5$f)) || _class4$e);
      var AnimationBlendEval = function () {
        function AnimationBlendEval(context, ignoreEmbeddedPlayers, base, children, inputs) {
          this._childEvaluators = children.map(function (child) {
            var _child$motion$createE, _child$motion;
            return (_child$motion$createE = (_child$motion = child.motion) === null || _child$motion === void 0 ? void 0 : _child$motion[createEval](context, ignoreEmbeddedPlayers)) !== null && _child$motion$createE !== void 0 ? _child$motion$createE : null;
          });
          this._weights = new Array(this._childEvaluators.length).fill(0);
          this._inputs = [].concat(inputs);
        }
        var _proto3 = AnimationBlendEval.prototype;
        _proto3.createPort = function createPort() {
          return new AnimationBlendPort(this, this._childEvaluators.map(function (childEval) {
            var _childEval$createPort;
            return (_childEval$createPort = childEval === null || childEval === void 0 ? void 0 : childEval.createPort()) !== null && _childEval$createPort !== void 0 ? _childEval$createPort : null;
          }));
        };
        _proto3.getChildWeight = function getChildWeight(childIndex) {
          return this._weights[childIndex];
        };
        _proto3.getChildMotionEval = function getChildMotionEval(childIndex) {
          return this._childEvaluators[childIndex];
        };
        _proto3.getClipStatuses = function getClipStatuses(baseWeight) {
          var children = this._childEvaluators,
            weights = this._weights;
          var nChildren = children.length;
          var iChild = 0;
          var currentChildIterator;
          return {
            next: function next() {
              while (true) {
                if (currentChildIterator) {
                  var result = currentChildIterator.next();
                  if (!result.done) {
                    return result;
                  }
                }
                if (iChild >= nChildren) {
                  return {
                    done: true,
                    value: undefined
                  };
                } else {
                  var child = children[iChild];
                  currentChildIterator = child === null || child === void 0 ? void 0 : child.getClipStatuses(baseWeight * weights[iChild]);
                  ++iChild;
                }
              }
            }
          };
        };
        _proto3.__evaluatePort = function __evaluatePort(port, progress, context) {
          var nChild = this._childEvaluators.length;
          var sumWeight = 0.0;
          var finalPose = null;
          for (var iChild = 0; iChild < nChild; ++iChild) {
            var _port$childPorts$iChi;
            var childWeight = this._weights[iChild];
            if (!childWeight) {
              continue;
            }
            var childOutput = (_port$childPorts$iChi = port.childPorts[iChild]) === null || _port$childPorts$iChi === void 0 ? void 0 : _port$childPorts$iChi.evaluate(progress, context);
            if (!childOutput) {
              continue;
            }
            sumWeight += childWeight;
            if (!finalPose) {
              finalPose = childOutput;
            } else {
              if (sumWeight) {
                var t = childWeight / sumWeight;
                blendPoseInto(finalPose, childOutput, t);
              }
              context.popPose();
            }
          }
          if (finalPose) {
            return finalPose;
          }
          return context.pushDefaultedPose();
        };
        _proto3.overrideClips = function overrideClips(context) {
          for (var iChild = 0; iChild < this._childEvaluators.length; ++iChild) {
            var _this$_childEvaluator;
            (_this$_childEvaluator = this._childEvaluators[iChild]) === null || _this$_childEvaluator === void 0 ? void 0 : _this$_childEvaluator.overrideClips(context);
          }
        };
        _proto3.setInput = function setInput(value, index) {
          this._inputs[index] = value;
          this.doEval();
        };
        _proto3.doEval = function doEval() {
          this.eval(this._weights, this._inputs);
        };
        _createClass(AnimationBlendEval, [{
          key: "childCount",
          get: function get() {
            return this._weights.length;
          }
        }, {
          key: "duration",
          get: function get() {
            var uniformDuration = 0.0;
            for (var iChild = 0; iChild < this._childEvaluators.length; ++iChild) {
              var _this$_childEvaluator2, _this$_childEvaluator3;
              uniformDuration += ((_this$_childEvaluator2 = (_this$_childEvaluator3 = this._childEvaluators[iChild]) === null || _this$_childEvaluator3 === void 0 ? void 0 : _this$_childEvaluator3.duration) !== null && _this$_childEvaluator2 !== void 0 ? _this$_childEvaluator2 : 0.0) * this._weights[iChild];
            }
            return uniformDuration;
          }
        }]);
        return AnimationBlendEval;
      }();
      var AnimationBlendPort = function () {
        function AnimationBlendPort(host, childPorts) {
          this.childPorts = [];
          this._host = void 0;
          this._host = host;
          this.childPorts = childPorts;
        }
        var _proto4 = AnimationBlendPort.prototype;
        _proto4.evaluate = function evaluate(progress, context) {
          return this._host.__evaluatePort(this, progress, context);
        };
        _proto4.reenter = function reenter() {
          var childPorts = this.childPorts;
          var nChildPorts = childPorts.length;
          for (var iChild = 0; iChild < nChildPorts; ++iChild) {
            var _childPorts$iChild;
            (_childPorts$iChild = childPorts[iChild]) === null || _childPorts$iChild === void 0 ? void 0 : _childPorts$iChild.reenter();
          }
        };
        return AnimationBlendPort;
      }();

      var _dec$1T, _class$1Q, _class2$1J, _initializer$1C, _initializer2$1p, _dec2$1B, _class4$d, _class5$e, _initializer3$14, _initializer4$V;
      var ccclass$A = ccclass$M,
        serializable$f = serializable$p;
      var BindableNumber = (_dec$1T = ccclass$A(CLASS_NAME_PREFIX_ANIM + "BindableNumber"), _dec$1T(_class$1Q = (_class2$1J = function () {
        function BindableNumber(value) {
          if (value === void 0) {
            value = 0.0;
          }
          this.variable = _initializer$1C && _initializer$1C();
          this.value = _initializer2$1p && _initializer2$1p();
          this.value = value;
        }
        var _proto = BindableNumber.prototype;
        _proto.clone = function clone() {
          var that = new BindableNumber();
          that.value = this.value;
          that.variable = this.variable;
          return that;
        };
        return BindableNumber;
      }(), (_initializer$1C = applyDecoratedInitializer(_class2$1J.prototype, "variable", [serializable$f], function () {
        return '';
      }), _initializer2$1p = applyDecoratedInitializer(_class2$1J.prototype, "value", [serializable$f], function () {
        return 0.0;
      })), _class2$1J)) || _class$1Q);
      var BindableBoolean = (_dec2$1B = ccclass$A(CLASS_NAME_PREFIX_ANIM + "BindableBoolean"), _dec2$1B(_class4$d = (_class5$e = function () {
        function BindableBoolean(value) {
          if (value === void 0) {
            value = false;
          }
          this.variable = _initializer3$14 && _initializer3$14();
          this.value = _initializer4$V && _initializer4$V();
          this.value = value;
        }
        var _proto2 = BindableBoolean.prototype;
        _proto2.clone = function clone() {
          var that = new BindableBoolean();
          that.value = this.value;
          that.variable = this.variable;
          return that;
        };
        return BindableBoolean;
      }(), (_initializer3$14 = applyDecoratedInitializer(_class5$e.prototype, "variable", [serializable$f], function () {
        return '';
      }), _initializer4$V = applyDecoratedInitializer(_class5$e.prototype, "value", [serializable$f], function () {
        return false;
      })), _class5$e)) || _class4$d);
      function bindOr(context, bindable, type, callback, thisArg) {
        var variable = bindable.variable,
          value = bindable.value;
        if (!variable) {
          return value;
        }
        var varInstance = context.getVar(variable);
        if (!validateVariableExistence(varInstance, variable)) {
          return value;
        }
        if (varInstance.type !== type) {
          throw new VariableTypeMismatchedError(variable, 'number');
        }
        for (var _len = arguments.length, args = new Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) {
          args[_key - 5] = arguments[_key];
        }
        var initialValue = varInstance.bind.apply(varInstance, [callback, thisArg].concat(args));
        return initialValue;
      }
      function validateVariableExistence(varInstance, name) {
        if (!varInstance) {
          throw new VariableNotDefinedError(name);
        } else {
          return true;
        }
      }
      function validateVariableType(type, expected, name) {
        if (type !== expected) {
          throw new VariableTypeMismatchedError(name, 'number');
        }
      }
      function validateVariableTypeTriggerLike(type, name) {
        if (type !== VariableType.TRIGGER) {
          throw new VariableTypeMismatchedError(name, 'trigger');
        }
      }

      function blend1D(weights, thresholds, value) {
        weights.fill(0.0);
        if (thresholds.length === 0) ; else if (value <= thresholds[0]) {
          weights[0] = 1;
        } else if (value >= thresholds[thresholds.length - 1]) {
          weights[weights.length - 1] = 1;
        } else {
          var iUpper = 0;
          for (var iThresholds = 1; iThresholds < thresholds.length; ++iThresholds) {
            if (thresholds[iThresholds] > value) {
              iUpper = iThresholds;
              break;
            }
          }
          var lower = thresholds[iUpper - 1];
          var upper = thresholds[iUpper];
          var dVal = upper - lower;
          weights[iUpper - 1] = (upper - value) / dVal;
          weights[iUpper] = (value - lower) / dVal;
        }
      }

      var _dec$1S, _class$1P, _class2$1I, _initializer$1B, _dec2$1A, _class4$c, _class5$d, _initializer2$1o, _initializer3$13, _class6$6;
      var ccclass$z = ccclass$M,
        serializable$e = serializable$p;
      var AnimationBlend1DItem = (_dec$1S = ccclass$z(CLASS_NAME_PREFIX_ANIM + "AnimationBlend1DItem"), _dec$1S(_class$1P = (_class2$1I = function (_AnimationBlendItem) {
        _inheritsLoose(AnimationBlend1DItem, _AnimationBlendItem);
        function AnimationBlend1DItem() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _AnimationBlendItem.call.apply(_AnimationBlendItem, [this].concat(args)) || this;
          _this.threshold = _initializer$1B && _initializer$1B();
          return _this;
        }
        var _proto = AnimationBlend1DItem.prototype;
        _proto.clone = function clone() {
          var that = new AnimationBlend1DItem();
          this._copyTo(that);
          return that;
        };
        _proto._copyTo = function _copyTo(that) {
          _AnimationBlendItem.prototype._copyTo.call(this, that);
          that.threshold = this.threshold;
          return that;
        };
        return AnimationBlend1DItem;
      }(AnimationBlendItem), (_initializer$1B = applyDecoratedInitializer(_class2$1I.prototype, "threshold", [serializable$e], function () {
        return 0.0;
      })), _class2$1I)) || _class$1P);
      var AnimationBlend1D = (_dec2$1A = ccclass$z('cc.animation.AnimationBlend1D'), _dec2$1A(_class4$c = (_class5$d = (_class6$6 = function (_AnimationBlend) {
        _inheritsLoose(AnimationBlend1D, _AnimationBlend);
        function AnimationBlend1D() {
          var _this2;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this2 = _AnimationBlend.call.apply(_AnimationBlend, [this].concat(args)) || this;
          _this2._items = _initializer2$1o && _initializer2$1o();
          _this2.param = _initializer3$13 && _initializer3$13();
          return _this2;
        }
        var _proto2 = AnimationBlend1D.prototype;
        _proto2.clone = function clone() {
          var that = new AnimationBlend1D();
          this.copyTo(that);
          that._items = this._items.map(function (item) {
            return item.clone();
          });
          that.param = this.param.clone();
          return that;
        };
        _proto2[createEval] = function (context, ignoreEmbeddedPlayers) {
          var evaluation = new AnimationBlend1DEval(context, ignoreEmbeddedPlayers, this, this._items, this._items.map(function (_ref) {
            var threshold = _ref.threshold;
            return threshold;
          }), 0.0);
          var initialValue = bindOr(context, this.param, VariableType.FLOAT, evaluation.setInput, evaluation, 0);
          evaluation.setInput(initialValue, 0);
          return evaluation;
        };
        _createClass(AnimationBlend1D, [{
          key: "items",
          get: function get() {
            return this._items;
          },
          set: function set(value) {
            this._items = Array.from(value).sort(function (_ref2, _ref3) {
              var lhs = _ref2.threshold;
              var rhs = _ref3.threshold;
              return lhs - rhs;
            });
          }
        }]);
        return AnimationBlend1D;
      }(AnimationBlend), _class6$6.Item = AnimationBlend1DItem, _class6$6), (_initializer2$1o = applyDecoratedInitializer(_class5$d.prototype, "_items", [serializable$e], function () {
        return [];
      }), _initializer3$13 = applyDecoratedInitializer(_class5$d.prototype, "param", [serializable$e], function () {
        return new BindableNumber();
      })), _class5$d)) || _class4$c);
      var AnimationBlend1DEval = function (_AnimationBlendEval) {
        _inheritsLoose(AnimationBlend1DEval, _AnimationBlendEval);
        function AnimationBlend1DEval(context, ignoreEmbeddedPlayers, base, items, thresholds, input) {
          var _this3;
          _this3 = _AnimationBlendEval.call(this, context, ignoreEmbeddedPlayers, base, items, [input]) || this;
          _this3._thresholds = thresholds;
          _this3.doEval();
          return _this3;
        }
        var _proto3 = AnimationBlend1DEval.prototype;
        _proto3.eval = function _eval(weights, _ref4) {
          var value = _ref4[0];
          blend1D(weights, this._thresholds, value);
        };
        return AnimationBlend1DEval;
      }(AnimationBlendEval);

      var blendSimpleDirectional = function () {
        var CACHE_NORMALIZED_SAMPLE = new Vec2();
        var CACHE_BARYCENTRIC_SOLUTIONS = {
          wA: 0,
          wB: 0
        };
        return function blendSimpleDirectional(weights, samples, input) {
          assertIsTrue(weights.length === samples.length);
          if (samples.length === 0) {
            return;
          }
          if (samples.length === 1) {
            weights[0] = 1.0;
            return;
          }
          if (Vec2.strictEquals(input, Vec2.ZERO)) {
            var _iCenter = samples.findIndex(function (sample) {
              return Vec2.strictEquals(sample, Vec2.ZERO);
            });
            if (_iCenter >= 0) {
              weights[_iCenter] = 1.0;
            } else {
              weights.fill(1.0 / samples.length);
            }
            return;
          }
          var iSectorStart = -1;
          var iSectorEnd = -1;
          var iCenter = -1;
          var lhsCosAngle = Number.NEGATIVE_INFINITY;
          var rhsCosAngle = Number.NEGATIVE_INFINITY;
          var inputX = input.x,
            inputY = input.y;
          for (var iSample = 0; iSample < samples.length; ++iSample) {
            var sample = samples[iSample];
            if (Vec2.equals(sample, Vec2.ZERO)) {
              iCenter = iSample;
              continue;
            }
            var sampleNormalized = Vec2.normalize(CACHE_NORMALIZED_SAMPLE, sample);
            var cosAngle = Vec2.dot(sampleNormalized, input);
            var sign = sampleNormalized.x * inputY - sampleNormalized.y * inputX;
            if (sign > 0) {
              if (cosAngle >= rhsCosAngle) {
                rhsCosAngle = cosAngle;
                iSectorStart = iSample;
              }
            } else if (cosAngle >= lhsCosAngle) {
              lhsCosAngle = cosAngle;
              iSectorEnd = iSample;
            }
          }
          var centerWeight = 0.0;
          if (iSectorStart < 0 || iSectorEnd < 0) {
            centerWeight = 1.0;
          } else {
            var _solveBarycentric = solveBarycentric(samples[iSectorStart], samples[iSectorEnd], input, CACHE_BARYCENTRIC_SOLUTIONS),
              wA = _solveBarycentric.wA,
              wB = _solveBarycentric.wB;
            var w1 = 0.0;
            var w2 = 0.0;
            var sum = wA + wB;
            if (sum > 1) {
              w1 = wA / sum;
              w2 = wB / sum;
            } else if (sum < 0) {
              w1 = 0.0;
              w2 = 0.0;
              centerWeight = 1.0;
            } else {
              w1 = wA;
              w2 = wB;
              centerWeight = 1.0 - sum;
            }
            weights[iSectorStart] = w1;
            weights[iSectorEnd] = w2;
          }
          if (centerWeight > 0.0) {
            if (iCenter >= 0) {
              weights[iCenter] = centerWeight;
            } else {
              var average = centerWeight / weights.length;
              for (var i = 0; i < weights.length; ++i) {
                weights[i] += average;
              }
            }
          }
        };
      }();
      function sampleFreeformCartesian(weights, thresholds, value) {
        sampleFreeform(weights, thresholds, value, getGradientBandCartesianCoords);
      }
      function sampleFreeform(weights, samples, value, getGradientBandCoords) {
        weights.fill(0.0);
        var pIpInput = new Vec2(0, 0);
        var pIJ = new Vec2(0, 0);
        var sumInfluence = 0.0;
        var nSamples = samples.length;
        for (var iSample = 0; iSample < nSamples; ++iSample) {
          var influence = Number.MAX_VALUE;
          var outsideHull = false;
          for (var jSample = 0; jSample < nSamples; ++jSample) {
            if (iSample === jSample) {
              continue;
            }
            getGradientBandCoords(samples[iSample], samples[jSample], value, pIpInput, pIJ);
            var t = 1 - Vec2.dot(pIpInput, pIJ) / Vec2.lengthSqr(pIJ);
            if (t < 0) {
              outsideHull = true;
              break;
            }
            influence = Math.min(influence, t);
          }
          if (!outsideHull) {
            weights[iSample] = influence;
            sumInfluence += influence;
          }
        }
        if (sumInfluence > 0) {
          weights.forEach(function (influence, index) {
            return weights[index] = influence / sumInfluence;
          });
        }
      }
      function solveBarycentric(a, b, p, resolutions) {
        var det = Vec2.cross(a, b);
        if (!det) {
          resolutions.wA = 0.0;
          resolutions.wB = 0.0;
        } else {
          resolutions.wA = Vec2.cross(p, b) / det;
          resolutions.wB = Vec2.cross(p, a) / -det;
        }
        return resolutions;
      }
      var getGradientBandCartesianCoords = function getGradientBandCartesianCoords(pI, pJ, input, pIpInput, pIpJ) {
        Vec2.subtract(pIpInput, input, pI);
        Vec2.subtract(pIpJ, pJ, pI);
      };
      var PRECOMPUTED_VIJ_DATA_STRIDE = 3;
      var PolarSpaceGradientBandInterpolator2D = function () {
        function PolarSpaceGradientBandInterpolator2D(examples) {
          var angleMultiplier = PolarSpaceGradientBandInterpolator2D._ANGLE_MULTIPLIER;
          var nExamples = examples.length;
          var exampleMagnitudes = this._exampleMagnitudes = new Array(nExamples).fill(0.0);
          var exampleDirections = this._exampleDirections = examples.map(function (example, iExample) {
            var direction = Vec2.copy(new Vec2(), example);
            var magnitude = Vec2.len(direction);
            exampleMagnitudes[iExample] = magnitude;
            if (!approx(magnitude, 0.0, 1e-5)) {
              Vec2.multiplyScalar(direction, direction, 1.0 / magnitude);
            }
            return direction;
          });
          var precomputedVIJs = this._precomputedVIJs = new Float32Array(PRECOMPUTED_VIJ_DATA_STRIDE * nExamples * nExamples);
          for (var iExample = 0; iExample < nExamples; ++iExample) {
            var magnitudeI = exampleMagnitudes[iExample];
            var directionI = exampleDirections[iExample];
            for (var jExample = 0; jExample < nExamples; ++jExample) {
              if (iExample === jExample) {
                continue;
              }
              var magnitudeJ = exampleMagnitudes[jExample];
              var directionJ = exampleDirections[jExample];
              var averagedMagnitude = (magnitudeI + magnitudeJ) / 2;
              var pOutput = PRECOMPUTED_VIJ_DATA_STRIDE * (nExamples * iExample + jExample);
              precomputedVIJs[pOutput + 0] = (magnitudeJ - magnitudeI) / averagedMagnitude;
              precomputedVIJs[pOutput + 1] = signedAngle(directionI, directionJ) * angleMultiplier;
              precomputedVIJs[pOutput + 2] = averagedMagnitude;
            }
          }
          this._cacheVIXAngles = new Float32Array(nExamples);
        }
        var _proto = PolarSpaceGradientBandInterpolator2D.prototype;
        _proto.interpolate = function interpolate(weights, input) {
          var exampleDirections = this._exampleDirections,
            exampleMagnitudes = this._exampleMagnitudes,
            precomputedVIJs = this._precomputedVIJs,
            cacheVIXAngles = this._cacheVIXAngles;
          var cacheInputDirection = PolarSpaceGradientBandInterpolator2D._CACHE_INPUT_DIRECTION,
            cacheVIJ = PolarSpaceGradientBandInterpolator2D._CACHE_VIJ,
            cacheVIX = PolarSpaceGradientBandInterpolator2D._CACHE_VIX,
            angleMultiplier = PolarSpaceGradientBandInterpolator2D._ANGLE_MULTIPLIER;
          var nExamples = exampleDirections.length;
          assertIsTrue(weights.length === nExamples);
          if (nExamples === 0) {
            return;
          } else if (nExamples === 1) {
            weights[0] = 1.0;
            return;
          }
          var vX = input;
          var magnitudeX = Vec2.len(vX);
          var vIXAngles = cacheVIXAngles;
          if (Vec2.equals(vX, Vec2.ZERO)) {
            for (var iExample = 0; iExample < nExamples; ++iExample) {
              vIXAngles[iExample] = 0.0;
            }
          } else {
            var directionX = Vec2.multiplyScalar(cacheInputDirection, vX, 1.0 / magnitudeX);
            for (var _iExample = 0; _iExample < nExamples; ++_iExample) {
              var directionI = exampleDirections[_iExample];
              if (Vec2.equals(directionI, Vec2.ZERO)) {
                vIXAngles[_iExample] = 0.0;
              } else {
                vIXAngles[_iExample] = signedAngle(directionI, directionX) * angleMultiplier;
              }
            }
          }
          var totalWeight = 0.0;
          for (var _iExample2 = 0; _iExample2 < nExamples; ++_iExample2) {
            var magnitudeI = exampleMagnitudes[_iExample2];
            var _directionI = exampleDirections[_iExample2];
            var minInfluence = Number.POSITIVE_INFINITY;
            for (var jExample = 0; jExample < nExamples; ++jExample) {
              if (_iExample2 === jExample) {
                continue;
              }
              var directionJ = exampleDirections[jExample];
              var precomputedDataIndex = PRECOMPUTED_VIJ_DATA_STRIDE * (nExamples * _iExample2 + jExample);
              var vIJMag = precomputedVIJs[precomputedDataIndex + 0],
                vIJAnglePrecomputed = precomputedVIJs[precomputedDataIndex + 1],
                averagedMagnitude = precomputedVIJs[precomputedDataIndex + 2];
              var vIJAngle = vIJAnglePrecomputed;
              var vIXAngle = vIXAngles[_iExample2];
              if (Vec2.equals(_directionI, Vec2.ZERO)) {
                vIJAngle = vIXAngles[jExample];
              } else if (Vec2.equals(directionJ, Vec2.ZERO)) {
                vIJAngle = vIXAngles[_iExample2];
              } else if (Vec2.equals(vX, Vec2.ZERO)) {
                vIXAngle = vIJAngle;
              }
              var vIJ = Vec2.set(cacheVIJ, vIJMag, vIJAngle);
              var vIX = Vec2.set(cacheVIX, (magnitudeX - magnitudeI) / averagedMagnitude, vIXAngle);
              var influence = 1.0 - Vec2.dot(vIX, vIJ) / Vec2.lengthSqr(vIJ);
              if (influence <= 0) {
                minInfluence = 0.0;
                break;
              }
              minInfluence = Math.min(minInfluence, influence);
            }
            weights[_iExample2] = minInfluence;
            totalWeight += minInfluence;
          }
          if (totalWeight > 0) {
            for (var _iExample3 = 0; _iExample3 < nExamples; ++_iExample3) {
              weights[_iExample3] /= totalWeight;
            }
          } else {
            var averaged = 1.0 / nExamples;
            for (var _iExample4 = 0; _iExample4 < nExamples; ++_iExample4) {
              weights[_iExample4] = averaged;
            }
          }
        };
        return PolarSpaceGradientBandInterpolator2D;
      }();
      PolarSpaceGradientBandInterpolator2D._CACHE_INPUT_DIRECTION = new Vec2();
      PolarSpaceGradientBandInterpolator2D._CACHE_VIJ = new Vec2();
      PolarSpaceGradientBandInterpolator2D._CACHE_VIX = new Vec2();
      PolarSpaceGradientBandInterpolator2D._ANGLE_MULTIPLIER = 1.0;
      function signedAngle(v1, v2) {
        var angle = Vec2.angle(v1, v2);
        var determinate = v1.x * v2.y - v1.y * v2.x;
        return determinate < 0 ? -angle : angle;
      }

      var _dec$1R, _class$1O, _class2$1H, _initializer$1A, _dec2$1z, _class4$b, _class5$c, _initializer2$1n, _initializer3$12, _initializer4$U, _initializer5$J, _class6$5;
      var ccclass$y = ccclass$M,
        serializable$d = serializable$p;
      var Algorithm;
      (function (Algorithm) {
        Algorithm[Algorithm["SIMPLE_DIRECTIONAL"] = 0] = "SIMPLE_DIRECTIONAL";
        Algorithm[Algorithm["FREEFORM_CARTESIAN"] = 1] = "FREEFORM_CARTESIAN";
        Algorithm[Algorithm["FREEFORM_DIRECTIONAL"] = 2] = "FREEFORM_DIRECTIONAL";
      })(Algorithm || (Algorithm = {}));
      ccenum(Algorithm);
      var AnimationBlend2DItem = (_dec$1R = ccclass$y(CLASS_NAME_PREFIX_ANIM + "AnimationBlend2DItem"), _dec$1R(_class$1O = (_class2$1H = function (_AnimationBlendItem) {
        _inheritsLoose(AnimationBlend2DItem, _AnimationBlendItem);
        function AnimationBlend2DItem() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _AnimationBlendItem.call.apply(_AnimationBlendItem, [this].concat(args)) || this;
          _this.threshold = _initializer$1A && _initializer$1A();
          return _this;
        }
        var _proto = AnimationBlend2DItem.prototype;
        _proto.clone = function clone() {
          var that = new AnimationBlend2DItem();
          this._copyTo(that);
          return that;
        };
        _proto._copyTo = function _copyTo(that) {
          _AnimationBlendItem.prototype._copyTo.call(this, that);
          Vec2.copy(that.threshold, this.threshold);
          return that;
        };
        return AnimationBlend2DItem;
      }(AnimationBlendItem), (_initializer$1A = applyDecoratedInitializer(_class2$1H.prototype, "threshold", [serializable$d], function () {
        return new Vec2();
      })), _class2$1H)) || _class$1O);
      var AnimationBlend2D = (_dec2$1z = ccclass$y('cc.animation.AnimationBlend2D'), _dec2$1z(_class4$b = (_class5$c = (_class6$5 = function (_AnimationBlend) {
        _inheritsLoose(AnimationBlend2D, _AnimationBlend);
        function AnimationBlend2D() {
          var _this2;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this2 = _AnimationBlend.call.apply(_AnimationBlend, [this].concat(args)) || this;
          _this2._items = _initializer2$1n && _initializer2$1n();
          _this2.paramX = _initializer3$12 && _initializer3$12();
          _this2.paramY = _initializer4$U && _initializer4$U();
          _this2._algorithm = _initializer5$J && _initializer5$J();
          _this2._polarSpaceGBI = undefined;
          return _this2;
        }
        var _proto2 = AnimationBlend2D.prototype;
        _proto2.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          this._tryReconstructPolarSpaceInterpolator();
        };
        _proto2.clone = function clone() {
          var that = new AnimationBlend2D();
          this.copyTo(that);
          that._items = this._items.map(function (item) {
            var _item$clone;
            return (_item$clone = item === null || item === void 0 ? void 0 : item.clone()) !== null && _item$clone !== void 0 ? _item$clone : null;
          });
          that.paramX = this.paramX.clone();
          that.paramY = this.paramY.clone();
          that.algorithm = this._algorithm;
          return that;
        };
        _proto2[createEval] = function (context, ignoreEmbeddedPlayers) {
          var algorithm = this.algorithm;
          var evaluation;
          switch (algorithm) {
            case Algorithm.FREEFORM_DIRECTIONAL:
              assertIsTrue(this._polarSpaceGBI, "The polar space interpolator is not setup correctly!");
              evaluation = new PolarSpaceGradientBandBlend2DEval(context, ignoreEmbeddedPlayers, this, this._items, this._polarSpaceGBI, [0.0, 0.0]);
              break;
            default:
              assertIsTrue(false);
            case Algorithm.SIMPLE_DIRECTIONAL:
            case Algorithm.FREEFORM_CARTESIAN:
              evaluation = new AnimationBlend2DEval(context, ignoreEmbeddedPlayers, this, this._items, this._items.map(function (_ref) {
                var threshold = _ref.threshold;
                return threshold;
              }), algorithm, [0.0, 0.0]);
              break;
          }
          var initialValueX = bindOr(context, this.paramX, VariableType.FLOAT, evaluation.setInput, evaluation, 0);
          var initialValueY = bindOr(context, this.paramY, VariableType.FLOAT, evaluation.setInput, evaluation, 1);
          evaluation.setInput(initialValueX, 0);
          evaluation.setInput(initialValueY, 1);
          return evaluation;
        };
        _proto2._tryReconstructPolarSpaceInterpolator = function _tryReconstructPolarSpaceInterpolator() {
          if (this._algorithm === Algorithm.FREEFORM_DIRECTIONAL) {
            this._polarSpaceGBI = new PolarSpaceGradientBandInterpolator2D(this._items.map(function (item) {
              return item.threshold;
            }));
          } else {
            this._polarSpaceGBI = undefined;
          }
        };
        _createClass(AnimationBlend2D, [{
          key: "algorithm",
          get: function get() {
            return this._algorithm;
          },
          set: function set(value) {
            if (value === this._algorithm) {
              return;
            }
            this._algorithm = value;
            this._tryReconstructPolarSpaceInterpolator();
          }
        }, {
          key: "items",
          get: function get() {
            return this._items;
          },
          set: function set(items) {
            this._items = Array.from(items);
            this._tryReconstructPolarSpaceInterpolator();
          }
        }]);
        return AnimationBlend2D;
      }(AnimationBlend), _class6$5.Algorithm = Algorithm, _class6$5.Item = AnimationBlend2DItem, _class6$5), (_initializer2$1n = applyDecoratedInitializer(_class5$c.prototype, "_items", [serializable$d], function () {
        return [];
      }), _initializer3$12 = applyDecoratedInitializer(_class5$c.prototype, "paramX", [serializable$d], function () {
        return new BindableNumber();
      }), _initializer4$U = applyDecoratedInitializer(_class5$c.prototype, "paramY", [serializable$d], function () {
        return new BindableNumber();
      }), _initializer5$J = applyDecoratedInitializer(_class5$c.prototype, "_algorithm", [serializable$d], function () {
        return Algorithm.SIMPLE_DIRECTIONAL;
      })), _class5$c)) || _class4$b);
      var AnimationBlend2DEval = function (_AnimationBlendEval) {
        _inheritsLoose(AnimationBlend2DEval, _AnimationBlendEval);
        function AnimationBlend2DEval(context, ignoreEmbeddedPlayers, base, items, thresholds, algorithm, inputs) {
          var _this3;
          _this3 = _AnimationBlendEval.call(this, context, ignoreEmbeddedPlayers, base, items, inputs) || this;
          _this3._thresholds = void 0;
          _this3._algorithm = void 0;
          _this3._value = new Vec2();
          _this3._thresholds = thresholds;
          _this3._algorithm = algorithm;
          _this3.doEval();
          return _this3;
        }
        var _proto3 = AnimationBlend2DEval.prototype;
        _proto3.eval = function _eval(weights, _ref2) {
          var x = _ref2[0],
            y = _ref2[1];
          Vec2.set(this._value, x, y);
          weights.fill(0);
          switch (this._algorithm) {
            case Algorithm.SIMPLE_DIRECTIONAL:
              blendSimpleDirectional(weights, this._thresholds, this._value);
              break;
            case Algorithm.FREEFORM_CARTESIAN:
              sampleFreeformCartesian(weights, this._thresholds, this._value);
              break;
          }
        };
        return AnimationBlend2DEval;
      }(AnimationBlendEval);
      var PolarSpaceGradientBandBlend2DEval = function (_AnimationBlendEval2) {
        _inheritsLoose(PolarSpaceGradientBandBlend2DEval, _AnimationBlendEval2);
        function PolarSpaceGradientBandBlend2DEval(context, ignoreEmbeddedPlayers, base, items, interpolator, inputs) {
          var _this4;
          _this4 = _AnimationBlendEval2.call(this, context, ignoreEmbeddedPlayers, base, items, inputs) || this;
          _this4._interpolator = void 0;
          _this4._value = new Vec2();
          _this4._interpolator = interpolator;
          _this4.doEval();
          return _this4;
        }
        var _proto4 = PolarSpaceGradientBandBlend2DEval.prototype;
        _proto4.eval = function _eval(weights, _ref3) {
          var x = _ref3[0],
            y = _ref3[1];
          Vec2.set(this._value, x, y);
          weights.fill(0);
          this._interpolator.interpolate(weights, this._value);
        };
        return PolarSpaceGradientBandBlend2DEval;
      }(AnimationBlendEval);

      var _dec$1Q, _class$1N, _class2$1G, _initializer$1z, _dec2$1y, _class4$a, _class5$b, _initializer2$1m, _class6$4;
      var ccclass$x = ccclass$M,
        serializable$c = serializable$p;
      var AnimationBlendDirectItem = (_dec$1Q = ccclass$x(CLASS_NAME_PREFIX_ANIM + "AnimationBlendDirectItem"), _dec$1Q(_class$1N = (_class2$1G = function (_AnimationBlendItem) {
        _inheritsLoose(AnimationBlendDirectItem, _AnimationBlendItem);
        function AnimationBlendDirectItem() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _AnimationBlendItem.call.apply(_AnimationBlendItem, [this].concat(args)) || this;
          _this.weight = _initializer$1z && _initializer$1z();
          return _this;
        }
        var _proto = AnimationBlendDirectItem.prototype;
        _proto.clone = function clone() {
          var that = new AnimationBlendDirectItem();
          this._copyTo(that);
          return that;
        };
        _proto._copyTo = function _copyTo(that) {
          _AnimationBlendItem.prototype._copyTo.call(this, that);
          that.weight = this.weight;
          return that;
        };
        return AnimationBlendDirectItem;
      }(AnimationBlendItem), (_initializer$1z = applyDecoratedInitializer(_class2$1G.prototype, "weight", [serializable$c], function () {
        return new BindableNumber(0.0);
      })), _class2$1G)) || _class$1N);
      (_dec2$1y = ccclass$x('cc.animation.AnimationBlendDirect'), _dec2$1y(_class4$a = (_class5$b = (_class6$4 = function (_AnimationBlend) {
        _inheritsLoose(AnimationBlendDirect, _AnimationBlend);
        function AnimationBlendDirect() {
          var _this2;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this2 = _AnimationBlend.call.apply(_AnimationBlend, [this].concat(args)) || this;
          _this2._items = _initializer2$1m && _initializer2$1m();
          return _this2;
        }
        var _proto2 = AnimationBlendDirect.prototype;
        _proto2.clone = function clone() {
          var that = new AnimationBlendDirect();
          this.copyTo(that);
          that._items = this._items.map(function (item) {
            var _item$clone;
            return (_item$clone = item === null || item === void 0 ? void 0 : item.clone()) !== null && _item$clone !== void 0 ? _item$clone : null;
          });
          return that;
        };
        _proto2[createEval] = function (context, ignoreEmbeddedPlayers) {
          var myEval = new AnimationBlendDirectEval(context, ignoreEmbeddedPlayers, this, this._items, new Array(this._items.length).fill(0.0));
          for (var iItem = 0; iItem < this._items.length; ++iItem) {
            var item = this._items[iItem];
            var initialValue = bindOr(context, item.weight, VariableType.FLOAT, myEval.setInput, myEval, iItem);
            myEval.setInput(initialValue, iItem);
          }
          return myEval;
        };
        _createClass(AnimationBlendDirect, [{
          key: "items",
          get: function get() {
            return this._items;
          },
          set: function set(value) {
            this._items = Array.from(value);
          }
        }]);
        return AnimationBlendDirect;
      }(AnimationBlend), _class6$4.Item = AnimationBlendDirectItem, _class6$4), (_initializer2$1m = applyDecoratedInitializer(_class5$b.prototype, "_items", [serializable$c], function () {
        return [];
      })), _class5$b)) || _class4$a);
      var AnimationBlendDirectEval = function (_AnimationBlendEval) {
        _inheritsLoose(AnimationBlendDirectEval, _AnimationBlendEval);
        function AnimationBlendDirectEval() {
          var _this3;
          for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
            args[_key3] = arguments[_key3];
          }
          _this3 = _AnimationBlendEval.call.apply(_AnimationBlendEval, [this].concat(args)) || this;
          _this3.doEval();
          return _this3;
        }
        var _proto3 = AnimationBlendDirectEval.prototype;
        _proto3.eval = function _eval(weights, inputs) {
          var nChildren = weights.length;
          for (var iChild = 0; iChild < nChildren; ++iChild) {
            weights[iChild] = inputs[iChild];
          }
        };
        return AnimationBlendDirectEval;
      }(AnimationBlendEval);

      var _dec$1P, _class$1M, _class2$1F, _initializer$1y, _initializer2$1l, _dec2$1x, _dec3$1b, _class4$9, _class5$a, _initializer3$11;
      var JointMask = (_dec$1P = ccclass$M('cc.JointMask'), _dec$1P(_class$1M = (_class2$1F = function JointMask() {
        this.path = _initializer$1y && _initializer$1y();
        this.enabled = _initializer2$1l && _initializer2$1l();
      }, (_initializer$1y = applyDecoratedInitializer(_class2$1F.prototype, "path", [serializable$p], function () {
        return '';
      }), _initializer2$1l = applyDecoratedInitializer(_class2$1F.prototype, "enabled", [serializable$p], function () {
        return true;
      })), _class2$1F)) || _class$1M);
      (_dec2$1x = ccclass$M(CLASS_NAME_PREFIX_ANIM + "AnimationMask"), _dec3$1b = type$d(JointMask), _dec2$1x(_class4$9 = (_class5$a = function (_Asset) {
        _inheritsLoose(AnimationMask, _Asset);
        function AnimationMask() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this._jointMasks = _initializer3$11 && _initializer3$11();
          return _this;
        }
        var _proto = AnimationMask.prototype;
        _proto.addJoint = function addJoint(path, enabled) {
          this.removeJoint(path);
          var info = new JointMask();
          info.path = path;
          info.enabled = enabled;
          this._jointMasks.push(info);
        };
        _proto.removeJoint = function removeJoint(removal) {
          removeIf(this._jointMasks, function (_ref) {
            var path = _ref.path;
            return path === removal;
          });
        };
        _proto.clear = function clear() {
          this._jointMasks.length = 0;
        };
        _proto.filterDisabledNodes = function filterDisabledNodes(root) {
          var jointMasks = this._jointMasks;
          var nJointMasks = jointMasks.length;
          var disabledNodes = new Set();
          for (var iJointMask = 0; iJointMask < nJointMasks; ++iJointMask) {
            var _jointMasks$iJointMas = jointMasks[iJointMask],
              path = _jointMasks$iJointMas.path,
              enabled = _jointMasks$iJointMas.enabled;
            if (enabled) {
              continue;
            }
            var node = root.getChildByPath(path);
            if (node) {
              disabledNodes.add(node);
            }
          }
          return disabledNodes;
        };
        _proto.isExcluded = function isExcluded(path) {
          var _this$_jointMasks$fin, _this$_jointMasks$fin2;
          return !((_this$_jointMasks$fin = (_this$_jointMasks$fin2 = this._jointMasks.find(function (_ref2) {
            var p = _ref2.path;
            return p === path;
          })) === null || _this$_jointMasks$fin2 === void 0 ? void 0 : _this$_jointMasks$fin2.enabled) !== null && _this$_jointMasks$fin !== void 0 ? _this$_jointMasks$fin : true);
        };
        _createClass(AnimationMask, [{
          key: "joints",
          get: function get() {
            return this._jointMasks;
          },
          set: function set(value) {
            this.clear();
            for (var _iterator = _createForOfIteratorHelperLoose(value), _step; !(_step = _iterator()).done;) {
              var joint = _step.value;
              this.addJoint(joint.path, joint.enabled);
            }
          }
        }]);
        return AnimationMask;
      }(Asset), (_initializer3$11 = applyDecoratedInitializer(_class5$a.prototype, "_jointMasks", [serializable$p], function () {
        return [];
      }), _applyDecoratedDescriptor(_class5$a.prototype, "joints", [_dec3$1b], Object.getOwnPropertyDescriptor(_class5$a.prototype, "joints"), _class5$a.prototype)), _class5$a)) || _class4$9);

      var _Symbol$iterator;
      var _dec$1O, _class$1L, _class2$1E, _initializer$1x, _initializer2$1k, _dec2$1w, _dec3$1a, _class4$8, _class5$9, _initializer3$10, _initializer4$T, _dec4$T, _class7$3, _class8$5, _initializer5$I;
      var ClipOverrideEntry = (_dec$1O = ccclass$M(CLASS_NAME_PREFIX_ANIM + "ClipOverrideEntry"), _dec$1O(_class$1L = (_class2$1E = function ClipOverrideEntry() {
        this.original = _initializer$1x && _initializer$1x();
        this.substitution = _initializer2$1k && _initializer2$1k();
      }, (_initializer$1x = applyDecoratedInitializer(_class2$1E.prototype, "original", [serializable$p], function () {
        return null;
      }), _initializer2$1k = applyDecoratedInitializer(_class2$1E.prototype, "substitution", [serializable$p], function () {
        return null;
      })), _class2$1E)) || _class$1L);
      var AnimationGraphVariant = (_dec2$1w = ccclass$M(CLASS_NAME_PREFIX_ANIM + "AnimationGraphVariant"), _dec3$1a = type$d(AnimationGraph), _dec2$1w(_class4$8 = (_class5$9 = function (_AnimationGraphLike) {
        _inheritsLoose(AnimationGraphVariant, _AnimationGraphLike);
        function AnimationGraphVariant() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _AnimationGraphLike.call.apply(_AnimationGraphLike, [this].concat(args)) || this;
          _this._graph = _initializer3$10 && _initializer3$10();
          _this._clipOverrides = _initializer4$T && _initializer4$T();
          return _this;
        }
        _createClass(AnimationGraphVariant, [{
          key: "original",
          get: function get() {
            return this._graph;
          },
          set: function set(value) {
            this._graph = value;
          }
        }, {
          key: "clipOverrides",
          get: function get() {
            return this._clipOverrides;
          }
        }]);
        return AnimationGraphVariant;
      }(AnimationGraphLike), (_applyDecoratedDescriptor(_class5$9.prototype, "original", [_dec3$1a], Object.getOwnPropertyDescriptor(_class5$9.prototype, "original"), _class5$9.prototype), _initializer3$10 = applyDecoratedInitializer(_class5$9.prototype, "_graph", [serializable$p], function () {
        return null;
      }), _initializer4$T = applyDecoratedInitializer(_class5$9.prototype, "_clipOverrides", [serializable$p], function () {
        return new ClipOverrideMap();
      })), _class5$9)) || _class4$8);
      var ClipOverrideMap = (_dec4$T = ccclass$M(CLASS_NAME_PREFIX_ANIM + "ClipOverrideMap"), _dec4$T(_class7$3 = (_class8$5 = (_Symbol$iterator = Symbol.iterator, function () {
        function ClipOverrideMap() {
          this._entries = _initializer5$I && _initializer5$I();
        }
        var _proto = ClipOverrideMap.prototype;
        _proto[_Symbol$iterator] = function () {
          return this._entries[Symbol.iterator]();
        };
        _proto.has = function has(original) {
          return !!this._entries.find(function (_ref) {
            var o = _ref.original;
            return o === original;
          });
        };
        _proto.get = function get(original) {
          var entry = this._entries.find(function (_ref2) {
            var o = _ref2.original;
            return o === original;
          });
          return entry === null || entry === void 0 ? void 0 : entry.substitution;
        };
        _proto.set = function set(original, substitution) {
          var entry = this._entries.find(function (_ref3) {
            var o = _ref3.original;
            return o === original;
          });
          if (entry) {
            entry.substitution = substitution;
          } else {
            var newEntry = new ClipOverrideEntry();
            newEntry.original = original;
            newEntry.substitution = substitution;
            this._entries.push(newEntry);
          }
        };
        _proto["delete"] = function _delete(original) {
          removeIf(this._entries, function (_ref4) {
            var o = _ref4.original;
            return o === original;
          });
        };
        _proto.clear = function clear() {
          this._entries.length = 0;
        };
        _createClass(ClipOverrideMap, [{
          key: "size",
          get: function get() {
            return this._entries.length;
          }
        }]);
        return ClipOverrideMap;
      }()), (_initializer5$I = applyDecoratedInitializer(_class8$5.prototype, "_entries", [serializable$p], function () {
        return [];
      })), _class8$5)) || _class7$3);

      var MAX_ANIMATION_LAYER = 32;

      var TRANSFORM_STRIDE_IN_FLOATS = 10;
      var TRANSFORM_STRIDE_IN_BYTES = Float64Array.BYTES_PER_ELEMENT * TRANSFORM_STRIDE_IN_FLOATS;
      var ROTATION_OFFSET = 3;
      var SCALE_OFFSET = ROTATION_OFFSET + 4;
      var TransformArray = function () {
        function TransformArray(bufferOrLength, byteOffset, length_) {
          this._data = void 0;
          if (typeof bufferOrLength === 'undefined') {
            this._data = new Float64Array();
          } else if (typeof bufferOrLength === 'number') {
            this._data = new Float64Array(TRANSFORM_STRIDE_IN_FLOATS * bufferOrLength);
          } else {
            this._data = new Float64Array(bufferOrLength, byteOffset, typeof length_ === 'number' ? TRANSFORM_STRIDE_IN_FLOATS * length_ : undefined);
          }
        }
        var _proto = TransformArray.prototype;
        _proto.getTransform = function getTransform(index, out) {
          var data = this._data;
          var position = out.position,
            rotation = out.rotation,
            scale = out.scale;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.fromArray(position, data, baseOffset);
          Quat.fromArray(rotation, data, baseOffset + ROTATION_OFFSET);
          Vec3.fromArray(scale, data, baseOffset + SCALE_OFFSET);
          return out;
        };
        _proto.getPosition = function getPosition(index, out) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.fromArray(out, data, baseOffset);
          return out;
        };
        _proto.getRotation = function getRotation(index, out) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Quat.fromArray(out, data, baseOffset + ROTATION_OFFSET);
          return out;
        };
        _proto.getScale = function getScale(index, out) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.fromArray(out, data, baseOffset + SCALE_OFFSET);
          return out;
        };
        _proto.setTransform = function setTransform(index, value) {
          var data = this._data;
          var position = value.position,
            rotation = value.rotation,
            scale = value.scale;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.toArray(data, position, baseOffset);
          Quat.toArray(data, rotation, baseOffset + ROTATION_OFFSET);
          Vec3.toArray(data, scale, baseOffset + SCALE_OFFSET);
        };
        _proto.setPosition = function setPosition(index, value) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.toArray(data, value, baseOffset);
        };
        _proto.setRotation = function setRotation(index, value) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Quat.toArray(data, value, baseOffset + ROTATION_OFFSET);
        };
        _proto.setScale = function setScale(index, value) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.toArray(data, value, baseOffset + SCALE_OFFSET);
        };
        _proto.copyWithin = function copyWithin(target, start, end) {
          this._data.copyWithin(target * TRANSFORM_STRIDE_IN_FLOATS, start * TRANSFORM_STRIDE_IN_FLOATS, typeof end === 'number' ? end * TRANSFORM_STRIDE_IN_FLOATS : undefined);
        };
        _proto.fill = function fill(value, start, end) {
          var _start, _end;
          var length = this.length;
          (_start = start) !== null && _start !== void 0 ? _start : start = 0;
          (_end = end) !== null && _end !== void 0 ? _end : end = length;
          if (start >= length) {
            return;
          }
          this.setTransform(start, value);
          for (var i = start + 1; i < end; ++i) {
            this.copyWithin(i, start, start + 1);
          }
        };
        _proto.fillZero = function fillZero(start, end) {
          this._data.fill(0.0, typeof start === 'number' ? start * TRANSFORM_STRIDE_IN_FLOATS : undefined, typeof end === 'number' ? end * TRANSFORM_STRIDE_IN_FLOATS : undefined);
        };
        _proto.set = function set(transformArray, targetOffset) {
          this._data.set(transformArray._data, typeof targetOffset === 'number' ? targetOffset * TRANSFORM_STRIDE_IN_FLOATS : undefined);
        };
        _proto.slice = function slice(start, end) {
          var dataSliced = this._data.slice(typeof start === 'number' ? start * TRANSFORM_STRIDE_IN_FLOATS : undefined, typeof end === 'number' ? end * TRANSFORM_STRIDE_IN_FLOATS : undefined);
          return new TransformArray(dataSliced.buffer, dataSliced.byteOffset, dataSliced.length / TRANSFORM_STRIDE_IN_FLOATS);
        };
        _proto.copyRange = function copyRange(targetOffset, source, sourceOffset, size) {
          var sizeInFloats = TRANSFORM_STRIDE_IN_FLOATS * size;
          var targetFloats = this._data;
          var targetStartInFloats = TRANSFORM_STRIDE_IN_FLOATS * targetOffset;
          var sourceFloats = source._data;
          var sourceStartInFloats = TRANSFORM_STRIDE_IN_FLOATS * sourceOffset;
          for (var i = 0; i < sizeInFloats; ++i) {
            targetFloats[targetStartInFloats + i] = sourceFloats[sourceStartInFloats + i];
          }
        };
        _createClass(TransformArray, [{
          key: "buffer",
          get: function get() {
            return this._data.buffer;
          }
        }, {
          key: "byteLength",
          get: function get() {
            return this._data.byteLength;
          }
        }, {
          key: "byteOffset",
          get: function get() {
            return this._data.byteOffset;
          }
        }, {
          key: "length",
          get: function get() {
            return this._data.length / TRANSFORM_STRIDE_IN_FLOATS;
          }
        }], [{
          key: "BYTES_PER_ELEMENT",
          get: function get() {
            return TRANSFORM_STRIDE_IN_BYTES;
          }
        }]);
        return TransformArray;
      }();

      var allocatorPageCountTag = Symbol('[[The count of pages used by this allocator.]]' );
      var onStackPurgedTag = Symbol("[[Notify that theres is no allocator on the stack anymore.]]" );
      var SharedMemoryPage = function SharedMemoryPage(byteLength) {
        this.buffer = void 0;
        this.useCount = 0;
        this.buffer = new ArrayBuffer(byteLength);
      };
      var PagedStack = function () {
        function PagedStack(_manager, _pageSize) {
          this._locking = false;
          this._pages = [];
          this._allocatorCount = 0;
          this._manager = _manager;
          this._pageSize = _pageSize;
        }
        var _proto = PagedStack.prototype;
        _proto.debugLock = function debugLock() {
          assertIsTrue(!this._locking, "The memory is locking.");
          this._locking = true;
        };
        _proto.debugUnlock = function debugUnlock() {
          assertIsTrue(this._locking, "Wrong execution logic: the memory is not locking.");
          this._locking = false;
        };
        _proto.getPageMemory = function getPageMemory(index) {
          assertIsTrue(index >= 0 && index < this._pages.length, "Page index out of range");
          return this._pages[index].buffer;
        };
        _proto.pushPage = function pushPage(allocator) {
          var oldAllocatorPageCount = allocator[allocatorPageCountTag];
          assertIsTrue(oldAllocatorPageCount <= this._pages.length);
          if (oldAllocatorPageCount === this._pages.length) {
            this._pushNewPage();
          }
          assertIsTrue(oldAllocatorPageCount < this._pages.length);
          var page = this._pages[oldAllocatorPageCount];
          ++page.useCount;
          ++allocator[allocatorPageCountTag];
          return page;
        };
        _proto.popPage = function popPage(allocator) {
          var allocatorPageCount = allocator[allocatorPageCountTag];
          assertIsTrue(allocatorPageCount > 0);
          var allocatorLastPageIndex = allocatorPageCount - 1;
          var lastPage = this._pages[allocatorLastPageIndex];
          assertIsTrue(lastPage.useCount > 0);
          --lastPage.useCount;
          --allocator[allocatorPageCountTag];
          if (lastPage.useCount === 0) {
            assertIsTrue(allocatorLastPageIndex === this._pages.length - 1);
            this._pages.pop();
          }
        };
        _proto.createAllocator = function createAllocator(sliceSize) {
          var allocator = new SharedStackBasedAllocator(this, sliceSize);
          ++this._allocatorCount;
          return allocator;
        };
        _proto.destroyAllocator = function destroyAllocator(allocator) {
          var allocatorPageCount = allocator[allocatorPageCountTag];
          for (var iPage = 0; iPage < allocatorPageCount; ++iPage) {
            var page = this._pages[iPage];
            assertIsTrue(page.useCount > 0);
            --page.useCount;
          }
          assertIsTrue(this._allocatorCount > 0);
          --this._allocatorCount;
          if (this._allocatorCount === 0) {
            this._manager[onStackPurgedTag](this);
          }
        };
        _proto._pushNewPage = function _pushNewPage() {
          var newPage = new SharedMemoryPage(this._pageSize);
          this._pages.push(newPage);
        };
        _createClass(PagedStack, [{
          key: "pageSize",
          get: function get() {
            return this._pageSize;
          }
        }, {
          key: "debugLocking",
          get: function get() {
            return this._locking;
          }
        }, {
          key: "allocatorCount",
          get: function get() {
            return this._allocatorCount;
          }
        }]);
        return PagedStack;
      }();
      var SharedMemorySlice = function SharedMemorySlice(buffer, byteOffset) {
        this.buffer = buffer;
        this.byteOffset = byteOffset;
      };
      var SharedStackBasedAllocator = function () {
        function SharedStackBasedAllocator(_resource, _sliceSize) {
          this[allocatorPageCountTag] = 0;
          this._slicesPerPage = 0;
          this._slices = [];
          this._resource = _resource;
          this._sliceSize = _sliceSize;
          var slicesPerPage = Math.floor(this._resource.pageSize / _sliceSize);
          assertIsTrue(slicesPerPage > 0);
          this._slicesPerPage = slicesPerPage;
        }
        var _proto2 = SharedStackBasedAllocator.prototype;
        _proto2.destroy = function destroy() {
          assertIsTrue(this._slices.length === 0, "Can not destroy the allocator since it's not empty.");
          assertIsTrue(!this._resource.debugLocking, "Can not destroy the allocator since it's locking.");
          this._resource.destroyAllocator(this);
        };
        _proto2.debugLock = function debugLock() {
          this._resource.debugLock();
        };
        _proto2.debugUnlock = function debugUnlock() {
          this._resource.debugUnlock();
        };
        _proto2.push = function push() {
          var sliceLength = this._sliceSize,
            slices = this._slices,
            slicesPerPage = this._slicesPerPage;
          var desiredSliceIndex = slices.length;
          var newSliceIndexInPage = 0;
          var newSlicePageIndex = 0;
          if (sliceLength === 0) {
            if (this[allocatorPageCountTag] === 0) {
              this._resource.pushPage(this);
            }
            assertIsTrue(this[allocatorPageCountTag] === 1);
          } else {
            var capacity = slicesPerPage * this[allocatorPageCountTag];
            assertIsTrue(desiredSliceIndex <= capacity);
            if (desiredSliceIndex === capacity) {
              this._resource.pushPage(this);
              assertIsTrue(desiredSliceIndex < slicesPerPage * this[allocatorPageCountTag]);
            }
            newSliceIndexInPage = desiredSliceIndex % slicesPerPage;
            newSlicePageIndex = (desiredSliceIndex - newSliceIndexInPage) / slicesPerPage;
            assertIsTrue(this[allocatorPageCountTag] * slicesPerPage >= desiredSliceIndex);
          }
          var pageMemory = this._resource.getPageMemory(newSlicePageIndex);
          var newSlice = new SharedMemorySlice(pageMemory, sliceLength * newSliceIndexInPage);
          this._slices.push(newSlice);
          return newSlice;
        };
        _proto2.pop = function pop() {
          var slices = this._slices,
            slicesPerPage = this._slicesPerPage;
          var allocatedCount = slices.length;
          assertIsTrue(allocatedCount > 0);
          var removingSliceIndex = allocatedCount - 1;
          if (this._sliceSize === 0) {
            assertIsTrue(this[allocatorPageCountTag] === 1);
            if (removingSliceIndex === 0) {
              this._resource.popPage(this);
            }
          } else {
            var removingSliceIndexInPage = removingSliceIndex % slicesPerPage;
            if (removingSliceIndexInPage === 0) {
              this._resource.popPage(this);
            }
          }
          this._slices.pop();
        };
        _createClass(SharedStackBasedAllocator, [{
          key: "isEmpty",
          get: function get() {
            return this._slices.length === 0;
          }
        }]);
        return SharedStackBasedAllocator;
      }();
      var SharedStackBasedAllocatorManager = function () {
        function SharedStackBasedAllocatorManager(_thresholds) {
          this._stacks = new Map();
          this._thresholds = _thresholds;
          assertIsTrue(_thresholds.every(function (v, i, arr) {
            return i === 0 || v > arr[i - 1];
          }));
        }
        var _proto3 = SharedStackBasedAllocatorManager.prototype;
        _proto3.createAllocator = function createAllocator(pageSize) {
          var allocationPageSize = pageSize;
          var stackPageSize = this._selectStackPageSize(allocationPageSize);
          var stack = this._stacks.get(stackPageSize);
          if (!stack) {
            stack = new PagedStack(this, stackPageSize);
            this._stacks.set(stackPageSize, stack);
          }
          return stack.createAllocator(allocationPageSize);
        };
        _proto3[onStackPurgedTag] = function (stack) {
          var stackFound = false;
          for (var _iterator = _createForOfIteratorHelperLoose(this._stacks), _step; !(_step = _iterator()).done;) {
            var _step$value = _step.value,
              k = _step$value[0],
              v = _step$value[1];
            if (v === stack) {
              this._stacks["delete"](k);
              stackFound = true;
              break;
            }
          }
          if (!stackFound) {
            assertIsTrue(false, "Given allocator is not of mime.");
          }
        };
        _proto3._selectStackPageSize = function _selectStackPageSize(allocationPageSize) {
          var thresholdIndex = binarySearchEpsilon(this._thresholds, allocationPageSize);
          var stackPageSize = allocationPageSize;
          if (thresholdIndex >= 0) {
            stackPageSize = this._thresholds[thresholdIndex];
          } else {
            thresholdIndex = ~thresholdIndex;
            if (thresholdIndex === this._thresholds.length) ; else {
              assertIsTrue(thresholdIndex >= 0 && thresholdIndex < this._thresholds.length);
              stackPageSize = this._thresholds[thresholdIndex];
            }
          }
          return stackPageSize;
        };
        _createClass(SharedStackBasedAllocatorManager, [{
          key: "isEmpty",
          get: function get() {
            return this._stacks.size === 0;
          }
        }]);
        return SharedStackBasedAllocatorManager;
      }();

      var PoseStackAllocator = function () {
        function PoseStackAllocator(transformCount, auxiliaryCurveCount) {
          this._poses = [];
          this._allocatedCount = 0;
          this._memoryAllocator = void 0;
          this._transformCount = transformCount;
          this._auxiliaryCurveCount = auxiliaryCurveCount;
          var poseBytes = calculateRequiredBytes(transformCount, auxiliaryCurveCount, 1);
          this._memoryAllocator = globalPosePageMemoryAllocatorManager.createAllocator(poseBytes);
        }
        var _proto = PoseStackAllocator.prototype;
        _proto.destroy = function destroy() {
          assertIsTrue(this._allocatedCount === 0, "Can not destroy the allocator since it's not empty.");
          for (var iPose = 0; iPose < this._poses.length; ++iPose) {
            this._memoryAllocator.pop();
          }
          this._poses.length = 0;
          return this._memoryAllocator.destroy();
        };
        _proto.push = function push() {
          if (this._allocatedCount === 0) {
            this._memoryAllocator.debugLock();
          }
          if (this._allocatedCount === this._poses.length) {
            this._allocateNewPose();
            assertIsTrue(this._allocatedCount < this._poses.length);
          }
          var pose = this._poses[this._allocatedCount];
          ++this._allocatedCount;
          return pose;
        };
        _proto.pop = function pop() {
          assertIsTrue(this._allocatedCount > 0, "PoseStackAllocator: push/pop does not match.");
          --this._allocatedCount;
          if (this._allocatedCount === 0) {
            this._memoryAllocator.debugUnlock();
          }
        };
        _proto._allocateNewPose = function _allocateNewPose() {
          var slice = this._memoryAllocator.push();
          var transformsByteLength = TransformArray.BYTES_PER_ELEMENT * this._transformCount;
          var baseOffset = slice.byteOffset;
          var transforms = new TransformArray(slice.buffer, baseOffset, this._transformCount);
          var auxiliaryCurves = new Float64Array(slice.buffer, baseOffset + transformsByteLength, this._auxiliaryCurveCount);
          var pose = Pose._create(transforms, auxiliaryCurves);
          this._poses.push(pose);
        };
        _createClass(PoseStackAllocator, [{
          key: "allocatedCount",
          get: function get() {
            return this._allocatedCount;
          }
        }, {
          key: "top",
          get: function get() {
            assertIsTrue(this._allocatedCount > 0);
            return this._poses[this._allocatedCount - 1];
          }
        }]);
        return PoseStackAllocator;
      }();
      function calculateRequiredBytes(transformCount, auxiliaryCurveCount, capacity) {
        return (TransformArray.BYTES_PER_ELEMENT * transformCount + Float64Array.BYTES_PER_ELEMENT * auxiliaryCurveCount) * capacity;
      }
      var PAGE_SIZE = calculateRequiredBytes(128, 10, 4);
      var globalPosePageMemoryAllocatorManager = new SharedStackBasedAllocatorManager([PAGE_SIZE]);

      function partition(array, predicate) {
        var nElements = array.length;
        var iFirstGroup2Element = 0;
        for (; iFirstGroup2Element < nElements; ++iFirstGroup2Element) {
          var _element = array[iFirstGroup2Element];
          if (!predicate(_element, iFirstGroup2Element, array)) {
            break;
          }
        }
        if (iFirstGroup2Element === nElements) {
          return nElements;
        }
        var nGroup1 = iFirstGroup2Element;
        for (var iElement = iFirstGroup2Element + 1; iElement < nElements; ++iElement) {
          var _element2 = array[iElement];
          var isFirstGroupElement = predicate(_element2, iElement, array);
          if (isFirstGroupElement) {
            var t = _element2;
            array[iElement] = array[nGroup1];
            array[nGroup1] = t;
            ++nGroup1;
          }
        }
        return nGroup1;
      }

      var TransformSpace;
      (function (TransformSpace) {
        TransformSpace[TransformSpace["WORLD"] = 0] = "WORLD";
        TransformSpace[TransformSpace["COMPONENT"] = 1] = "COMPONENT";
        TransformSpace[TransformSpace["PARENT"] = 2] = "PARENT";
        TransformSpace[TransformSpace["LOCAL"] = 3] = "LOCAL";
      })(TransformSpace || (TransformSpace = {}));
      ccenum(TransformSpace);

      var MAX_POSE_PER_PAGE = 8;
      var allocationInfoTag = Symbol('PoseHeapAllocator');
      function isPagedPose(pose) {
        return allocationInfoTag in pose;
      }
      var PoseHeapAllocator = function () {
        function PoseHeapAllocator(transformCount, metaValueCount) {
          this._transformCount = 0;
          this._metaValueCount = 0;
          this._pages = [];
          this._allocatedCount = 0;
          this._foremostPossibleFreePage = 0;
          this._transformCount = transformCount;
          this._metaValueCount = metaValueCount;
        }
        var _proto = PoseHeapAllocator.prototype;
        _proto.allocatePose = function allocatePose() {
          ++this._allocatedCount;
          var pages = this._pages;
          var nPages = pages.length;
          for (var _iPage = this._foremostPossibleFreePage; _iPage < nPages; ++_iPage) {
            var _page = pages[_iPage];
            var _pose = _page.tryAllocate();
            if (_pose) {
              _pose[allocationInfoTag].pageIndex = _iPage;
              if (_page.freeCount === 0) {
                ++this._foremostPossibleFreePage;
              }
              return _pose;
            }
          }
          var pose = this._allocatePoseInNewPage();
          this._foremostPossibleFreePage = pose[allocationInfoTag].pageIndex;
          return pose;
        };
        _proto.destroyPose = function destroyPose(pose) {
          assertIsTrue(isPagedPose(pose));
          var pages = this._pages;
          var nPages = pages.length;
          var pageIndex = pose[allocationInfoTag].pageIndex;
          assertIsTrue(pageIndex >= 0 && pageIndex < nPages);
          var page = pages[pageIndex];
          page.deallocate(pose);
          --this._allocatedCount;
          if (pageIndex < this._foremostPossibleFreePage) {
            assertIsTrue(page.freeCount > 0);
            this._foremostPossibleFreePage = pageIndex;
          }
        };
        _proto._allocatePoseInNewPage = function _allocatePoseInNewPage() {
          var page = new PosePage(this._transformCount, this._metaValueCount, 4);
          var pageIndex = this._pages.length;
          this._pages.push(page);
          var pose = page.tryAllocate();
          assertIsTrue(pose);
          pose[allocationInfoTag].pageIndex = pageIndex;
          return pose;
        };
        _createClass(PoseHeapAllocator, [{
          key: "allocatedCount",
          get: function get() {
            return this._allocatedCount;
          }
        }]);
        return PoseHeapAllocator;
      }();
      var AllocationInfo = function () {
        function AllocationInfo() {
          this._id = -1;
        }
        _createClass(AllocationInfo, [{
          key: "pageIndex",
          get: function get() {
            return this._id >> POSE_INDEX_BITS;
          },
          set: function set(value) {
            this._id &= POSE_INDEX_MASK;
            this._id |= value << POSE_INDEX_BITS;
          }
        }, {
          key: "poseIndex",
          get: function get() {
            return this._id & POSE_INDEX_MASK;
          },
          set: function set(value) {
            this._id &= ~POSE_INDEX_MASK;
            this._id |= value;
          }
        }]);
        return AllocationInfo;
      }();
      var POSE_INDEX_MASK = 7;
      var POSE_INDEX_BITS = 3;
      assertIsTrue(POSE_INDEX_MASK + 1 >= MAX_POSE_PER_PAGE);
      var PosePage = function () {
        function PosePage(_transformCount, _metaValueCount, _capacity) {
          this._buffer = void 0;
          this._idleFlags = 0xF;
          this._poses = void 0;
          this._freeCount = 0;
          this._transformCount = _transformCount;
          this._metaValueCount = _metaValueCount;
          this._capacity = _capacity;
          var byteLength = (TransformArray.BYTES_PER_ELEMENT * _transformCount + Float64Array.BYTES_PER_ELEMENT * _metaValueCount) * _capacity;
          this._buffer = new ArrayBuffer(byteLength);
          this._poses = new Array(_capacity).fill(null);
          this._freeCount = _capacity;
        }
        var _proto2 = PosePage.prototype;
        _proto2.tryAllocate = function tryAllocate() {
          var _poses$idlePoseIndex;
          var poses = this._poses,
            idleFlags = this._idleFlags,
            capacity = this._capacity;
          var idlePoseIndex = findRightmostSetBit(idleFlags);
          if (idlePoseIndex >= capacity) {
            return null;
          }
          assertIsTrue(idlePoseIndex >= 0 && idlePoseIndex < poses.length);
          var pose = (_poses$idlePoseIndex = poses[idlePoseIndex]) !== null && _poses$idlePoseIndex !== void 0 ? _poses$idlePoseIndex : poses[idlePoseIndex] = this._createPose(idlePoseIndex);
          pose[allocationInfoTag].poseIndex = idlePoseIndex;
          this._idleFlags &= ~(1 << idlePoseIndex);
          assertIsTrue(this._freeCount > 0);
          --this._freeCount;
          return pose;
        };
        _proto2.deallocate = function deallocate(pose) {
          var poses = this._poses;
          var poseIndex = pose[allocationInfoTag].poseIndex;
          assertIsTrue(poseIndex >= 0 && poseIndex < poses.length);
          assertIsTrue(poses[poseIndex] === pose);
          this._idleFlags |= 1 << poseIndex;
          assertIsTrue(this._freeCount < this._capacity);
          ++this._freeCount;
        };
        _proto2._createPose = function _createPose(index) {
          var transformsByteLength = TransformArray.BYTES_PER_ELEMENT * this._transformCount;
          var baseOffset = (transformsByteLength + Float64Array.BYTES_PER_ELEMENT * this._metaValueCount) * index;
          var transforms = new TransformArray(this._buffer, baseOffset, this._transformCount);
          var metaValues = new Float64Array(this._buffer, baseOffset + transformsByteLength, this._metaValueCount);
          var pose = Pose._create(transforms, metaValues);
          pose[allocationInfoTag] = new AllocationInfo();
          return pose;
        };
        _createClass(PosePage, [{
          key: "capacity",
          get: function get() {
            return this._capacity;
          }
        }, {
          key: "freeCount",
          get: function get() {
            return this._freeCount;
          }
        }]);
        return PosePage;
      }();
      function findRightmostSetBit(bits) {
        return bits === 0 ? Infinity : Math.log2(bits & -bits);
      }

      var _dec$1N, _dec2$1v, _dec3$19, _dec4$S, _dec5$O, _dec6$z, _dec7$q, _class3$z;
      function findBoneByNameRecursively(from, name) {
        if (from.name === name) {
          return from;
        }
        var nChildren = from.children.length;
        for (var iChild = 0; iChild < nChildren; ++iChild) {
          var found = findBoneByNameRecursively(from.children[iChild], name);
          if (found) {
            return found;
          }
        }
        return null;
      }
      var AnimationGraphBindingContext = function () {
        function AnimationGraphBindingContext(origin, poseLayoutMaintainer, varRegistry, _controller) {
          var _this = this;
          this._origin = void 0;
          this._layoutMaintainer = void 0;
          this._varRegistry = void 0;
          this._additiveFlagStack = [];
          this._triggerResetter = function (name) {
            return _this._resetTrigger(name);
          };
          this._isLayerWideContextPropertiesSet = false;
          this._stashView = void 0;
          this._motionSyncManager = void 0;
          this._clipOverrides = undefined;
          this._controller = _controller;
          this._origin = origin;
          this._layoutMaintainer = poseLayoutMaintainer;
          this._varRegistry = varRegistry;
          this._additiveFlagStack = [false];
        }
        var _proto = AnimationGraphBindingContext.prototype;
        _proto.bindTransform = function bindTransform(bone) {
          var boneNode = this._origin.getChildByPath(bone);
          if (!boneNode) {
            return null;
          }
          return this._layoutMaintainer.getOrCreateTransformBinding(boneNode);
        };
        _proto.bindTransformByName = function bindTransformByName(bone) {
          var boneNode = findBoneByNameRecursively(this._origin, bone);
          if (!boneNode) {
            return null;
          }
          return this._layoutMaintainer.getOrCreateTransformBinding(boneNode);
        };
        _proto.getBoneChildren = function getBoneChildren(bone) {
          var boneNode = findBoneByNameRecursively(this._origin, bone);
          if (!boneNode) {
            return [];
          }
          return boneNode.children.map(function (childNode) {
            return childNode.name;
          });
        };
        _proto.getParentBoneNameByName = function getParentBoneNameByName(bone) {
          var _boneNode$parent;
          var boneNode = findBoneByNameRecursively(this._origin, bone);
          if (!boneNode) {
            return null;
          }
          return boneNode === this._origin ? '' : (_boneNode$parent = boneNode.parent) === null || _boneNode$parent === void 0 ? void 0 : _boneNode$parent.name;
        };
        _proto.bindAuxiliaryCurve = function bindAuxiliaryCurve(name) {
          return this._layoutMaintainer.getOrCreateAuxiliaryCurveBinding(name);
        };
        _proto.getEvaluationTimeAuxiliaryCurveView = function getEvaluationTimeAuxiliaryCurveView() {
          return this._layoutMaintainer.auxiliaryCurveRegistry;
        };
        _proto.getVar = function getVar(id) {
          return this._varRegistry[id];
        };
        _proto._pushAdditiveFlag = function _pushAdditiveFlag(additive) {
          this._additiveFlagStack.push(additive);
        };
        _proto._popAdditiveFlag = function _popAdditiveFlag() {
          assertIsTrue(this._additiveFlagStack.length > 1);
          this._additiveFlagStack.pop();
        };
        _proto._integrityCheck = function _integrityCheck() {
          return this._additiveFlagStack.length === 1;
        };
        _proto._setLayerWideContextProperties = function _setLayerWideContextProperties(stashView, motionSyncManager) {
          assertIsTrue(!this._isLayerWideContextPropertiesSet);
          this._isLayerWideContextPropertiesSet = true;
          this._stashView = stashView;
          this._motionSyncManager = motionSyncManager;
        };
        _proto._unsetLayerWideContextProperties = function _unsetLayerWideContextProperties() {
          assertIsTrue(this._isLayerWideContextPropertiesSet);
          this._isLayerWideContextPropertiesSet = false;
          this._stashView = undefined;
          this._motionSyncManager = undefined;
        };
        _proto._setClipOverrides = function _setClipOverrides(clipOverrides) {
          this._clipOverrides = clipOverrides;
        };
        _proto._resetTrigger = function _resetTrigger(triggerName) {
          var varInstance = this._varRegistry[triggerName];
          if (!varInstance) {
            return;
          }
          varInstance.value = false;
        };
        _createClass(AnimationGraphBindingContext, [{
          key: "origin",
          get: function get() {
            return this._origin;
          }
        }, {
          key: "controller",
          get: function get() {
            return this._controller;
          }
        }, {
          key: "triggerResetter",
          get: function get() {
            return this._triggerResetter;
          }
        }, {
          key: "clipOverrides",
          get: function get() {
            return this._clipOverrides;
          }
        }, {
          key: "additive",
          get: function get() {
            var additiveFlagStack = this._additiveFlagStack;
            return additiveFlagStack[additiveFlagStack.length - 1];
          }
        }, {
          key: "stashView",
          get: function get() {
            assertIsTrue(this._stashView);
            return this._stashView;
          }
        }, {
          key: "motionSyncManager",
          get: function get() {
            assertIsTrue(this._motionSyncManager);
            return this._motionSyncManager;
          }
        }]);
        return AnimationGraphBindingContext;
      }();
      var cacheTransform = new Transform$1();
      var AuxiliaryCurveRegistry = function () {
        function AuxiliaryCurveRegistry() {
          this._namedCurves = new Map();
        }
        var _proto2 = AuxiliaryCurveRegistry.prototype;
        _proto2.names = function names() {
          return this._namedCurves.keys();
        };
        _proto2.has = function has(name) {
          return this._namedCurves.has(name);
        };
        _proto2.get = function get(name) {
          var _this$_namedCurves$ge;
          return (_this$_namedCurves$ge = this._namedCurves.get(name)) !== null && _this$_namedCurves$ge !== void 0 ? _this$_namedCurves$ge : 0.0;
        };
        _proto2.set = function set(name, value) {
          this._namedCurves.set(name, value);
        };
        return AuxiliaryCurveRegistry;
      }();
      var LayoutChangeFlag;
      (function (LayoutChangeFlag) {
        LayoutChangeFlag[LayoutChangeFlag["TRANSFORM_COUNT"] = 1] = "TRANSFORM_COUNT";
        LayoutChangeFlag[LayoutChangeFlag["TRANSFORM_ORDER"] = 2] = "TRANSFORM_ORDER";
        LayoutChangeFlag[LayoutChangeFlag["AUXILIARY_CURVE_COUNT"] = 4] = "AUXILIARY_CURVE_COUNT";
      })(LayoutChangeFlag || (LayoutChangeFlag = {}));
      var checkBindStatus = function checkBindStatus(bindStarted) {
        if (bindStarted === void 0) {
          bindStarted = false;
        }
        return function (_, _propertyKey, descriptor) {
          var vendor = descriptor.value;
          if (vendor) {
            descriptor.value = function () {
              assertIsTrue(this._bindStarted === bindStarted, bindStarted ? "The operation is invalid since bind has not been started." : "The operation is invalid since bind has already been started.");
              for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
              }
              return vendor.call.apply(vendor, [this].concat(args));
            };
          }
        };
      };
      var AnimationGraphPoseLayoutMaintainer = (_dec$1N = checkBindStatus(true), _dec2$1v = checkBindStatus(true), _dec3$19 = checkBindStatus(true), _dec4$S = checkBindStatus(true), _dec5$O = checkBindStatus(true), _dec6$z = checkBindStatus(false), _dec7$q = checkBindStatus(true), (_class3$z = function () {
        function AnimationGraphPoseLayoutMaintainer(origin, auxiliaryCurveRegistry) {
          this._origin = void 0;
          this._auxiliaryCurveRegistry = void 0;
          this._auxiliaryCurveRecords = [];
          this._transformRecords = [];
          this._parentTable = [];
          this._bindStarted = false;
          this._transformCountBeforeBind = -1;
          this._auxiliaryCurveCountBeforeBind = -1;
          this._origin = origin;
          this._auxiliaryCurveRegistry = auxiliaryCurveRegistry;
        }
        var _proto3 = AnimationGraphPoseLayoutMaintainer.prototype;
        _proto3.getOrCreateTransformBinding = function getOrCreateTransformBinding(node) {
          var origin = this._origin;
          var debugIntegrityCheckLengthOfPathToOrigin = 0;
          var isValidNode = false;
          for (var current = node; current; current = current.parent) {
            if (current === origin) {
              isValidNode = true;
              break;
            }
            {
              ++debugIntegrityCheckLengthOfPathToOrigin;
            }
          }
          if (!isValidNode) {
            return null;
          }
          var handle = this._getOrCreateTransformBinding(node);
          if (node !== origin) {
            {
              --debugIntegrityCheckLengthOfPathToOrigin;
              assertIsTrue(debugIntegrityCheckLengthOfPathToOrigin >= 0);
            }
            for (var parent = node.parent; parent !== origin; parent = parent.parent) {
              assertIsTrue(parent);
              void this._getOrCreateTransformBinding(parent);
              {
                --debugIntegrityCheckLengthOfPathToOrigin;
                assertIsTrue(debugIntegrityCheckLengthOfPathToOrigin >= 0);
              }
            }
          }
          {
            assertIsTrue(debugIntegrityCheckLengthOfPathToOrigin === 0);
          }
          return handle;
        };
        _proto3._getOrCreateTransformBinding = function _getOrCreateTransformBinding(node) {
          var transformRecords = this._transformRecords;
          var transformIndex = transformRecords.findIndex(function (transformRecord) {
            return transformRecord.node === node;
          });
          if (transformIndex >= 0) {
            var _transformRecord = transformRecords[transformIndex];
            ++_transformRecord.refCount;
            return _transformRecord.handle;
          }
          var newNodeIndex = 0;
          var _loop = function _loop(parent) {
            var parentIndex = transformRecords.findIndex(function (transformRecord) {
              return transformRecord.node === parent;
            });
            if (parentIndex >= 0) {
              newNodeIndex = parentIndex + 1;
              return 1;
            }
          };
          for (var parent = node.parent; parent; parent = parent.parent) {
            if (_loop(parent)) break;
          }
          for (var _transformIndex = newNodeIndex; _transformIndex < transformRecords.length; ++_transformIndex) {
            ++transformRecords[_transformIndex].handle.index;
          }
          var transformRecord = new TransformRecord(new TransformHandleInternal(this, newNodeIndex), node);
          transformRecords.splice(newNodeIndex, 0, transformRecord);
          return transformRecord.handle;
        };
        _proto3.getOrCreateAuxiliaryCurveBinding = function getOrCreateAuxiliaryCurveBinding(name) {
          var auxiliaryCurveRecords = this._auxiliaryCurveRecords;
          var auxiliaryCurveIndex = auxiliaryCurveRecords.findIndex(function (record) {
            return record.name === name;
          });
          if (auxiliaryCurveIndex >= 0) {
            var auxiliaryCurveRecord = auxiliaryCurveRecords[auxiliaryCurveIndex];
            ++auxiliaryCurveRecord.refCount;
            return auxiliaryCurveRecord.handle;
          } else {
            var newAuxiliaryCurveIndex = auxiliaryCurveRecords.length;
            var _auxiliaryCurveRecord = new AuxiliaryCurveRecord(new AuxiliaryCurveHandleInternal(this, newAuxiliaryCurveIndex), name);
            auxiliaryCurveRecords.push(_auxiliaryCurveRecord);
            return _auxiliaryCurveRecord.handle;
          }
        };
        _proto3.createEvaluationContext = function createEvaluationContext() {
          assertIsTrue(!this._bindStarted);
          return new AnimationGraphEvaluationContext(this.transformCount, this.auxiliaryCurveCount, this._parentTable.slice(), this._origin);
        };
        _proto3.resetPoseStashAllocator = function resetPoseStashAllocator(allocator) {
          assertIsTrue(!this._bindStarted);
          allocator._reset(this.transformCount, this.auxiliaryCurveCount);
        };
        _proto3.createTransformFilter = function createTransformFilter(mask) {
          var origin = this._origin;
          var involvedTransformIndices = [];
          for (var _iterator = _createForOfIteratorHelperLoose(this._transformRecords), _step; !(_step = _iterator()).done;) {
            var _step$value = _step.value,
              node = _step$value.node,
              handle = _step$value.handle;
            var path = countPath(origin, node);
            if (typeof path === 'undefined') {
              error(node.getPathInHierarchy() + " is not a child of " + origin.getPathInHierarchy());
            } else if (mask.isExcluded(path)) {
              continue;
            }
            involvedTransformIndices.push(handle.index);
          }
          involvedTransformIndices.sort();
          var poseFilter = new TransformFilter(involvedTransformIndices);
          return poseFilter;
          function countPath(from, to) {
            var path = [];
            for (var node = to; node; node = node.parent) {
              if (node === from) {
                return path.join('/');
              } else {
                path.unshift(node.name);
              }
            }
            return undefined;
          }
        };
        _proto3.fetchDefaultTransforms = function fetchDefaultTransforms(transforms) {
          var nTransforms = this._transformRecords.length;
          assertIsTrue(transforms.length === nTransforms);
          for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
            var defaultTransform = this._transformRecords[iTransform].defaultTransform;
            transforms.setTransform(iTransform, defaultTransform);
          }
        };
        _proto3.apply = function apply(pose) {
          var transforms = pose.transforms,
            auxiliaryCurves = pose.auxiliaryCurves;
          var nTransforms = this._transformRecords.length;
          assertIsTrue(transforms.length === nTransforms);
          for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
            var transform = transforms.getTransform(iTransform, cacheTransform);
            var node = this._transformRecords[iTransform].node;
            node.setRTS(transform.rotation, transform.position, transform.scale);
          }
          var nAuxiliaryCurves = this._auxiliaryCurveRecords.length;
          for (var iAuxiliaryCurve = 0; iAuxiliaryCurve < nAuxiliaryCurves; ++iAuxiliaryCurve) {
            var _curveName = this._auxiliaryCurveRecords[iAuxiliaryCurve].name;
            var curveValue = auxiliaryCurves[iAuxiliaryCurve];
            this._auxiliaryCurveRegistry.set(_curveName, curveValue);
          }
        };
        _proto3._destroyTransformHandle = function _destroyTransformHandle(index) {
          assertIsTrue(index >= 0 && index < this._transformRecords.length, "Invalid transform handle.");
          var record = this._transformRecords[index];
          assertIsTrue(record.refCount > 0, "Something work wrong: refCount mismatch.");
          --record.refCount;
        };
        _proto3._destroyAuxiliaryCurveHandle = function _destroyAuxiliaryCurveHandle(index) {
          assertIsTrue(index >= 0 && index < this._auxiliaryCurveRecords.length, "Invalid auxiliary value handle.");
          var record = this._auxiliaryCurveRecords[index];
          assertIsTrue(record.refCount > 0, "Something work wrong: refCount mismatch.");
          --record.refCount;
        };
        _proto3.startBind = function startBind() {
          this._bindStarted = true;
          this._transformCountBeforeBind = this._transformRecords.length;
          this._auxiliaryCurveCountBeforeBind = this._auxiliaryCurveRecords.length;
        };
        _proto3.endBind = function endBind() {
          var transformRecords = this._transformRecords,
            auxiliaryCurveRecords = this._auxiliaryCurveRecords;
          var changeFlags = 0;
          trimRecords(transformRecords);
          if (transformRecords.length !== this._transformCountBeforeBind) {
            changeFlags |= LayoutChangeFlag.TRANSFORM_COUNT;
            var nRecords = transformRecords.length;
            for (var iRecord = 0; iRecord < nRecords; ++iRecord) {
              var record = transformRecords[iRecord];
              record.order = iRecord;
            }
          } else {
            var _nRecords = transformRecords.length;
            var orderChanged = false;
            for (var _iRecord = 0; _iRecord < _nRecords; ++_iRecord) {
              var _record = transformRecords[_iRecord];
              if (_record.order !== _iRecord) {
                orderChanged = true;
                _record.order = _iRecord;
              }
            }
            if (orderChanged) {
              changeFlags |= LayoutChangeFlag.TRANSFORM_ORDER;
            }
          }
          trimRecords(auxiliaryCurveRecords);
          if (auxiliaryCurveRecords.length !== this._auxiliaryCurveCountBeforeBind) {
            changeFlags |= LayoutChangeFlag.AUXILIARY_CURVE_COUNT;
          }
          var parentTable = this._parentTable,
            origin = this._origin;
          parentTable.length = transformRecords.length;
          var _loop2 = function _loop2() {
            var node = transformRecords[iTransform].node;
            if (node === origin) {
              parentTable[iTransform] = -1;
              return 1;
            }
            var parent = node.parent;
            if (parent === origin) {
              var parentIndex = transformRecords.findIndex(function (record) {
                return record.node === parent;
              });
              parentTable[iTransform] = parentIndex >= 0 ? parentIndex : -1;
            } else {
              var _parentIndex = transformRecords.findIndex(function (record) {
                return record.node === parent;
              });
              assertIsTrue(_parentIndex >= 0, "Parent node is not bound!");
              assertIsTrue(_parentIndex < iTransform);
              parentTable[iTransform] = _parentIndex;
            }
          };
          for (var iTransform = 0; iTransform < transformRecords.length; ++iTransform) {
            if (_loop2()) continue;
          }
          this._bindStarted = false;
          {
            transformRecords.forEach(function (transformRecord, index, transformRecords) {
              assertIsTrue(transformRecord.handle.index === index, "Bad transform handle.");
              assertIsTrue(transformRecord.order === index, "Bad transform order field.");
              var _loop3 = function _loop3(parent) {
                var parentIndex = transformRecords.findIndex(function (r) {
                  return r.node === parent;
                });
                if (parentIndex >= 0) {
                  assertIsTrue(parentIndex < index, "Bad transform order.");
                }
              };
              for (var parent = transformRecord.node.parent; parent; parent = parent.parent) {
                _loop3(parent);
              }
            });
            this._transformCountBeforeBind = -1;
            this._auxiliaryCurveCountBeforeBind = -1;
          }
          return changeFlags;
        };
        _createClass(AnimationGraphPoseLayoutMaintainer, [{
          key: "transformCount",
          get: function get() {
            return this._transformRecords.length;
          }
        }, {
          key: "auxiliaryCurveCount",
          get: function get() {
            return this._auxiliaryCurveRecords.length;
          }
        }, {
          key: "auxiliaryCurveRegistry",
          get: function (_get) {
            function get() {
              return _get.apply(this, arguments);
            }
            get.toString = function () {
              return _get.toString();
            };
            return get;
          }(function () {
            return this._auxiliaryCurveRegistry;
          })
        }]);
        return AnimationGraphPoseLayoutMaintainer;
      }(), (_applyDecoratedDescriptor(_class3$z.prototype, "getOrCreateTransformBinding", [_dec$1N], Object.getOwnPropertyDescriptor(_class3$z.prototype, "getOrCreateTransformBinding"), _class3$z.prototype), _applyDecoratedDescriptor(_class3$z.prototype, "_getOrCreateTransformBinding", [_dec2$1v], Object.getOwnPropertyDescriptor(_class3$z.prototype, "_getOrCreateTransformBinding"), _class3$z.prototype), _applyDecoratedDescriptor(_class3$z.prototype, "getOrCreateAuxiliaryCurveBinding", [_dec3$19], Object.getOwnPropertyDescriptor(_class3$z.prototype, "getOrCreateAuxiliaryCurveBinding"), _class3$z.prototype), _applyDecoratedDescriptor(_class3$z.prototype, "_destroyTransformHandle", [_dec4$S], Object.getOwnPropertyDescriptor(_class3$z.prototype, "_destroyTransformHandle"), _class3$z.prototype), _applyDecoratedDescriptor(_class3$z.prototype, "_destroyAuxiliaryCurveHandle", [_dec5$O], Object.getOwnPropertyDescriptor(_class3$z.prototype, "_destroyAuxiliaryCurveHandle"), _class3$z.prototype), _applyDecoratedDescriptor(_class3$z.prototype, "startBind", [_dec6$z], Object.getOwnPropertyDescriptor(_class3$z.prototype, "startBind"), _class3$z.prototype), _applyDecoratedDescriptor(_class3$z.prototype, "endBind", [_dec7$q], Object.getOwnPropertyDescriptor(_class3$z.prototype, "endBind"), _class3$z.prototype)), _class3$z));
      var TransformRecord = function TransformRecord(handle, node) {
        this.order = -1;
        this.refCount = 1;
        this.handle = void 0;
        this.node = void 0;
        this.defaultTransform = void 0;
        this.handle = handle;
        this.node = node;
        var defaultTransform = new Transform$1();
        defaultTransform.position = node.position;
        defaultTransform.rotation = node.rotation;
        defaultTransform.scale = node.scale;
        this.defaultTransform = defaultTransform;
      };
      var AuxiliaryCurveRecord = function AuxiliaryCurveRecord(handle, name) {
        this.refCount = 1;
        this.handle = void 0;
        this.name = void 0;
        this.handle = handle;
        this.name = name;
      };
      function trimRecords(records) {
        var nUsedRecords = partition(records, function (record) {
          assertIsTrue(record.refCount >= 0);
          return record.refCount > 0;
        });
        assertIsTrue(nUsedRecords <= records.length);
        if (nUsedRecords === records.length) {
          return;
        }
        for (var iRecord = 0; iRecord < nUsedRecords; ++iRecord) {
          records[iRecord].handle.index = iRecord;
        }
        {
          records.slice(nUsedRecords).forEach(function (record) {
            return record.refCount = -1;
          });
        }
        records.splice(nUsedRecords, records.length - nUsedRecords);
      }
      var defaultTransformsTag = Symbol('[[DefaultTransforms]]');
      var AnimationGraphSettleContext = function () {
        function AnimationGraphSettleContext(_layoutMaintainer) {
          this._layoutMaintainer = _layoutMaintainer;
        }
        var _proto4 = AnimationGraphSettleContext.prototype;
        _proto4.createTransformFilter = function createTransformFilter(mask) {
          return this._layoutMaintainer.createTransformFilter(mask);
        };
        _createClass(AnimationGraphSettleContext, [{
          key: "transformCount",
          get: function get() {
            return this._layoutMaintainer.transformCount;
          }
        }]);
        return AnimationGraphSettleContext;
      }();
      var cacheTransform_spaceConversion = new Transform$1();
      var cacheParentTransform_spaceConversion = new Transform$1();
      var AnimationGraphEvaluationContext = function () {
        function AnimationGraphEvaluationContext(transformCount, metaValueCount, parentTable, componentNode) {
          this[defaultTransformsTag] = void 0;
          this._poseAllocator = void 0;
          this._parentTable = void 0;
          this._componentNode = void 0;
          this._cacheComponentToWorldTransform = new Transform$1();
          {
            assertIsTrue(transformCount === parentTable.length);
            assertIsTrue(parentTable.every(function (parentIndex, currentIndex) {
              if (parentIndex < 0) {
                return true;
              }
              return parentIndex < currentIndex;
            }));
          }
          this._poseAllocator = new PoseStackAllocator(transformCount, metaValueCount);
          this._parentTable = parentTable;
          this._componentNode = componentNode;
          this[defaultTransformsTag] = new TransformArray(transformCount);
        }
        var _proto5 = AnimationGraphEvaluationContext.prototype;
        _proto5.destroy = function destroy() {
          this._poseAllocator.destroy();
        };
        _proto5.pushDefaultedPose = function pushDefaultedPose() {
          var pose = this._poseAllocator.push();
          pose.transforms.set(this[defaultTransformsTag]);
          pose._poseTransformSpace = PoseTransformSpace.LOCAL;
          pose.auxiliaryCurves.fill(0.0);
          return pose;
        };
        _proto5.pushDefaultedPoseInComponentSpace = function pushDefaultedPoseInComponentSpace() {
          var pose = this.pushDefaultedPose();
          this._poseTransformsSpaceLocalToComponent(pose);
          return pose;
        };
        _proto5.pushZeroDeltaPose = function pushZeroDeltaPose() {
          var pose = this._poseAllocator.push();
          pose.transforms.fill(ZERO_DELTA_TRANSFORM);
          pose._poseTransformSpace = PoseTransformSpace.LOCAL;
          pose.auxiliaryCurves.fill(0.0);
          return pose;
        };
        _proto5.pushDuplicatedPose = function pushDuplicatedPose(src) {
          var pose = this._poseAllocator.push();
          pose.transforms.set(src.transforms);
          pose._poseTransformSpace = src._poseTransformSpace;
          pose.auxiliaryCurves.set(src.auxiliaryCurves);
          return pose;
        };
        _proto5.popPose = function popPose() {
          this._poseAllocator.pop();
        };
        _proto5._isStackTopPose_debugging = function _isStackTopPose_debugging(pose) {
          return pose === this._poseAllocator.top;
        };
        _proto5._poseTransformsSpaceLocalToComponent = function _poseTransformsSpaceLocalToComponent(pose) {
          var transforms = pose.transforms;
          var nTransforms = transforms.length;
          for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
            var parentTransformIndex = this._parentTable[iTransform];
            if (parentTransformIndex < 0) {
              continue;
            }
            var transform = transforms.getTransform(iTransform, cacheTransform_spaceConversion);
            var parentTransform = transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion);
            Transform$1.multiply(transform, parentTransform, transform);
            transforms.setTransform(iTransform, transform);
          }
          pose._poseTransformSpace = PoseTransformSpace.COMPONENT;
        };
        _proto5._poseTransformsSpaceComponentToLocal = function _poseTransformsSpaceComponentToLocal(pose) {
          var transforms = pose.transforms;
          var nTransforms = transforms.length;
          for (var iTransform = nTransforms - 1; iTransform >= 0; --iTransform) {
            var parentTransformIndex = this._parentTable[iTransform];
            if (parentTransformIndex < 0) {
              continue;
            }
            var transform = transforms.getTransform(iTransform, cacheTransform_spaceConversion);
            var parentTransform = transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion);
            Transform$1.calculateRelative(transform, transform, parentTransform);
            transforms.setTransform(iTransform, transform);
          }
          pose._poseTransformSpace = PoseTransformSpace.LOCAL;
        };
        _proto5._convertPoseSpaceTransformToTargetSpace = function _convertPoseSpaceTransformToTargetSpace(transform, outTransformSpace, pose, poseTransformIndex) {
          var poseSpace = pose._poseTransformSpace;
          switch (outTransformSpace) {
            default:
              {
                assertIsTrue(false);
              }
              break;
            case TransformSpace.WORLD:
              if (poseSpace === PoseTransformSpace.COMPONENT) {
                Transform$1.multiply(transform, this._getComponentToWorldTransform(), transform);
              } else {
                assertIsTrue(poseSpace === PoseTransformSpace.LOCAL);
                Transform$1.multiply(transform, this._getLocalToWorldTransform(cacheParentTransform_spaceConversion, pose, poseTransformIndex), transform);
              }
              break;
            case TransformSpace.COMPONENT:
              if (poseSpace === PoseTransformSpace.COMPONENT) ; else {
                assertIsTrue(poseSpace === PoseTransformSpace.LOCAL);
                Transform$1.multiply(transform, this._getLocalToComponentTransform(cacheParentTransform_spaceConversion, pose, poseTransformIndex), transform);
              }
              break;
            case TransformSpace.PARENT:
              {
                if (poseSpace === PoseTransformSpace.COMPONENT) {
                  var parentTransformIndex = this._parentTable[poseTransformIndex];
                  if (parentTransformIndex >= 0) {
                    var parentComponentTransform = pose.transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion);
                    var invParentComponentTransform = Transform$1.invert(parentComponentTransform, parentComponentTransform);
                    Transform$1.multiply(transform, invParentComponentTransform, transform);
                  }
                } else {
                  assertIsTrue(poseSpace === PoseTransformSpace.LOCAL);
                }
                break;
              }
            case TransformSpace.LOCAL:
              {
                assertIsTrue(poseSpace === PoseTransformSpace.COMPONENT || poseSpace === PoseTransformSpace.LOCAL);
                var boneTransform = pose.transforms.getTransform(poseTransformIndex, cacheParentTransform_spaceConversion);
                var invBoneTransform = Transform$1.invert(boneTransform, boneTransform);
                Transform$1.multiply(transform, invBoneTransform, transform);
                break;
              }
          }
          return transform;
        };
        _proto5._convertTransformToPoseTransformSpace = function _convertTransformToPoseTransformSpace(transform, transformSpace, pose, poseTransformIndex) {
          var poseSpace = pose._poseTransformSpace;
          switch (transformSpace) {
            default:
              {
                assertIsTrue(false);
              }
              break;
            case TransformSpace.WORLD:
              if (poseSpace === PoseTransformSpace.COMPONENT) {
                var worldToComponent = Transform$1.invert(cacheParentTransform_spaceConversion, this._getComponentToWorldTransform());
                Transform$1.multiply(transform, worldToComponent, transform);
              } else {
                assertIsTrue(poseSpace === PoseTransformSpace.LOCAL);
                var localToWorld = this._getLocalToWorldTransform(cacheParentTransform_spaceConversion, pose, poseTransformIndex);
                var worldToLocal = Transform$1.invert(localToWorld, localToWorld);
                Transform$1.multiply(transform, worldToLocal, transform);
              }
              break;
            case TransformSpace.COMPONENT:
              if (poseSpace === PoseTransformSpace.COMPONENT) ; else {
                assertIsTrue(poseSpace === PoseTransformSpace.LOCAL);
                var localToComponent = this._getLocalToComponentTransform(cacheParentTransform_spaceConversion, pose, poseTransformIndex);
                var componentToLocal = Transform$1.invert(localToComponent, localToComponent);
                Transform$1.multiply(transform, componentToLocal, transform);
              }
              break;
            case TransformSpace.PARENT:
              {
                if (poseSpace === PoseTransformSpace.COMPONENT) {
                  var parentTransformIndex = this._parentTable[poseTransformIndex];
                  if (parentTransformIndex >= 0) {
                    var parentTransform = pose.transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion);
                    Transform$1.multiply(transform, parentTransform, transform);
                  }
                }
                break;
              }
            case TransformSpace.LOCAL:
              {
                assertIsTrue(poseSpace === PoseTransformSpace.COMPONENT || poseSpace === PoseTransformSpace.LOCAL);
                var currentTransform = pose.transforms.getTransform(poseTransformIndex, cacheParentTransform_spaceConversion);
                Transform$1.multiply(transform, currentTransform, transform);
                break;
              }
          }
          return transform;
        };
        _proto5._getComponentToWorldTransform = function _getComponentToWorldTransform() {
          var result = this._cacheComponentToWorldTransform;
          var componentNode = this._componentNode;
          result.position = componentNode.worldPosition;
          result.rotation = componentNode.worldRotation;
          result.scale = componentNode.worldScale;
          return result;
        };
        _proto5._getLocalToComponentTransform = function _getLocalToComponentTransform(out, pose, transformIndex) {
          var parentTable = this._parentTable;
          Transform$1.setIdentity(out);
          for (var iTransform = parentTable[transformIndex]; iTransform >= 0; iTransform = parentTable[iTransform]) {
            var localTransform = pose.transforms.getTransform(iTransform, cacheTransform_spaceConversion);
            Transform$1.multiply(out, localTransform, out);
          }
          return out;
        };
        _proto5._getLocalToWorldTransform = function _getLocalToWorldTransform(out, pose, transformIndex) {
          this._getLocalToComponentTransform(out, pose, transformIndex);
          Transform$1.multiply(out, this._getComponentToWorldTransform(), out);
          return out;
        };
        _createClass(AnimationGraphEvaluationContext, [{
          key: "allocatedPoseCount",
          get: function get() {
            return this._poseAllocator.allocatedCount;
          }
        }, {
          key: "parentTable",
          get: function get() {
            return this._parentTable;
          }
        }, {
          key: "_stackSize_debugging",
          get: function get() {
            return this._poseAllocator.allocatedCount;
          }
        }]);
        return AnimationGraphEvaluationContext;
      }();
      var TransformHandleInternal = function () {
        function TransformHandleInternal(host, index) {
          this.index = -1;
          this._host = void 0;
          this._host = host;
          this.index = index;
        }
        var _proto6 = TransformHandleInternal.prototype;
        _proto6.destroy = function destroy() {
          this._host._destroyTransformHandle(this.index);
        };
        return TransformHandleInternal;
      }();
      var AuxiliaryCurveHandleInternal = function () {
        function AuxiliaryCurveHandleInternal(host, index) {
          this.index = -1;
          this._host = void 0;
          this._host = host;
          this.index = index;
        }
        var _proto7 = AuxiliaryCurveHandleInternal.prototype;
        _proto7.destroy = function destroy() {
          this._host._destroyAuxiliaryCurveHandle(this.index);
        };
        return AuxiliaryCurveHandleInternal;
      }();
      var AnimationGraphUpdateContextGenerator = function () {
        function AnimationGraphUpdateContextGenerator() {
          this._context = {
            deltaTime: 0.0,
            indicativeWeight: 0.0
          };
        }
        var _proto8 = AnimationGraphUpdateContextGenerator.prototype;
        _proto8.generate = function generate(deltaTime, indicativeWeight) {
          this._context.deltaTime = deltaTime;
          this._context.indicativeWeight = indicativeWeight;
          return this._context;
        };
        _proto8.forkSubWeight = function forkSubWeight(base, subWeight) {
          this._context.deltaTime = base.deltaTime;
          this._context.indicativeWeight = base.indicativeWeight * subWeight;
        };
        return AnimationGraphUpdateContextGenerator;
      }();
      var DeferredPoseStashAllocator = function () {
        function DeferredPoseStashAllocator() {
          this._allocator = null;
        }
        var _proto9 = DeferredPoseStashAllocator.prototype;
        _proto9._reset = function _reset(transformCount, auxiliaryCurveCount) {
          this._allocator = new PoseHeapAllocator(transformCount, auxiliaryCurveCount);
        };
        _proto9.allocatePose = function allocatePose() {
          assertIsTrue(this._allocator);
          var pose = this._allocator.allocatePose();
          return pose;
        };
        _proto9.destroyPose = function destroyPose(pose) {
          assertIsTrue(this._allocator);
          return this._allocator.destroyPose(pose);
        };
        _createClass(DeferredPoseStashAllocator, [{
          key: "allocatedPoseCount",
          get: function get() {
            assertIsTrue(this._allocator);
            return this._allocator.allocatedCount;
          }
        }]);
        return DeferredPoseStashAllocator;
      }();

      var _dec$1M, _class$1K, _class2$1D, _initializer$1w, _initializer2$1j, _class3$y;
      var ccclass$w = ccclass$M,
        serializable$b = serializable$p;
      var UnaryOperator;
      (function (UnaryOperator) {
        UnaryOperator[UnaryOperator["TRUTHY"] = 0] = "TRUTHY";
        UnaryOperator[UnaryOperator["FALSY"] = 1] = "FALSY";
      })(UnaryOperator || (UnaryOperator = {}));
      (_dec$1M = ccclass$w(CLASS_NAME_PREFIX_ANIM + "UnaryCondition"), _dec$1M(_class$1K = (_class2$1D = (_class3$y = function () {
        function UnaryCondition() {
          this.operator = _initializer$1w && _initializer$1w();
          this.operand = _initializer2$1j && _initializer2$1j();
        }
        var _proto = UnaryCondition.prototype;
        _proto.clone = function clone() {
          var that = new UnaryCondition();
          that.operator = this.operator;
          that.operand = this.operand.clone();
          return that;
        };
        _proto[createEval] = function (context) {
          var operator = this.operator,
            operand = this.operand;
          var evaluation = new UnaryConditionEval(operator, false);
          var value = bindOr(context, operand, VariableType.BOOLEAN, evaluation.setOperand, evaluation);
          evaluation.reset(value);
          return evaluation;
        };
        return UnaryCondition;
      }(), _class3$y.Operator = UnaryOperator, _class3$y), (_initializer$1w = applyDecoratedInitializer(_class2$1D.prototype, "operator", [serializable$b], function () {
        return UnaryOperator.TRUTHY;
      }), _initializer2$1j = applyDecoratedInitializer(_class2$1D.prototype, "operand", [serializable$b], function () {
        return new BindableBoolean();
      })), _class2$1D)) || _class$1K);
      var UnaryConditionEval = function () {
        function UnaryConditionEval(operator, operand) {
          this._operator = operator;
          this._operand = operand;
          this._eval();
        }
        var _proto2 = UnaryConditionEval.prototype;
        _proto2.reset = function reset(value) {
          this.setOperand(value);
        };
        _proto2.setOperand = function setOperand(value) {
          this._operand = value;
          this._eval();
        };
        _proto2.eval = function _eval() {
          return this._result;
        };
        _proto2._eval = function _eval() {
          var operand = this._operand;
          switch (this._operator) {
            default:
            case UnaryOperator.TRUTHY:
              this._result = !!operand;
              break;
            case UnaryOperator.FALSY:
              this._result = !operand;
              break;
          }
        };
        return UnaryConditionEval;
      }();

      var TCBindingValueType;
      (function (TCBindingValueType) {
        TCBindingValueType[TCBindingValueType["FLOAT"] = 0] = "FLOAT";
        TCBindingValueType[TCBindingValueType["INTEGER"] = 3] = "INTEGER";
      })(TCBindingValueType || (TCBindingValueType = {}));
      var TCBinding = function TCBinding() {};

      var provide = function provide() {
        for (var _len = arguments.length, valueTypes = new Array(_len), _key = 0; _key < _len; _key++) {
          valueTypes[_key] = arguments[_key];
        }
        return function () {} ;
      };
      var TCBindingTransitionSourceFilter;
      (function (TCBindingTransitionSourceFilter) {
        TCBindingTransitionSourceFilter[TCBindingTransitionSourceFilter["MOTION"] = 1] = "MOTION";
        TCBindingTransitionSourceFilter[TCBindingTransitionSourceFilter["POSE"] = 2] = "POSE";
        TCBindingTransitionSourceFilter[TCBindingTransitionSourceFilter["EMPTY"] = 4] = "EMPTY";
        TCBindingTransitionSourceFilter[TCBindingTransitionSourceFilter["WEIGHTED"] = 7] = "WEIGHTED";
      })(TCBindingTransitionSourceFilter || (TCBindingTransitionSourceFilter = {}));
      var support = function support(transitionSourceFilter) {
        return function () {} ;
      };

      var _dec$1L, _dec2$1u, _class$1J, _class2$1C, _initializer$1v, _initializer2$1i;
      var ccclass$v = ccclass$M,
        serializable$a = serializable$p;
      var TCVariableBinding = (_dec$1L = ccclass$v(CLASS_NAME_PREFIX_ANIM + "TCVariableBinding"), _dec2$1u = provide(TCBindingValueType.FLOAT, TCBindingValueType.INTEGER), _dec$1L(_class$1J = _dec2$1u(_class$1J = (_class2$1C = function (_TCBinding) {
        _inheritsLoose(TCVariableBinding, _TCBinding);
        function TCVariableBinding() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _TCBinding.call.apply(_TCBinding, [this].concat(args)) || this;
          _this.type = _initializer$1v && _initializer$1v();
          _this.variableName = _initializer2$1i && _initializer2$1i();
          return _this;
        }
        var _proto = TCVariableBinding.prototype;
        _proto.getValueType = function getValueType() {
          return this.type;
        };
        _proto.bind = function bind(context) {
          var varInstance = context.getVar(this.variableName);
          if (!varInstance) {
            return undefined;
          }
          return new TCVariableBindingEvaluation(varInstance);
        };
        return TCVariableBinding;
      }(TCBinding), (_initializer$1v = applyDecoratedInitializer(_class2$1C.prototype, "type", [serializable$a, editorOnly], function () {
        return TCBindingValueType.FLOAT;
      }), _initializer2$1i = applyDecoratedInitializer(_class2$1C.prototype, "variableName", [serializable$a], function () {
        return '';
      })), _class2$1C)) || _class$1J) || _class$1J);
      var TCVariableBindingEvaluation = function () {
        function TCVariableBindingEvaluation(_varInstance) {
          this._varInstance = _varInstance;
        }
        var _proto2 = TCVariableBindingEvaluation.prototype;
        _proto2.evaluate = function evaluate() {
          return this._varInstance.value;
        };
        return TCVariableBindingEvaluation;
      }();

      var _dec$1K, _dec2$1t, _class$1I, _class2$1B, _initializer$1u;
      var ccclass$u = ccclass$M,
        serializable$9 = serializable$p;
      (_dec$1K = ccclass$u(CLASS_NAME_PREFIX_ANIM + "TCAuxiliaryCurveBinding"), _dec2$1t = provide(TCBindingValueType.FLOAT), _dec$1K(_class$1I = _dec2$1t(_class$1I = (_class2$1B = function (_TCBinding) {
        _inheritsLoose(TCAuxiliaryCurveBinding, _TCBinding);
        function TCAuxiliaryCurveBinding() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _TCBinding.call.apply(_TCBinding, [this].concat(args)) || this;
          _this.curveName = _initializer$1u && _initializer$1u();
          return _this;
        }
        var _proto = TCAuxiliaryCurveBinding.prototype;
        _proto.getValueType = function getValueType() {
          return TCBindingValueType.FLOAT;
        };
        _proto.bind = function bind(context) {
          var view = context.getEvaluationTimeAuxiliaryCurveView();
          return new TCAuxiliaryCurveBindingEvaluation(view, this.curveName);
        };
        return TCAuxiliaryCurveBinding;
      }(TCBinding), (_initializer$1u = applyDecoratedInitializer(_class2$1B.prototype, "curveName", [serializable$9], function () {
        return '';
      })), _class2$1B)) || _class$1I) || _class$1I);
      var TCAuxiliaryCurveBindingEvaluation = function () {
        function TCAuxiliaryCurveBindingEvaluation(_view, _curveName) {
          this._view = _view;
          this._curveName = _curveName;
        }
        var _proto2 = TCAuxiliaryCurveBindingEvaluation.prototype;
        _proto2.evaluate = function evaluate() {
          return this._view.get(this._curveName);
        };
        return TCAuxiliaryCurveBindingEvaluation;
      }();

      var _dec$1J, _dec2$1s, _dec3$18, _class$1H;
      var ccclass$t = ccclass$M;
      (_dec$1J = ccclass$t(CLASS_NAME_PREFIX_ANIM + "TCStateWeightBinding"), _dec2$1s = provide(TCBindingValueType.FLOAT), _dec3$18 = support(TCBindingTransitionSourceFilter.WEIGHTED), _dec$1J(_class$1H = _dec2$1s(_class$1H = _dec3$18(_class$1H = function (_TCBinding) {
        _inheritsLoose(TCStateWeightBinding, _TCBinding);
        function TCStateWeightBinding() {
          return _TCBinding.apply(this, arguments) || this;
        }
        var _proto = TCStateWeightBinding.prototype;
        _proto.getValueType = function getValueType() {
          return TCBindingValueType.FLOAT;
        };
        _proto.bind = function bind(_context) {
          return new TCStateWeightBindingEvaluation();
        };
        return TCStateWeightBinding;
      }(TCBinding)) || _class$1H) || _class$1H) || _class$1H);
      var TCStateWeightBindingEvaluation = function () {
        function TCStateWeightBindingEvaluation() {}
        var _proto2 = TCStateWeightBindingEvaluation.prototype;
        _proto2.evaluate = function evaluate(context) {
          return context.sourceStateWeight;
        };
        return TCStateWeightBindingEvaluation;
      }();

      var _dec$1I, _dec2$1r, _dec3$17, _class$1G;
      var ccclass$s = ccclass$M;
      (_dec$1I = ccclass$s(CLASS_NAME_PREFIX_ANIM + "TCStateMotionTimeBinding"), _dec2$1r = provide(TCBindingValueType.FLOAT), _dec3$17 = support(TCBindingTransitionSourceFilter.POSE), _dec$1I(_class$1G = _dec2$1r(_class$1G = _dec3$17(_class$1G = function (_TCBinding) {
        _inheritsLoose(TCStateMotionTimeBinding, _TCBinding);
        function TCStateMotionTimeBinding() {
          return _TCBinding.apply(this, arguments) || this;
        }
        var _proto = TCStateMotionTimeBinding.prototype;
        _proto.getValueType = function getValueType() {
          return TCBindingValueType.FLOAT;
        };
        _proto.bind = function bind(_context) {
          return new TCStateMotionTimeBindingEvaluation();
        };
        return TCStateMotionTimeBinding;
      }(TCBinding)) || _class$1G) || _class$1G) || _class$1G);
      var TCStateMotionTimeBindingEvaluation = function () {
        function TCStateMotionTimeBindingEvaluation() {}
        var _proto2 = TCStateMotionTimeBindingEvaluation.prototype;
        _proto2.evaluate = function evaluate(context) {
          return context.sourceStateMotionTimeNormalized;
        };
        return TCStateMotionTimeBindingEvaluation;
      }();

      var _dec$1H, _class$1F, _class2$1A, _initializer$1t, _initializer2$1h, _initializer3$$, _initializer4$S, _class3$x;
      var ccclass$r = ccclass$M,
        serializable$8 = serializable$p;
      var BinaryOperator;
      (function (BinaryOperator) {
        BinaryOperator[BinaryOperator["EQUAL_TO"] = 0] = "EQUAL_TO";
        BinaryOperator[BinaryOperator["NOT_EQUAL_TO"] = 1] = "NOT_EQUAL_TO";
        BinaryOperator[BinaryOperator["LESS_THAN"] = 2] = "LESS_THAN";
        BinaryOperator[BinaryOperator["LESS_THAN_OR_EQUAL_TO"] = 3] = "LESS_THAN_OR_EQUAL_TO";
        BinaryOperator[BinaryOperator["GREATER_THAN"] = 4] = "GREATER_THAN";
        BinaryOperator[BinaryOperator["GREATER_THAN_OR_EQUAL_TO"] = 5] = "GREATER_THAN_OR_EQUAL_TO";
      })(BinaryOperator || (BinaryOperator = {}));
      (_dec$1H = ccclass$r(CLASS_NAME_PREFIX_ANIM + "BinaryCondition"), _dec$1H(_class$1F = (_class2$1A = (_class3$x = function () {
        function BinaryCondition() {
          this.operator = _initializer$1t && _initializer$1t();
          this.lhs = _initializer2$1h && _initializer2$1h();
          this.lhsBinding = _initializer3$$ && _initializer3$$();
          this.rhs = _initializer4$S && _initializer4$S();
        }
        var _proto = BinaryCondition.prototype;
        _proto.clone = function clone() {
          var that = new BinaryCondition();
          that.operator = this.operator;
          that.lhs = this.lhs;
          that.lhsBinding = instantiate(this.lhsBinding);
          that.rhs = this.rhs;
          return that;
        };
        _proto[createEval] = function (context) {
          var _this$lhsBinding;
          var lhsBindingEvaluation = (_this$lhsBinding = this.lhsBinding) === null || _this$lhsBinding === void 0 ? void 0 : _this$lhsBinding.bind(context);
          var binaryConditionEval = new BinaryConditionEval(this.operator, this.lhs, this.rhs, lhsBindingEvaluation);
          return binaryConditionEval;
        };
        return BinaryCondition;
      }(), _class3$x.Operator = BinaryOperator, _class3$x), (_initializer$1t = applyDecoratedInitializer(_class2$1A.prototype, "operator", [serializable$8], function () {
        return BinaryOperator.EQUAL_TO;
      }), _initializer2$1h = applyDecoratedInitializer(_class2$1A.prototype, "lhs", [serializable$8], function () {
        return 0.0;
      }), _initializer3$$ = applyDecoratedInitializer(_class2$1A.prototype, "lhsBinding", [serializable$8], function () {
        return new TCVariableBinding();
      }), _initializer4$S = applyDecoratedInitializer(_class2$1A.prototype, "rhs", [serializable$8], function () {
        return 0.0;
      })), _class2$1A)) || _class$1F);
      var BinaryConditionEval = function () {
        function BinaryConditionEval(_operator, lhsValue, rhsValue, _lhsBindingEvaluation) {
          this._operator = _operator;
          this._lhsBindingEvaluation = _lhsBindingEvaluation;
          this._lhsValue = lhsValue;
          this._rhsValue = rhsValue;
        }
        var _proto2 = BinaryConditionEval.prototype;
        _proto2.eval = function _eval(context) {
          var _this$_lhsBindingEval, _this$_lhsBindingEval2;
          var lhsValue = (_this$_lhsBindingEval = (_this$_lhsBindingEval2 = this._lhsBindingEvaluation) === null || _this$_lhsBindingEval2 === void 0 ? void 0 : _this$_lhsBindingEval2.evaluate(context)) !== null && _this$_lhsBindingEval !== void 0 ? _this$_lhsBindingEval : this._lhsValue;
          var rhsValue = this._rhsValue;
          switch (this._operator) {
            default:
            case BinaryOperator.EQUAL_TO:
              return lhsValue === rhsValue;
            case BinaryOperator.NOT_EQUAL_TO:
              return lhsValue !== rhsValue;
            case BinaryOperator.LESS_THAN:
              return lhsValue < rhsValue;
            case BinaryOperator.LESS_THAN_OR_EQUAL_TO:
              return lhsValue <= rhsValue;
            case BinaryOperator.GREATER_THAN:
              return lhsValue > rhsValue;
            case BinaryOperator.GREATER_THAN_OR_EQUAL_TO:
              return lhsValue >= rhsValue;
          }
        };
        return BinaryConditionEval;
      }();

      var _dec$1G, _class$1E, _class2$1z, _initializer$1s;
      var ccclass$q = ccclass$M,
        serializable$7 = serializable$p;
      var TriggerCondition = (_dec$1G = ccclass$q(CLASS_NAME_PREFIX_ANIM + "TriggerCondition"), _dec$1G(_class$1E = (_class2$1z = function () {
        function TriggerCondition() {
          this.trigger = _initializer$1s && _initializer$1s();
        }
        var _proto = TriggerCondition.prototype;
        _proto.clone = function clone() {
          var that = new TriggerCondition();
          that.trigger = this.trigger;
          return that;
        };
        _proto[createEval] = function (context) {
          var evaluation = new TriggerConditionEval(false);
          var triggerInstance = context.getVar(this.trigger);
          if (validateVariableExistence(triggerInstance, this.trigger)) {
            validateVariableTypeTriggerLike(triggerInstance.type, this.trigger);
            evaluation.setTrigger(triggerInstance.bind(evaluation.setTrigger, evaluation));
          }
          return evaluation;
        };
        return TriggerCondition;
      }(), (_initializer$1s = applyDecoratedInitializer(_class2$1z.prototype, "trigger", [serializable$7], function () {
        return '';
      })), _class2$1z)) || _class$1E);
      var TriggerConditionEval = function () {
        function TriggerConditionEval(triggered) {
          this._triggered = false;
          this._triggered = triggered;
        }
        var _proto2 = TriggerConditionEval.prototype;
        _proto2.setTrigger = function setTrigger(trigger) {
          this._triggered = trigger;
        };
        _proto2.eval = function _eval() {
          return this._triggered;
        };
        return TriggerConditionEval;
      }();

      var _dec$1F, _class$1D;
      var StateMachineComponent = (_dec$1F = ccclass$M(CLASS_NAME_PREFIX_ANIM + "StateMachineComponent"), _dec$1F(_class$1D = function () {
        function StateMachineComponent() {}
        var _proto = StateMachineComponent.prototype;
        _proto.onMotionStateEnter = function onMotionStateEnter(controller, motionStateStatus) {};
        _proto.onMotionStateExit = function onMotionStateExit(controller, motionStateStatus) {};
        _proto.onMotionStateUpdate = function onMotionStateUpdate(controller, motionStateStatus) {};
        _proto.onStateMachineEnter = function onStateMachineEnter(controller) {};
        _proto.onStateMachineExit = function onStateMachineExit(controller) {};
        return StateMachineComponent;
      }()) || _class$1D);

      var _dec$1E, _class$1C, _class2$1y, _initializer$1r;
      var MotionSyncInfo = (_dec$1E = ccclass$M(CLASS_NAME_PREFIX_ANIM + "MotionSyncInfo"), _dec$1E(_class$1C = (_class2$1y = function MotionSyncInfo() {
        this.group = _initializer$1r && _initializer$1r();
      }, (_initializer$1r = applyDecoratedInitializer(_class2$1y.prototype, "group", [serializable$p], function () {
        return '';
      })), _class2$1y)) || _class$1C);

      var POSE_GRAPH_NODE_MENU_PREFIX_POSE = "i18n:ENGINE.animation_graph.pose_graph_node_sub_categories.pose_nodes/";

      function makeCreateNodeFactory(create_) {
        return {
          listEntries: function listEntries(context) {
            return [{
              arg: {
                type: 'clip-motion'
              },
              menu: 'i18n:ENGINE.animation_graph.pose_graph_node_sub_menus.play_or_sample_clip_motion'
            }, {
              arg: {
                type: 'animation-blend-1d'
              },
              menu: 'i18n:ENGINE.animation_graph.pose_graph_node_sub_menus.play_or_sample_animation_blend_1d'
            }, {
              arg: {
                type: 'animation-blend-2d'
              },
              menu: 'i18n:ENGINE.animation_graph.pose_graph_node_sub_menus.play_or_sample_animation_blend_2d'
            }];
          },
          create: function create(arg) {
            var motion = null;
            switch (arg.type) {
              case 'clip-motion':
                motion = new ClipMotion();
                break;
              case 'animation-blend-1d':
                motion = new AnimationBlend1D();
                break;
              case 'animation-blend-2d':
                motion = new AnimationBlend2D();
                break;
            }
            return create_(motion);
          }
        };
      }

      var _dec$1D, _dec2$1q, _dec3$16, _dec4$R, _dec5$N, _dec6$y, _class$1B, _class2$1x, _initializer$1q, _initializer2$1g, _descriptor, _descriptor2;
      var ZERO_DURATION_THRESHOLD = 1e-5;
      var PoseNodePlayMotion = (_dec$1D = ccclass$M(CLASS_NAME_PREFIX_ANIM + "PoseNodePlayMotion"), _dec2$1q = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE), _dec3$16 = poseGraphCreateNodeFactory(makeCreateNodeFactory(function (motion) {
        var node = new PoseNodePlayMotion();
        node.motion = motion;
        return node;
      })), _dec4$R = poseGraphNodeAppearance({
        themeColor: '#227F9B'
      }), _dec5$N = input({
        type: PoseGraphType.FLOAT
      }), _dec6$y = input({
        type: PoseGraphType.FLOAT
      }), _dec$1D(_class$1B = _dec2$1q(_class$1B = _dec3$16(_class$1B = _dec4$R(_class$1B = (_class2$1x = function (_PoseNode) {
        _inheritsLoose(PoseNodePlayMotion, _PoseNode);
        function PoseNodePlayMotion() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNode.call.apply(_PoseNode, [this].concat(args)) || this;
          _this.motion = _initializer$1q && _initializer$1q();
          _this.syncInfo = _initializer2$1g && _initializer2$1g();
          _initializerDefineProperty(_this, "startTime", _descriptor, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "speedMultiplier", _descriptor2, _assertThisInitialized(_this));
          _this._workspace = null;
          _this._runtimeSyncRecord = undefined;
          return _this;
        }
        var _proto = PoseNodePlayMotion.prototype;
        _proto.bind = function bind(context) {
          var motion = this.motion;
          if (!motion) {
            return;
          }
          var motionEval = motion[createEval](context, false);
          if (!motionEval) {
            return;
          }
          this._workspace = new Workspace(motionEval, motionEval.createPort());
          if (this.syncInfo.group) {
            this._runtimeSyncRecord = context.motionSyncManager.register(this.syncInfo);
          }
        };
        _proto.settle = function settle(context) {};
        _proto.reenter = function reenter() {
          if (this._workspace) {
            var runtimeSyncRecord = this._runtimeSyncRecord,
              duration = this._workspace.motionEval.duration;
            this._forceEvaluateEvaluation();
            var startTimeNormalized = duration < ZERO_DURATION_THRESHOLD ? 0.0 : clamp01(this.startTime / duration);
            if (runtimeSyncRecord) {
              runtimeSyncRecord.notifyRenter(startTimeNormalized);
            } else {
              this._workspace.normalizedTime = startTimeNormalized;
            }
            this._workspace.lastIndicativeWeight = 0.0;
          }
        };
        _proto.doUpdate = function doUpdate(context) {
          if (this._workspace) {
            var deltaTime = context.deltaTime;
            var runtimeSyncRecord = this._runtimeSyncRecord;
            var duration = this._workspace.motionEval.duration;
            var normalizedDeltaTime = 0.0;
            if (duration > ZERO_DURATION_THRESHOLD) {
              normalizedDeltaTime = deltaTime * this.speedMultiplier / duration;
            }
            if (runtimeSyncRecord) {
              runtimeSyncRecord.notifyUpdate(normalizedDeltaTime, context.indicativeWeight);
            } else {
              this._workspace.normalizedTime += normalizedDeltaTime;
            }
            this._workspace.lastIndicativeWeight = context.indicativeWeight;
          }
        };
        _proto.doEvaluate = function doEvaluate(context) {
          if (!this._workspace) {
            return context.pushDefaultedPose();
          } else {
            var normalizedTime = this._runtimeSyncRecord ? this._runtimeSyncRecord.getSyncedEnterTime() : this._workspace.normalizedTime;
            return this._workspace.motionEvalPort.evaluate(normalizedTime, context);
          }
        };
        _createClass(PoseNodePlayMotion, [{
          key: "lastIndicativeWeight",
          get: function get() {
            var _this$_workspace$last, _this$_workspace;
            return (_this$_workspace$last = (_this$_workspace = this._workspace) === null || _this$_workspace === void 0 ? void 0 : _this$_workspace.lastIndicativeWeight) !== null && _this$_workspace$last !== void 0 ? _this$_workspace$last : 0.0;
          }
        }, {
          key: "elapsedMotionTime",
          get: function get() {
            var _this$_workspace$norm, _this$_workspace2;
            return (_this$_workspace$norm = (_this$_workspace2 = this._workspace) === null || _this$_workspace2 === void 0 ? void 0 : _this$_workspace2.normalizedTime) !== null && _this$_workspace$norm !== void 0 ? _this$_workspace$norm : 0.0;
          }
        }]);
        return PoseNodePlayMotion;
      }(PoseNode), (_initializer$1q = applyDecoratedInitializer(_class2$1x.prototype, "motion", [serializable$p], function () {
        return new ClipMotion();
      }), _initializer2$1g = applyDecoratedInitializer(_class2$1x.prototype, "syncInfo", [serializable$p], function () {
        return new MotionSyncInfo();
      }), _descriptor = _applyDecoratedDescriptor(_class2$1x.prototype, "startTime", [serializable$p, _dec5$N], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.0;
        }
      }), _descriptor2 = _applyDecoratedDescriptor(_class2$1x.prototype, "speedMultiplier", [serializable$p, _dec6$y], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1.0;
        }
      })), _class2$1x)) || _class$1B) || _class$1B) || _class$1B) || _class$1B);
      var Workspace = function Workspace(motionEval, motionEvalPort) {
        this.normalizedTime = 0.0;
        this.lastIndicativeWeight = 0.0;
        this.motionEval = motionEval;
        this.motionEvalPort = motionEvalPort;
      };

      function isEvaluatableNode(node) {
        return node instanceof PoseNode || node instanceof PureValueNode;
      }
      var InstantiatedPoseGraph = function () {
        function InstantiatedPoseGraph(_rootPoseNode, _countingPlayMotionNodes) {
          this._rootPoseNode = _rootPoseNode;
          this._countingPlayMotionNodes = _countingPlayMotionNodes;
        }
        var _proto = InstantiatedPoseGraph.prototype;
        _proto.bind = function bind(context) {
          var _this$_rootPoseNode;
          (_this$_rootPoseNode = this._rootPoseNode) === null || _this$_rootPoseNode === void 0 ? void 0 : _this$_rootPoseNode.bind(context);
        };
        _proto.settle = function settle(context) {
          var _this$_rootPoseNode2;
          (_this$_rootPoseNode2 = this._rootPoseNode) === null || _this$_rootPoseNode2 === void 0 ? void 0 : _this$_rootPoseNode2.settle(context);
        };
        _proto.reenter = function reenter() {
          var _this$_rootPoseNode3;
          (_this$_rootPoseNode3 = this._rootPoseNode) === null || _this$_rootPoseNode3 === void 0 ? void 0 : _this$_rootPoseNode3.reenter();
        };
        _proto.update = function update(context) {
          var _this$_rootPoseNode4;
          (_this$_rootPoseNode4 = this._rootPoseNode) === null || _this$_rootPoseNode4 === void 0 ? void 0 : _this$_rootPoseNode4.update(context);
        };
        _proto.evaluate = function evaluate(context) {
          var _this$_rootPoseNode$e, _this$_rootPoseNode5;
          return (_this$_rootPoseNode$e = (_this$_rootPoseNode5 = this._rootPoseNode) === null || _this$_rootPoseNode5 === void 0 ? void 0 : _this$_rootPoseNode5.evaluate(context, PoseTransformSpaceRequirement.LOCAL)) !== null && _this$_rootPoseNode$e !== void 0 ? _this$_rootPoseNode$e : null;
        };
        _proto.countMotionTime = function countMotionTime() {
          var playMotionNodes = this._countingPlayMotionNodes;
          if (!playMotionNodes) {
            {
              assertIsTrue(false, "Should not call countMotionTime() on this pose graph " + "since \"mayCountMotionTime\" was not passed to instantiatePoseGraph()");
            }
            return 0.0;
          }
          var maxWeightedTime = 0.0;
          var maxWeight = Number.NEGATIVE_INFINITY;
          for (var iPlayMotionNode = 0; iPlayMotionNode < playMotionNodes.length; ++iPlayMotionNode) {
            var _playMotionNodes$iPla = playMotionNodes[iPlayMotionNode],
              elapsedMotionTime = _playMotionNodes$iPla.elapsedMotionTime,
              lastIndicativeWeight = _playMotionNodes$iPla.lastIndicativeWeight;
            if (lastIndicativeWeight > maxWeight) {
              maxWeight = lastIndicativeWeight;
              maxWeightedTime = elapsedMotionTime;
            }
          }
          return maxWeightedTime;
        };
        return InstantiatedPoseGraph;
      }();
      function instantiatePoseGraph(graph, linkContext, mayCountMotionTime) {
        if (mayCountMotionTime === void 0) {
          mayCountMotionTime = false;
        }
        var outputNode = graph.outputNode;
        var outputNodeShell = graph.getShell(outputNode);
        assertIsTrue(outputNodeShell);
        var bindings = outputNodeShell.getBindings();
        assertIsTrue(bindings.length < 2);
        if (bindings.length === 0) {
          return new InstantiatedPoseGraph(undefined, mayCountMotionTime ? [] : undefined);
        }
        var binding = bindings[0];
        assertIsTrue(binding.outputIndex === 0);
        assertIsTrue(binding.producer instanceof PoseNode);
        var instantiationMap = new Map();
        var mainRecord = instantiateNode(graph, binding.producer, instantiationMap, linkContext);
        assertIsTrue(mainRecord instanceof PoseNode);
        return new InstantiatedPoseGraph(mainRecord, mayCountMotionTime ? Array.from(instantiationMap.values()).filter(function (node) {
          return node instanceof PoseNodePlayMotion;
        }) : undefined);
      }
      function instantiateNode(graph, node, instantiationMap, linkContext) {
        var shell = graph.getShell(node);
        assertIsTrue(shell, "Want to instantiate an unbound graph?");
        var existing = instantiationMap.get(node);
        if (existing) {
          return existing;
        }
        var instantiated = instantiate(node);
        if ('__callOnAfterDeserializeRecursive' in instantiated) {
          instantiated.__callOnAfterDeserializeRecursive();
        }
        if (instantiated instanceof PureValueNode) {
          instantiated.link(linkContext);
        }
        var consumerNode = instantiated;
        var runtimePVNodePropertyBindings = [];
        for (var _iterator = _createForOfIteratorHelperLoose(shell.getBindings()), _step; !(_step = _iterator()).done;) {
          var _step$value = _step.value,
            producerNode = _step$value.producer,
            producerOutputIndex = _step$value.outputIndex,
            consumerInputPath = _step$value.inputPath;
          if (!isEvaluatableNode(producerNode)) {
            warn("There's a input bound to a node with unrecognized type.");
            continue;
          }
          var producer = instantiateNode(graph, producerNode, instantiationMap, linkContext);
          if (producer instanceof PoseNode) {
            assertIsTrue(consumerNode instanceof PoseNode);
            linkPoseNode(consumerNode, consumerInputPath, producer, producerOutputIndex);
          } else {
            var runtimePVNodePropertyBinding = linkPVNode(consumerNode, consumerInputPath, producer, producerOutputIndex);
            if (runtimePVNodePropertyBinding) {
              runtimePVNodePropertyBindings.push(runtimePVNodePropertyBinding);
            }
          }
        }
        var dependencyEvaluation = new DependencyEvaluation(runtimePVNodePropertyBindings);
        var evaluation;
        if (consumerNode instanceof PoseNode) {
          consumerNode._setDependencyEvaluation(dependencyEvaluation);
          evaluation = consumerNode;
        } else {
          var pureValueNodeEvaluation = new RuntimePVNodeEvaluation(consumerNode, dependencyEvaluation);
          evaluation = pureValueNodeEvaluation;
        }
        instantiationMap.set(node, evaluation);
        return evaluation;
      }
      var DependencyEvaluation = function () {
        function DependencyEvaluation(bindingEvaluations) {
          this._bindingEvaluations = void 0;
          this._bindingEvaluations = bindingEvaluations;
        }
        var _proto2 = DependencyEvaluation.prototype;
        _proto2.evaluate = function evaluate() {
          var bindingEvaluations = this._bindingEvaluations;
          for (var _iterator2 = _createForOfIteratorHelperLoose(bindingEvaluations), _step2; !(_step2 = _iterator2()).done;) {
            var binding = _step2.value;
            binding.evaluate();
          }
        };
        return DependencyEvaluation;
      }();
      var RuntimePVNodeEvaluation = function () {
        function RuntimePVNodeEvaluation(_node, _dependency) {
          this._outputs = void 0;
          this._node = _node;
          this._dependency = _dependency;
          this._outputs = new Array(_node.outputCount);
        }
        var _proto3 = RuntimePVNodeEvaluation.prototype;
        _proto3.getDefaultOutput = function getDefaultOutput() {
          return this.getOutput(0);
        };
        _proto3.getOutput = function getOutput(outputIndex) {
          return this._outputs[outputIndex];
        };
        _proto3.evaluate = function evaluate() {
          var node = this._node,
            dependency = this._dependency;
          dependency.evaluate();
          node.selfEvaluate(this._outputs);
        };
        _createClass(RuntimePVNodeEvaluation, [{
          key: "node",
          get: function get() {
            return this._node;
          }
        }, {
          key: "outputCount",
          get: function get() {
            return this._outputs.length;
          }
        }]);
        return RuntimePVNodeEvaluation;
      }();
      function linkPoseNode(consumerNode, consumerInputPath, producerNode, producerOutputIndex) {
        var consumerPropertyKey = consumerInputPath[0],
          _consumerInputPath$ = consumerInputPath[1],
          consumerElementIndex = _consumerInputPath$ === void 0 ? -1 : _consumerInputPath$;
        if (!(consumerPropertyKey in consumerNode)) {
          warn("Invalid binding: consumer node has no property " + consumerPropertyKey);
          return;
        }
        if (producerOutputIndex !== 0) {
          warn("Node " + producerNode.toString() + " does not have specified output " + producerOutputIndex + ".");
          return;
        }
        var consumerProperty = consumerNode[consumerPropertyKey];
        if (consumerElementIndex < 0) {
          if (consumerProperty !== null) {
            warn("Invalid binding: consumer node's input " + consumerPropertyKey + " should be leaved as evaluation before evaluation.");
            return;
          }
          consumerNode[consumerPropertyKey] = producerNode;
          return;
        }
        if (!Array.isArray(consumerProperty)) {
          warn("Invalid binding: consumer node's input " + consumerPropertyKey + " should be an array.");
          return;
        }
        if (consumerElementIndex >= consumerProperty.length) {
          warn("Invalid binding: consumer node's input " + consumerPropertyKey + " " + ("have length " + consumerProperty.length + " but the binding specified " + consumerElementIndex));
          return;
        }
        if (consumerProperty[consumerElementIndex] !== null) {
          warn("Invalid binding: consumer node's input " + consumerPropertyKey + "[" + consumerElementIndex + "] should be leaved as null before evaluation");
          return;
        }
        consumerProperty[consumerElementIndex] = producerNode;
      }
      var RuntimePVNodePlainPropertyBinding = function () {
        function RuntimePVNodePlainPropertyBinding(_consumerNode, _consumerPropertyKey, _producerRecord, _producerOutputIndex) {
          this._consumerNode = _consumerNode;
          this._consumerPropertyKey = _consumerPropertyKey;
          this._producerRecord = _producerRecord;
          this._producerOutputIndex = _producerOutputIndex;
        }
        var _proto4 = RuntimePVNodePlainPropertyBinding.prototype;
        _proto4.evaluate = function evaluate() {
          this._producerRecord.evaluate();
          this._consumerNode[this._consumerPropertyKey] = this._producerRecord.getOutput(this._producerOutputIndex);
        };
        return RuntimePVNodePlainPropertyBinding;
      }();
      var RuntimePVNodeArrayElementPropertyBinding = function () {
        function RuntimePVNodeArrayElementPropertyBinding(_consumerNode, _consumerPropertyKey, _consumerElementIndex, _producerRecord, _producerOutputIndex) {
          this._consumerNode = _consumerNode;
          this._consumerPropertyKey = _consumerPropertyKey;
          this._consumerElementIndex = _consumerElementIndex;
          this._producerRecord = _producerRecord;
          this._producerOutputIndex = _producerOutputIndex;
        }
        var _proto5 = RuntimePVNodeArrayElementPropertyBinding.prototype;
        _proto5.evaluate = function evaluate() {
          this._producerRecord.evaluate();
          this._consumerNode[this._consumerPropertyKey][this._consumerElementIndex] = this._producerRecord.getOutput(this._producerOutputIndex);
        };
        return RuntimePVNodeArrayElementPropertyBinding;
      }();
      function linkPVNode(consumerNode, consumerInputPath, producerRecord, producerOutputIndex) {
        var consumerPropertyKey = consumerInputPath[0],
          _consumerInputPath$2 = consumerInputPath[1],
          consumerElementIndex = _consumerInputPath$2 === void 0 ? -1 : _consumerInputPath$2;
        if (!(consumerPropertyKey in consumerNode)) {
          warn("Invalid binding: consumer node has no property " + consumerPropertyKey);
          return undefined;
        }
        var consumerProperty = consumerNode[consumerPropertyKey];
        if (consumerElementIndex < 0) {
          return new RuntimePVNodePlainPropertyBinding(consumerNode, consumerPropertyKey, producerRecord, producerOutputIndex);
        }
        if (!Array.isArray(consumerProperty)) {
          warn("Invalid binding: consumer node's input " + consumerPropertyKey + " should be an array.");
          return undefined;
        }
        if (consumerElementIndex >= consumerProperty.length) {
          warn("Invalid binding: consumer node's input " + consumerPropertyKey + " " + ("have length " + consumerProperty.length + " but the binding specified " + consumerElementIndex));
          return undefined;
        }
        return new RuntimePVNodeArrayElementPropertyBinding(consumerNode, consumerPropertyKey, consumerElementIndex, producerRecord, producerOutputIndex);
      }

      var _emptyClipStatusesIte;
      var MAX_TRANSITIONS_PER_FRAME = 16;
      var TopLevelStateMachineEvaluation = function () {
        function TopLevelStateMachineEvaluation(stateMachine, name, context) {
          this.passthroughWeight = 1.0;
          this._motionStates = [];
          this._proceduralPoseStates = [];
          this._topLevelEntry = void 0;
          this._topLevelExit = void 0;
          this._currentNode = void 0;
          this._pendingTransitionPath = [];
          this._activatedTransitions = [];
          this._activatedTransitionPool = ActivatedTransition.createPool(4);
          this._updateContextGenerator = new AnimationGraphUpdateContextGenerator();
          this._conditionEvaluationContext = new ConditionEvaluationContextImpl();
          this._additive = false;
          this._additive = context.additive;
          this.name = name;
          this._controller = context.controller;
          var _this$_addStateMachin = this._addStateMachine(stateMachine, null, context, name),
            entry = _this$_addStateMachin.entry,
            exit = _this$_addStateMachin.exit;
          this._topLevelEntry = entry;
          this._topLevelExit = exit;
          this._currentNode = entry;
          entry.increaseActiveReference();
          this._resetTrigger = context.triggerResetter;
        }
        var _proto = TopLevelStateMachineEvaluation.prototype;
        _proto.settle = function settle(context) {
          var proceduralPoseStates = this._proceduralPoseStates;
          var nProceduralPoseStates = proceduralPoseStates.length;
          for (var iState = 0; iState < nProceduralPoseStates; ++iState) {
            var state = proceduralPoseStates[iState];
            state.settle(context);
          }
        };
        _proto.reenter = function reenter() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._activatedTransitions), _step; !(_step = _iterator()).done;) {
            var transition = _step.value;
            transition.destination.decreaseActiveReference();
            this._activatedTransitionPool.free(transition);
          }
          this._activatedTransitions.length = 0;
          this._topLevelEntry.increaseActiveReference();
          this._currentNode.decreaseActiveReference();
          this._currentNode = this._topLevelEntry;
        };
        _proto.update = function update(context) {
          assertIsTrue(!this.exited);
          this._loopMatchTransitions();
          this._resetStateTickFlagsAndWeights();
          this._updateActivatedTransitions(context.deltaTime);
          this._commitStateUpdates(context);
        };
        _proto.evaluate = function evaluate(context) {
          var sampled = this._sample(context);
          if (sampled) {
            return sampled;
          }
          return this._pushNullishPose(context);
        };
        _proto.getCurrentStateStatus = function getCurrentStateStatus() {
          var currentNode = this._currentNode;
          if (currentNode.kind === NodeKind.animation) {
            return currentNode.getStatus();
          } else if (currentNode.kind === NodeKind.procedural) {
            return currentNode.getStatus();
          } else {
            return null;
          }
        };
        _proto.getCurrentClipStatuses = function getCurrentClipStatuses() {
          var currentNode = this._currentNode;
          if (currentNode.kind === NodeKind.animation) {
            return currentNode.getClipStatuses(currentNode.absoluteWeight);
          } else {
            return emptyClipStatusesIterable;
          }
        };
        _proto.getCurrentTransition = function getCurrentTransition(transitionStatus) {
          var activatedTransitions = this._activatedTransitions;
          if (activatedTransitions.length === 0) {
            return false;
          }
          var lastActivatedTransition = activatedTransitions[activatedTransitions.length - 1];
          var baseDurationState = activatedTransitions.length === 1 ? this._currentNode : activatedTransitions[activatedTransitions.length - 2].destination;
          var absoluteDuration = lastActivatedTransition.getAbsoluteDuration(baseDurationState);
          transitionStatus.duration = absoluteDuration;
          transitionStatus.time = lastActivatedTransition.normalizedElapsedTime * absoluteDuration;
          return true;
        };
        _proto.getNextStateStatus = function getNextStateStatus() {
          var activatedTransitions = this._activatedTransitions;
          if (activatedTransitions.length === 0) {
            return null;
          }
          var lastState = activatedTransitions[activatedTransitions.length - 1].destination;
          switch (lastState.kind) {
            default:
              break;
            case NodeKind.procedural:
              return lastState.getStatus();
            case NodeKind.animation:
              return lastState.getStatus();
          }
          return null;
        };
        _proto.getNextClipStatuses = function getNextClipStatuses() {
          var _lastState$getClipSta;
          var activatedTransitions = this._activatedTransitions;
          if (activatedTransitions.length === 0) {
            return emptyClipStatusesIterable;
          }
          var lastActivatedTransition = activatedTransitions[activatedTransitions.length - 1];
          var lastState = lastActivatedTransition.destination;
          switch (lastState.kind) {
            default:
              return emptyClipStatusesIterable;
            case NodeKind.animation:
              return (_lastState$getClipSta = lastState.getClipStatuses(lastActivatedTransition.destination.absoluteWeight)) !== null && _lastState$getClipSta !== void 0 ? _lastState$getClipSta : emptyClipStatusesIterable;
          }
        };
        _proto.overrideClips = function overrideClips(context) {
          var motionStates = this._motionStates;
          var nMotionStates = motionStates.length;
          for (var iMotionState = 0; iMotionState < nMotionStates; ++iMotionState) {
            var node = motionStates[iMotionState];
            node.overrideClips(context);
          }
        };
        _proto._addStateMachine = function _addStateMachine(graph, parentStateMachineInfo, context, __DEBUG_ID__) {
          var _this = this;
          var nodes = Array.from(graph.states());
          var entryEval;
          var anyNode;
          var exitEval;
          var nodeEvaluations = nodes.map(function (node) {
            if (node instanceof MotionState) {
              var motionStateEval = new VMSMEval(node, context);
              _this._motionStates.push(motionStateEval);
              return motionStateEval;
            } else if (node === graph.entryState) {
              return entryEval = new SpecialStateEval(node, NodeKind.entry, node.name);
            } else if (node === graph.exitState) {
              return exitEval = new SpecialStateEval(node, NodeKind.exit, node.name);
            } else if (node === graph.anyState) {
              return anyNode = new SpecialStateEval(node, NodeKind.any, node.name);
            } else if (node instanceof EmptyState) {
              return new EmptyStateEval(node);
            } else if (node instanceof ProceduralPoseState_) {
              var stateEval = new ProceduralPoseStateEval(node, context);
              _this._proceduralPoseStates.push(stateEval);
              return stateEval;
            } else {
              assertIsTrue(node instanceof SubStateMachine);
              return null;
            }
          });
          assertIsNonNullable(entryEval, 'Entry node is missing');
          assertIsNonNullable(exitEval, 'Exit node is missing');
          assertIsNonNullable(anyNode, 'Any node is missing');
          var stateMachineInfo = {
            components: null,
            parent: parentStateMachineInfo,
            entry: entryEval,
            exit: exitEval,
            any: anyNode
          };
          for (var iNode = 0; iNode < nodes.length; ++iNode) {
            var nodeEval = nodeEvaluations[iNode];
            if (nodeEval) {
              nodeEval.stateMachine = stateMachineInfo;
            }
          }
          var subStateMachineInfos = nodes.map(function (node) {
            if (node instanceof SubStateMachine) {
              var subStateMachineInfo = _this._addStateMachine(node.stateMachine, stateMachineInfo, context, __DEBUG_ID__ + "/" + node.name);
              subStateMachineInfo.components = new InstantiatedComponents(node);
              return subStateMachineInfo;
            } else {
              return null;
            }
          });
          {
            for (var _iterator2 = _createForOfIteratorHelperLoose(nodeEvaluations), _step2; !(_step2 = _iterator2()).done;) {
              var _nodeEval = _step2.value;
              if (_nodeEval) {
                _nodeEval.setPrefix_debug(__DEBUG_ID__ + "/");
              }
            }
          }
          for (var _iNode = 0; _iNode < nodes.length; ++_iNode) {
            var node = nodes[_iNode];
            var outgoingTemplates = graph.getOutgoings(node);
            var fromNode = void 0;
            if (node instanceof SubStateMachine) {
              var subStateMachineInfo = subStateMachineInfos[_iNode];
              assertIsNonNullable(subStateMachineInfo);
              fromNode = subStateMachineInfo.exit;
            } else {
              var _nodeEval2 = nodeEvaluations[_iNode];
              assertIsNonNullable(_nodeEval2);
              fromNode = _nodeEval2;
            }
            var _loop = function _loop() {
              var outgoing = _step3.value;
              var outgoingNode = outgoing.to;
              var iOutgoingNode = nodes.findIndex(function (nodeTemplate) {
                return nodeTemplate === outgoing.to;
              });
              if (iOutgoingNode < 0) {
                assertIsTrue(false, 'Bad animation data');
              }
              var toNode;
              if (outgoingNode instanceof SubStateMachine) {
                var _subStateMachineInfo = subStateMachineInfos[iOutgoingNode];
                assertIsNonNullable(_subStateMachineInfo);
                toNode = _subStateMachineInfo.entry;
              } else {
                var _nodeEval3 = nodeEvaluations[iOutgoingNode];
                assertIsNonNullable(_nodeEval3);
                if (_nodeEval3 instanceof VMSMEval) {
                  toNode = _nodeEval3.entry;
                } else {
                  toNode = _nodeEval3;
                }
              }
              var conditions = outgoing.conditions.map(function (condition) {
                return condition[createEval](context);
              });
              var transitionEval = {
                conditions: conditions,
                to: toNode,
                triggers: undefined,
                duration: 0.0,
                normalizedDuration: false,
                destinationStart: 0.0,
                relativeDestinationStart: false,
                exitCondition: 0.0,
                exitConditionEnabled: false,
                activated: false,
                startEventBinding: undefined,
                endEventBinding: undefined
              };
              if (isAnimationTransition(outgoing) || outgoing instanceof EmptyStateTransition || outgoing instanceof ProceduralPoseTransition_) {
                transitionEval.duration = outgoing.duration;
                transitionEval.destinationStart = outgoing.destinationStart;
                transitionEval.relativeDestinationStart = outgoing.relativeDestinationStart;
                if (outgoing.startEventBinding.isBound) {
                  transitionEval.startEventBinding = outgoing.startEventBinding;
                }
                if (outgoing.endEventBinding.isBound) {
                  transitionEval.endEventBinding = outgoing.endEventBinding;
                }
                if (isAnimationTransition(outgoing)) {
                  transitionEval.normalizedDuration = outgoing.relativeDuration;
                  transitionEval.exitConditionEnabled = outgoing.exitConditionEnabled;
                  transitionEval.exitCondition = outgoing.exitCondition;
                }
              }
              transitionEval.conditions.forEach(function (conditionEval, iCondition) {
                var condition = outgoing.conditions[iCondition];
                if (condition instanceof TriggerCondition && condition.trigger) {
                  var _transitionEval$trigg;
                  ((_transitionEval$trigg = transitionEval.triggers) !== null && _transitionEval$trigg !== void 0 ? _transitionEval$trigg : transitionEval.triggers = []).push(condition.trigger);
                }
              });
              fromNode.addTransition(transitionEval);
            };
            for (var _iterator3 = _createForOfIteratorHelperLoose(outgoingTemplates), _step3; !(_step3 = _iterator3()).done;) {
              _loop();
            }
          }
          return stateMachineInfo;
        };
        _proto._loopMatchTransitions = function _loopMatchTransitions() {
          var pendingTransitionPath = this._pendingTransitionPath,
            activatedTransitions = this._activatedTransitions;
          assertIsTrue(pendingTransitionPath.length === 0);
          var matchingSource = activatedTransitions.length === 0 ? this._currentNode : activatedTransitions[activatedTransitions.length - 1].destination;
          for (var iterations = 0;; ++iterations) {
            if (iterations >= MAX_TRANSITIONS_PER_FRAME) {
              var prettyPath = '';
              {
                var lastDestination = activatedTransitions[activatedTransitions.length - 1].destination;
                var loopFormPosition = -1;
                for (var i = activatedTransitions.length - 2; i >= 0; --i) {
                  if (activatedTransitions[i].destination === lastDestination) {
                    loopFormPosition = i;
                    break;
                  }
                }
                prettyPath = this._currentNode.name + " --> ... --> ";
                var pathToPrint = loopFormPosition < 0 ? activatedTransitions.slice(-MAX_TRANSITIONS_PER_FRAME) : activatedTransitions.slice(loopFormPosition);
                prettyPath += "" + pathToPrint.map(function (t) {
                  return t.destination.name;
                }).join(' --> ');
              }
              warnID(14000, MAX_TRANSITIONS_PER_FRAME, prettyPath);
              break;
            }
            var transition = this._matchNextTransition(matchingSource);
            if (!transition) {
              break;
            }
            var destinationState = transition.to;
            var currentMatchingSource = matchingSource;
            matchingSource = destinationState;
            if (!isRealState(destinationState)) {
              pendingTransitionPath.push(transition);
              continue;
            }
            if (destinationState === currentMatchingSource) {
              break;
            }
            this._activateTransition(pendingTransitionPath, transition);
            pendingTransitionPath.length = 0;
          }
          pendingTransitionPath.length = 0;
        };
        _proto._resetStateTickFlagsAndWeights = function _resetStateTickFlagsAndWeights() {
          var currentNode = this._currentNode,
            activatedTransitions = this._activatedTransitions;
          currentNode.resetTickFlagsAndWeight();
          for (var iTransition = 0; iTransition < activatedTransitions.length; ++iTransition) {
            var destination = activatedTransitions[iTransition].destination;
            destination.resetTickFlagsAndWeight();
          }
        };
        _proto._commitStateUpdates = function _commitStateUpdates(parentContext) {
          var currentNode = this._currentNode,
            activatedTransitions = this._activatedTransitions;
            this._updateContextGenerator;
          this._commitStateUpdate(currentNode, parentContext);
          for (var iTransition = 0; iTransition < activatedTransitions.length; ++iTransition) {
            var transition = activatedTransitions[iTransition];
            var destination = transition.destination;
            this._commitStateUpdate(destination, parentContext);
          }
        };
        _proto._commitStateUpdate = function _commitStateUpdate(state, parentContext) {
          var updateContextGenerator = this._updateContextGenerator;
          if (state.testTickFlag(StateTickFlag.UPDATED)) {
            return;
          }
          state.setTickFlag(StateTickFlag.UPDATED);
          if (state.kind === NodeKind.animation) {
            state.update(parentContext.deltaTime, this._controller);
          } else if (state.kind === NodeKind.procedural) {
            var updateContext = updateContextGenerator.generate(parentContext.deltaTime, parentContext.indicativeWeight * state.absoluteWeight);
            state.update(updateContext);
          }
        };
        _proto._sample = function _sample(context) {
          var currentNode = this._currentNode,
            activatedTransitions = this._activatedTransitions;
          var passthroughWeight = 1.0;
          var finalPose = null;
          var sumActualBlendedWeight = 0.0;
          if (currentNode.kind === NodeKind.animation) {
            var _currentNode$evaluate;
            finalPose = (_currentNode$evaluate = currentNode.evaluate(context)) !== null && _currentNode$evaluate !== void 0 ? _currentNode$evaluate : this._pushNullishPose(context);
          } else if (currentNode.kind === NodeKind.procedural) {
            var _currentNode$evaluate2;
            finalPose = (_currentNode$evaluate2 = currentNode.evaluate(context)) !== null && _currentNode$evaluate2 !== void 0 ? _currentNode$evaluate2 : this._pushNullishPose(context);
          } else {
            passthroughWeight -= currentNode.absoluteWeight;
            finalPose = null;
          }
          if (finalPose) {
            sumActualBlendedWeight = currentNode.absoluteWeight;
          }
          currentNode.setTickFlag(StateTickFlag.EVALUATED);
          for (var iTransition = 0; iTransition < activatedTransitions.length; ++iTransition) {
            var transition = activatedTransitions[iTransition];
            var destination = transition.destination;
            if (destination.testTickFlag(StateTickFlag.EVALUATED)) {
              continue;
            }
            destination.setTickFlag(StateTickFlag.EVALUATED);
            var destAbsoluteWeight = destination.absoluteWeight;
            var destPose = void 0;
            if (destination.kind === NodeKind.empty) {
              passthroughWeight -= destAbsoluteWeight;
              destPose = null;
            } else {
              var _destination$evaluate;
              destPose = (_destination$evaluate = destination.evaluate(context)) !== null && _destination$evaluate !== void 0 ? _destination$evaluate : this._pushNullishPose(context);
            }
            if (!destPose) {
              continue;
            }
            if (!finalPose) {
              finalPose = destPose;
            } else {
              sumActualBlendedWeight += destAbsoluteWeight;
              if (sumActualBlendedWeight) {
                var t = destAbsoluteWeight / sumActualBlendedWeight;
                blendPoseInto(finalPose, destPose, t);
                context.popPose();
              } else {
                finalPose = destPose;
              }
            }
          }
          this.passthroughWeight = passthroughWeight;
          return finalPose;
        };
        _proto._pushNullishPose = function _pushNullishPose(context) {
          return this._additive ? context.pushZeroDeltaPose() : context.pushDefaultedPose();
        };
        _proto._matchNextTransition = function _matchNextTransition(sourceState) {
          var transition = this._matchTransition(sourceState, sourceState);
          if (transition) {
            return transition;
          }
          if (sourceState.kind === NodeKind.animation || sourceState.kind === NodeKind.procedural) {
            var _transition = this._matchAnyScoped(sourceState);
            if (_transition) {
              return _transition;
            }
          }
          return null;
        };
        _proto._matchAnyScoped = function _matchAnyScoped(realNode) {
          for (var ancestor = realNode.stateMachine; ancestor !== null; ancestor = ancestor.parent) {
            var transition = this._matchTransition(ancestor.any, realNode);
            if (transition) {
              return transition;
            }
          }
          return null;
        };
        _proto._matchTransition = function _matchTransition(node, realNode) {
          assertIsTrue(node === realNode || node.kind === NodeKind.any);
          var conditionEvaluationContext = this._conditionEvaluationContext;
          conditionEvaluationContext.set(realNode);
          var outgoingTransitions = node.outgoingTransitions;
          var nTransitions = outgoingTransitions.length;
          for (var iTransition = 0; iTransition < nTransitions; ++iTransition) {
            var transition = outgoingTransitions[iTransition];
            if (transition.activated) {
              continue;
            }
            var conditions = transition.conditions;
            var nConditions = conditions.length;
            if (nConditions === 0) {
              if (node.kind === NodeKind.entry || node.kind === NodeKind.exit) {
                {
                  conditionEvaluationContext.unset();
                }
                return transition;
              }
              if (!transition.exitConditionEnabled) {
                continue;
              }
            }
            if (realNode.kind === NodeKind.animation && transition.exitConditionEnabled) {
              var exitTime = realNode.duration * transition.exitCondition;
              var currentStateTime = realNode.time;
              if (currentStateTime < exitTime) {
                break;
              }
            }
            var satisfied = true;
            for (var iCondition = 0; iCondition < nConditions; ++iCondition) {
              var condition = conditions[iCondition];
              if (!condition.eval(this._conditionEvaluationContext)) {
                satisfied = false;
                break;
              }
            }
            if (!satisfied) {
              continue;
            }
            {
              conditionEvaluationContext.unset();
            }
            return transition;
          }
          {
            conditionEvaluationContext.unset();
          }
          return null;
        };
        _proto._activateTransition = function _activateTransition(prefix, lastTransition) {
          var destinationState = lastTransition.to;
          assertIsTrue(isRealState(destinationState));
          var activatedTransition = this._activatedTransitionPool.alloc();
          activatedTransition.reset(prefix, lastTransition);
          this._activatedTransitions.push(activatedTransition);
          var nTransitions = activatedTransition.path.length;
          for (var iTransition = 0; iTransition < nTransitions; ++iTransition) {
            var transition = activatedTransition.path[iTransition];
            this._resetTriggersOnTransition(transition);
          }
          for (var iDetailedTransition = 0; iDetailedTransition < activatedTransition.path.length; ++iDetailedTransition) {
            var detailedTransition = activatedTransition.path[iDetailedTransition];
            this._callEnterMethods(detailedTransition.to);
          }
          assertIsTrue(this._activatedTransitions.length > 0);
          var previousState = this._activatedTransitions.length === 1 ? this._currentNode : this._activatedTransitions[this._activatedTransitions.length - 2].destination;
          if (previousState instanceof EventifiedStateEval) {
            if (previousState.transitionOutEventBinding) {
              this._emit(previousState.transitionOutEventBinding);
            }
          }
          if (lastTransition.startEventBinding) {
            this._emit(lastTransition.startEventBinding);
          }
          if (destinationState instanceof EventifiedStateEval) {
            if (destinationState.transitionInEventBinding) {
              this._emit(destinationState.transitionInEventBinding);
            }
          }
        };
        _proto._updateActivatedTransitions = function _updateActivatedTransitions(deltaTime) {
          var activatedTransitions = this._activatedTransitions;
          var iTransition = activatedTransitions.length - 1;
          var remainingWeight = 1.0;
          var lastTransitionIndex = iTransition;
          for (; iTransition >= 0; --iTransition) {
            var transition = activatedTransitions[iTransition];
            var sourceState = iTransition === 0 ? this._currentNode : activatedTransitions[iTransition - 1].destination;
            transition.update(deltaTime, sourceState);
            if (transition.done) {
              this._dropActivatedTransitions(lastTransitionIndex);
              break;
            }
            var destinationWeight = transition.normalizedElapsedTime * remainingWeight;
            transition.destination.increaseAbsoluteWeight(destinationWeight);
            remainingWeight *= 1.0 - transition.normalizedElapsedTime;
            lastTransitionIndex = iTransition - 1;
          }
          this._currentNode.increaseAbsoluteWeight(remainingWeight);
        };
        _proto._dropActivatedTransitions = function _dropActivatedTransitions(lastTransitionIndex) {
          var activatedTransition = this._activatedTransitions,
            activatedTransitionPool = this._activatedTransitionPool;
          assertIsTrue(lastTransitionIndex >= 0 && lastTransitionIndex < activatedTransition.length);
          var lenSubpath = lastTransitionIndex + 1;
          var lastTransition = activatedTransition[lastTransitionIndex];
          var newCurrentState = lastTransition.destination;
          {
            assertIsTrue(lastTransition.path.length !== 0);
            var lastRealTransition = lastTransition.path[lastTransition.path.length - 1];
            if (lastRealTransition.endEventBinding) {
              this._emit(lastRealTransition.endEventBinding);
            }
          }
          this._callExitMethods(this._currentNode);
          for (var iTransition = 0; iTransition <= lastTransitionIndex; ++iTransition) {
            var transition = activatedTransition[iTransition];
            if (iTransition !== lastTransitionIndex) {
              transition.destination.decreaseActiveReference();
            }
            var iLastExitingDetailedTransition = iTransition === lastTransitionIndex ? transition.path.length - 1 : transition.path.length;
            for (var iDetailedTransition = 0; iDetailedTransition < iLastExitingDetailedTransition; ++iDetailedTransition) {
              var detailedTransition = transition.path[iDetailedTransition];
              this._callExitMethods(detailedTransition.to);
            }
            activatedTransitionPool.free(transition);
          }
          if (lastTransitionIndex === activatedTransition.length - 1) {
            activatedTransition.length = 0;
          } else {
            for (var _iTransition = lastTransitionIndex + 1; _iTransition < activatedTransition.length; ++_iTransition) {
              activatedTransition[_iTransition - lenSubpath] = activatedTransition[_iTransition];
            }
            activatedTransition.length -= lenSubpath;
          }
          this._currentNode.decreaseActiveReference();
          this._currentNode = newCurrentState;
        };
        _proto._resetTriggersOnTransition = function _resetTriggersOnTransition(transition) {
          var triggers = transition.triggers;
          if (triggers) {
            var nTriggers = triggers.length;
            for (var iTrigger = 0; iTrigger < nTriggers; ++iTrigger) {
              var trigger = triggers[iTrigger];
              this._resetTrigger(trigger);
            }
          }
        };
        _proto._resetTrigger = function _resetTrigger(name) {
          var triggerResetFn = this._triggerReset;
          triggerResetFn(name);
        };
        _proto._callEnterMethods = function _callEnterMethods(node) {
          var _node$stateMachine$co;
          var controller = this._controller;
          switch (node.kind) {
            default:
              break;
            case NodeKind.animation:
              {
                node.components.callMotionStateEnterMethods(controller, node.getStatus());
                break;
              }
            case NodeKind.entry:
              (_node$stateMachine$co = node.stateMachine.components) === null || _node$stateMachine$co === void 0 ? void 0 : _node$stateMachine$co.callStateMachineEnterMethods(controller);
              break;
          }
        };
        _proto._callExitMethods = function _callExitMethods(node) {
          var _node$stateMachine$co2;
          var controller = this._controller;
          switch (node.kind) {
            default:
              break;
            case NodeKind.animation:
              {
                node.components.callMotionStateExitMethods(controller, node.getStatus());
                break;
              }
            case NodeKind.exit:
              (_node$stateMachine$co2 = node.stateMachine.components) === null || _node$stateMachine$co2 === void 0 ? void 0 : _node$stateMachine$co2.callStateMachineExitMethods(controller);
              break;
          }
        };
        _proto._emit = function _emit(eventBinding) {
          eventBinding.emit(this._controller.node);
        };
        _createClass(TopLevelStateMachineEvaluation, [{
          key: "exited",
          get: function get() {
            return this._currentNode === this._topLevelExit;
          }
        }]);
        return TopLevelStateMachineEvaluation;
      }();
      function isRealState(stateEval) {
        return stateEval.kind === NodeKind.animation || stateEval.kind === NodeKind.empty || stateEval.kind === NodeKind.procedural;
      }
      function createStateStatusCache() {
        return {
          progress: 0.0
        };
      }
      var emptyClipStatusesIterator = {
        next: function next() {
          return {
            done: true,
            value: undefined
          };
        }
      };
      var emptyClipStatusesIterable = (_emptyClipStatusesIte = {}, _emptyClipStatusesIte[Symbol.iterator] = function () {
        return emptyClipStatusesIterator;
      }, _emptyClipStatusesIte);
      var NodeKind;
      (function (NodeKind) {
        NodeKind[NodeKind["entry"] = 0] = "entry";
        NodeKind[NodeKind["exit"] = 1] = "exit";
        NodeKind[NodeKind["any"] = 2] = "any";
        NodeKind[NodeKind["animation"] = 3] = "animation";
        NodeKind[NodeKind["empty"] = 4] = "empty";
        NodeKind[NodeKind["procedural"] = 5] = "procedural";
      })(NodeKind || (NodeKind = {}));
      var StateEval = function () {
        function StateEval(node) {
          this.name = void 0;
          this.outgoingTransitions = [];
          this._activeReferenceCount = 0;
          this._tickFlags = 0;
          this._absoluteWeight = 0.0;
          this.name = node.name;
        }
        var _proto2 = StateEval.prototype;
        _proto2.setPrefix_debug = function setPrefix_debug(prefix) {
          this.__DEBUG_ID__ = "" + prefix + this.name;
        };
        _proto2.addTransition = function addTransition(transition) {
          this.outgoingTransitions.push(transition);
        };
        _proto2.increaseActiveReference = function increaseActiveReference() {
          if (this._activeReferenceCount === 0) {
            this._absoluteWeight = 0.0;
            this._tickFlags = 0;
          }
          ++this._activeReferenceCount;
        };
        _proto2.decreaseActiveReference = function decreaseActiveReference() {
          {
            this._checkActivated();
          }
          --this._activeReferenceCount;
        };
        _proto2.resetTickFlagsAndWeight = function resetTickFlagsAndWeight() {
          this._checkActivated();
          this._absoluteWeight = 0.0;
          this._tickFlags = 0;
        };
        _proto2.increaseAbsoluteWeight = function increaseAbsoluteWeight(weight) {
          this._absoluteWeight += weight;
        };
        _proto2.testTickFlag = function testTickFlag(flag) {
          {
            this._checkActivated();
          }
          return !!(this._tickFlags & flag);
        };
        _proto2.setTickFlag = function setTickFlag(flag) {
          {
            this._checkActivated();
          }
          assertIsTrue(!this.testTickFlag(flag), "Can not set " + StateTickFlag[flag] + " since it has been set!");
          this._tickFlags |= flag;
        };
        _proto2._checkActivated = function _checkActivated() {
          assertIsTrue(this._activeReferenceCount > 0, "The state has not been activated");
        };
        _createClass(StateEval, [{
          key: "absoluteWeight",
          get: function get() {
            return this._absoluteWeight;
          }
        }, {
          key: "activeReferenceCount",
          get: function get() {
            return this._activeReferenceCount;
          }
        }]);
        return StateEval;
      }();
      var EventifiedStateEval = function (_StateEval) {
        _inheritsLoose(EventifiedStateEval, _StateEval);
        function EventifiedStateEval(state) {
          var _this2;
          _this2 = _StateEval.call(this, state) || this;
          _this2.transitionInEventBinding = undefined;
          _this2.transitionOutEventBinding = undefined;
          if (state.transitionInEventBinding.isBound) {
            _this2.transitionInEventBinding = state.transitionInEventBinding;
          }
          if (state.transitionOutEventBinding.isBound) {
            _this2.transitionOutEventBinding = state.transitionOutEventBinding;
          }
          return _this2;
        }
        return EventifiedStateEval;
      }(StateEval);
      var StateTickFlag;
      (function (StateTickFlag) {
        StateTickFlag[StateTickFlag["UPDATED"] = 1] = "UPDATED";
        StateTickFlag[StateTickFlag["EVALUATED"] = 2] = "EVALUATED";
      })(StateTickFlag || (StateTickFlag = {}));
      var InstantiatedComponents = function () {
        function InstantiatedComponents(node) {
          this._components = node.instantiateComponents();
        }
        var _proto3 = InstantiatedComponents.prototype;
        _proto3.callMotionStateEnterMethods = function callMotionStateEnterMethods(controller, status) {
          this._callMotionStateCallbackIfNonDefault('onMotionStateEnter', controller, status);
        };
        _proto3.callMotionStateUpdateMethods = function callMotionStateUpdateMethods(controller, status) {
          this._callMotionStateCallbackIfNonDefault('onMotionStateUpdate', controller, status);
        };
        _proto3.callMotionStateExitMethods = function callMotionStateExitMethods(controller, status) {
          this._callMotionStateCallbackIfNonDefault('onMotionStateExit', controller, status);
        };
        _proto3.callStateMachineEnterMethods = function callStateMachineEnterMethods(controller) {
          this._callStateMachineCallbackIfNonDefault('onStateMachineEnter', controller);
        };
        _proto3.callStateMachineExitMethods = function callStateMachineExitMethods(controller) {
          this._callStateMachineCallbackIfNonDefault('onStateMachineExit', controller);
        };
        _proto3._callMotionStateCallbackIfNonDefault = function _callMotionStateCallbackIfNonDefault(methodName, controller, status) {
          var components = this._components;
          var nComponents = components.length;
          for (var iComponent = 0; iComponent < nComponents; ++iComponent) {
            var component = components[iComponent];
            if (component[methodName] !== StateMachineComponent.prototype[methodName]) {
              component[methodName](controller, status);
            }
          }
        };
        _proto3._callStateMachineCallbackIfNonDefault = function _callStateMachineCallbackIfNonDefault(methodName, controller) {
          var components = this._components;
          var nComponents = components.length;
          for (var iComponent = 0; iComponent < nComponents; ++iComponent) {
            var component = components[iComponent];
            if (component[methodName] !== StateMachineComponent.prototype[methodName]) {
              component[methodName](controller);
            }
          }
        };
        return InstantiatedComponents;
      }();
      var VMSMEval = function () {
        function VMSMEval(state, context) {
          var _state$motion$createE, _state$motion;
          this._source = null;
          this._baseSpeed = 1.0;
          this._speed = 1.0;
          this._publicState = void 0;
          this._privateState = void 0;
          var name = state.name;
          this._baseSpeed = state.speed;
          this._setSpeedMultiplier(1.0);
          if (state.speedMultiplierEnabled && state.speedMultiplier) {
            var speedMultiplierVarName = state.speedMultiplier;
            var varInstance = context.getVar(speedMultiplierVarName);
            if (validateVariableExistence(varInstance, speedMultiplierVarName)) {
              validateVariableType(varInstance.type, VariableType.FLOAT, speedMultiplierVarName);
              varInstance.bind(this._setSpeedMultiplier, this);
              var initialSpeedMultiplier = varInstance.value;
              this._setSpeedMultiplier(initialSpeedMultiplier);
            }
          }
          var sourceEval = (_state$motion$createE = (_state$motion = state.motion) === null || _state$motion === void 0 ? void 0 : _state$motion[createEval](context, false)) !== null && _state$motion$createE !== void 0 ? _state$motion$createE : null;
          if (sourceEval) {
            Object.defineProperty(sourceEval, '__DEBUG_ID__', {
              value: name
            });
          }
          this._source = sourceEval;
          this._publicState = new VMSMInternalState(this, state, sourceEval === null || sourceEval === void 0 ? void 0 : sourceEval.createPort());
          this._privateState = new VMSMInternalState(this, state, sourceEval === null || sourceEval === void 0 ? void 0 : sourceEval.createPort());
          this.components = new InstantiatedComponents(state);
        }
        var _proto4 = VMSMEval.prototype;
        _proto4.setPrefix_debug = function setPrefix_debug(prefix) {
          this._publicState.setPrefix_debug(prefix);
          this._privateState.setPrefix_debug(prefix);
        };
        _proto4.addTransition = function addTransition(transition) {
          if (transition.to === this._publicState) {
            this._publicState.addTransition(_extends({}, transition, {
              to: this._privateState
            }));
          } else {
            this._publicState.addTransition(transition);
          }
          this._privateState.addTransition(transition);
        };
        _proto4.getClipStatuses = function getClipStatuses(baseWeight) {
          var source = this._source;
          if (!source) {
            return emptyClipStatusesIterable;
          } else {
            var _ref;
            return _ref = {}, _ref[Symbol.iterator] = function () {
              return source.getClipStatuses(baseWeight);
            }, _ref;
          }
        };
        _proto4.overrideClips = function overrideClips(context) {
          var _this$_source;
          (_this$_source = this._source) === null || _this$_source === void 0 ? void 0 : _this$_source.overrideClips(context);
        };
        _proto4._setSpeedMultiplier = function _setSpeedMultiplier(value) {
          this._speed = this._baseSpeed * value;
        };
        _createClass(VMSMEval, [{
          key: "duration",
          get: function get() {
            var _this$_source$duratio, _this$_source2;
            return (_this$_source$duratio = (_this$_source2 = this._source) === null || _this$_source2 === void 0 ? void 0 : _this$_source2.duration) !== null && _this$_source$duratio !== void 0 ? _this$_source$duratio : 0.0;
          }
        }, {
          key: "speed",
          get: function get() {
            return this._speed;
          }
        }, {
          key: "entry",
          get: function get() {
            return this._publicState;
          }
        }, {
          key: "stateMachine",
          get: function get() {
            return this._stateMachine;
          },
          set: function set(value) {
            this._stateMachine = value;
            this._publicState.stateMachine = value;
            this._privateState.stateMachine = value;
          }
        }]);
        return VMSMEval;
      }();
      var VMSMInternalState = function (_EventifiedStateEval) {
        _inheritsLoose(VMSMInternalState, _EventifiedStateEval);
        function VMSMInternalState(container, containerState, port) {
          var _this3;
          _this3 = _EventifiedStateEval.call(this, containerState) || this;
          _this3.kind = NodeKind.animation;
          _this3._container = void 0;
          _this3._progress = 0.0;
          _this3._port = void 0;
          _this3._statusCache = createStateStatusCache();
          _this3._container = container;
          _this3._port = port;
          return _this3;
        }
        var _proto5 = VMSMInternalState.prototype;
        _proto5.reenter = function reenter(initialTimeNormalized) {
          var _this$_port;
          this._progress = initialTimeNormalized;
          (_this$_port = this._port) === null || _this$_port === void 0 ? void 0 : _this$_port.reenter();
        };
        _proto5.getStatus = function getStatus() {
          var stateStatus = this._statusCache;
          {
            stateStatus.__DEBUG_ID__ = this.name;
          }
          stateStatus.progress = normalizeProgress(this._progress);
          return stateStatus;
        };
        _proto5.getClipStatuses = function getClipStatuses(baseWeight) {
          return this._container.getClipStatuses(baseWeight);
        };
        _proto5.update = function update(deltaTime, controller) {
          this._progress = calcProgressUpdate(this._progress, this.duration, deltaTime * this._container.speed);
          this._container.components.callMotionStateUpdateMethods(controller, this.getStatus());
        };
        _proto5.evaluate = function evaluate(context) {
          var _this$_port$evaluate, _this$_port2;
          return (_this$_port$evaluate = (_this$_port2 = this._port) === null || _this$_port2 === void 0 ? void 0 : _this$_port2.evaluate(this._progress, context)) !== null && _this$_port$evaluate !== void 0 ? _this$_port$evaluate : null;
        };
        _createClass(VMSMInternalState, [{
          key: "duration",
          get: function get() {
            return this._container.duration;
          }
        }, {
          key: "components",
          get: function get() {
            return this._container.components;
          }
        }, {
          key: "normalizedTime",
          get: function get() {
            return this._progress;
          }
        }, {
          key: "time",
          get: function get() {
            return this._progress * this._container.duration;
          }
        }]);
        return VMSMInternalState;
      }(EventifiedStateEval);
      function calcProgressUpdate(currentProgress, duration, deltaTime) {
        if (duration === 0.0) {
          return 0.0;
        }
        var progress = currentProgress + deltaTime / duration;
        return progress;
      }
      function normalizeProgress(progress) {
        var signedFrac = progress - Math.trunc(progress);
        return signedFrac >= 0.0 ? signedFrac : 1.0 + signedFrac;
      }
      var SpecialStateEval = function (_StateEval2) {
        _inheritsLoose(SpecialStateEval, _StateEval2);
        function SpecialStateEval(node, kind, name) {
          var _this4;
          _this4 = _StateEval2.call(this, node) || this;
          _this4.kind = void 0;
          _this4.kind = kind;
          return _this4;
        }
        return SpecialStateEval;
      }(StateEval);
      var EmptyStateEval = function (_StateEval3) {
        _inheritsLoose(EmptyStateEval, _StateEval3);
        function EmptyStateEval(node) {
          var _this5;
          _this5 = _StateEval3.call(this, node) || this;
          _this5.kind = NodeKind.empty;
          return _this5;
        }
        return EmptyStateEval;
      }(StateEval);
      var ProceduralPoseStateEval = function (_EventifiedStateEval2) {
        _inheritsLoose(ProceduralPoseStateEval, _EventifiedStateEval2);
        function ProceduralPoseStateEval(state, context) {
          var _this6;
          _this6 = _EventifiedStateEval2.call(this, state) || this;
          _this6.kind = NodeKind.procedural;
          _this6.elapsedTime = 0.0;
          _this6.statusCache = createStateStatusCache();
          _this6._instantiatedPoseGraph = void 0;
          _this6._statusCache = createStateStatusCache();
          _this6._elapsedTime = 0.0;
          var instantiatedPoseGraph = instantiatePoseGraph(state.graph, context, true);
          instantiatedPoseGraph.bind(context);
          _this6._instantiatedPoseGraph = instantiatedPoseGraph;
          {
            _this6._statusCache.__DEBUG_ID__ = state.name;
          }
          _this6._statusCache.progress = 0.0;
          return _this6;
        }
        var _proto6 = ProceduralPoseStateEval.prototype;
        _proto6.settle = function settle(context) {
          this._instantiatedPoseGraph.settle(context);
        };
        _proto6.reenter = function reenter() {
          this._statusCache.progress = 0.0;
          this._instantiatedPoseGraph.reenter();
        };
        _proto6.update = function update(context) {
          this._elapsedTime += context.deltaTime;
          this._instantiatedPoseGraph.update(context);
        };
        _proto6.evaluate = function evaluate(context) {
          var _this$_instantiatedPo;
          return (_this$_instantiatedPo = this._instantiatedPoseGraph.evaluate(context)) !== null && _this$_instantiatedPo !== void 0 ? _this$_instantiatedPo : null;
        };
        _proto6.getStatus = function getStatus() {
          this._statusCache.progress = normalizeProgress(this._elapsedTime);
          return this._statusCache;
        };
        _proto6.countMotionTime = function countMotionTime() {
          return this._instantiatedPoseGraph.countMotionTime();
        };
        return ProceduralPoseStateEval;
      }(EventifiedStateEval);
      var ConditionEvaluationContextImpl = function () {
        function ConditionEvaluationContextImpl() {
          this.sourceStateWeight = 0.0;
          this._sourceState = undefined;
        }
        var _proto7 = ConditionEvaluationContextImpl.prototype;
        _proto7.set = function set(sourceState) {
          this._sourceState = sourceState;
          if (isRealState(sourceState)) {
            assertIsTrue(sourceState.activeReferenceCount);
            this.sourceStateWeight = sourceState.absoluteWeight;
          } else {
            this.sourceStateWeight = 0.0;
          }
        };
        _proto7.unset = function unset() {
          this._sourceState = undefined;
          this.sourceStateWeight = 0.0;
        };
        _createClass(ConditionEvaluationContextImpl, [{
          key: "sourceStateMotionTimeNormalized",
          get: function get() {
            var sourceState = this._sourceState;
            assertIsTrue(sourceState && (sourceState.kind === NodeKind.animation || sourceState.kind === NodeKind.procedural) && sourceState.activeReferenceCount, "State motion time is only defined on activated motion states and procedural pose states.");
            switch (sourceState.kind) {
              case NodeKind.animation:
                return sourceState.normalizedTime;
              case NodeKind.procedural:
                return sourceState.countMotionTime();
              default:
                return 0.0;
            }
          }
        }]);
        return ConditionEvaluationContextImpl;
      }();
      var ActivatedTransition = function () {
        function ActivatedTransition() {
          this.normalizedElapsedTime = 0.0;
          this.path = [];
          this._durationMultiplier = 1.0;
        }
        var _proto8 = ActivatedTransition.prototype;
        _proto8.getAbsoluteDuration = function getAbsoluteDuration(baseDurationState) {
          return this._getAbsoluteDurationUnscaled(baseDurationState) * this._durationMultiplier;
        };
        _proto8.update = function update(deltaTime, fromState) {
          if (!isRealState(fromState)) {
            this.normalizedElapsedTime = 1.0;
            return;
          }
          var transitionDurationAbsolute = this.getAbsoluteDuration(fromState);
          var contrib = 0.0;
          if (transitionDurationAbsolute <= 0.0) {
            contrib = 0.0;
            this.normalizedElapsedTime = 1.0;
          } else {
            var elapsedTransitionTime = this.normalizedElapsedTime * transitionDurationAbsolute;
            var remainTransitionTime = transitionDurationAbsolute - elapsedTransitionTime;
            assertIsTrue(remainTransitionTime >= 0.0);
            contrib = Math.min(remainTransitionTime, deltaTime);
            var newTransitionProgress = clamp01((elapsedTransitionTime + contrib) / transitionDurationAbsolute);
            this.normalizedElapsedTime = newTransitionProgress;
            assertIsTrue(newTransitionProgress >= 0.0 && newTransitionProgress <= 1.0);
          }
        };
        ActivatedTransition.createPool = function createPool(initialCapacity) {
          var destructor = function (transitionInstance) {
            transitionInstance.normalizedElapsedTime = Number.NaN;
          };
          var pool = new Pool(function () {
            return new ActivatedTransition();
          }, initialCapacity, destructor);
          return pool;
        };
        _proto8.reset = function reset(prefix, lastTransition) {
          var destinationState = lastTransition.to;
          assertIsTrue(isRealState(destinationState));
          this.normalizedElapsedTime = 0.0;
          this.destination = destinationState;
          this.path = [].concat(prefix, [lastTransition]);
          var previousActiveReferenceCount = destinationState.activeReferenceCount;
          destinationState.increaseActiveReference();
          if (previousActiveReferenceCount === 0) {
            if (destinationState.kind === NodeKind.animation) {
              var _this$path$ = this.path[0],
                destinationStart = _this$path$.destinationStart,
                isRelativeDestinationStart = _this$path$.relativeDestinationStart;
              var destinationStartRatio = isRelativeDestinationStart ? destinationStart : destinationState.duration === 0 ? 0.0 : destinationStart / destinationState.duration;
              destinationState.reenter(destinationStartRatio);
            } else if (destinationState.kind === NodeKind.procedural) {
              destinationState.reenter();
            }
          }
          assertIsTrue(destinationState.activeReferenceCount > 0);
          this._durationMultiplier = 1.0 - destinationState.absoluteWeight;
        };
        _proto8._getAbsoluteDurationUnscaled = function _getAbsoluteDurationUnscaled(baseDurationState) {
          assertIsTrue(this.path.length !== 0);
          var _this$path$2 = this.path[0],
            duration = _this$path$2.duration,
            normalizedDuration = _this$path$2.normalizedDuration;
          if (!normalizedDuration) {
            return duration;
          }
          var baseDuration = baseDurationState.kind === NodeKind.animation ? baseDurationState.duration : 1.0;
          return baseDuration * duration;
        };
        _createClass(ActivatedTransition, [{
          key: "done",
          get: function get() {
            return approx(this.normalizedElapsedTime, 1.0, 1e-6);
          }
        }]);
        return ActivatedTransition;
      }();

      var RuntimeMotionSyncManager = function () {
        function RuntimeMotionSyncManager() {
          this._groups = [];
        }
        var _proto = RuntimeMotionSyncManager.prototype;
        _proto.register = function register(syncInfo) {
          var groupName = syncInfo.group;
          var group = this._groups.find(function (group) {
            return group.name === groupName;
          });
          if (!group) {
            group = new Group(groupName);
            this._groups.push(group);
          }
          return group.addMember();
        };
        _proto.sync = function sync() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._groups), _step; !(_step = _iterator()).done;) {
            var group = _step.value;
            group.sync();
          }
        };
        return RuntimeMotionSyncManager;
      }();
      var Group = function () {
        function Group(name) {
          this._lastLeader = undefined;
          this._records = [];
          this.name = name;
        }
        var _proto2 = Group.prototype;
        _proto2.addMember = function addMember() {
          var record = new RuntimeMotionSyncRecordImpl();
          this._records.push(record);
          return record;
        };
        _proto2.sync = function sync() {
          var records = this._records;
          var nRecords = records.length;
          assertIsTrue(nRecords > 0);
          var lastLeader = this._lastLeader;
          this._lastLeader = undefined;
          if (records.every(function (r) {
            return !r.active;
          })) {
            return;
          }
          records.sort(function (a, b) {
            var kA = a.active ? a.weight : -1.0;
            var kB = b.active ? b.weight : -1.0;
            return kB - kA;
          });
          {
            var firstInactiveRecord = records.findIndex(function (r) {
              return !r.active;
            });
            assertIsTrue((firstInactiveRecord < 0 ? [] : records.slice(firstInactiveRecord)).every(function (r) {
              return !r.active;
            }));
          }
          var leaderIndex = 0;
          var leaderWeight = records[0].weight;
          if (records[leaderIndex] !== lastLeader) {
            for (var iRecord = 0; iRecord < nRecords; ++iRecord) {
              var record = records[iRecord];
              if (!record.active || !approx(record.weight, leaderWeight, 1e-6)) {
                break;
              }
              if (record === lastLeader) {
                leaderIndex = iRecord;
                break;
              }
            }
          }
          assertIsTrue(records[leaderIndex].active);
          this._lastLeader = records[leaderIndex];
          var leaderNormalizedTime = records[leaderIndex].normalizedTime;
          for (var _iRecord = 0; _iRecord < nRecords; ++_iRecord) {
            var _record = records[_iRecord];
            if (!_record.active) {
              break;
            }
            _record.normalizedTime = leaderNormalizedTime;
            _record.reset();
          }
        };
        return Group;
      }();
      var RuntimeMotionSyncRecordImpl = function () {
        function RuntimeMotionSyncRecordImpl() {
          this.normalizedTime = 0.0;
          this.weight = 0.0;
          this.active = false;
        }
        var _proto3 = RuntimeMotionSyncRecordImpl.prototype;
        _proto3.notifyRenter = function notifyRenter(normalizedTime) {
          this.reset();
          this.normalizedTime = normalizedTime;
        };
        _proto3.notifyUpdate = function notifyUpdate(normalizedDeltaTime, weight) {
          this.normalizedTime += normalizedDeltaTime;
          if (this.active) {
            this.weight += weight;
          } else {
            this.active = true;
            this.weight = weight;
          }
        };
        _proto3.reset = function reset() {
          this.active = false;
          this.weight = 0.0;
        };
        _proto3.getSyncedEnterTime = function getSyncedEnterTime() {
          return this.normalizedTime;
        };
        return RuntimeMotionSyncRecordImpl;
      }();

      var StashRecordState;
      (function (StashRecordState) {
        StashRecordState[StashRecordState["UNINITIALIZED"] = 0] = "UNINITIALIZED";
        StashRecordState[StashRecordState["UNSETTLED"] = 1] = "UNSETTLED";
        StashRecordState[StashRecordState["SETTLED"] = 2] = "SETTLED";
        StashRecordState[StashRecordState["UP_TO_DATE"] = 3] = "UP_TO_DATE";
        StashRecordState[StashRecordState["OUTDATED"] = 4] = "OUTDATED";
        StashRecordState[StashRecordState["UPDATING"] = 5] = "UPDATING";
        StashRecordState[StashRecordState["UPDATED"] = 6] = "UPDATED";
        StashRecordState[StashRecordState["EVALUATING"] = 7] = "EVALUATING";
        StashRecordState[StashRecordState["EVALUATED"] = 8] = "EVALUATED";
      })(StashRecordState || (StashRecordState = {}));
      var RuntimeStashRecord = function () {
        function RuntimeStashRecord(_allocator) {
          this._state = StashRecordState.UNINITIALIZED;
          this._instantiatedPoseGraph = undefined;
          this._maxRequestedUpdateTime = 0.0;
          this._evaluationCache = null;
          this._updateContextGenerator = new AnimationGraphUpdateContextGenerator();
          this._allocator = _allocator;
        }
        var _proto = RuntimeStashRecord.prototype;
        _proto.set = function set(stash, context) {
          assertIsTrue(this._state === StashRecordState.UNINITIALIZED, "The stash has already been set.");
          var instantiatedPoseGraph = instantiatePoseGraph(stash.graph, context);
          instantiatedPoseGraph.bind(context);
          this._instantiatedPoseGraph = instantiatedPoseGraph;
          this._state = StashRecordState.UNSETTLED;
        };
        _proto.settle = function settle(context) {
          assertIsTrue(this._state === StashRecordState.UNSETTLED || this._state === StashRecordState.SETTLED);
          assertIsTrue(this._instantiatedPoseGraph);
          this._instantiatedPoseGraph.settle(context);
          this._state = StashRecordState.SETTLED;
        };
        _proto.reset = function reset() {
          switch (this._state) {
            case StashRecordState.SETTLED:
            case StashRecordState.OUTDATED:
              break;
            case StashRecordState.UP_TO_DATE:
              this._state = StashRecordState.OUTDATED;
              break;
            case StashRecordState.UPDATED:
            case StashRecordState.EVALUATED:
              if (this._evaluationCache) {
                this._allocator.destroyPose(this._evaluationCache);
                this._evaluationCache = null;
              }
              this._maxRequestedUpdateTime = 0.0;
              this._state = StashRecordState.UP_TO_DATE;
              break;
            case StashRecordState.UNINITIALIZED:
            default:
              assertIsTrue(false, "Unexpected stash state");
          }
        };
        _proto.reenter = function reenter() {
          switch (this._state) {
            default:
              assertIsTrue(false, "Unexpected stash state " + this._state + " when reenter().");
              break;
            case StashRecordState.UP_TO_DATE:
            case StashRecordState.UPDATED:
              break;
            case StashRecordState.SETTLED:
            case StashRecordState.OUTDATED:
              {
                this._state = StashRecordState.UP_TO_DATE;
                assertIsTrue(this._instantiatedPoseGraph);
                this._instantiatedPoseGraph.reenter();
                break;
              }
          }
        };
        _proto.requestUpdate = function requestUpdate(context) {
          var deltaTime = context.deltaTime;
          assertIsTrue(this._state === StashRecordState.OUTDATED || this._state === StashRecordState.UP_TO_DATE || this._state === StashRecordState.UPDATING || this._state === StashRecordState.UPDATED);
          assertIsTrue(this._instantiatedPoseGraph);
          if (this._state === StashRecordState.UPDATING) {
            return;
          }
          var diffDeltaTime = Math.max(0.0, deltaTime - this._maxRequestedUpdateTime);
          if (this._state === StashRecordState.UPDATED) {
            if (approx(diffDeltaTime, 0.0, 1e-8)) {
              return;
            } else {
              {
                error("Arrived here indicates a violent of PR #14990. Please report the BUG.");
                return;
              }
            }
          }
          this._state = StashRecordState.UPDATING;
          this._maxRequestedUpdateTime = Math.max(deltaTime, this._maxRequestedUpdateTime);
          var updateContext = this._updateContextGenerator.generate(diffDeltaTime, context.indicativeWeight);
          this._instantiatedPoseGraph.update(updateContext);
          this._state = StashRecordState.UPDATED;
        };
        _proto.evaluate = function evaluate(context) {
          switch (this._state) {
            default:
              assertIsTrue(false, "Unexpected stash state " + this._state + " when evaluate().");
              break;
            case StashRecordState.EVALUATING:
              this._state = StashRecordState.EVALUATED;
              break;
            case StashRecordState.EVALUATED:
              break;
            case StashRecordState.UPDATED:
              {
                var _this$_instantiatedPo;
                assertIsTrue(!this._evaluationCache);
                this._state = StashRecordState.EVALUATING;
                var _pose = (_this$_instantiatedPo = this._instantiatedPoseGraph) === null || _this$_instantiatedPo === void 0 ? void 0 : _this$_instantiatedPo.evaluate(context);
                this._state = StashRecordState.EVALUATED;
                if (_pose) {
                  var heapPose = this._allocator.allocatePose();
                  heapPose.transforms.set(_pose.transforms);
                  heapPose.auxiliaryCurves.set(_pose.auxiliaryCurves);
                  this._evaluationCache = heapPose;
                  context.popPose();
                }
                this._state = StashRecordState.EVALUATED;
                break;
              }
          }
          assertIsTrue(this._state === StashRecordState.EVALUATED);
          assertIsTrue(this._instantiatedPoseGraph);
          return this._evaluationCache ? context.pushDuplicatedPose(this._evaluationCache) : null;
        };
        return RuntimeStashRecord;
      }();
      var RuntimeStashManager = function () {
        function RuntimeStashManager(allocator) {
          this._allocator = void 0;
          this._stashEvaluations = {};
          this._allocator = allocator;
        }
        var _proto2 = RuntimeStashManager.prototype;
        _proto2.bindStash = function bindStash(id) {
          return this._stashEvaluations[id];
        };
        _proto2.getStash = function getStash(id) {
          return this._stashEvaluations[id];
        };
        _proto2.addStash = function addStash(id) {
          this._stashEvaluations[id] = new RuntimeStashRecord(this._allocator);
        };
        _proto2.setStash = function setStash(id, stash, context) {
          assertIsTrue(id in this._stashEvaluations);
          this._stashEvaluations[id].set(stash, context);
        };
        _proto2.reset = function reset() {
          for (var stashId in this._stashEvaluations) {
            var record = this._stashEvaluations[stashId];
            record.reset();
          }
        };
        _proto2.settle = function settle(context) {
          for (var stashId in this._stashEvaluations) {
            var record = this._stashEvaluations[stashId];
            record.settle(context);
          }
        };
        return RuntimeStashManager;
      }();

      var DefaultTopLevelPoseNode = function (_PoseNode) {
        _inheritsLoose(DefaultTopLevelPoseNode, _PoseNode);
        function DefaultTopLevelPoseNode(graph, bindingContext, poseStashAllocator) {
          var _this;
          _this = _PoseNode.call(this) || this;
          _this._layerRecords = void 0;
          var layerEvaluationRecords = graph.layers.map(function (layer) {
            var record = new LayerEvaluationRecord(layer, bindingContext, poseStashAllocator);
            return record;
          });
          _this._layerRecords = layerEvaluationRecords;
          return _this;
        }
        var _proto = DefaultTopLevelPoseNode.prototype;
        _proto.reenter = function reenter() {};
        _proto.bind = function bind(_context) {};
        _proto.settle = function settle(context) {
          var layerRecords = this._layerRecords;
          var nLayers = layerRecords.length;
          for (var iLayer = 0; iLayer < nLayers; ++iLayer) {
            layerRecords[iLayer].settle(context);
          }
        };
        _proto.getLayerWeight = function getLayerWeight(layerIndex) {
          assertIsTrue(layerIndex >= 0 && layerIndex < this._layerRecords.length, "Invalid layer index");
          return this._layerRecords[layerIndex].weight;
        };
        _proto.setLayerWeight = function setLayerWeight(layerIndex, weight) {
          assertIsTrue(layerIndex >= 0 && layerIndex < this._layerRecords.length, "Invalid layer index");
          this._layerRecords[layerIndex].weight = weight;
        };
        _proto.getLayerTopLevelStateMachineEvaluation = function getLayerTopLevelStateMachineEvaluation(layerIndex) {
          return this._layerRecords[layerIndex].stateMachineEvaluation;
        };
        _proto.overrideClips = function overrideClips(context) {
          var layerRecords = this._layerRecords;
          var nLayers = layerRecords.length;
          for (var iLayer = 0; iLayer < nLayers; ++iLayer) {
            var layerRecord = layerRecords[iLayer];
            context._pushAdditiveFlag(layerRecord.additive);
            layerRecord.stateMachineEvaluation.overrideClips(context);
            context._popAdditiveFlag();
          }
        };
        _proto.doUpdate = function doUpdate(context) {
          var layerRecords = this._layerRecords;
          var nLayers = layerRecords.length;
          for (var iLayer = 0; iLayer < nLayers; ++iLayer) {
            layerRecords[iLayer].update(context);
          }
        };
        _proto.doEvaluate = function doEvaluate(context) {
          var finalPose = context.pushDefaultedPose();
          var layerRecords = this._layerRecords;
          var nLayers = layerRecords.length;
          for (var iLayer = 0; iLayer < nLayers; ++iLayer) {
            var layer = layerRecords[iLayer];
            var layerPose = layer.stateMachineEvaluation.evaluate(context);
            var layerActualWeight = layer.weight * layer.stateMachineEvaluation.passthroughWeight;
            var transformFilter = layer.transformFilter;
            if (layer.additive) {
              applyDeltaPose(finalPose, layerPose, layerActualWeight, transformFilter);
            } else {
              blendPoseInto(finalPose, layerPose, layerActualWeight, transformFilter);
            }
            context.popPose();
            layer.postEvaluate();
          }
          return finalPose;
        };
        _createClass(DefaultTopLevelPoseNode, [{
          key: "layerCount",
          get: function get() {
            return this._layerRecords.length;
          }
        }]);
        return DefaultTopLevelPoseNode;
      }(PoseNode);
      var LayerEvaluationRecord = function () {
        function LayerEvaluationRecord(layer, bindingContext, poseStashAllocator) {
          var _layer$mask;
          this.additive = false;
          this.weight = 0.0;
          this._topLevelStateMachineEval = void 0;
          this._stashManager = void 0;
          this._motionSyncManager = void 0;
          this._mask = undefined;
          this.transformFilter = undefined;
          var stashManager = new RuntimeStashManager(poseStashAllocator);
          for (var _iterator = _createForOfIteratorHelperLoose(layer.stashes()), _step; !(_step = _iterator()).done;) {
            var _step$value = _step.value,
              stashId = _step$value[0];
              _step$value[1];
            stashManager.addStash(stashId);
          }
          this._stashManager = stashManager;
          var motionSyncManager = new RuntimeMotionSyncManager();
          this._motionSyncManager = motionSyncManager;
          bindingContext._setLayerWideContextProperties(stashManager, motionSyncManager);
          for (var _iterator2 = _createForOfIteratorHelperLoose(layer.stashes()), _step2; !(_step2 = _iterator2()).done;) {
            var _step2$value = _step2.value,
              _stashId = _step2$value[0],
              stash = _step2$value[1];
            stashManager.setStash(_stashId, stash, bindingContext);
          }
          this.weight = layer.weight;
          var additive = this.additive = layer.additive;
          this._mask = (_layer$mask = layer.mask) !== null && _layer$mask !== void 0 ? _layer$mask : undefined;
          bindingContext._pushAdditiveFlag(additive);
          this._topLevelStateMachineEval = new TopLevelStateMachineEvaluation(layer.stateMachine, layer.name, bindingContext);
          bindingContext._popAdditiveFlag();
          bindingContext._unsetLayerWideContextProperties();
        }
        var _proto2 = LayerEvaluationRecord.prototype;
        _proto2.settle = function settle(context) {
          if (this._mask) {
            this.transformFilter = context.createTransformFilter(this._mask);
          }
          this._stashManager.settle(context);
          this._topLevelStateMachineEval.settle(context);
        };
        _proto2.update = function update(context) {
          this.stateMachineEvaluation.update(context);
          this._motionSyncManager.sync();
        };
        _proto2.postEvaluate = function postEvaluate() {
          this._stashManager.reset();
        };
        _createClass(LayerEvaluationRecord, [{
          key: "stateMachineEvaluation",
          get: function get() {
            return this._topLevelStateMachineEval;
          }
        }]);
        return LayerEvaluationRecord;
      }();

      var AnimationGraphEval = function () {
        function AnimationGraphEval(graph, root, controller, clipOverrides) {
          this._currentTransitionCache = {
            duration: 0.0,
            time: 0.0
          };
          this._rootPoseNode = void 0;
          this._varInstances = {};
          this._hasAutoTrigger = false;
          this._auxiliaryCurveRegistry = new AuxiliaryCurveRegistry();
          this._poseLayoutMaintainer = void 0;
          this._bindingContext = void 0;
          this._settleContext = void 0;
          this._rootUpdateContextGenerator = new AnimationGraphUpdateContextGenerator();
          {
            if (graph.layers.length >= MAX_ANIMATION_LAYER) {
              throw new Error("Max layer count exceeds. " + ("Allowed: " + MAX_ANIMATION_LAYER + ", actual: " + graph.layers.length));
            }
          }
          for (var _iterator = _createForOfIteratorHelperLoose(graph.variables), _step; !(_step = _iterator()).done;) {
            var _step$value = _step.value,
              name = _step$value[0],
              variable = _step$value[1];
            var varInstance = variable[createInstanceTag]();
            this._varInstances[name] = varInstance;
            if (varInstance instanceof VarInstanceTrigger) {
              if (varInstance.resetMode === TriggerResetMode.NEXT_FRAME_OR_AFTER_CONSUMED) {
                this._hasAutoTrigger = true;
              }
            }
          }
          var poseLayoutMaintainer = new AnimationGraphPoseLayoutMaintainer(root, this._auxiliaryCurveRegistry);
          this._poseLayoutMaintainer = poseLayoutMaintainer;
          var bindingContext = new AnimationGraphBindingContext(root, poseLayoutMaintainer, this._varInstances, controller);
          bindingContext._setClipOverrides(clipOverrides !== null && clipOverrides !== void 0 ? clipOverrides : undefined);
          this._bindingContext = bindingContext;
          var settleContext = new AnimationGraphSettleContext(poseLayoutMaintainer);
          this._settleContext = settleContext;
          poseLayoutMaintainer.startBind();
          var poseStashAllocator = new DeferredPoseStashAllocator();
          this._poseStashAllocator = poseStashAllocator;
          this._rootPoseNode = new DefaultTopLevelPoseNode(graph, bindingContext, poseStashAllocator);
          this._root = root;
          this._initializeContexts();
        }
        var _proto = AnimationGraphEval.prototype;
        _proto.destroy = function destroy() {
          this._evaluationContext.destroy();
        };
        _proto._destroyAfterException_debugging = function _destroyAfterException_debugging() {
          var stackSize = this._evaluationContext._stackSize_debugging;
          if (stackSize !== 0) {
            for (var i = 0; i < stackSize; ++i) {
              this._evaluationContext.popPose();
            }
          }
          this._evaluationContext.destroy();
        };
        _proto.update = function update(deltaTime) {
          var evaluationContext = this._evaluationContext,
            poseLayoutMaintainer = this._poseLayoutMaintainer,
            rootUpdateContextGenerator = this._rootUpdateContextGenerator,
            rootPoseNode = this._rootPoseNode;
          var updateContext = rootUpdateContextGenerator.generate(deltaTime, 1.0);
          rootPoseNode.update(updateContext);
          var finalPose = rootPoseNode.evaluate(evaluationContext, PoseTransformSpaceRequirement.LOCAL);
          if (this._hasAutoTrigger) {
            var varInstances = this._varInstances;
            for (var varName in varInstances) {
              var varInstance = varInstances[varName];
              if (varInstance instanceof VarInstanceTrigger && varInstance.resetMode === TriggerResetMode.NEXT_FRAME_OR_AFTER_CONSUMED) {
                varInstance.value = false;
              }
            }
          }
          poseLayoutMaintainer.apply(finalPose);
          evaluationContext.popPose();
          {
            assertIsTrue(evaluationContext.allocatedPoseCount === 0, "Pose leaked.");
            assertIsTrue(this._poseStashAllocator.allocatedPoseCount === 0, "Pose leaked.");
          }
        };
        _proto.getVariables = function getVariables() {
          return Object.entries(this._varInstances);
        };
        _proto.getCurrentStateStatus = function getCurrentStateStatus(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getCurrentStateStatus();
        };
        _proto.getCurrentClipStatuses = function getCurrentClipStatuses(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getCurrentClipStatuses();
        };
        _proto.getCurrentTransition = function getCurrentTransition(layer) {
          var currentTransition = this._currentTransitionCache;
          var isInTransition = this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getCurrentTransition(currentTransition);
          return isInTransition ? currentTransition : null;
        };
        _proto.getNextStateStatus = function getNextStateStatus(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getNextStateStatus();
        };
        _proto.getNextClipStatuses = function getNextClipStatuses(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getNextClipStatuses();
        };
        _proto.getValue = function getValue(name) {
          var varInstance = this._varInstances[name];
          if (!varInstance) {
            return undefined;
          } else {
            return varInstance.value;
          }
        };
        _proto.setValue = function setValue(name, value) {
          var varInstance = this._varInstances[name];
          if (!varInstance) {
            return;
          }
          varInstance.value = value;
        };
        _proto.getLayerWeight = function getLayerWeight(layerIndex) {
          return this._rootPoseNode.getLayerWeight(layerIndex);
        };
        _proto.setLayerWeight = function setLayerWeight(layerIndex, weight) {
          this._rootPoseNode.setLayerWeight(layerIndex, weight);
        };
        _proto.overrideClips = function overrideClips(overrides) {
          var poseLayoutMaintainer = this._poseLayoutMaintainer;
          poseLayoutMaintainer.startBind();
          this._bindingContext._setClipOverrides(overrides);
          this._rootPoseNode.overrideClips(this._bindingContext);
          this._updateAfterPossiblePoseLayoutChange();
        };
        _proto.getAuxiliaryCurveValue = function getAuxiliaryCurveValue(curveName) {
          return this._auxiliaryCurveRegistry.get(curveName);
        };
        _proto._initializeContexts = function _initializeContexts() {
          var poseLayoutMaintainer = this._poseLayoutMaintainer;
          void poseLayoutMaintainer.endBind();
          this._createOrUpdateTransformFilters();
          var evaluationContext = poseLayoutMaintainer.createEvaluationContext();
          this._evaluationContext = evaluationContext;
          poseLayoutMaintainer.fetchDefaultTransforms(evaluationContext[defaultTransformsTag]);
          poseLayoutMaintainer.resetPoseStashAllocator(this._poseStashAllocator);
        };
        _proto._updateAfterPossiblePoseLayoutChange = function _updateAfterPossiblePoseLayoutChange() {
          var poseLayoutMaintainer = this._poseLayoutMaintainer;
          var layoutChangeFlags = poseLayoutMaintainer.endBind();
          if (layoutChangeFlags === 0) {
            return;
          }
          if (layoutChangeFlags & LayoutChangeFlag.TRANSFORM_COUNT || layoutChangeFlags & LayoutChangeFlag.TRANSFORM_ORDER) {
            this._createOrUpdateTransformFilters();
          }
          var evaluationContextRecreated = false;
          if (layoutChangeFlags & LayoutChangeFlag.TRANSFORM_COUNT || layoutChangeFlags & LayoutChangeFlag.AUXILIARY_CURVE_COUNT) {
            var evaluationContext = poseLayoutMaintainer.createEvaluationContext();
            this._evaluationContext.destroy();
            this._evaluationContext = evaluationContext;
            evaluationContextRecreated = true;
            poseLayoutMaintainer.resetPoseStashAllocator(this._poseStashAllocator);
          }
          if (evaluationContextRecreated || layoutChangeFlags & LayoutChangeFlag.TRANSFORM_COUNT || layoutChangeFlags & LayoutChangeFlag.TRANSFORM_ORDER) {
            poseLayoutMaintainer.fetchDefaultTransforms(this._evaluationContext[defaultTransformsTag]);
          }
        };
        _proto._createOrUpdateTransformFilters = function _createOrUpdateTransformFilters() {
          this._rootPoseNode.settle(this._settleContext);
        };
        _createClass(AnimationGraphEval, [{
          key: "layerCount",
          get: function get() {
            return this._rootPoseNode.layerCount;
          }
        }]);
        return AnimationGraphEval;
      }();

      var _dec$1C, _dec2$1p, _dec3$15, _class$1A, _class2$1w, _initializer$1p;
      var ccclass$p = ccclass$M,
        type$6 = type$d,
        serializable$6 = serializable$p,
        formerlySerializedAs = formerlySerializedAs$4;
      var AnimationController = (_dec$1C = ccclass$p('cc.animation.AnimationController'), _dec2$1p = type$6(AnimationGraphLike), _dec3$15 = formerlySerializedAs('graph'), _dec$1C(_class$1A = (_class2$1w = function (_Component) {
        _inheritsLoose(AnimationController, _Component);
        function AnimationController() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._graph = _initializer$1p && _initializer$1p();
          _this._graphEval = null;
          return _this;
        }
        var _proto = AnimationController.prototype;
        _proto.__preload = function __preload() {
          var graph = this.graph;
          if (graph) {
            var originalGraph;
            var clipOverrides = null;
            if (graph instanceof AnimationGraphVariant) {
              if (!graph.original) {
                return;
              }
              originalGraph = graph.original;
              clipOverrides = graph.clipOverrides;
            } else {
              assertIsTrue(graph instanceof AnimationGraph);
              originalGraph = graph;
            }
            var graphEval = new AnimationGraphEval(originalGraph, this.node, this, clipOverrides);
            this._graphEval = graphEval;
          }
        };
        _proto.onDestroy = function onDestroy() {
          var _this$_graphEval;
          (_this$_graphEval = this._graphEval) === null || _this$_graphEval === void 0 ? void 0 : _this$_graphEval.destroy();
        };
        _proto.update = function update(deltaTime) {
          var _this$_graphEval2;
          (_this$_graphEval2 = this._graphEval) === null || _this$_graphEval2 === void 0 ? void 0 : _this$_graphEval2.update(deltaTime);
        };
        _proto.getVariables = function getVariables() {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getVariables();
        };
        _proto.setValue = function setValue(name, value) {
          return this.setValue_experimental(name, value);
        };
        _proto.setValue_experimental = function setValue_experimental(name, value) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          graphEval.setValue(name, value);
        };
        _proto.getValue = function getValue(name) {
          var value = this.getValue_experimental(name);
          if (typeof value === 'object') {
            {
              warn("Obtaining variable \"" + name + "\" is not of primitive type, " + "which is currently supported experimentally and should be explicitly obtained through this.getValue_experimental()");
            }
            return undefined;
          } else {
            return value;
          }
        };
        _proto.getValue_experimental = function getValue_experimental(name) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getValue(name);
        };
        _proto.getCurrentStateStatus = function getCurrentStateStatus(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getCurrentStateStatus(layer);
        };
        _proto.getCurrentClipStatuses = function getCurrentClipStatuses(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getCurrentClipStatuses(layer);
        };
        _proto.getCurrentTransition = function getCurrentTransition(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getCurrentTransition(layer);
        };
        _proto.getNextStateStatus = function getNextStateStatus(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getNextStateStatus(layer);
        };
        _proto.getNextClipStatuses = function getNextClipStatuses(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getNextClipStatuses(layer);
        };
        _proto.getLayerWeight = function getLayerWeight(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getLayerWeight(layer);
        };
        _proto.setLayerWeight = function setLayerWeight(layer, weight) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.setLayerWeight(layer, weight);
        };
        _proto.overrideClips_experimental = function overrideClips_experimental(overrides) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          graphEval.overrideClips(overrides);
        };
        _proto.getAuxiliaryCurveValue_experimental = function getAuxiliaryCurveValue_experimental(curveName) {
          var graphEval = this._graphEval;
          if (!graphEval) {
            return 0.0;
          }
          return graphEval.getAuxiliaryCurveValue(curveName);
        };
        _createClass(AnimationController, [{
          key: "graph",
          get: function get() {
            return this._graph;
          },
          set: function set(value) {
            this._graph = value;
          }
        }, {
          key: "layerCount",
          get: function get() {
            var _this$_graphEval$laye, _this$_graphEval3;
            return (_this$_graphEval$laye = (_this$_graphEval3 = this._graphEval) === null || _this$_graphEval3 === void 0 ? void 0 : _this$_graphEval3.layerCount) !== null && _this$_graphEval$laye !== void 0 ? _this$_graphEval$laye : 0;
          }
        }]);
        return AnimationController;
      }(Component), (_applyDecoratedDescriptor(_class2$1w.prototype, "graph", [_dec2$1p], Object.getOwnPropertyDescriptor(_class2$1w.prototype, "graph"), _class2$1w.prototype), _initializer$1p = applyDecoratedInitializer(_class2$1w.prototype, "_graph", [serializable$6, _dec3$15], function () {
        return null;
      })), _class2$1w)) || _class$1A);

      var animation = /*#__PURE__*/Object.freeze({
        __proto__: null,
        UniformProxyFactory: UniformProxyFactory,
        MorphWeightValueProxy: MorphWeightValueProxy,
        MorphWeightsValueProxy: MorphWeightsValueProxy,
        MorphWeightsAllValueProxy: MorphWeightsAllValueProxy,
        Track: Track,
        TrackPath: TrackPath,
        RealTrack: RealTrack,
        VectorTrack: VectorTrack,
        QuatTrack: QuatTrack,
        ColorTrack: ColorTrack,
        SizeTrack: SizeTrack,
        ObjectTrack: ObjectTrack,
        isPropertyPath: isPropertyPath,
        isCustomPath: isCustomPath,
        HierarchyPath: HierarchyPath,
        ComponentPath: ComponentPath,
        CubicSplineVec2Value: CubicSplineVec2Value,
        CubicSplineVec3Value: CubicSplineVec3Value,
        CubicSplineVec4Value: CubicSplineVec4Value,
        CubicSplineQuatValue: CubicSplineQuatValue,
        CubicSplineNumberValue: CubicSplineNumberValue,
        AnimationController: AnimationController,
        get VariableType () { return VariableType; },
        StateMachineComponent: StateMachineComponent
      });
      exports('aq', animation);

      var BlendStateBuffer = function () {
        function BlendStateBuffer() {
          this._nodeBlendStates = new Map();
        }
        var _proto = BlendStateBuffer.prototype;
        _proto.createWriter = function createWriter(node, property, host, constants) {
          var propertyBlendState = this.ref(node, property);
          return new BlendStateWriterInternal(node, property, propertyBlendState, host, constants);
        };
        _proto.destroyWriter = function destroyWriter(writer) {
          var internal = writer;
          this.deRef(internal.node, internal.property);
        };
        _proto.ref = function ref(node, property) {
          var nodeBlendState = this._nodeBlendStates.get(node);
          if (!nodeBlendState) {
            nodeBlendState = this.createNodeBlendState();
            this._nodeBlendStates.set(node, nodeBlendState);
          }
          var propertyBlendState = nodeBlendState.refProperty(node, property);
          return propertyBlendState;
        };
        _proto.deRef = function deRef(node, property) {
          var nodeBlendState = this._nodeBlendStates.get(node);
          if (!nodeBlendState) {
            return;
          }
          nodeBlendState.deRefProperty(property);
          if (nodeBlendState.empty) {
            this._nodeBlendStates["delete"](node);
          }
        };
        _proto.apply = function apply() {
          this._nodeBlendStates.forEach(function (nodeBlendState, node) {
            nodeBlendState.apply(node);
          });
        };
        return BlendStateBuffer;
      }();
      var BlendStateWriterInternal = function () {
        function BlendStateWriterInternal(_node, _property, _propertyBlendState, _host, _constants) {
          this._node = _node;
          this._property = _property;
          this._propertyBlendState = _propertyBlendState;
          this._host = _host;
          this._constants = _constants;
        }
        var _proto2 = BlendStateWriterInternal.prototype;
        _proto2.getValue = function getValue() {
          return this._node[this._property];
        };
        _proto2.setValue = function setValue(value) {
          var propertyBlendState = this._propertyBlendState,
            host = this._host;
          var weight = host.weight;
          propertyBlendState.blend(value, weight);
        };
        _createClass(BlendStateWriterInternal, [{
          key: "node",
          get: function get() {
            return this._node;
          }
        }, {
          key: "property",
          get: function get() {
            return this._property;
          }
        }]);
        return BlendStateWriterInternal;
      }();
      var TransformApplyFlag;
      (function (TransformApplyFlag) {
        TransformApplyFlag[TransformApplyFlag["POSITION"] = 1] = "POSITION";
        TransformApplyFlag[TransformApplyFlag["ROTATION"] = 2] = "ROTATION";
        TransformApplyFlag[TransformApplyFlag["SCALE"] = 4] = "SCALE";
        TransformApplyFlag[TransformApplyFlag["EULER_ANGLES"] = 8] = "EULER_ANGLES";
      })(TransformApplyFlag || (TransformApplyFlag = {}));
      TransformApplyFlag.POSITION | TransformApplyFlag.ROTATION | TransformApplyFlag.SCALE | TransformApplyFlag.EULER_ANGLES;
      var LegacyVec3PropertyBlendState = function () {
        function LegacyVec3PropertyBlendState() {
          this.refCount = 0;
          this.accumulatedWeight = 0.0;
          this.result = new Vec3();
        }
        var _proto3 = LegacyVec3PropertyBlendState.prototype;
        _proto3.blend = function blend(value, weight) {
          this.accumulatedWeight = mixAveragedVec3(this.result, this.result, this.accumulatedWeight, value, weight);
        };
        _proto3.reset = function reset() {
          this.accumulatedWeight = 0.0;
          Vec3.zero(this.result);
        };
        return LegacyVec3PropertyBlendState;
      }();
      var LegacyQuatPropertyBlendState = function () {
        function LegacyQuatPropertyBlendState() {
          this.refCount = 0;
          this.accumulatedWeight = 0.0;
          this.result = new Quat();
        }
        var _proto4 = LegacyQuatPropertyBlendState.prototype;
        _proto4.blend = function blend(value, weight) {
          this.accumulatedWeight = mixAveragedQuat(this.result, this.result, this.accumulatedWeight, value, weight);
        };
        _proto4.reset = function reset() {
          this.accumulatedWeight = 0.0;
          Quat.identity(this.result);
        };
        return LegacyQuatPropertyBlendState;
      }();
      var NodeBlendState = function () {
        function NodeBlendState() {
          this._transformApplyFlags = 0;
          this._properties = {};
        }
        var _proto5 = NodeBlendState.prototype;
        _proto5.refProperty = function refProperty(node, property) {
          var _properties$property, _properties$property2;
          var properties = this._properties;
          var propertyBlendState;
          switch (property) {
            default:
            case 'position':
            case 'scale':
            case 'eulerAngles':
              propertyBlendState = (_properties$property = properties[property]) !== null && _properties$property !== void 0 ? _properties$property : properties[property] = this._createVec3BlendState(node[property]);
              break;
            case 'rotation':
              propertyBlendState = (_properties$property2 = properties[property]) !== null && _properties$property2 !== void 0 ? _properties$property2 : properties[property] = this._createQuatBlendState(node.rotation);
              break;
          }
          ++propertyBlendState.refCount;
          return propertyBlendState;
        };
        _proto5.deRefProperty = function deRefProperty(property) {
          var properties = this._properties;
          var propertyBlendState = properties[property];
          if (!propertyBlendState) {
            return;
          }
          --propertyBlendState.refCount;
          if (propertyBlendState.refCount > 0) {
            return;
          }
          delete properties[property];
        };
        _proto5.apply = function apply(node) {
          var transformApplyFlags = this._transformApplyFlags,
            _this$_properties = this._properties,
            position = _this$_properties.position,
            scale = _this$_properties.scale,
            rotation = _this$_properties.rotation,
            eulerAngles = _this$_properties.eulerAngles;
          if (!transformApplyFlags) {
            return;
          }
          var t;
          var s;
          var r;
          if (position && transformApplyFlags & TransformApplyFlag.POSITION) {
            t = position.result;
          }
          if (scale && transformApplyFlags & TransformApplyFlag.SCALE) {
            s = scale.result;
          }
          if (eulerAngles && transformApplyFlags & TransformApplyFlag.EULER_ANGLES) {
            r = eulerAngles.result;
          }
          if (rotation && transformApplyFlags & TransformApplyFlag.ROTATION) {
            r = rotation.result;
          }
          if (r || t || s) {
            node.setRTS(r, t, s);
          }
          this._transformApplyFlags = 0;
        };
        _createClass(NodeBlendState, [{
          key: "empty",
          get: function get() {
            var properties = this._properties;
            return !properties.position && !properties.rotation && !properties.eulerAngles && !properties.scale;
          }
        }]);
        return NodeBlendState;
      }();
      var LegacyNodeBlendState = function (_NodeBlendState) {
        _inheritsLoose(LegacyNodeBlendState, _NodeBlendState);
        function LegacyNodeBlendState() {
          return _NodeBlendState.apply(this, arguments) || this;
        }
        var _proto6 = LegacyNodeBlendState.prototype;
        _proto6.apply = function apply(node) {
          var _this$_properties2 = this._properties,
            position = _this$_properties2.position,
            scale = _this$_properties2.scale,
            rotation = _this$_properties2.rotation,
            eulerAngles = _this$_properties2.eulerAngles;
          if (position && position.accumulatedWeight) {
            this._transformApplyFlags |= TransformApplyFlag.POSITION;
            if (position.accumulatedWeight < 1.0) {
              position.blend(node.position, 1.0 - position.accumulatedWeight);
            }
          }
          if (scale && scale.accumulatedWeight) {
            this._transformApplyFlags |= TransformApplyFlag.SCALE;
            if (scale.accumulatedWeight < 1.0) {
              scale.blend(node.scale, 1.0 - scale.accumulatedWeight);
            }
          }
          if (eulerAngles && eulerAngles.accumulatedWeight) {
            this._transformApplyFlags |= TransformApplyFlag.EULER_ANGLES;
            if (eulerAngles.accumulatedWeight < 1.0) {
              eulerAngles.blend(node.eulerAngles, 1.0 - eulerAngles.accumulatedWeight);
            }
          }
          if (rotation && rotation.accumulatedWeight) {
            this._transformApplyFlags |= TransformApplyFlag.ROTATION;
            if (rotation.accumulatedWeight < 1.0) {
              rotation.blend(node.rotation, 1.0 - rotation.accumulatedWeight);
            }
          }
          _NodeBlendState.prototype.apply.call(this, node);
          position === null || position === void 0 ? void 0 : position.reset();
          scale === null || scale === void 0 ? void 0 : scale.reset();
          rotation === null || rotation === void 0 ? void 0 : rotation.reset();
          eulerAngles === null || eulerAngles === void 0 ? void 0 : eulerAngles.reset();
        };
        _proto6._createVec3BlendState = function _createVec3BlendState(_currentValue) {
          return new LegacyVec3PropertyBlendState();
        };
        _proto6._createQuatBlendState = function _createQuatBlendState(_currentValue) {
          return new LegacyQuatPropertyBlendState();
        };
        return LegacyNodeBlendState;
      }(NodeBlendState);
      var LegacyBlendStateBuffer = function (_BlendStateBuffer) {
        _inheritsLoose(LegacyBlendStateBuffer, _BlendStateBuffer);
        function LegacyBlendStateBuffer() {
          return _BlendStateBuffer.apply(this, arguments) || this;
        }
        var _proto7 = LegacyBlendStateBuffer.prototype;
        _proto7.createNodeBlendState = function createNodeBlendState() {
          return new LegacyNodeBlendState();
        };
        return LegacyBlendStateBuffer;
      }(BlendStateBuffer);
      function mixAveragedVec3(result, previous, accumulatedWeight, input, weight) {
        var newSum = accumulatedWeight + weight;
        if (weight === 1.0 && !accumulatedWeight) {
          Vec3.copy(result, input);
        } else if (newSum) {
          var t = weight / newSum;
          Vec3.lerp(result, result, input, t);
        }
        return newSum;
      }
      function mixAveragedQuat(result, previous, accumulatedWeight, input, weight) {
        var newSum = accumulatedWeight + weight;
        if (weight === 1.0 && !accumulatedWeight) {
          Quat.copy(result, input);
        } else if (newSum) {
          var t = weight / newSum;
          Quat.slerp(result, previous, input, t);
        }
        return newSum;
      }

      var _class$1z, _class2$1v;
      var AnimationManager = exports('az', ccclass$M(_class$1z = (_class2$1v = function (_System) {
        _inheritsLoose(AnimationManager, _System);
        function AnimationManager() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _System.call.apply(_System, [this].concat(args)) || this;
          _this._anims = new MutableForwardIterator([]);
          _this._crossFades = new MutableForwardIterator([]);
          _this._delayEvents = [];
          _this._blendStateBuffer = new LegacyBlendStateBuffer();
          _this._sockets = [];
          return _this;
        }
        var _proto = AnimationManager.prototype;
        _proto.addCrossFade = function addCrossFade(crossFade) {
          var index = this._crossFades.array.indexOf(crossFade);
          if (index === -1) {
            this._crossFades.push(crossFade);
          }
        };
        _proto.removeCrossFade = function removeCrossFade(crossFade) {
          var index = this._crossFades.array.indexOf(crossFade);
          if (index >= 0) {
            this._crossFades.fastRemoveAt(index);
          } else {
            errorID(3907);
          }
        };
        _proto.update = function update(dt) {
          var _delayEvents = this._delayEvents,
            crossFadesIter = this._crossFades,
            _sockets = this._sockets;
          {
            var crossFades = crossFadesIter.array;
            for (crossFadesIter.i = 0; crossFadesIter.i < crossFades.length; ++crossFadesIter.i) {
              var crossFade = crossFades[crossFadesIter.i];
              crossFade.update(dt);
            }
          }
          var iterator = this._anims;
          var array = iterator.array;
          for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
            var anim = array[iterator.i];
            if (!anim.isMotionless) {
              anim.update(dt);
            }
          }
          this._blendStateBuffer.apply();
          var stamp = director.getTotalFrames();
          for (var i = 0, l = _sockets.length; i < l; i++) {
            var _sockets$i = _sockets[i],
              target = _sockets$i.target,
              transform = _sockets$i.transform;
            target.matrix = getWorldMatrix(transform, stamp);
          }
          for (var _i = 0, _l = _delayEvents.length; _i < _l; _i++) {
            var event = _delayEvents[_i];
            event.fn.apply(event.thisArg, event.args);
          }
          _delayEvents.length = 0;
        };
        _proto.destruct = function destruct() {};
        _proto.addAnimation = function addAnimation(anim) {
          var index = this._anims.array.indexOf(anim);
          if (index === -1) {
            this._anims.push(anim);
          }
        };
        _proto.removeAnimation = function removeAnimation(anim) {
          var index = this._anims.array.indexOf(anim);
          if (index >= 0) {
            this._anims.fastRemoveAt(index);
          } else {
            errorID(3907);
          }
        };
        _proto.pushDelayEvent = function pushDelayEvent(fn, thisArg, args) {
          this._delayEvents.push({
            fn: fn,
            thisArg: thisArg,
            args: args
          });
        };
        _proto.addSockets = function addSockets(root, sockets) {
          var _this2 = this;
          var _loop = function _loop() {
            var socket = sockets[i];
            if (_this2._sockets.find(function (s) {
              return s.target === socket.target;
            })) {
              return 1;
            }
            var targetNode = root.getChildByPath(socket.path);
            var transform = socket.target && targetNode && getTransform(targetNode, root);
            if (transform) {
              _this2._sockets.push({
                target: socket.target,
                transform: transform
              });
            }
          };
          for (var i = 0; i < sockets.length; ++i) {
            if (_loop()) continue;
          }
        };
        _proto.removeSockets = function removeSockets(root, sockets) {
          for (var i = 0; i < sockets.length; ++i) {
            var socketToRemove = sockets[i];
            for (var j = 0; j < this._sockets.length; ++j) {
              var socket = this._sockets[j];
              if (socket.target === socketToRemove.target) {
                deleteTransform(socket.transform.node);
                this._sockets[j] = this._sockets[this._sockets.length - 1];
                this._sockets.length--;
                break;
              }
            }
          }
        };
        _createClass(AnimationManager, [{
          key: "blendState",
          get: function get() {
            return this._blendStateBuffer;
          }
        }]);
        return AnimationManager;
      }(System), _class2$1v.ID = 'animation', _class2$1v)) || _class$1z);
      director.on(Director.EVENT_INIT, function () {
        var animationManager = new AnimationManager();
        director.registerSystem(AnimationManager.ID, animationManager, System.Priority.HIGH);
      });
      legacyCC.AnimationManager = AnimationManager;

      var CrossFade = function (_Playable) {
        _inheritsLoose(CrossFade, _Playable);
        function CrossFade(scheduler) {
          var _this;
          _this = _Playable.call(this) || this;
          _this._managedStates = [];
          _this._fadings = [];
          _this._scheduled = false;
          _this._scheduler = scheduler !== null && scheduler !== void 0 ? scheduler : getGlobalAnimationManager();
          return _this;
        }
        var _proto = CrossFade.prototype;
        _proto.update = function update(deltaTime) {
          if (this.isMotionless) {
            return;
          }
          var managedStates = this._managedStates;
          var fadings = this._fadings;
          if (managedStates.length === 1 && fadings.length === 1) {
            var state = managedStates[0].state;
            if (state) {
              state.weight = 1.0;
            }
          } else {
            this._calculateWeights(deltaTime);
          }
          if (managedStates.length === 1 && fadings.length === 1) {
            this._unscheduleThis();
          }
        };
        _proto.crossFade = function crossFade(state, duration) {
          var _target$state;
          if (this._managedStates.length === 0) {
            duration = 0;
          }
          if (duration === 0) {
            this.clear();
          }
          var target = this._managedStates.find(function (weightedState) {
            return weightedState.state === state;
          });
          if (!target) {
            target = {
              state: state,
              reference: 0
            };
            if (state) {
              state.play();
            }
            this._managedStates.push(target);
          } else if ((_target$state = target.state) !== null && _target$state !== void 0 && _target$state.isMotionless) {
            target.state.play();
          }
          ++target.reference;
          this._fadings.unshift({
            easeDuration: duration,
            easeTime: 0,
            target: target
          });
          if (!this.isMotionless) {
            this._scheduleThis();
          }
        };
        _proto.clear = function clear() {
          for (var iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
            var state = this._managedStates[iManagedState].state;
            if (state) {
              state.stop();
            }
          }
          this._managedStates.length = 0;
          this._fadings.length = 0;
        };
        _proto.onPlay = function onPlay() {
          _Playable.prototype.onPlay.call(this);
          this._scheduleThis();
        };
        _proto.onPause = function onPause() {
          _Playable.prototype.onPause.call(this);
          for (var iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
            var state = this._managedStates[iManagedState].state;
            if (state) {
              state.pause();
            }
          }
          this._unscheduleThis();
        };
        _proto.onResume = function onResume() {
          _Playable.prototype.onResume.call(this);
          for (var iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
            var state = this._managedStates[iManagedState].state;
            if (state) {
              state.resume();
            }
          }
          this._scheduleThis();
        };
        _proto.onStop = function onStop() {
          _Playable.prototype.onStop.call(this);
          this.clear();
        };
        _proto._calculateWeights = function _calculateWeights(deltaTime) {
          var managedStates = this._managedStates;
          var fadings = this._fadings;
          for (var iManagedState = 0; iManagedState < managedStates.length; ++iManagedState) {
            var state = managedStates[iManagedState].state;
            if (state) {
              state.weight = 0;
            }
          }
          var absoluteWeight = 1.0;
          var deadFadingBegin = fadings.length;
          for (var iFading = 0; iFading < fadings.length; ++iFading) {
            var fading = fadings[iFading];
            fading.easeTime += deltaTime;
            var relativeWeight = fading.easeDuration === 0 ? 1 : clamp01(fading.easeTime / fading.easeDuration);
            var weight = relativeWeight * absoluteWeight;
            absoluteWeight *= 1.0 - relativeWeight;
            if (fading.target.state) {
              fading.target.state.weight += weight;
            }
            if (fading.easeTime >= fading.easeDuration) {
              deadFadingBegin = iFading + 1;
              fading.easeTime = fading.easeDuration;
              break;
            }
          }
          if (deadFadingBegin !== fadings.length) {
            for (var iDeadFading = deadFadingBegin; iDeadFading < fadings.length; ++iDeadFading) {
              var deadFading = fadings[iDeadFading];
              --deadFading.target.reference;
              if (deadFading.target.reference <= 0) {
                if (deadFading.target.state) {
                  deadFading.target.state.stop();
                }
                remove(this._managedStates, deadFading.target);
              }
            }
            fadings.splice(deadFadingBegin);
          }
        };
        _proto._scheduleThis = function _scheduleThis() {
          if (!this._scheduled) {
            this._scheduler.addCrossFade(this);
            this._scheduled = true;
          }
        };
        _proto._unscheduleThis = function _unscheduleThis() {
          if (this._scheduled) {
            this._scheduler.removeCrossFade(this);
            this._scheduled = false;
          }
        };
        return CrossFade;
      }(Playable);

      var _dec$1B, _dec2$1o, _dec3$14, _dec4$Q, _dec5$M, _class$1y, _class2$1u, _initializer$1o, _initializer2$1f, _initializer3$_, _class3$w;
      var Animation$2 = exports('at', (_dec$1B = ccclass$M('cc.Animation'), _dec2$1o = executionOrder$1(99), _dec3$14 = type$d([AnimationClip]), _dec4$Q = type$d(AnimationClip), _dec5$M = type$d([AnimationClip]), _dec$1B(_class$1y = _dec2$1o(_class$1y = (_class2$1u = (_class3$w = function (_Eventify) {
        _inheritsLoose(Animation, _Eventify);
        function Animation() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Eventify.call.apply(_Eventify, [this].concat(args)) || this;
          _this.playOnLoad = _initializer$1o && _initializer$1o();
          _this._crossFade = new CrossFade();
          _this._nameToState = createMap(true);
          _this._clips = _initializer2$1f && _initializer2$1f();
          _this._defaultClip = _initializer3$_ && _initializer3$_();
          _this._hasBeenPlayed = false;
          return _this;
        }
        var _proto = Animation.prototype;
        _proto.onLoad = function onLoad() {
          this.clips = this._clips;
          for (var stateName in this._nameToState) {
            var state = this._nameToState[stateName];
            state.initialize(this.node);
          }
        };
        _proto.start = function start() {
          if (this.playOnLoad && !this._hasBeenPlayed && this._defaultClip) {
            this.crossFade(this._defaultClip.name, 0);
          }
        };
        _proto.onEnable = function onEnable() {
          this._crossFade.resume();
        };
        _proto.onDisable = function onDisable() {
          this._crossFade.pause();
        };
        _proto.onDestroy = function onDestroy() {
          this._crossFade.stop();
          for (var name in this._nameToState) {
            var state = this._nameToState[name];
            state.destroy();
          }
          this._nameToState = createMap(true);
        };
        _proto.play = function play(name) {
          this._hasBeenPlayed = true;
          if (!name) {
            if (!this._defaultClip) {
              return;
            }
            name = this._defaultClip.name;
          }
          this.crossFade(name, 0);
        };
        _proto.crossFade = function crossFade(name, duration) {
          if (duration === void 0) {
            duration = 0.3;
          }
          this._hasBeenPlayed = true;
          var state = this._nameToState[name];
          if (state) {
            this.doPlayOrCrossFade(state, duration);
          }
        };
        _proto.pause = function pause() {
          this._crossFade.pause();
        };
        _proto.resume = function resume() {
          this._crossFade.resume();
        };
        _proto.stop = function stop() {
          this._crossFade.stop();
        };
        _proto.getState = function getState(name) {
          var state = this._nameToState[name];
          if (state && !state.curveLoaded) {
            state.initialize(this.node);
          }
          return state || null;
        };
        _proto.createState = function createState(clip, name) {
          name = name || clip.name;
          this.removeState(name);
          return this._doCreateState(clip, name);
        };
        _proto.removeState = function removeState(name) {
          var state = this._nameToState[name];
          if (state) {
            state.allowLastFrameEvent(false);
            state.stop();
            delete this._nameToState[name];
          }
        };
        _proto.addClip = function addClip(clip, name) {
          if (!contains$2(this._clips, clip)) {
            this._clips.push(clip);
          }
          return this.createState(clip, name);
        };
        _proto.removeClip = function removeClip(clip, force) {
          var removalState;
          for (var name in this._nameToState) {
            var state = this._nameToState[name];
            var stateClip = state.clip;
            if (stateClip === clip) {
              removalState = state;
              break;
            }
          }
          if (clip === this._defaultClip) {
            if (force) {
              this._defaultClip = null;
            } else {
              {
                warnID(3902);
              }
              return;
            }
          }
          if (removalState && removalState.isPlaying) {
            if (force) {
              removalState.stop();
            } else {
              {
                warnID(3903);
              }
              return;
            }
          }
          this._clips = this._clips.filter(function (item) {
            return item !== clip;
          });
          if (removalState) {
            delete this._nameToState[removalState.name];
          }
        };
        _proto.on = function on(type, callback, thisArg, once) {
          var ret = _Eventify.prototype.on.call(this, type, callback, thisArg, once);
          if (type === EventType$8.LASTFRAME) {
            this._syncAllowLastFrameEvent();
          }
          return ret;
        };
        _proto.once = function once(type, callback, thisArg) {
          var ret = _Eventify.prototype.once.call(this, type, callback, thisArg);
          if (type === EventType$8.LASTFRAME) {
            this._syncAllowLastFrameEvent();
          }
          return ret;
        };
        _proto.off = function off(type, callback, thisArg) {
          _Eventify.prototype.off.call(this, type, callback, thisArg);
          if (type === EventType$8.LASTFRAME) {
            this._syncDisallowLastFrameEvent();
          }
        };
        _proto._createState = function _createState(clip, name) {
          return new AnimationState$1(clip, name);
        };
        _proto._doCreateState = function _doCreateState(clip, name) {
          var state = this._createState(clip, name);
          state._setEventTarget(this);
          state.allowLastFrameEvent(this.hasEventListener(EventType$8.LASTFRAME));
          if (this.node) {
            state.initialize(this.node);
          }
          this._nameToState[state.name] = state;
          return state;
        };
        _proto.doPlayOrCrossFade = function doPlayOrCrossFade(state, duration) {
          this._crossFade.play();
          this._crossFade.crossFade(state, duration);
        };
        _proto._removeStateOfAutomaticClip = function _removeStateOfAutomaticClip(clip) {
          for (var name in this._nameToState) {
            var state = this._nameToState[name];
            if (equalClips(clip, state.clip)) {
              state.stop();
              delete this._nameToState[name];
            }
          }
        };
        _proto._syncAllowLastFrameEvent = function _syncAllowLastFrameEvent() {
          if (this.hasEventListener(EventType$8.LASTFRAME)) {
            for (var stateName in this._nameToState) {
              this._nameToState[stateName].allowLastFrameEvent(true);
            }
          }
        };
        _proto._syncDisallowLastFrameEvent = function _syncDisallowLastFrameEvent() {
          if (!this.hasEventListener(EventType$8.LASTFRAME)) {
            for (var stateName in this._nameToState) {
              this._nameToState[stateName].allowLastFrameEvent(false);
            }
          }
        };
        _createClass(Animation, [{
          key: "clips",
          get: function get() {
            return this._clips;
          },
          set: function set(value) {
            var _this2 = this;
            if (this._crossFade) {
              this._crossFade.clear();
            }
            for (var _iterator = _createForOfIteratorHelperLoose(this._clips), _step; !(_step = _iterator()).done;) {
              var clip = _step.value;
              if (clip) {
                this._removeStateOfAutomaticClip(clip);
              }
            }
            for (var _iterator2 = _createForOfIteratorHelperLoose(value), _step2; !(_step2 = _iterator2()).done;) {
              var _clip = _step2.value;
              if (_clip) {
                this.createState(_clip);
              }
            }
            var newDefaultClip = value.find(function (clip) {
              return equalClips(clip, _this2._defaultClip);
            });
            if (newDefaultClip) {
              this._defaultClip = newDefaultClip;
            } else {
              this._defaultClip = null;
            }
            this._clips = value;
          }
        }, {
          key: "defaultClip",
          get: function get() {
            return this._defaultClip;
          },
          set: function set(value) {
            this._defaultClip = value;
            if (!value) {
              return;
            }
            var isBoundedDefaultClip = this._clips.findIndex(function (clip) {
              return equalClips(clip, value);
            }) >= 0;
            if (!isBoundedDefaultClip) {
              this._clips.push(value);
              this.createState(value);
            }
          }
        }]);
        return Animation;
      }(Eventify(Component)), _class3$w.EventType = EventType$8, _class3$w), (_applyDecoratedDescriptor(_class2$1u.prototype, "clips", [_dec3$14], Object.getOwnPropertyDescriptor(_class2$1u.prototype, "clips"), _class2$1u.prototype), _applyDecoratedDescriptor(_class2$1u.prototype, "defaultClip", [_dec4$Q], Object.getOwnPropertyDescriptor(_class2$1u.prototype, "defaultClip"), _class2$1u.prototype), _initializer$1o = applyDecoratedInitializer(_class2$1u.prototype, "playOnLoad", [serializable$p], function () {
        return false;
      }), _initializer2$1f = applyDecoratedInitializer(_class2$1u.prototype, "_clips", [_dec5$M], function () {
        return [];
      }), _initializer3$_ = applyDecoratedInitializer(_class2$1u.prototype, "_defaultClip", [serializable$p], function () {
        return null;
      })), _class2$1u)) || _class$1y) || _class$1y));
      function equalClips(clip1, clip2) {
        if (clip1 === clip2) {
          return true;
        }
        return !!clip1 && !!clip2 && clip1._uuid === clip2._uuid && clip1._uuid;
      }
      legacyCC.Animation = Animation$2;
      legacyCC.AnimationComponent = Animation$2;
      setClassAlias(Animation$2, 'cc.AnimationComponent');

      var AudioEvent;
      (function (AudioEvent) {
        AudioEvent["PLAYED"] = "play";
        AudioEvent["PAUSED"] = "pause";
        AudioEvent["STOPPED"] = "stop";
        AudioEvent["SEEKED"] = "seeked";
        AudioEvent["ENDED"] = "ended";
        AudioEvent["INTERRUPTION_BEGIN"] = "interruptionBegin";
        AudioEvent["INTERRUPTION_END"] = "interruptionEnd";
        AudioEvent["USER_GESTURE"] = "on_gesture";
      })(AudioEvent || (AudioEvent = {}));
      var AudioType;
      (function (AudioType) {
        AudioType[AudioType["DOM_AUDIO"] = 0] = "DOM_AUDIO";
        AudioType[AudioType["WEB_AUDIO"] = 1] = "WEB_AUDIO";
        AudioType[AudioType["MINIGAME_AUDIO"] = 2] = "MINIGAME_AUDIO";
        AudioType[AudioType["NATIVE_AUDIO"] = 3] = "NATIVE_AUDIO";
        AudioType[AudioType["UNKNOWN_AUDIO"] = 4] = "UNKNOWN_AUDIO";
      })(AudioType || (AudioType = {}));
      var AudioState;
      (function (AudioState) {
        AudioState[AudioState["INIT"] = 0] = "INIT";
        AudioState[AudioState["PLAYING"] = 1] = "PLAYING";
        AudioState[AudioState["PAUSED"] = 2] = "PAUSED";
        AudioState[AudioState["STOPPED"] = 3] = "STOPPED";
        AudioState[AudioState["INTERRUPTED"] = 4] = "INTERRUPTED";
      })(AudioState || (AudioState = {}));
      var AudioPCMDataView = exports('aE', function () {
        function AudioPCMDataView() {
          this._bufferView = void 0;
          this._normalizeFactor = 1;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          if (args.length === 2) {
            this._bufferView = args[0];
            this._normalizeFactor = args[1];
          } else {
            var _arrayBuffer = args[0];
            var _Ctor = args[1];
            var _normalizeFactor = args[2];
            this._bufferView = new _Ctor(_arrayBuffer);
            this._normalizeFactor = _normalizeFactor;
          }
        }
        var _proto = AudioPCMDataView.prototype;
        _proto.getData = function getData(offset) {
          return this._bufferView[offset] * this._normalizeFactor;
        };
        _createClass(AudioPCMDataView, [{
          key: "length",
          get: function get() {
            return this._bufferView.length;
          }
        }]);
        return AudioPCMDataView;
      }());

      function removeUnneededCalls(instance) {
        var size = instance._operationQueue.length;
        var tmpQueue = instance._operationQueue.slice();
        var reserveOps = [];
        var seekSearched = false;
        for (var i = size - 1; i >= 0; i--) {
          var opInfo = tmpQueue[i];
          if (opInfo.op === 'stop') {
            reserveOps.push(opInfo);
            break;
          } else if (opInfo.op === 'seek') {
            if (!seekSearched) {
              reserveOps.push(opInfo);
              seekSearched = true;
            }
          } else if (seekSearched) {
            reserveOps.push(opInfo);
            break;
          } else if (reserveOps.length === 0) {
            reserveOps.push(opInfo);
          }
        }
        instance._operationQueue = reserveOps.reverse();
      }
      var operationId = 0;
      function _tryCallingRecursively(target, opInfo) {
        var _opInfo$func;
        if (opInfo.invoking) {
          return;
        }
        opInfo.invoking = true;
        (_opInfo$func = opInfo.func).call.apply(_opInfo$func, [target].concat(opInfo.args)).then(function () {
          opInfo.invoking = false;
          target._operationQueue.shift();
          target._eventTarget.emit(opInfo.id.toString());
          removeUnneededCalls(target);
          var nextOpInfo = target._operationQueue[0];
          if (nextOpInfo) {
            _tryCallingRecursively(target, nextOpInfo);
          }
        })["catch"](function (e) {});
      }
      function enqueueOperation(target, propertyKey, descriptor) {
        var originalOperation = descriptor.value;
        descriptor.value = function () {
          var _this = this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          return new Promise(function (resolve) {
            var id = operationId++;
            var instance = _this;
            instance._operationQueue.push({
              op: propertyKey,
              id: id,
              func: originalOperation,
              args: args,
              invoking: false
            });
            instance._eventTarget.once(id.toString(), resolve);
            var opInfo = instance._operationQueue[0];
            _tryCallingRecursively(instance, opInfo);
          });
        };
      }

      var _class2$1t;
      function ensurePlaying(domAudio) {
        return new Promise(function (resolve) {
          var promise = domAudio.play();
          if (promise === undefined) {
            return resolve();
          }
          promise.then(resolve)["catch"](function () {
            var onGesture = function onGesture() {
              domAudio.play().then(function () {
                canvas === null || canvas === void 0 ? void 0 : canvas.removeEventListener('touchend', onGesture, {
                  capture: true
                });
                canvas === null || canvas === void 0 ? void 0 : canvas.removeEventListener('mouseup', onGesture, {
                  capture: true
                });
              })["catch"](function (e) {});
              resolve();
            };
            var canvas = document.getElementById('GameCanvas');
            canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('touchend', onGesture, {
              capture: true
            });
            canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('mouseup', onGesture, {
              capture: true
            });
          });
          return null;
        });
      }
      var OneShotAudioDOM = function () {
        function OneShotAudioDOM(nativeAudio, volume) {
          this._domAudio = void 0;
          this._onPlayCb = void 0;
          this._onEndCb = void 0;
          this._domAudio = nativeAudio;
          nativeAudio.volume = volume;
        }
        var _proto = OneShotAudioDOM.prototype;
        _proto.play = function play() {
          var _this = this;
          ensurePlaying(this._domAudio).then(function () {
            var _this$onPlay;
            (_this$onPlay = _this.onPlay) === null || _this$onPlay === void 0 ? void 0 : _this$onPlay.call(_this);
          })["catch"](function (e) {});
        };
        _proto.stop = function stop() {
          this._domAudio.pause();
        };
        _createClass(OneShotAudioDOM, [{
          key: "onPlay",
          get: function get() {
            return this._onPlayCb;
          },
          set: function set(cb) {
            this._onPlayCb = cb;
          }
        }, {
          key: "onEnd",
          get: function get() {
            return this._onEndCb;
          },
          set: function set(cb) {
            if (this._onEndCb) {
              this._domAudio.removeEventListener('ended', this._onEndCb);
            }
            this._onEndCb = cb;
            if (cb) {
              this._domAudio.addEventListener('ended', cb);
            }
          }
        }]);
        return OneShotAudioDOM;
      }();
      var AudioPlayerDOM = (_class2$1t = function () {
        function AudioPlayerDOM(nativeAudio) {
          var _this2 = this;
          this._domAudio = void 0;
          this._state = AudioState.INIT;
          this._onEnded = void 0;
          this._eventTarget = new EventTarget();
          this._operationQueue = [];
          this._domAudio = nativeAudio;
          game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
          game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this);
          this._onEnded = function () {
            _this2.seek(0)["catch"](function (e) {});
            _this2._state = AudioState.INIT;
            _this2._eventTarget.emit(AudioEvent.ENDED);
          };
          this._domAudio.addEventListener('ended', this._onEnded);
        }
        var _proto2 = AudioPlayerDOM.prototype;
        _proto2.destroy = function destroy() {
          game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
          game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this);
          this._domAudio.removeEventListener('ended', this._onEnded);
          this._domAudio = null;
        };
        AudioPlayerDOM.load = function load(url) {
          return new Promise(function (resolve, reject) {
            AudioPlayerDOM.loadNative(url).then(function (domAudio) {
              resolve(new AudioPlayerDOM(domAudio));
            })["catch"](reject);
          });
        };
        AudioPlayerDOM.loadNative = function loadNative(url) {
          return new Promise(function (resolve, reject) {
            var domAudio = document.createElement('audio');
            var loadedEvent = 'canplaythrough';
            if (systemInfo.os === OS.IOS) {
              loadedEvent = 'loadedmetadata';
            } else if (systemInfo.browserType === BrowserType.FIREFOX) {
              loadedEvent = 'canplay';
            }
            var timer = setTimeout(function () {
              if (domAudio.readyState === 0) {
                failure();
              } else {
                success();
              }
            }, 8000);
            var clearEvent = function clearEvent() {
              clearTimeout(timer);
              domAudio.removeEventListener(loadedEvent, success, false);
              domAudio.removeEventListener('error', failure, false);
            };
            var success = function success() {
              clearEvent();
              resolve(domAudio);
            };
            var failure = function failure() {
              clearEvent();
              var message = "load audio failure - " + url;
              reject(new Error(message));
            };
            domAudio.addEventListener(loadedEvent, success, false);
            domAudio.addEventListener('error', failure, false);
            domAudio.src = url;
          });
        };
        AudioPlayerDOM.loadOneShotAudio = function loadOneShotAudio(url, volume) {
          return new Promise(function (resolve, reject) {
            AudioPlayerDOM.loadNative(url).then(function (domAudio) {
              var oneShotAudio = new OneShotAudioDOM(domAudio, volume);
              resolve(oneShotAudio);
            })["catch"](reject);
          });
        };
        _proto2._onInterruptedBegin = function _onInterruptedBegin() {
          var _this3 = this;
          if (this._state === AudioState.PLAYING) {
            this.pause().then(function () {
              _this3._state = AudioState.INTERRUPTED;
              _this3._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
            })["catch"](function (e) {});
          }
        };
        _proto2._onInterruptedEnd = function _onInterruptedEnd() {
          var _this4 = this;
          if (this._state === AudioState.INTERRUPTED) {
            this.play().then(function () {
              _this4._eventTarget.emit(AudioEvent.INTERRUPTION_END);
            })["catch"](function (e) {});
          }
        };
        _proto2.getPCMData = function getPCMData(channelIndex) {
          return undefined;
        };
        _proto2.seek = function seek(time) {
          time = clamp$1(time, 0, this.duration);
          this._domAudio.currentTime = time;
          return Promise.resolve();
        };
        _proto2.play = function play() {
          var _this5 = this;
          return new Promise(function (resolve) {
            ensurePlaying(_this5._domAudio).then(function () {
              _this5._state = AudioState.PLAYING;
              resolve();
            })["catch"](function (e) {});
          });
        };
        _proto2.pause = function pause() {
          this._domAudio.pause();
          this._state = AudioState.PAUSED;
          return Promise.resolve();
        };
        _proto2.stop = function stop() {
          var _this6 = this;
          return new Promise(function (resolve) {
            _this6._domAudio.pause();
            _this6._domAudio.currentTime = 0;
            _this6._state = AudioState.STOPPED;
            resolve();
          });
        };
        _proto2.onInterruptionBegin = function onInterruptionBegin(cb) {
          this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb);
        };
        _proto2.offInterruptionBegin = function offInterruptionBegin(cb) {
          this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb);
        };
        _proto2.onInterruptionEnd = function onInterruptionEnd(cb) {
          this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb);
        };
        _proto2.offInterruptionEnd = function offInterruptionEnd(cb) {
          this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb);
        };
        _proto2.onEnded = function onEnded(cb) {
          this._eventTarget.on(AudioEvent.ENDED, cb);
        };
        _proto2.offEnded = function offEnded(cb) {
          this._eventTarget.off(AudioEvent.ENDED, cb);
        };
        _createClass(AudioPlayerDOM, [{
          key: "src",
          get: function get() {
            return this._domAudio ? this._domAudio.src : '';
          }
        }, {
          key: "type",
          get: function get() {
            return AudioType.DOM_AUDIO;
          }
        }, {
          key: "state",
          get: function get() {
            return this._state;
          }
        }, {
          key: "loop",
          get: function get() {
            return this._domAudio.loop;
          },
          set: function set(val) {
            this._domAudio.loop = val;
          }
        }, {
          key: "volume",
          get: function get() {
            return this._domAudio.volume;
          },
          set: function set(val) {
            val = clamp01(val);
            this._domAudio.volume = val;
          }
        }, {
          key: "duration",
          get: function get() {
            return this._domAudio.duration;
          }
        }, {
          key: "currentTime",
          get: function get() {
            return this._domAudio.currentTime;
          }
        }, {
          key: "sampleRate",
          get: function get() {
            return 0;
          }
        }]);
        return AudioPlayerDOM;
      }(), (_applyDecoratedDescriptor(_class2$1t.prototype, "seek", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$1t.prototype, "seek"), _class2$1t.prototype), _applyDecoratedDescriptor(_class2$1t.prototype, "play", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$1t.prototype, "play"), _class2$1t.prototype), _applyDecoratedDescriptor(_class2$1t.prototype, "pause", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$1t.prototype, "pause"), _class2$1t.prototype), _applyDecoratedDescriptor(_class2$1t.prototype, "stop", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$1t.prototype, "stop"), _class2$1t.prototype)), _class2$1t);

      var AudioTimer = function () {
        function AudioTimer(nativeAudio) {
          this._nativeAudio = void 0;
          this._startTime = 0;
          this._startOffset = 0;
          this._isPaused = true;
          this._nativeAudio = nativeAudio;
        }
        var _proto = AudioTimer.prototype;
        _proto.destroy = function destroy() {
          this._nativeAudio = undefined;
        };
        _proto._now = function _now() {
          return performance.now() / 1000;
        };
        _proto._calculateCurrentTime = function _calculateCurrentTime() {
          var timePassed = this._now() - this._startTime;
          var currentTime = this._startOffset + timePassed;
          if (currentTime >= this.duration) {
            this._startTime = this._now();
            this._startOffset = 0;
          }
          return currentTime % this.duration;
        };
        _proto.start = function start() {
          this._isPaused = false;
          this._startTime = this._now();
        };
        _proto.pause = function pause() {
          if (this._isPaused) {
            return;
          }
          this._isPaused = true;
          this._startOffset = this._calculateCurrentTime();
        };
        _proto.stop = function stop() {
          this._isPaused = true;
          this._startOffset = 0;
        };
        _proto.seek = function seek(time) {
          this._startTime = this._now();
          this._startOffset = clamp$1(time, 0, this.duration);
        };
        _createClass(AudioTimer, [{
          key: "duration",
          get: function get() {
            return this._nativeAudio.duration;
          }
        }, {
          key: "currentTime",
          get: function get() {
            if (this._isPaused) {
              return this._startOffset;
            } else {
              return this._calculateCurrentTime();
            }
          }
        }]);
        return AudioTimer;
      }();

      var AudioBufferManager = function () {
        function AudioBufferManager() {
          this._audioBufferDataMap = {};
        }
        var _proto = AudioBufferManager.prototype;
        _proto.addCache = function addCache(url, audioBuffer) {
          var audioBufferData = this._audioBufferDataMap[url];
          if (audioBufferData) {
            console.warn("Audio buffer " + url + " has been cached");
            return;
          }
          this._audioBufferDataMap[url] = {
            usedCount: 1,
            audioBuffer: audioBuffer
          };
        };
        _proto.retainCache = function retainCache(url) {
          var audioBufferData = this._audioBufferDataMap[url];
          if (!audioBufferData) {
            console.warn("Audio buffer cache " + url + " has not been added.");
            return;
          }
          audioBufferData.usedCount++;
        };
        _proto.getCache = function getCache(url) {
          var audioBufferData = this._audioBufferDataMap[url];
          return audioBufferData === null || audioBufferData === void 0 ? void 0 : audioBufferData.audioBuffer;
        };
        _proto.tryReleasingCache = function tryReleasingCache(url) {
          var audioBufferData = this._audioBufferDataMap[url];
          if (!audioBufferData) {
            console.warn("Audio buffer cache " + url + " has not been added.");
            return;
          }
          if (--audioBufferData.usedCount <= 0) {
            delete this._audioBufferDataMap[url];
          }
        };
        return AudioBufferManager;
      }();
      var audioBufferManager = new AudioBufferManager();

      var _class3$v;
      var AudioContextClass = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;
      var _contextRunningEvent = 'on-context-running';
      var AudioContextAgent = function () {
        function AudioContextAgent() {
          var _this = this;
          this._eventTarget = void 0;
          this._context = void 0;
          this._isRunning = false;
          this._context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
          this._eventTarget = new EventTarget();
          this._context.onstatechange = function () {
            if (_this._context.state === 'running') {
              _this._isRunning = true;
              _this._eventTarget.emit(_contextRunningEvent);
            } else {
              _this._isRunning = false;
            }
          };
        }
        var _proto = AudioContextAgent.prototype;
        _proto.onceRunning = function onceRunning(cb, target) {
          this._eventTarget.once(_contextRunningEvent, cb, target);
        };
        _proto.offRunning = function offRunning(cb, target) {
          this._eventTarget.off(_contextRunningEvent, cb, target);
        };
        _proto.decodeAudioData = function decodeAudioData(audioData) {
          var _this2 = this;
          return new Promise(function (resolve, reject) {
            var promise = _this2._context.decodeAudioData(audioData, function (audioBuffer) {
              resolve(audioBuffer);
            }, function (err) {
              console.error('failed to load Web Audio', err);
            });
            promise === null || promise === void 0 ? void 0 : promise["catch"](reject);
          });
        };
        _proto.runContext = function runContext() {
          var _this3 = this;
          return new Promise(function (resolve) {
            if (_this3.isRunning) {
              resolve();
              return;
            }
            var context = _this3._context;
            if (!context.resume) {
              resolve();
              return;
            }
            context.resume()["catch"](function (e) {
              warn('runContext error', e);
            });
            if (context.state === 'running') {
              resolve();
              return;
            }
            var canvas = document.getElementById('GameCanvas');
            var onGesture = function onGesture() {
              context.resume().then(function () {
                canvas === null || canvas === void 0 ? void 0 : canvas.removeEventListener('touchend', onGesture, {
                  capture: true
                });
                canvas === null || canvas === void 0 ? void 0 : canvas.removeEventListener('mouseup', onGesture, {
                  capture: true
                });
                resolve();
              })["catch"](function (e) {
                warn('onGesture resume error', e);
              });
            };
            canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('touchend', onGesture, {
              capture: true
            });
            canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('mouseup', onGesture, {
              capture: true
            });
          });
        };
        _proto.createBufferSource = function createBufferSource(audioBuffer, loop) {
          var sourceBufferNode = this._context.createBufferSource();
          if (audioBuffer !== undefined) {
            sourceBufferNode.buffer = audioBuffer;
          }
          if (loop !== undefined) {
            sourceBufferNode.loop = loop;
          }
          return sourceBufferNode;
        };
        _proto.createGain = function createGain(volume) {
          if (volume === void 0) {
            volume = 1;
          }
          var gainNode = this._context.createGain();
          this.setGainValue(gainNode, volume);
          return gainNode;
        };
        _proto.setGainValue = function setGainValue(gain, volume) {
          if (gain.gain.setTargetAtTime) {
            try {
              gain.gain.setTargetAtTime(volume, this._context.currentTime, 0);
            } catch (e) {
              gain.gain.setTargetAtTime(volume, this._context.currentTime, 0.01);
            }
          } else {
            gain.gain.value = volume;
          }
        };
        _proto.connectContext = function connectContext(audioNode) {
          if (!this._context) {
            return;
          }
          audioNode.connect(this._context.destination);
        };
        _createClass(AudioContextAgent, [{
          key: "isRunning",
          get: function get() {
            return this._isRunning;
          }
        }, {
          key: "currentTime",
          get: function get() {
            return this._context.currentTime;
          }
        }]);
        return AudioContextAgent;
      }();
      AudioContextAgent.support = !!AudioContextClass;
      var audioContextAgent;
      if (AudioContextAgent.support) {
        audioContextAgent = new AudioContextAgent();
      }
      var OneShotAudioWeb = function () {
        function OneShotAudioWeb(audioBuffer, volume, url) {
          this._duration = void 0;
          this._bufferSourceNode = void 0;
          this._onPlayCb = void 0;
          this._currentTimer = 0;
          this._url = void 0;
          this._onEndCb = void 0;
          this._duration = audioBuffer.duration;
          this._url = url;
          this._bufferSourceNode = audioContextAgent.createBufferSource(audioBuffer, false);
          var gainNode = audioContextAgent.createGain(volume);
          this._bufferSourceNode.connect(gainNode);
          audioContextAgent.connectContext(gainNode);
        }
        var _proto2 = OneShotAudioWeb.prototype;
        _proto2.play = function play() {
          var _this4 = this;
          this._bufferSourceNode.start();
          audioContextAgent.runContext().then(function () {
            var _this4$onPlay;
            (_this4$onPlay = _this4.onPlay) === null || _this4$onPlay === void 0 ? void 0 : _this4$onPlay.call(_this4);
            _this4._currentTimer = window.setTimeout(function () {
              var _this4$onEnd;
              audioBufferManager.tryReleasingCache(_this4._url);
              (_this4$onEnd = _this4.onEnd) === null || _this4$onEnd === void 0 ? void 0 : _this4$onEnd.call(_this4);
            }, _this4._duration * 1000);
          })["catch"](function (e) {
            warn('play error', e);
          });
        };
        _proto2.stop = function stop() {
          clearTimeout(this._currentTimer);
          audioBufferManager.tryReleasingCache(this._url);
          this._bufferSourceNode.stop();
          this._bufferSourceNode.disconnect();
          this._bufferSourceNode.buffer = null;
        };
        _createClass(OneShotAudioWeb, [{
          key: "onPlay",
          get: function get() {
            return this._onPlayCb;
          },
          set: function set(cb) {
            this._onPlayCb = cb;
          }
        }, {
          key: "onEnd",
          get: function get() {
            return this._onEndCb;
          },
          set: function set(cb) {
            this._onEndCb = cb;
          }
        }]);
        return OneShotAudioWeb;
      }();
      var AudioPlayerWeb = (_class3$v = function () {
        function AudioPlayerWeb(audioBuffer, url) {
          this._src = void 0;
          this._audioBuffer = void 0;
          this._sourceNode = void 0;
          this._gainNode = void 0;
          this._currentTimer = 0;
          this._volume = 1;
          this._loop = false;
          this._state = AudioState.INIT;
          this._audioTimer = void 0;
          this._runningCallback = void 0;
          this._eventTarget = new EventTarget();
          this._operationQueue = [];
          this._audioBuffer = audioBuffer;
          this._audioTimer = new AudioTimer(audioBuffer);
          this._gainNode = audioContextAgent.createGain();
          audioContextAgent.connectContext(this._gainNode);
          this._src = url;
          game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
          game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this);
        }
        var _proto3 = AudioPlayerWeb.prototype;
        _proto3.destroy = function destroy() {
          window.clearTimeout(this._currentTimer);
          this._audioTimer.destroy();
          if (this._audioBuffer) {
            this._audioBuffer = null;
          }
          audioBufferManager.tryReleasingCache(this._src);
          game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
          game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this);
          this.offRunning();
        };
        AudioPlayerWeb.load = function load(url) {
          return new Promise(function (resolve, reject) {
            AudioPlayerWeb.loadNative(url).then(function (audioBuffer) {
              resolve(new AudioPlayerWeb(audioBuffer, url));
            })["catch"](reject);
          });
        };
        AudioPlayerWeb.loadNative = function loadNative(url) {
          return new Promise(function (resolve, reject) {
            var cachedAudioBuffer = audioBufferManager.getCache(url);
            if (cachedAudioBuffer) {
              audioBufferManager.retainCache(url);
              resolve(cachedAudioBuffer);
              return;
            }
            var xhr = new XMLHttpRequest();
            var errInfo = "load audio failed: " + url + ", status: ";
            xhr.open('GET', url, true);
            xhr.responseType = 'arraybuffer';
            xhr.onload = function () {
              if (xhr.status === 200 || xhr.status === 0) {
                audioContextAgent.decodeAudioData(xhr.response).then(function (decodedAudioBuffer) {
                  audioBufferManager.addCache(url, decodedAudioBuffer);
                  resolve(decodedAudioBuffer);
                })["catch"](function (e) {
                  warn('loadNative error', url, e);
                });
              } else {
                reject(new Error("" + errInfo + xhr.status + "(no response)"));
              }
            };
            xhr.onerror = function () {
              reject(new Error("" + errInfo + xhr.status + "(error)"));
            };
            xhr.ontimeout = function () {
              reject(new Error("" + errInfo + xhr.status + "(time out)"));
            };
            xhr.onabort = function () {
              reject(new Error("" + errInfo + xhr.status + "(abort)"));
            };
            xhr.send(null);
          });
        };
        AudioPlayerWeb.loadOneShotAudio = function loadOneShotAudio(url, volume) {
          return new Promise(function (resolve, reject) {
            AudioPlayerWeb.loadNative(url).then(function (audioBuffer) {
              var oneShotAudio = new OneShotAudioWeb(audioBuffer, volume, url);
              resolve(oneShotAudio);
            })["catch"](reject);
          });
        };
        _proto3.getPCMData = function getPCMData(channelIndex) {
          return new AudioPCMDataView(this._audioBuffer.getChannelData(channelIndex), 1);
        };
        _proto3._onInterruptedBegin = function _onInterruptedBegin() {
          var _this5 = this;
          if (this._state === AudioState.PLAYING) {
            this.pause().then(function () {
              _this5._state = AudioState.INTERRUPTED;
              _this5._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
            })["catch"](function (e) {
              warn('_onInterruptedBegin error', e);
            });
          }
        };
        _proto3._onInterruptedEnd = function _onInterruptedEnd() {
          var _this6 = this;
          if (this._state === AudioState.INTERRUPTED) {
            this.play().then(function () {
              _this6._eventTarget.emit(AudioEvent.INTERRUPTION_END);
            })["catch"](function (e) {
              warn('_onInterruptedEnd error', e);
            });
          }
        };
        _proto3.offRunning = function offRunning() {
          if (this._runningCallback) {
            audioContextAgent.offRunning(this._runningCallback);
            this._runningCallback = undefined;
          }
        };
        _proto3.seek = function seek(time) {
          var _this7 = this;
          return new Promise(function (resolve) {
            _this7.offRunning();
            _this7._audioTimer.seek(time);
            if (_this7._state === AudioState.PLAYING) {
              _this7._doPlay().then(resolve)["catch"](function (e) {
                warn('seek error', e);
              });
            } else {
              resolve();
            }
          });
        };
        _proto3.play = function play() {
          this.offRunning();
          return this._doPlay();
        };
        _proto3._doPlay = function _doPlay() {
          var _this8 = this;
          return new Promise(function (resolve) {
            if (audioContextAgent.isRunning) {
              _this8._startSourceNode();
              resolve();
            } else {
              _this8.offRunning();
              _this8._runningCallback = function () {
                _this8._startSourceNode();
                resolve();
              };
              audioContextAgent.onceRunning(_this8._runningCallback);
              audioContextAgent.runContext()["catch"](function (e) {
                warn('doPlay error', e);
              });
            }
          });
        };
        _proto3._startSourceNode = function _startSourceNode() {
          var _this9 = this;
          this._stopSourceNode();
          this._sourceNode = audioContextAgent.createBufferSource(this._audioBuffer, this.loop);
          this._sourceNode.connect(this._gainNode);
          this._sourceNode.loop = this._loop;
          this._sourceNode.start(0, this._audioTimer.currentTime);
          this._state = AudioState.PLAYING;
          this._audioTimer.start();
          var checkEnded = function checkEnded() {
            if (_this9.loop) {
              _this9._currentTimer = window.setTimeout(checkEnded, _this9._audioBuffer.duration * 1000);
            } else {
              _this9._audioTimer.stop();
              _this9._eventTarget.emit(AudioEvent.ENDED);
              _this9._state = AudioState.INIT;
            }
          };
          window.clearTimeout(this._currentTimer);
          this._currentTimer = window.setTimeout(checkEnded, (this._audioBuffer.duration - this._audioTimer.currentTime) * 1000);
        };
        _proto3._stopSourceNode = function _stopSourceNode() {
          try {
            if (this._sourceNode) {
              this._sourceNode.stop();
              this._sourceNode.disconnect();
              this._sourceNode.buffer = null;
              this._sourceNode = undefined;
            }
          } catch (e) {}
        };
        _proto3.pause = function pause() {
          this.offRunning();
          if (this._state !== AudioState.PLAYING || !this._sourceNode) {
            return Promise.resolve();
          }
          this._audioTimer.pause();
          this._state = AudioState.PAUSED;
          window.clearTimeout(this._currentTimer);
          this._stopSourceNode();
          return Promise.resolve();
        };
        _proto3.stop = function stop() {
          this.offRunning();
          if (!this._sourceNode) {
            this._audioTimer.stop();
            this._state = AudioState.STOPPED;
            return Promise.resolve();
          }
          this._audioTimer.stop();
          this._state = AudioState.STOPPED;
          window.clearTimeout(this._currentTimer);
          this._stopSourceNode();
          return Promise.resolve();
        };
        _proto3.onInterruptionBegin = function onInterruptionBegin(cb) {
          this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb);
        };
        _proto3.offInterruptionBegin = function offInterruptionBegin(cb) {
          this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb);
        };
        _proto3.onInterruptionEnd = function onInterruptionEnd(cb) {
          this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb);
        };
        _proto3.offInterruptionEnd = function offInterruptionEnd(cb) {
          this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb);
        };
        _proto3.onEnded = function onEnded(cb) {
          this._eventTarget.on(AudioEvent.ENDED, cb);
        };
        _proto3.offEnded = function offEnded(cb) {
          this._eventTarget.off(AudioEvent.ENDED, cb);
        };
        _createClass(AudioPlayerWeb, [{
          key: "sampleRate",
          get: function get() {
            return this._audioBuffer.sampleRate;
          }
        }, {
          key: "src",
          get: function get() {
            return this._src;
          }
        }, {
          key: "type",
          get: function get() {
            return AudioType.WEB_AUDIO;
          }
        }, {
          key: "state",
          get: function get() {
            return this._state;
          }
        }, {
          key: "loop",
          get: function get() {
            return this._loop;
          },
          set: function set(val) {
            this._loop = val;
            if (this._sourceNode) {
              this._sourceNode.loop = val;
            }
          }
        }, {
          key: "volume",
          get: function get() {
            return this._volume;
          },
          set: function set(val) {
            val = clamp01(val);
            this._volume = val;
            audioContextAgent.setGainValue(this._gainNode, val);
          }
        }, {
          key: "duration",
          get: function get() {
            return this._audioBuffer.duration;
          }
        }, {
          key: "currentTime",
          get: function get() {
            return this._audioTimer.currentTime;
          }
        }]);
        return AudioPlayerWeb;
      }(), (_applyDecoratedDescriptor(_class3$v.prototype, "seek", [enqueueOperation], Object.getOwnPropertyDescriptor(_class3$v.prototype, "seek"), _class3$v.prototype), _applyDecoratedDescriptor(_class3$v.prototype, "play", [enqueueOperation], Object.getOwnPropertyDescriptor(_class3$v.prototype, "play"), _class3$v.prototype), _applyDecoratedDescriptor(_class3$v.prototype, "pause", [enqueueOperation], Object.getOwnPropertyDescriptor(_class3$v.prototype, "pause"), _class3$v.prototype), _applyDecoratedDescriptor(_class3$v.prototype, "stop", [enqueueOperation], Object.getOwnPropertyDescriptor(_class3$v.prototype, "stop"), _class3$v.prototype)), _class3$v);

      var OneShotAudio = function () {
        function OneShotAudio(audio) {
          this._audio = void 0;
          this._audio = audio;
        }
        var _proto = OneShotAudio.prototype;
        _proto.play = function play() {
          this._audio.play();
        };
        _proto.stop = function stop() {
          this._audio.stop();
        };
        _createClass(OneShotAudio, [{
          key: "onPlay",
          get: function get() {
            return this._audio.onPlay;
          },
          set: function set(v) {
            this._audio.onPlay = v;
          }
        }, {
          key: "onEnd",
          get: function get() {
            return this._audio.onEnd;
          },
          set: function set(v) {
            this._audio.onEnd = v;
          }
        }]);
        return OneShotAudio;
      }();
      var AudioPlayer = function () {
        function AudioPlayer(player) {
          this._player = void 0;
          this._player = player;
        }
        AudioPlayer.load = function load(url, opts) {
          return new Promise(function (resolve, reject) {
            if ((opts === null || opts === void 0 ? void 0 : opts.audioLoadMode) === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
              if (!AudioContextAgent.support) {
                warnID(5201);
              }
              AudioPlayerDOM.load(url).then(function (domPlayer) {
                resolve(new AudioPlayer(domPlayer));
              })["catch"](reject);
            } else {
              AudioPlayerWeb.load(url).then(function (webPlayer) {
                resolve(new AudioPlayer(webPlayer));
              })["catch"](reject);
            }
          });
        };
        var _proto2 = AudioPlayer.prototype;
        _proto2.destroy = function destroy() {
          this._player.destroy();
        };
        AudioPlayer.loadNative = function loadNative(url, opts) {
          if ((opts === null || opts === void 0 ? void 0 : opts.audioLoadMode) === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
            if (!AudioContextAgent.support) {
              warnID(5201);
            }
            return AudioPlayerDOM.loadNative(url);
          }
          return AudioPlayerWeb.loadNative(url);
        };
        AudioPlayer.loadOneShotAudio = function loadOneShotAudio(url, volume, opts) {
          return new Promise(function (resolve, reject) {
            if ((opts === null || opts === void 0 ? void 0 : opts.audioLoadMode) === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
              if (!AudioContextAgent.support) {
                warnID(5201);
              }
              AudioPlayerDOM.loadOneShotAudio(url, volume).then(function (oneShotAudioDOM) {
                resolve(new OneShotAudio(oneShotAudioDOM));
              })["catch"](reject);
            } else {
              AudioPlayerWeb.loadOneShotAudio(url, volume).then(function (oneShotAudioWeb) {
                resolve(new OneShotAudio(oneShotAudioWeb));
              })["catch"](reject);
            }
          });
        };
        _proto2.getPCMData = function getPCMData(channelIndex) {
          return this._player.getPCMData(channelIndex);
        };
        _proto2.seek = function seek(time) {
          return this._player.seek(time);
        };
        _proto2.play = function play() {
          return this._player.play();
        };
        _proto2.pause = function pause() {
          return this._player.pause();
        };
        _proto2.stop = function stop() {
          return this._player.stop();
        };
        _proto2.onInterruptionBegin = function onInterruptionBegin(cb) {
          this._player.onInterruptionBegin(cb);
        };
        _proto2.offInterruptionBegin = function offInterruptionBegin(cb) {
          this._player.offInterruptionBegin(cb);
        };
        _proto2.onInterruptionEnd = function onInterruptionEnd(cb) {
          this._player.onInterruptionEnd(cb);
        };
        _proto2.offInterruptionEnd = function offInterruptionEnd(cb) {
          this._player.offInterruptionEnd(cb);
        };
        _proto2.onEnded = function onEnded(cb) {
          this._player.onEnded(cb);
        };
        _proto2.offEnded = function offEnded(cb) {
          this._player.offEnded(cb);
        };
        _createClass(AudioPlayer, [{
          key: "src",
          get: function get() {
            return this._player.src;
          }
        }, {
          key: "type",
          get: function get() {
            return this._player.type;
          }
        }, {
          key: "state",
          get: function get() {
            return this._player.state;
          }
        }, {
          key: "loop",
          get: function get() {
            return this._player.loop;
          },
          set: function set(val) {
            this._player.loop = val;
          }
        }, {
          key: "volume",
          get: function get() {
            return this._player.volume;
          },
          set: function set(val) {
            this._player.volume = val;
          }
        }, {
          key: "duration",
          get: function get() {
            return this._player.duration;
          }
        }, {
          key: "currentTime",
          get: function get() {
            return this._player.currentTime;
          }
        }, {
          key: "sampleRate",
          get: function get() {
            return this._player.sampleRate;
          }
        }]);
        return AudioPlayer;
      }();
      AudioPlayer.maxAudioChannel = 24;

      var _dec$1A, _class$1x, _class2$1s, _initializer$1n, _class3$u;
      var AudioClip = exports('aD', (_dec$1A = ccclass$M('cc.AudioClip'), _dec$1A(_class$1x = (_class2$1s = (_class3$u = function (_Asset) {
        _inheritsLoose(AudioClip, _Asset);
        function AudioClip() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this._duration = _initializer$1n && _initializer$1n();
          _this._loadMode = AudioType.UNKNOWN_AUDIO;
          _this._meta = null;
          _this._player = null;
          return _this;
        }
        var _proto = AudioClip.prototype;
        _proto.destroy = function destroy() {
          var _this$_player;
          var destroyResult = _Asset.prototype.destroy.call(this);
          (_this$_player = this._player) === null || _this$_player === void 0 ? void 0 : _this$_player.destroy();
          this._player = null;
          if (this._meta) {
            this._meta.player = null;
          }
          return destroyResult;
        };
        _proto.validate = function validate() {
          return !!this._meta;
        };
        _proto.getDuration = function getDuration() {
          if (this._duration) {
            return this._duration;
          }
          return this._meta ? this._meta.duration : 0;
        };
        _proto.getCurrentTime = function getCurrentTime() {
          return this._player ? this._player.currentTime : 0;
        };
        _proto.getVolume = function getVolume() {
          return this._player ? this._player.volume : 0;
        };
        _proto.getLoop = function getLoop() {
          return this._player ? this._player.loop : false;
        };
        _proto.setCurrentTime = function setCurrentTime(time) {
          var _this$_player2;
          (_this$_player2 = this._player) === null || _this$_player2 === void 0 ? void 0 : _this$_player2.seek(time)["catch"](function (e) {});
        };
        _proto.setVolume = function setVolume(volume) {
          if (this._player) {
            this._player.volume = volume;
          }
        };
        _proto.setLoop = function setLoop(loop) {
          if (this._player) {
            this._player.loop = loop;
          }
        };
        _proto.play = function play() {
          var _this$_player3;
          (_this$_player3 = this._player) === null || _this$_player3 === void 0 ? void 0 : _this$_player3.play()["catch"](function (e) {});
        };
        _proto.pause = function pause() {
          var _this$_player4;
          (_this$_player4 = this._player) === null || _this$_player4 === void 0 ? void 0 : _this$_player4.pause()["catch"](function (e) {});
        };
        _proto.stop = function stop() {
          var _this$_player5;
          (_this$_player5 = this._player) === null || _this$_player5 === void 0 ? void 0 : _this$_player5.stop()["catch"](function (e) {});
        };
        _proto.playOneShot = function playOneShot(volume) {
          if (volume === void 0) {
            volume = 1;
          }
          if (this._nativeAsset) {
            AudioPlayer.loadOneShotAudio(this._nativeAsset.url, volume).then(function (oneShotAudio) {
              oneShotAudio.play();
            })["catch"](function (e) {});
          }
        };
        _createClass(AudioClip, [{
          key: "duration",
          set: function set(v) {
            this._duration = v;
          }
        }, {
          key: "_nativeAsset",
          get: function get() {
            return this._meta;
          },
          set: function set(meta) {
            this._meta = meta;
            if (meta) {
              this._loadMode = meta.type;
              this._player = meta.player;
            } else {
              this._meta = null;
              this._loadMode = AudioType.UNKNOWN_AUDIO;
              this._duration = 0;
            }
          }
        }, {
          key: "_nativeDep",
          get: function get() {
            return {
              uuid: this._uuid,
              audioLoadMode: this.loadMode,
              ext: this._native,
              __isNative__: true
            };
          }
        }, {
          key: "loadMode",
          get: function get() {
            return this._loadMode;
          }
        }, {
          key: "state",
          get: function get() {
            return this._player ? this._player.state : AudioState.INIT;
          }
        }]);
        return AudioClip;
      }(Asset), _class3$u.AudioType = AudioType, _class3$u), (_initializer$1n = applyDecoratedInitializer(_class2$1s.prototype, "_duration", [serializable$p], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$1s.prototype, "_nativeDep", [override$1], Object.getOwnPropertyDescriptor(_class2$1s.prototype, "_nativeDep"), _class2$1s.prototype)), _class2$1s)) || _class$1x));
      legacyCC.AudioClip = AudioClip;

      function loadAudioPlayer(url, options, onComplete) {
        AudioPlayer.load(url, {
          audioLoadMode: options.audioLoadMode
        }).then(function (player) {
          var audioMeta = {
            player: player,
            url: url,
            duration: player.duration,
            type: player.type
          };
          onComplete(null, audioMeta);
        })["catch"](function (err) {
          onComplete(err);
        });
      }
      function createAudioClip(id, data, options, onComplete) {
        var out = new AudioClip();
        out._nativeUrl = id;
        out._nativeAsset = data;
        out.duration = data.duration;
        onComplete(null, out);
      }
      downloader$1.register({
        '.mp3': loadAudioPlayer,
        '.ogg': loadAudioPlayer,
        '.wav': loadAudioPlayer,
        '.m4a': loadAudioPlayer
      });
      factory.register({
        '.mp3': createAudioClip,
        '.ogg': createAudioClip,
        '.wav': createAudioClip,
        '.m4a': createAudioClip
      });

      var AudioManager = function () {
        function AudioManager() {
          this._oneShotAudioInfoList = [];
          this._audioPlayerInfoList = [];
        }
        var _proto = AudioManager.prototype;
        _proto._findIndex = function _findIndex(audioInfoList, audio) {
          return audioInfoList.findIndex(function (item) {
            return item.audio === audio;
          });
        };
        _proto._tryAddPlaying = function _tryAddPlaying(audioInfoList, audio) {
          var idx = this._findIndex(audioInfoList, audio);
          if (idx > -1) {
            audioInfoList[idx].playTime = performance.now();
            return false;
          }
          audioInfoList.push({
            audio: audio,
            playTime: performance.now()
          });
          return true;
        };
        _proto.addPlaying = function addPlaying(audio) {
          if (audio instanceof AudioPlayer) {
            this._tryAddPlaying(this._audioPlayerInfoList, audio);
          } else {
            this._tryAddPlaying(this._oneShotAudioInfoList, audio);
          }
        };
        _proto._tryRemovePlaying = function _tryRemovePlaying(audioInfoList, audio) {
          var idx = this._findIndex(audioInfoList, audio);
          if (idx === -1) {
            return false;
          }
          fastRemoveAt$2(audioInfoList, idx);
          return true;
        };
        _proto.removePlaying = function removePlaying(audio) {
          if (audio instanceof AudioPlayer) {
            this._tryRemovePlaying(this._audioPlayerInfoList, audio);
          } else {
            this._tryRemovePlaying(this._oneShotAudioInfoList, audio);
          }
        };
        _proto.discardOnePlayingIfNeeded = function discardOnePlayingIfNeeded() {
          if (this._audioPlayerInfoList.length + this._oneShotAudioInfoList.length < AudioPlayer.maxAudioChannel) {
            return;
          }
          var audioInfoToDiscard;
          if (this._oneShotAudioInfoList.length > 0) {
            this._oneShotAudioInfoList.forEach(function (audioInfo) {
              if (!audioInfoToDiscard || audioInfo.playTime < audioInfoToDiscard.playTime) {
                audioInfoToDiscard = audioInfo;
              }
            });
          } else {
            this._audioPlayerInfoList.forEach(function (audioInfo) {
              if (!audioInfoToDiscard || audioInfo.playTime < audioInfoToDiscard.playTime) {
                audioInfoToDiscard = audioInfo;
              }
            });
          }
          if (audioInfoToDiscard) {
            audioInfoToDiscard.audio.stop();
            this.removePlaying(audioInfoToDiscard.audio);
          }
        };
        _proto.pause = function pause() {
          this._oneShotAudioInfoList.forEach(function (info) {
            info.audio.stop();
          });
          this._audioPlayerInfoList.forEach(function (info) {
            info.audio.pause()["catch"](function (e) {});
          });
        };
        _proto.resume = function resume() {
          this._audioPlayerInfoList.forEach(function (info) {
            info.audio.play()["catch"](function (e) {});
          });
        };
        return AudioManager;
      }();
      var audioManager = new AudioManager();

      var _dec$1z, _dec2$1n, _dec3$13, _class$1w, _class2$1r, _initializer$1m, _initializer2$1e, _initializer3$Z, _initializer4$R, _class3$t;
      var _LOADED_EVENT = 'audiosource-loaded';
      var AudioSourceEventType;
      (function (AudioSourceEventType) {
        AudioSourceEventType["STARTED"] = "started";
        AudioSourceEventType["ENDED"] = "ended";
      })(AudioSourceEventType || (AudioSourceEventType = {}));
      var AudioOperationType;
      (function (AudioOperationType) {
        AudioOperationType["PLAY"] = "play";
        AudioOperationType["STOP"] = "stop";
        AudioOperationType["PAUSE"] = "pause";
        AudioOperationType["SEEK"] = "seek";
      })(AudioOperationType || (AudioOperationType = {}));
      var AudioSource = exports('aC', (_dec$1z = ccclass$M('cc.AudioSource'), _dec2$1n = type$d(AudioClip), _dec3$13 = type$d(AudioClip), _dec$1z(_class$1w = (_class2$1r = (_class3$t = function (_Component) {
        _inheritsLoose(AudioSource, _Component);
        function AudioSource() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._clip = _initializer$1m && _initializer$1m();
          _this._player = null;
          _this._hasRegisterListener = false;
          _this._loop = _initializer2$1e && _initializer2$1e();
          _this._playOnAwake = _initializer3$Z && _initializer3$Z();
          _this._volume = _initializer4$R && _initializer4$R();
          _this._cachedCurrentTime = -1;
          _this._operationsBeforeLoading = [];
          _this._isLoaded = false;
          _this._lastSetClip = null;
          return _this;
        }
        var _proto = AudioSource.prototype;
        _proto._resetPlayer = function _resetPlayer() {
          if (this._player) {
            audioManager.removePlaying(this._player);
            this._unregisterListener();
            this._player.destroy();
            this._player = null;
          }
        };
        _proto._syncPlayer = function _syncPlayer() {
          var _this2 = this;
          var clip = this._clip;
          if (this._lastSetClip === clip) {
            return;
          }
          if (!clip) {
            this._lastSetClip = null;
            this._resetPlayer();
            return;
          }
          if (!clip._nativeAsset) {
            console.error('Invalid audio clip');
            return;
          }
          this._isLoaded = false;
          this._lastSetClip = clip;
          this._operationsBeforeLoading.length = 0;
          AudioPlayer.load(clip._nativeAsset.url, {
            audioLoadMode: clip.loadMode
          }).then(function (player) {
            var _this2$node;
            if (_this2._lastSetClip !== clip) {
              player.destroy();
              return;
            }
            _this2._isLoaded = true;
            _this2._resetPlayer();
            _this2._player = player;
            _this2._syncStates();
            (_this2$node = _this2.node) === null || _this2$node === void 0 ? void 0 : _this2$node.emit(_LOADED_EVENT);
          })["catch"](function (e) {});
        };
        _proto._registerListener = function _registerListener() {
          var _this3 = this;
          if (!this._hasRegisterListener && this._player) {
            var player = this._player;
            player.onEnded(function () {
              var _this3$node;
              audioManager.removePlaying(player);
              (_this3$node = _this3.node) === null || _this3$node === void 0 ? void 0 : _this3$node.emit(AudioSourceEventType.ENDED, _this3);
            });
            player.onInterruptionBegin(function () {
              audioManager.removePlaying(player);
            });
            player.onInterruptionEnd(function () {
              if (_this3._player === player) {
                audioManager.addPlaying(player);
              }
            });
            this._hasRegisterListener = true;
          }
        };
        _proto._unregisterListener = function _unregisterListener() {
          if (this._player && this._hasRegisterListener) {
            this._player.offEnded();
            this._player.offInterruptionBegin();
            this._player.offInterruptionEnd();
            this._hasRegisterListener = false;
          }
        };
        _proto.onLoad = function onLoad() {
          this._syncPlayer();
        };
        _proto.onEnable = function onEnable() {
          if (this._playOnAwake && !this.playing) {
            this.play();
          }
        };
        _proto.onDisable = function onDisable() {
          var rootNode = this._getRootNode();
          if (rootNode !== null && rootNode !== void 0 && rootNode._persistNode) {
            return;
          }
          this.pause();
        };
        _proto.onDestroy = function onDestroy() {
          this.stop();
          this.clip = null;
        };
        _proto.getPCMData = function getPCMData(channelIndex) {
          var _this4 = this;
          return new Promise(function (resolve) {
            if (channelIndex !== 0 && channelIndex !== 1) {
              console.warn('Only support channel index 0 or 1 to get buffer');
              resolve(undefined);
              return;
            }
            if (_this4._player) {
              resolve(_this4._player.getPCMData(channelIndex));
            } else {
              var _this4$node;
              (_this4$node = _this4.node) === null || _this4$node === void 0 ? void 0 : _this4$node.once(_LOADED_EVENT, function () {
                var _this4$_player;
                resolve((_this4$_player = _this4._player) === null || _this4$_player === void 0 ? void 0 : _this4$_player.getPCMData(channelIndex));
              });
            }
          });
        };
        _proto.getSampleRate = function getSampleRate() {
          var _this5 = this;
          return new Promise(function (resolve) {
            if (_this5._player) {
              resolve(_this5._player.sampleRate);
            } else {
              var _this5$node;
              (_this5$node = _this5.node) === null || _this5$node === void 0 ? void 0 : _this5$node.once(_LOADED_EVENT, function () {
                resolve(_this5._player.sampleRate);
              });
            }
          });
        };
        _proto._getRootNode = function _getRootNode() {
          var _currentNode, _currentNode$parent;
          var currentNode = this.node;
          var currentGrandparentNode = (_currentNode = currentNode) === null || _currentNode === void 0 ? void 0 : (_currentNode$parent = _currentNode.parent) === null || _currentNode$parent === void 0 ? void 0 : _currentNode$parent.parent;
          while (currentGrandparentNode) {
            var _currentNode2, _currentNode3, _currentNode3$parent;
            currentNode = (_currentNode2 = currentNode) === null || _currentNode2 === void 0 ? void 0 : _currentNode2.parent;
            currentGrandparentNode = (_currentNode3 = currentNode) === null || _currentNode3 === void 0 ? void 0 : (_currentNode3$parent = _currentNode3.parent) === null || _currentNode3$parent === void 0 ? void 0 : _currentNode3$parent.parent;
          }
          return currentNode;
        };
        _proto.play = function play() {
          var _this6 = this;
          if (!this._isLoaded && this.clip) {
            this._operationsBeforeLoading.push({
              op: AudioOperationType.PLAY,
              params: null
            });
            return;
          }
          this._registerListener();
          audioManager.discardOnePlayingIfNeeded();
          if (this.state === AudioState.PLAYING) {
            var _this$_player;
            (_this$_player = this._player) === null || _this$_player === void 0 ? void 0 : _this$_player.stop()["catch"](function (e) {});
          }
          var player = this._player;
          if (player) {
            player.play().then(function () {
              var _this6$node;
              (_this6$node = _this6.node) === null || _this6$node === void 0 ? void 0 : _this6$node.emit(AudioSourceEventType.STARTED, _this6);
            })["catch"](function (e) {
              audioManager.removePlaying(player);
            });
            audioManager.addPlaying(player);
          }
        };
        _proto.pause = function pause() {
          var _this$_player2;
          if (!this._isLoaded && this.clip) {
            this._operationsBeforeLoading.push({
              op: AudioOperationType.PAUSE,
              params: null
            });
            return;
          }
          (_this$_player2 = this._player) === null || _this$_player2 === void 0 ? void 0 : _this$_player2.pause()["catch"](function (e) {});
        };
        _proto.stop = function stop() {
          if (!this._isLoaded && this.clip) {
            this._operationsBeforeLoading.push({
              op: AudioOperationType.STOP,
              params: null
            });
            return;
          }
          if (this._player) {
            this._player.stop()["catch"](function (e) {});
            audioManager.removePlaying(this._player);
          }
        };
        _proto.playOneShot = function playOneShot(clip, volumeScale) {
          if (volumeScale === void 0) {
            volumeScale = 1;
          }
          if (!clip._nativeAsset) {
            console.error('Invalid audio clip');
            return;
          }
          var player;
          AudioPlayer.loadOneShotAudio(clip._nativeAsset.url, this._volume * volumeScale, {
            audioLoadMode: clip.loadMode
          }).then(function (oneShotAudio) {
            player = oneShotAudio;
            audioManager.discardOnePlayingIfNeeded();
            oneShotAudio.onEnd = function () {
              audioManager.removePlaying(oneShotAudio);
            };
            oneShotAudio.play();
            audioManager.addPlaying(oneShotAudio);
          })["catch"](function (e) {
            if (player) {
              audioManager.removePlaying(player);
            }
          });
        };
        _proto._syncStates = function _syncStates() {
          var _this7 = this;
          if (this._player) {
            this._player.loop = this._loop;
            this._player.volume = this._volume;
            this._operationsBeforeLoading.forEach(function (opInfo) {
              if (opInfo.op === AudioOperationType.SEEK) {
                _this7._cachedCurrentTime = opInfo.params && opInfo.params[0];
                if (_this7._player) {
                  _this7._player.seek(_this7._cachedCurrentTime)["catch"](function (e) {});
                }
              } else {
                var _this7$opInfo$op;
                (_this7$opInfo$op = _this7[opInfo.op]) === null || _this7$opInfo$op === void 0 ? void 0 : _this7$opInfo$op.call(_this7);
              }
            });
            this._operationsBeforeLoading.length = 0;
          }
        };
        _createClass(AudioSource, [{
          key: "clip",
          get: function get() {
            return this._clip;
          },
          set: function set(val) {
            if (val === this._clip) {
              return;
            }
            this._clip = val;
            this._syncPlayer();
          }
        }, {
          key: "loop",
          get: function get() {
            return this._loop;
          },
          set: function set(val) {
            this._loop = val;
            if (this._player) {
              this._player.loop = val;
            }
          }
        }, {
          key: "playOnAwake",
          get: function get() {
            return this._playOnAwake;
          },
          set: function set(val) {
            this._playOnAwake = val;
          }
        }, {
          key: "volume",
          get: function get() {
            return this._volume;
          },
          set: function set(val) {
            if (Number.isNaN(val)) {
              console.warn('illegal audio volume!');
              return;
            }
            val = clamp$1(val, 0, 1);
            if (this._player) {
              this._player.volume = val;
              this._volume = this._player.volume;
            } else {
              this._volume = val;
            }
          }
        }, {
          key: "currentTime",
          get: function get() {
            return this._player ? this._player.currentTime : this._cachedCurrentTime < 0 ? 0 : this._cachedCurrentTime;
          },
          set: function set(num) {
            var _this$_player3;
            if (Number.isNaN(num)) {
              console.warn('illegal audio time!');
              return;
            }
            num = clamp$1(num, 0, this.duration);
            if (!this._isLoaded && this.clip) {
              this._operationsBeforeLoading.push({
                op: AudioOperationType.SEEK,
                params: [num]
              });
              return;
            }
            this._cachedCurrentTime = num;
            (_this$_player3 = this._player) === null || _this$_player3 === void 0 ? void 0 : _this$_player3.seek(this._cachedCurrentTime)["catch"](function (e) {});
          }
        }, {
          key: "duration",
          get: function get() {
            var _this$_clip$getDurati, _this$_clip;
            return (_this$_clip$getDurati = (_this$_clip = this._clip) === null || _this$_clip === void 0 ? void 0 : _this$_clip.getDuration()) !== null && _this$_clip$getDurati !== void 0 ? _this$_clip$getDurati : this._player ? this._player.duration : 0;
          }
        }, {
          key: "state",
          get: function get() {
            return this._player ? this._player.state : AudioState.INIT;
          }
        }, {
          key: "playing",
          get: function get() {
            return this.state === AudioSource.AudioState.PLAYING;
          }
        }], [{
          key: "maxAudioChannel",
          get: function get() {
            return AudioPlayer.maxAudioChannel;
          }
        }]);
        return AudioSource;
      }(Component), _class3$t.AudioState = AudioState, _class3$t.EventType = AudioSourceEventType, _class3$t), (_initializer$1m = applyDecoratedInitializer(_class2$1r.prototype, "_clip", [_dec2$1n], function () {
        return null;
      }), _initializer2$1e = applyDecoratedInitializer(_class2$1r.prototype, "_loop", [serializable$p], function () {
        return false;
      }), _initializer3$Z = applyDecoratedInitializer(_class2$1r.prototype, "_playOnAwake", [serializable$p], function () {
        return true;
      }), _initializer4$R = applyDecoratedInitializer(_class2$1r.prototype, "_volume", [serializable$p], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$1r.prototype, "clip", [_dec3$13], Object.getOwnPropertyDescriptor(_class2$1r.prototype, "clip"), _class2$1r.prototype)), _class2$1r)) || _class$1w));

      replaceProperty(AudioClip, 'AudioClip', [{
        name: 'PlayingState',
        newName: 'AudioState',
        target: AudioSource,
        targetName: 'AudioSource'
      }]);
      markAsWarning(AudioClip.prototype, 'AudioClip.prototype', ['state', 'play', 'pause', 'stop', 'playOneShot', 'setCurrentTime', 'setVolume', 'setLoop', 'getCurrentTime', 'getVolume', 'getLoop'].map(function (item) {
        return {
          name: item,
          suggest: "please use AudioSource.prototype." + item + " instead"
        };
      }));

      legacyCC.AudioSourceComponent = AudioSource;
      setClassAlias(AudioSource, 'cc.AudioSourceComponent');

      legacyCC.log = log;
      legacyCC.warn = warn;
      legacyCC.error = error;
      legacyCC.assert = assert;
      legacyCC._throw = _throw;
      legacyCC.logID = logID;
      legacyCC.warnID = warnID;
      legacyCC.errorID = errorID;
      legacyCC.assertID = assertID;
      legacyCC.debug = debug$1;
      legacyCC.path = {
        join: join,
        extname: extname,
        mainFileName: mainFileName,
        basename: basename,
        dirname: dirname,
        changeExtname: changeExtname,
        changeBasename: changeBasename,
        _normalize: _normalize,
        stripSep: stripSep,
        get sep() {
          return getSeperator();
        }
      };

      function isUICamera(camera) {
        var scene = camera.scene;
        var batches = scene.batches;
        for (var i = 0; batches && i < batches.length; i++) {
          var batch = batches[i];
          if (camera.visibility & batch.visFlags) {
            return true;
          }
        }
        return false;
      }

      var CameraInfo = function CameraInfo(camera, id, windowID, width, height) {
        this.camera = void 0;
        this.id = 0xFFFFFFFF;
        this.windowID = 0xFFFFFFFF;
        this.width = 0;
        this.height = 0;
        this.camera = camera;
        this.id = id;
        this.windowID = windowID;
        this.width = width;
        this.height = height;
      };
      var cameraInfos = new Map();
      var windowInfos = new Map();
      function prepareRenderWindow(camera) {
        var windowID = windowInfos.get(camera.window);
        if (windowID === undefined) {
          windowID = windowInfos.size;
          windowInfos.set(camera.window, windowID);
        }
        return windowID;
      }
      function prepareResource(ppl, camera, initResourceFunc, updateResourceFunc) {
        var info = cameraInfos.get(camera);
        if (info !== undefined) {
          var width = camera.window.width;
          var height = camera.window.height;
          if (width === 0) {
            width = 1;
          }
          if (height === 0) {
            height = 1;
          }
          var _windowID = prepareRenderWindow(camera);
          info.width = width;
          info.height = height;
          info.windowID = _windowID;
          updateResourceFunc(ppl, info);
          return info;
        }
        var windowID = prepareRenderWindow(camera);
        info = new CameraInfo(camera, cameraInfos.size, windowID, camera.window.width ? camera.window.width : 1, camera.window.height ? camera.window.height : 1);
        initResourceFunc(ppl, info);
        cameraInfos.set(camera, info);
        return info;
      }
      function buildShadowRes(ppl, name, width, height) {
        var fboW = width;
        var fboH = height;
        var shadowMapName = name;
        var device = ppl.device;
        if (!ppl.containsResource(shadowMapName)) {
          var format = supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8;
          ppl.addRenderTarget(shadowMapName, format, fboW, fboH, ResourceResidency.MANAGED);
          ppl.addDepthStencil(shadowMapName + "Depth", Format.DEPTH_STENCIL, fboW, fboH, ResourceResidency.MANAGED);
        }
        ppl.updateRenderTarget(shadowMapName, fboW, fboH);
        ppl.updateDepthStencil(shadowMapName + "Depth", fboW, fboH);
      }
      var shadowInfo = new ShadowInfo();
      function setupShadowRes(ppl, cameraInfo) {
        var camera = cameraInfo.camera;
        validPunctualLightsCulling(ppl, camera);
        var pipeline = ppl;
        var shadow = pipeline.pipelineSceneData.shadows;
        var validPunctualLights = ppl.pipelineSceneData.validPunctualLights;
        var shadows = ppl.pipelineSceneData.shadows;
        shadowInfo.reset();
        if (!shadow.enabled || shadow.type !== ShadowType.ShadowMap) {
          return shadowInfo;
        }
        shadowInfo.shadowEnabled = true;
        var _validLights = shadowInfo.validLights;
        var n = 0;
        var m = 0;
        for (; n < shadow.maxReceived && m < validPunctualLights.length;) {
          var light = validPunctualLights[m];
          if (light.type === LightType.SPOT) {
            var spotLight = light;
            if (spotLight.shadowEnabled) {
              _validLights.push(light);
              n++;
            }
          }
          m++;
        }
        var _ref = camera.scene,
          mainLight = _ref.mainLight;
        var mapWidth = shadows.size.x;
        var mapHeight = shadows.size.y;
        if (mainLight && mainLight.shadowEnabled) {
          shadowInfo.mainLightShadowNames[0] = "MainLightShadow" + cameraInfo.id;
          if (mainLight.shadowFixedArea) {
            buildShadowRes(ppl, shadowInfo.mainLightShadowNames[0], mapWidth, mapHeight);
          } else {
            var csmLevel = pipeline.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1;
            shadowInfo.mainLightShadowNames[0] = "MainLightShadow" + cameraInfo.id;
            for (var i = 0; i < csmLevel; i++) {
              buildShadowRes(ppl, shadowInfo.mainLightShadowNames[0], mapWidth, mapHeight);
            }
          }
        }
        for (var l = 0; l < _validLights.length; l++) {
          _validLights[l];
          var passName = "SpotLightShadow" + l.toString() + cameraInfo.id;
          shadowInfo.spotLightShadowNames[l] = passName;
          buildShadowRes(ppl, shadowInfo.spotLightShadowNames[l], mapWidth, mapHeight);
        }
        return shadowInfo;
      }
      var updateShadowRes = setupShadowRes;
      var shadowPass;
      function buildShadowPass(passName, ppl, camera, light, level, width, height) {
        var fboW = width;
        var fboH = height;
        var area = getRenderArea(camera, width, height, light, level);
        width = area.width;
        height = area.height;
        var shadowMapName = passName;
        if (!level) {
          shadowPass = ppl.addRenderPass(width, height, 'default');
          shadowPass.name = passName;
          shadowPass.setViewport(new Viewport(0, 0, fboW, fboH));
          shadowPass.addRenderTarget(shadowMapName, LoadOp.CLEAR, StoreOp.STORE, new Color(1, 1, 1, camera.clearColor.w));
          shadowPass.addDepthStencil(shadowMapName + "Depth", LoadOp.CLEAR, StoreOp.DISCARD, camera.clearDepth, camera.clearStencil, ClearFlagBit.DEPTH_STENCIL);
        }
        var queue = shadowPass.addQueue(QueueHint.RENDER_OPAQUE, 'shadow-caster');
        queue.addSceneOfCamera(camera, new LightInfo(light, level), SceneFlags.SHADOW_CASTER);
        queue.setViewport(new Viewport(area.x, area.y, area.width, area.height));
      }
      function setupShadowPass(ppl, cameraInfo) {
        if (!shadowInfo.shadowEnabled) return;
        var camera = cameraInfo.camera;
        var shadows = ppl.pipelineSceneData.shadows;
        var mapWidth = shadows.size.x;
        var mapHeight = shadows.size.y;
        var _ref2 = camera.scene,
          mainLight = _ref2.mainLight;
        if (mainLight && mainLight.shadowEnabled) {
          shadowInfo.mainLightShadowNames[0] = "MainLightShadow" + cameraInfo.id;
          if (mainLight.shadowFixedArea) {
            buildShadowPass(shadowInfo.mainLightShadowNames[0], ppl, camera, mainLight, 0, mapWidth, mapHeight);
          } else {
            var csmLevel = ppl.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1;
            shadowInfo.mainLightShadowNames[0] = "MainLightShadow" + cameraInfo.id;
            for (var i = 0; i < csmLevel; i++) {
              buildShadowPass(shadowInfo.mainLightShadowNames[0], ppl, camera, mainLight, i, mapWidth, mapHeight);
            }
          }
        }
        for (var l = 0; l < shadowInfo.validLights.length; l++) {
          var light = shadowInfo.validLights[l];
          var passName = "SpotLightShadow" + l.toString() + cameraInfo.id;
          shadowInfo.spotLightShadowNames[l] = passName;
          buildShadowPass(passName, ppl, camera, light, 0, mapWidth, mapHeight);
        }
      }
      function setupForwardRes(ppl, cameraInfo, isOffScreen) {
        if (isOffScreen === void 0) {
          isOffScreen = false;
        }
        var camera = cameraInfo.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        setupShadowRes(ppl, cameraInfo);
        if (!isOffScreen) {
          ppl.addRenderWindow("ForwardColor" + cameraInfo.id, Format.BGRA8, width, height, cameraInfo.camera.window);
        } else {
          ppl.addRenderTarget("ForwardColor" + cameraInfo.id, getRTFormatBeforeToneMapping(ppl), width, height, ResourceResidency.PERSISTENT);
        }
        ppl.addDepthStencil("ForwardDepthStencil" + cameraInfo.id, Format.DEPTH_STENCIL, width, height);
      }
      function updateForwardRes(ppl, cameraInfo, isOffScreen) {
        if (isOffScreen === void 0) {
          isOffScreen = false;
        }
        var camera = cameraInfo.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        updateShadowRes(ppl, cameraInfo);
        if (!isOffScreen) {
          ppl.updateRenderWindow("ForwardColor" + cameraInfo.id, cameraInfo.camera.window);
        } else {
          ppl.updateRenderTarget("ForwardColor" + cameraInfo.id, width, height);
        }
        ppl.updateDepthStencil("ForwardDepthStencil" + cameraInfo.id, width, height);
      }
      function setupDeferredForward(ppl, cameraInfo, inputColor, clusterLighting) {
        var area = getRenderArea(cameraInfo.camera, cameraInfo.camera.window.width, cameraInfo.camera.window.height);
        var width = area.width;
        var height = area.height;
        var forwardPass = ppl.addRenderPass(width, height, 'default');
        var camera = cameraInfo.camera;
        forwardPass.addRenderTarget(inputColor, LoadOp.LOAD, StoreOp.STORE);
        forwardPass.addDepthStencil(gBufferInfo.ds, LoadOp.LOAD, StoreOp.DISCARD);
        for (var _iterator = _createForOfIteratorHelperLoose(shadowInfo.mainLightShadowNames), _step; !(_step = _iterator()).done;) {
          var dirShadowName = _step.value;
          if (ppl.containsResource(dirShadowName)) {
            forwardPass.addTexture(dirShadowName, 'cc_shadowMap');
          }
        }
        for (var _iterator2 = _createForOfIteratorHelperLoose(shadowInfo.spotLightShadowNames), _step2; !(_step2 = _iterator2()).done;) {
          var spotShadowName = _step2.value;
          if (ppl.containsResource(spotShadowName)) {
            forwardPass.addTexture(spotShadowName, 'cc_spotShadowMap');
          }
        }
        var sceneFlags = SceneFlags.OPAQUE_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.CUTOUT_OBJECT | SceneFlags.DRAW_INSTANCING;
        sceneFlags |= clusterLighting ? SceneFlags.CLUSTERED_LIGHTING : SceneFlags.DEFAULT_LIGHTING;
        forwardPass.addQueue(QueueHint.RENDER_OPAQUE, 'deferred-forward').addSceneOfCamera(camera, new LightInfo(), sceneFlags);
        forwardPass.addQueue(QueueHint.RENDER_TRANSPARENT, 'deferred-forward').addSceneOfCamera(camera, new LightInfo(), SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY);
      }
      function setupForwardPass(ppl, cameraInfo, isOffScreen, enabledAlpha) {
        if (isOffScreen === void 0) {
          isOffScreen = false;
        }
        if (enabledAlpha === void 0) {
          enabledAlpha = true;
        }
        setupShadowPass(ppl, cameraInfo);
        var cameraID = cameraInfo.id;
        var area = getRenderArea(cameraInfo.camera, cameraInfo.camera.window.width, cameraInfo.camera.window.height);
        var width = area.width;
        var height = area.height;
        var forwardPass = ppl.addRenderPass(width, height, 'default');
        forwardPass.name = "ForwardPass" + cameraID;
        forwardPass.setViewport(new Viewport(area.x, area.y, width, height));
        for (var _iterator3 = _createForOfIteratorHelperLoose(shadowInfo.mainLightShadowNames), _step3; !(_step3 = _iterator3()).done;) {
          var dirShadowName = _step3.value;
          if (ppl.containsResource(dirShadowName)) {
            forwardPass.addTexture(dirShadowName, 'cc_shadowMap');
          }
        }
        for (var _iterator4 = _createForOfIteratorHelperLoose(shadowInfo.spotLightShadowNames), _step4; !(_step4 = _iterator4()).done;) {
          var spotShadowName = _step4.value;
          if (ppl.containsResource(spotShadowName)) {
            forwardPass.addTexture(spotShadowName, 'cc_spotShadowMap');
          }
        }
        var camera = cameraInfo.camera;
        forwardPass.addRenderTarget("ForwardColor" + cameraInfo.id, isOffScreen ? LoadOp.CLEAR : getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w));
        forwardPass.addDepthStencil("ForwardDepthStencil" + cameraInfo.id, isOffScreen ? LoadOp.CLEAR : getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), isOffScreen ? StoreOp.DISCARD : StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag);
        forwardPass.addQueue(QueueHint.RENDER_OPAQUE).addSceneOfCamera(camera, new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.CUTOUT_OBJECT | SceneFlags.DEFAULT_LIGHTING | SceneFlags.DRAW_INSTANCING);
        var sceneFlags = SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY;
        if (!isOffScreen) {
          sceneFlags |= SceneFlags.UI;
          forwardPass.showStatistics = true;
        }
        if (enabledAlpha) {
          forwardPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), sceneFlags);
        }
        return {
          rtName: "ForwardColor" + cameraInfo.id,
          dsName: "ForwardDepthStencil" + cameraInfo.id
        };
      }
      var gBufferInfo = new GBufferInfo();
      function setupGBufferRes(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var gBufferPassRTName = "gBufferPassColorCamera" + info.id;
        var gBufferPassNormal = "gBufferPassNormal" + info.id;
        var gBufferPassEmissive = "gBufferPassEmissive" + info.id;
        var gBufferPassDSName = "gBufferPassDSCamera" + info.id;
        var colFormat = Format.RGBA16F;
        ppl.addRenderTarget(gBufferPassRTName, colFormat, width, height, ResourceResidency.MANAGED);
        ppl.addRenderTarget(gBufferPassEmissive, colFormat, width, height, ResourceResidency.MANAGED);
        ppl.addRenderTarget(gBufferPassNormal, colFormat, width, height, ResourceResidency.MANAGED);
        ppl.addDepthStencil(gBufferPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED);
        gBufferInfo.color = gBufferPassRTName;
        gBufferInfo.normal = gBufferPassNormal;
        gBufferInfo.emissive = gBufferPassEmissive;
        gBufferInfo.ds = gBufferPassDSName;
      }
      function updateGBufferRes(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var gBufferPassRTName = "gBufferPassColorCamera" + info.id;
        var gBufferPassNormal = "gBufferPassNormal" + info.id;
        var gBufferPassEmissive = "gBufferPassEmissive" + info.id;
        var gBufferPassDSName = "gBufferPassDSCamera" + info.id;
        ppl.updateRenderTarget(gBufferPassRTName, width, height);
        ppl.updateRenderTarget(gBufferPassEmissive, width, height);
        ppl.updateRenderTarget(gBufferPassNormal, width, height);
        ppl.updateDepthStencil(gBufferPassDSName, width, height);
      }
      new Color(0, 0, 0, 0);
      function setupGBufferPass(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var gBufferPassRTName = gBufferInfo.color;
        var gBufferPassNormal = gBufferInfo.normal;
        var gBufferPassEmissive = gBufferInfo.emissive;
        var gBufferPassDSName = gBufferInfo.ds;
        var gBufferPass = ppl.addRenderPass(width, height, 'gbuffer');
        gBufferPass.name = "CameraGBufferPass" + info.id;
        gBufferPass.setViewport(new Viewport(area.x, area.y, width, height));
        var rtColor = new Color(0, 0, 0, 0);
        if (camera.clearFlag & ClearFlagBit.COLOR) {
          if (ppl.pipelineSceneData.isHDR) {
            SRGBToLinear(rtColor, camera.clearColor);
          } else {
            rtColor.x = camera.clearColor.x;
            rtColor.y = camera.clearColor.y;
            rtColor.z = camera.clearColor.z;
          }
        }
        gBufferPass.addRenderTarget(gBufferPassRTName, LoadOp.CLEAR, StoreOp.STORE, rtColor);
        gBufferPass.addRenderTarget(gBufferPassEmissive, LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 0));
        gBufferPass.addRenderTarget(gBufferPassNormal, LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 0));
        gBufferPass.addDepthStencil(gBufferPassDSName, LoadOp.CLEAR, StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag);
        gBufferPass.addQueue(QueueHint.RENDER_OPAQUE, 'gbuffer').addSceneOfCamera(camera, new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT);
        return gBufferPass;
      }
      function setupLightingRes(ppl, info) {
        setupShadowRes(ppl, info);
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var deferredLightingPassRTName = "deferredLightingPassRTName" + info.id;
        ppl.addRenderTarget(deferredLightingPassRTName, Format.RGBA8, width, height, ResourceResidency.MANAGED);
      }
      function updateLightingRes(ppl, info) {
        updateShadowRes(ppl, info);
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var deferredLightingPassRTName = "deferredLightingPassRTName" + info.id;
        ppl.updateRenderTarget(deferredLightingPassRTName, width, height);
      }
      var lightingInfo;
      function setupLightingPass(pipeline, info, useCluster) {
        setupShadowPass(pipeline, info);
        if (!lightingInfo) {
          lightingInfo = new LightingInfo(useCluster);
        }
        var ppl = pipeline;
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var cameraID = getCameraUniqueID(camera);
        var deferredLightingPassRTName = "deferredLightingPassRTName" + info.id;
        var lightingPass = ppl.addRenderPass(width, height, 'deferred-lighting');
        lightingPass.name = "CameraLightingPass" + info.id;
        lightingPass.setViewport(new Viewport(area.x, area.y, width, height));
        for (var _iterator5 = _createForOfIteratorHelperLoose(shadowInfo.mainLightShadowNames), _step5; !(_step5 = _iterator5()).done;) {
          var dirShadowName = _step5.value;
          if (ppl.containsResource(dirShadowName)) {
            lightingPass.addTexture(dirShadowName, 'cc_shadowMap');
          }
        }
        for (var _iterator6 = _createForOfIteratorHelperLoose(shadowInfo.spotLightShadowNames), _step6; !(_step6 = _iterator6()).done;) {
          var spotShadowName = _step6.value;
          if (ppl.containsResource(spotShadowName)) {
            lightingPass.addTexture(spotShadowName, 'cc_spotShadowMap');
          }
        }
        if (ppl.containsResource(gBufferInfo.color)) {
          lightingPass.addTexture(gBufferInfo.color, 'albedoMap');
          lightingPass.addTexture(gBufferInfo.normal, 'normalMap');
          lightingPass.addTexture(gBufferInfo.emissive, 'emissiveMap');
          lightingPass.addTexture(gBufferInfo.ds, 'depthStencil');
        }
        var clusterLightBufferName = "clusterLightBuffer" + cameraID;
        var clusterLightIndicesBufferName = "clusterLightIndicesBuffer" + cameraID;
        var clusterLightGridBufferName = "clusterLightGridBuffer" + cameraID;
        if (ppl.containsResource(clusterLightBufferName)) {
          lightingPass.addStorageBuffer(clusterLightBufferName, AccessType.READ, 'b_ccLightsBuffer');
          lightingPass.addStorageBuffer(clusterLightIndicesBufferName, AccessType.READ, 'b_clusterLightIndicesBuffer');
          lightingPass.addStorageBuffer(clusterLightGridBufferName, AccessType.READ, 'b_clusterLightGridBuffer');
        }
        var lightingClearColor = new Color(0, 0, 0, 0);
        if (camera.clearFlag & ClearFlagBit.COLOR) {
          lightingClearColor.x = camera.clearColor.x;
          lightingClearColor.y = camera.clearColor.y;
          lightingClearColor.z = camera.clearColor.z;
        }
        lightingClearColor.w = 0;
        lightingPass.addRenderTarget(deferredLightingPassRTName, LoadOp.CLEAR, StoreOp.STORE, lightingClearColor);
        lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad(camera, lightingInfo.deferredLightingMaterial, 0, SceneFlags.VOLUMETRIC_LIGHTING);
        return {
          rtName: deferredLightingPassRTName
        };
      }
      function setupPostprocessRes(ppl, info) {
        var cameraID = info.id;
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var postprocessPassRTName = "postprocessPassRTName" + cameraID;
        var postprocessPassDS = "postprocessPassDS" + cameraID;
        ppl.addRenderWindow(postprocessPassRTName, Format.BGRA8, width, height, camera.window);
        ppl.addDepthStencil(postprocessPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED);
      }
      function updatePostprocessRes(ppl, info) {
        var cameraID = info.id;
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var postprocessPassRTName = "postprocessPassRTName" + cameraID;
        var postprocessPassDS = "postprocessPassDS" + cameraID;
        ppl.updateRenderWindow(postprocessPassRTName, camera.window);
        ppl.updateDepthStencil(postprocessPassDS, width, height);
      }
      var postInfo;
      function setupPostprocessPass(ppl, info, inputTex) {
        if (!postInfo) {
          postInfo = new PostInfo();
        }
        var cameraID = info.id;
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var postprocessPassRTName = "postprocessPassRTName" + cameraID;
        var postprocessPassDS = "postprocessPassDS" + cameraID;
        var postprocessPass = ppl.addRenderPass(width, height, 'post-process');
        postprocessPass.name = "CameraPostprocessPass" + cameraID;
        postprocessPass.setViewport(new Viewport(area.x, area.y, area.width, area.height));
        if (ppl.containsResource(inputTex)) {
          postprocessPass.addTexture(inputTex, 'outputResultMap');
        }
        var postClearColor = new Color(0, 0, 0, camera.clearColor.w);
        if (camera.clearFlag & ClearFlagBit.COLOR) {
          postClearColor.x = camera.clearColor.x;
          postClearColor.y = camera.clearColor.y;
          postClearColor.z = camera.clearColor.z;
        }
        postprocessPass.addRenderTarget(postprocessPassRTName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, postClearColor);
        postprocessPass.addDepthStencil(postprocessPassDS, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag);
        postprocessPass.addQueue(QueueHint.NONE).addCameraQuad(camera, postInfo.postMaterial, 0, SceneFlags.NONE);
        if (getProfilerCamera() === camera) {
          postprocessPass.showStatistics = true;
        }
        return {
          rtName: postprocessPassRTName,
          dsName: postprocessPassDS
        };
      }
      function setupUIRes(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var dsUIAndProfilerPassRTName = "dsUIAndProfilerPassColor" + info.id;
        var dsUIAndProfilerPassDSName = "dsUIAndProfilerPassDS" + info.id;
        ppl.addRenderWindow(dsUIAndProfilerPassRTName, Format.BGRA8, width, height, camera.window);
        ppl.addDepthStencil(dsUIAndProfilerPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED);
      }
      function updateUIRes(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var dsUIAndProfilerPassRTName = "dsUIAndProfilerPassColor" + info.id;
        var dsUIAndProfilerPassDSName = "dsUIAndProfilerPassDS" + info.id;
        ppl.updateRenderWindow(dsUIAndProfilerPassRTName, camera.window);
        ppl.updateDepthStencil(dsUIAndProfilerPassDSName, width, height);
      }
      function setupUIPass(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var dsUIAndProfilerPassRTName = "dsUIAndProfilerPassColor" + info.id;
        var dsUIAndProfilerPassDSName = "dsUIAndProfilerPassDS" + info.id;
        var uiAndProfilerPass = ppl.addRenderPass(width, height, 'default');
        uiAndProfilerPass.name = "CameraUIAndProfilerPass" + info.id;
        uiAndProfilerPass.setViewport(new Viewport(area.x, area.y, width, height));
        uiAndProfilerPass.addRenderTarget(dsUIAndProfilerPassRTName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w));
        uiAndProfilerPass.addDepthStencil(dsUIAndProfilerPassDSName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag);
        var sceneFlags = SceneFlags.UI;
        uiAndProfilerPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), sceneFlags);
        if (getProfilerCamera() === camera) {
          uiAndProfilerPass.showStatistics = true;
        }
      }

      var ForwardPipelineBuilder = exports('dA', function () {
        function ForwardPipelineBuilder() {}
        var _proto = ForwardPipelineBuilder.prototype;
        _proto.setup = function setup(cameras, ppl) {
          for (var i = 0; i < cameras.length; i++) {
            var camera = cameras[i];
            if (camera.scene === null) {
              continue;
            }
            ppl.update(camera);
            var info = prepareResource(ppl, camera, this.initResource, this.updateResource);
            setupForwardPass(ppl, info);
          }
        };
        _proto.initResource = function initResource(ppl, cameraInfo) {
          setupForwardRes(ppl, cameraInfo);
        };
        _proto.updateResource = function updateResource(ppl, cameraInfo) {
          updateForwardRes(ppl, cameraInfo);
        };
        return ForwardPipelineBuilder;
      }());
      var DeferredPipelineBuilder = exports('dB', function () {
        function DeferredPipelineBuilder() {}
        var _proto2 = DeferredPipelineBuilder.prototype;
        _proto2.setup = function setup(cameras, ppl) {
          for (var i = 0; i < cameras.length; ++i) {
            var camera = cameras[i];
            if (!camera.scene) {
              continue;
            }
            ppl.update(camera);
            var forceDisableCluster = false;
            var useCluster = !forceDisableCluster && ppl.device.hasFeature(Feature.COMPUTE_SHADER);
            var isGameView = camera.cameraUsage === CameraUsage.GAME || camera.cameraUsage === CameraUsage.GAME_VIEW;
            var info = prepareResource(ppl, camera, this.initResource, this.updateResource);
            if (!isGameView) {
              setupForwardPass(ppl, info);
              continue;
            }
            if (!isUICamera(camera)) {
              if (useCluster) {
                buildClusterPasses(camera, ppl);
              }
              setupGBufferPass(ppl, info);
              var lightInfo = setupLightingPass(ppl, info, useCluster);
              setupDeferredForward(ppl, info, lightInfo.rtName, useCluster);
              setupPostprocessPass(ppl, info, lightInfo.rtName);
              continue;
            }
            setupUIPass(ppl, info);
          }
        };
        _proto2.initResource = function initResource(ppl, cameraInfo) {
          if (!isUICamera(cameraInfo.camera)) {
            setupGBufferRes(ppl, cameraInfo);
            setupLightingRes(ppl, cameraInfo);
            setupPostprocessRes(ppl, cameraInfo);
          } else {
            setupUIRes(ppl, cameraInfo);
          }
        };
        _proto2.updateResource = function updateResource(ppl, cameraInfo) {
          if (!isUICamera(cameraInfo.camera)) {
            updateGBufferRes(ppl, cameraInfo);
            updateLightingRes(ppl, cameraInfo);
            updatePostprocessRes(ppl, cameraInfo);
          } else {
            updateUIRes(ppl, cameraInfo);
          }
        };
        return DeferredPipelineBuilder;
      }());

      var NodePool = exports('ez', function () {
        function NodePool(poolHandlerComp) {
          this.poolHandlerComp = void 0;
          this._pool = void 0;
          this.poolHandlerComp = poolHandlerComp;
          this._pool = [];
        }
        var _proto = NodePool.prototype;
        _proto.size = function size() {
          return this._pool.length;
        };
        _proto.clear = function clear() {
          var count = this._pool.length;
          for (var i = 0; i < count; ++i) {
            this._pool[i].destroy();
          }
          this._pool.length = 0;
        };
        _proto.put = function put(obj) {
          if (obj && this._pool.indexOf(obj) === -1) {
            obj.removeFromParent();
            var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null;
            if (handler && handler.unuse) {
              handler.unuse();
            }
            this._pool.push(obj);
          }
        };
        _proto.get = function get() {
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          var last = this._pool.length - 1;
          if (last < 0) {
            return null;
          } else {
            var obj = this._pool[last];
            this._pool.length = last;
            var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null;
            if (handler && handler.reuse) {
              handler.reuse(arguments);
            }
            return obj;
          }
        };
        return NodePool;
      }());
      legacyCC.NodePool = NodePool;

      var _globalThis$jsb, _globalJsb$copyTextTo;
      var globalJsb = (_globalThis$jsb = globalThis.jsb) !== null && _globalThis$jsb !== void 0 ? _globalThis$jsb : {};
      var _native = exports('eR', {
        DownloaderHints: globalJsb.DownloaderHints,
        Downloader: globalJsb.Downloader,
        zipUtils: globalJsb.zipUtils,
        fileUtils: globalJsb.fileUtils,
        DebugRenderer: globalJsb.DebugRenderer,
        copyTextToClipboard: (_globalJsb$copyTextTo = globalJsb.copyTextToClipboard) === null || _globalJsb$copyTextTo === void 0 ? void 0 : _globalJsb$copyTextTo.bind(globalJsb),
        garbageCollect: globalJsb.garbageCollect,
        reflection: globalJsb.reflection,
        bridge: globalJsb.bridge,
        jsbBridgeWrapper: globalJsb.jsbBridgeWrapper,
        AssetsManager: globalJsb.AssetsManager,
        EventAssetsManager: globalJsb.EventAssetsManager,
        Manifest: globalJsb.Manifest,
        saveImageData: globalJsb.saveImageData,
        process: globalJsb.process,
        adpf: globalJsb.adpf
      });

      legacyCC.renderer = renderer;

      var __extends=undefined&&undefined.__extends||function(){var extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b;}||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];};return function(d,b){extendStatics(d,b);function __(){this.constructor=d;}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __());};}();var dragonBones={};(function(dragonBones){})(dragonBones||(dragonBones={}));(function(dragonBones){var DragonBones=function(){function DragonBones(eventManager){this._clock=new dragonBones.WorldClock();this._events=[];this._objects=[];this._eventManager=null;this._eventManager=eventManager;console.info("DragonBones: "+DragonBones.VERSION+"\nWebsite: http://dragonbones.com/\nSource and Demo: https://github.com/DragonBones/");}DragonBones.prototype.advanceTime=function(passedTime){if(this._objects.length>0){for(var _i=0,_a=this._objects;_i<_a.length;_i++){var object=_a[_i];object.returnToPool();}this._objects.length=0;}this._clock.advanceTime(passedTime);if(this._events.length>0){for(var i=0;i<this._events.length;++i){var eventObject=this._events[i];var armature=eventObject.armature;if(armature._armatureData!==null){armature.eventDispatcher.dispatchDBEvent(eventObject.type,eventObject);if(eventObject.type===dragonBones.EventObject.SOUND_EVENT){this._eventManager.dispatchDBEvent(eventObject.type,eventObject);}}this.bufferObject(eventObject);}this._events.length=0;}};DragonBones.prototype.bufferEvent=function(value){if(this._events.indexOf(value)<0){this._events.push(value);}};DragonBones.prototype.bufferObject=function(object){if(this._objects.indexOf(object)<0){this._objects.push(object);}};Object.defineProperty(DragonBones.prototype,"clock",{get:function get(){return this._clock;},enumerable:true,configurable:true});Object.defineProperty(DragonBones.prototype,"eventManager",{get:function get(){return this._eventManager;},enumerable:true,configurable:true});DragonBones.VERSION="5.6.300";DragonBones.yDown=false;DragonBones.debug=false;DragonBones.debugDraw=false;DragonBones.webAssembly=false;return DragonBones;}();dragonBones.DragonBones=DragonBones;})(dragonBones||(dragonBones={}));if(!console.warn){console.warn=function(){};}if(!console.assert){console.assert=function(){};}if(!Date.now){Date.now=function now(){return new Date().getTime();};}var __extends=function __extends(t,e){function r(){this.constructor=t;}for(var i in e){if(e.hasOwnProperty(i)){t[i]=e[i];}}r.prototype=e.prototype,t.prototype=new r();};(function(dragonBones){var BaseObject=function(){function BaseObject(){this.hashCode=BaseObject._hashCode++;this._isInPool=false;}BaseObject._returnObject=function(object){var classType=String(object.constructor);var maxCount=classType in BaseObject._maxCountMap?BaseObject._maxCountMap[classType]:BaseObject._defaultMaxCount;var pool=BaseObject._poolsMap[classType]=BaseObject._poolsMap[classType]||[];if(pool.length<maxCount){if(!object._isInPool){object._isInPool=true;pool.push(object);}else {console.warn("The object is already in the pool.");}}};BaseObject.toString=function(){throw new Error();};BaseObject.setMaxCount=function(objectConstructor,maxCount){if(maxCount<0||maxCount!==maxCount){maxCount=0;}if(objectConstructor!==null){var classType=String(objectConstructor);var pool=classType in BaseObject._poolsMap?BaseObject._poolsMap[classType]:null;if(pool!==null&&pool.length>maxCount){pool.length=maxCount;}BaseObject._maxCountMap[classType]=maxCount;}else {BaseObject._defaultMaxCount=maxCount;for(var classType in BaseObject._poolsMap){var pool=BaseObject._poolsMap[classType];if(pool.length>maxCount){pool.length=maxCount;}if(classType in BaseObject._maxCountMap){BaseObject._maxCountMap[classType]=maxCount;}}}};BaseObject.clearPool=function(objectConstructor){if(objectConstructor===void 0){objectConstructor=null;}if(objectConstructor!==null){var classType=String(objectConstructor);var pool=classType in BaseObject._poolsMap?BaseObject._poolsMap[classType]:null;if(pool!==null&&pool.length>0){pool.length=0;}}else {for(var k in BaseObject._poolsMap){var pool=BaseObject._poolsMap[k];pool.length=0;}}};BaseObject.borrowObject=function(objectConstructor){var classType=String(objectConstructor);var pool=classType in BaseObject._poolsMap?BaseObject._poolsMap[classType]:null;if(pool!==null&&pool.length>0){var object_1=pool.pop();object_1._isInPool=false;return object_1;}var object=new objectConstructor();object._onClear();return object;};BaseObject.prototype.returnToPool=function(){this._onClear();BaseObject._returnObject(this);};BaseObject._hashCode=0;BaseObject._defaultMaxCount=3000;BaseObject._maxCountMap={};BaseObject._poolsMap={};return BaseObject;}();dragonBones.BaseObject=BaseObject;})(dragonBones||(dragonBones={}));(function(dragonBones){var Matrix=function(){function Matrix(a,b,c,d,tx,ty){if(a===void 0){a=1.0;}if(b===void 0){b=0.0;}if(c===void 0){c=0.0;}if(d===void 0){d=1.0;}if(tx===void 0){tx=0.0;}if(ty===void 0){ty=0.0;}this.a=a;this.b=b;this.c=c;this.d=d;this.tx=tx;this.ty=ty;}Matrix.prototype.toString=function(){return "[object dragonBones.Matrix] a:"+this.a+" b:"+this.b+" c:"+this.c+" d:"+this.d+" tx:"+this.tx+" ty:"+this.ty;};Matrix.prototype.copyFrom=function(value){this.a=value.a;this.b=value.b;this.c=value.c;this.d=value.d;this.tx=value.tx;this.ty=value.ty;return this;};Matrix.prototype.copyFromArray=function(value,offset){if(offset===void 0){offset=0;}this.a=value[offset];this.b=value[offset+1];this.c=value[offset+2];this.d=value[offset+3];this.tx=value[offset+4];this.ty=value[offset+5];return this;};Matrix.prototype.identity=function(){this.a=this.d=1.0;this.b=this.c=0.0;this.tx=this.ty=0.0;return this;};Matrix.prototype.concat=function(value){var aA=this.a*value.a;var bA=0.0;var cA=0.0;var dA=this.d*value.d;var txA=this.tx*value.a+value.tx;var tyA=this.ty*value.d+value.ty;if(this.b!==0.0||this.c!==0.0){aA+=this.b*value.c;bA+=this.b*value.d;cA+=this.c*value.a;dA+=this.c*value.b;}if(value.b!==0.0||value.c!==0.0){bA+=this.a*value.b;cA+=this.d*value.c;txA+=this.ty*value.c;tyA+=this.tx*value.b;}this.a=aA;this.b=bA;this.c=cA;this.d=dA;this.tx=txA;this.ty=tyA;return this;};Matrix.prototype.invert=function(){var aA=this.a;var bA=this.b;var cA=this.c;var dA=this.d;var txA=this.tx;var tyA=this.ty;if(bA===0.0&&cA===0.0){this.b=this.c=0.0;if(aA===0.0||dA===0.0){this.a=this.b=this.tx=this.ty=0.0;}else {aA=this.a=1.0/aA;dA=this.d=1.0/dA;this.tx=-aA*txA;this.ty=-dA*tyA;}return this;}var determinant=aA*dA-bA*cA;if(determinant===0.0){this.a=this.d=1.0;this.b=this.c=0.0;this.tx=this.ty=0.0;return this;}determinant=1.0/determinant;var k=this.a=dA*determinant;bA=this.b=-bA*determinant;cA=this.c=-cA*determinant;dA=this.d=aA*determinant;this.tx=-(k*txA+cA*tyA);this.ty=-(bA*txA+dA*tyA);return this;};Matrix.prototype.transformPoint=function(x,y,result,delta){if(delta===void 0){delta=false;}result.x=this.a*x+this.c*y;result.y=this.b*x+this.d*y;if(!delta){result.x+=this.tx;result.y+=this.ty;}};Matrix.prototype.transformRectangle=function(rectangle,delta){if(delta===void 0){delta=false;}var a=this.a;var b=this.b;var c=this.c;var d=this.d;var tx=delta?0.0:this.tx;var ty=delta?0.0:this.ty;var x=rectangle.x;var y=rectangle.y;var xMax=x+rectangle.width;var yMax=y+rectangle.height;var x0=a*x+c*y+tx;var y0=b*x+d*y+ty;var x1=a*xMax+c*y+tx;var y1=b*xMax+d*y+ty;var x2=a*xMax+c*yMax+tx;var y2=b*xMax+d*yMax+ty;var x3=a*x+c*yMax+tx;var y3=b*x+d*yMax+ty;var tmp=0.0;if(x0>x1){tmp=x0;x0=x1;x1=tmp;}if(x2>x3){tmp=x2;x2=x3;x3=tmp;}rectangle.x=Math.floor(x0<x2?x0:x2);rectangle.width=Math.ceil((x1>x3?x1:x3)-rectangle.x);if(y0>y1){tmp=y0;y0=y1;y1=tmp;}if(y2>y3){tmp=y2;y2=y3;y3=tmp;}rectangle.y=Math.floor(y0<y2?y0:y2);rectangle.height=Math.ceil((y1>y3?y1:y3)-rectangle.y);};return Matrix;}();dragonBones.Matrix=Matrix;})(dragonBones||(dragonBones={}));(function(dragonBones){var Transform=function(){function Transform(x,y,skew,rotation,scaleX,scaleY){if(x===void 0){x=0.0;}if(y===void 0){y=0.0;}if(skew===void 0){skew=0.0;}if(rotation===void 0){rotation=0.0;}if(scaleX===void 0){scaleX=1.0;}if(scaleY===void 0){scaleY=1.0;}this.x=x;this.y=y;this.skew=skew;this.rotation=rotation;this.scaleX=scaleX;this.scaleY=scaleY;}Transform.normalizeRadian=function(value){value=(value+Math.PI)%(Math.PI*2.0);value+=value>0.0?-Math.PI:Math.PI;return value;};Transform.prototype.toString=function(){return "[object dragonBones.Transform] x:"+this.x+" y:"+this.y+" skewX:"+this.skew*180.0/Math.PI+" skewY:"+this.rotation*180.0/Math.PI+" scaleX:"+this.scaleX+" scaleY:"+this.scaleY;};Transform.prototype.copyFrom=function(value){this.x=value.x;this.y=value.y;this.skew=value.skew;this.rotation=value.rotation;this.scaleX=value.scaleX;this.scaleY=value.scaleY;return this;};Transform.prototype.identity=function(){this.x=this.y=0.0;this.skew=this.rotation=0.0;this.scaleX=this.scaleY=1.0;return this;};Transform.prototype.add=function(value){this.x+=value.x;this.y+=value.y;this.skew+=value.skew;this.rotation+=value.rotation;this.scaleX*=value.scaleX;this.scaleY*=value.scaleY;return this;};Transform.prototype.minus=function(value){this.x-=value.x;this.y-=value.y;this.skew-=value.skew;this.rotation-=value.rotation;this.scaleX/=value.scaleX;this.scaleY/=value.scaleY;return this;};Transform.prototype.fromMatrix=function(matrix){var backupScaleX=this.scaleX,backupScaleY=this.scaleY;var PI_Q=Transform.PI_Q;this.x=matrix.tx;this.y=matrix.ty;this.rotation=Math.atan(matrix.b/matrix.a);var skewX=Math.atan(-matrix.c/matrix.d);this.scaleX=this.rotation>-PI_Q&&this.rotation<PI_Q?matrix.a/Math.cos(this.rotation):matrix.b/Math.sin(this.rotation);this.scaleY=skewX>-PI_Q&&skewX<PI_Q?matrix.d/Math.cos(skewX):-matrix.c/Math.sin(skewX);if(backupScaleX>=0.0&&this.scaleX<0.0){this.scaleX=-this.scaleX;this.rotation=this.rotation-Math.PI;}if(backupScaleY>=0.0&&this.scaleY<0.0){this.scaleY=-this.scaleY;skewX=skewX-Math.PI;}this.skew=skewX-this.rotation;return this;};Transform.prototype.toMatrix=function(matrix){if(this.rotation===0.0){matrix.a=1.0;matrix.b=0.0;}else {matrix.a=Math.cos(this.rotation);matrix.b=Math.sin(this.rotation);}if(this.skew===0.0){matrix.c=-matrix.b;matrix.d=matrix.a;}else {matrix.c=-Math.sin(this.skew+this.rotation);matrix.d=Math.cos(this.skew+this.rotation);}if(this.scaleX!==1.0){matrix.a*=this.scaleX;matrix.b*=this.scaleX;}if(this.scaleY!==1.0){matrix.c*=this.scaleY;matrix.d*=this.scaleY;}matrix.tx=this.x;matrix.ty=this.y;return this;};Transform.PI=Math.PI;Transform.PI_D=Math.PI*2.0;Transform.PI_H=Math.PI/2.0;Transform.PI_Q=Math.PI/4.0;Transform.RAD_DEG=180.0/Math.PI;Transform.DEG_RAD=Math.PI/180.0;return Transform;}();dragonBones.Transform=Transform;})(dragonBones||(dragonBones={}));(function(dragonBones){var ColorTransform=function(){function ColorTransform(alphaMultiplier,redMultiplier,greenMultiplier,blueMultiplier,alphaOffset,redOffset,greenOffset,blueOffset){if(alphaMultiplier===void 0){alphaMultiplier=1.0;}if(redMultiplier===void 0){redMultiplier=1.0;}if(greenMultiplier===void 0){greenMultiplier=1.0;}if(blueMultiplier===void 0){blueMultiplier=1.0;}if(alphaOffset===void 0){alphaOffset=0;}if(redOffset===void 0){redOffset=0;}if(greenOffset===void 0){greenOffset=0;}if(blueOffset===void 0){blueOffset=0;}this.alphaMultiplier=alphaMultiplier;this.redMultiplier=redMultiplier;this.greenMultiplier=greenMultiplier;this.blueMultiplier=blueMultiplier;this.alphaOffset=alphaOffset;this.redOffset=redOffset;this.greenOffset=greenOffset;this.blueOffset=blueOffset;}ColorTransform.prototype.copyFrom=function(value){this.alphaMultiplier=value.alphaMultiplier;this.redMultiplier=value.redMultiplier;this.greenMultiplier=value.greenMultiplier;this.blueMultiplier=value.blueMultiplier;this.alphaOffset=value.alphaOffset;this.redOffset=value.redOffset;this.greenOffset=value.greenOffset;this.blueOffset=value.blueOffset;};ColorTransform.prototype.identity=function(){this.alphaMultiplier=this.redMultiplier=this.greenMultiplier=this.blueMultiplier=1.0;this.alphaOffset=this.redOffset=this.greenOffset=this.blueOffset=0;};return ColorTransform;}();dragonBones.ColorTransform=ColorTransform;})(dragonBones||(dragonBones={}));(function(dragonBones){var Point=function(){function Point(x,y){if(x===void 0){x=0.0;}if(y===void 0){y=0.0;}this.x=x;this.y=y;}Point.prototype.copyFrom=function(value){this.x=value.x;this.y=value.y;};Point.prototype.clear=function(){this.x=this.y=0.0;};return Point;}();dragonBones.Point=Point;})(dragonBones||(dragonBones={}));(function(dragonBones){var Rectangle=function(){function Rectangle(x,y,width,height){if(x===void 0){x=0.0;}if(y===void 0){y=0.0;}if(width===void 0){width=0.0;}if(height===void 0){height=0.0;}this.x=x;this.y=y;this.width=width;this.height=height;}Rectangle.prototype.copyFrom=function(value){this.x=value.x;this.y=value.y;this.width=value.width;this.height=value.height;};Rectangle.prototype.clear=function(){this.x=this.y=0.0;this.width=this.height=0.0;};return Rectangle;}();dragonBones.Rectangle=Rectangle;})(dragonBones||(dragonBones={}));(function(dragonBones){var UserData=function(_super){__extends(UserData,_super);function UserData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.ints=[];_this.floats=[];_this.strings=[];return _this;}UserData.toString=function(){return "[class dragonBones.UserData]";};UserData.prototype._onClear=function(){this.ints.length=0;this.floats.length=0;this.strings.length=0;};UserData.prototype.addInt=function(value){this.ints.push(value);};UserData.prototype.addFloat=function(value){this.floats.push(value);};UserData.prototype.addString=function(value){this.strings.push(value);};UserData.prototype.getInt=function(index){if(index===void 0){index=0;}return index>=0&&index<this.ints.length?this.ints[index]:0;};UserData.prototype.getFloat=function(index){if(index===void 0){index=0;}return index>=0&&index<this.floats.length?this.floats[index]:0.0;};UserData.prototype.getString=function(index){if(index===void 0){index=0;}return index>=0&&index<this.strings.length?this.strings[index]:"";};return UserData;}(dragonBones.BaseObject);dragonBones.UserData=UserData;var ActionData=function(_super){__extends(ActionData,_super);function ActionData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.data=null;return _this;}ActionData.toString=function(){return "[class dragonBones.ActionData]";};ActionData.prototype._onClear=function(){if(this.data!==null){this.data.returnToPool();}this.type=0;this.name="";this.bone=null;this.slot=null;this.data=null;};return ActionData;}(dragonBones.BaseObject);dragonBones.ActionData=ActionData;})(dragonBones||(dragonBones={}));(function(dragonBones){var DragonBonesData=function(_super){__extends(DragonBonesData,_super);function DragonBonesData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.frameIndices=[];_this.cachedFrames=[];_this.armatureNames=[];_this.armatures={};_this.userData=null;return _this;}DragonBonesData.toString=function(){return "[class dragonBones.DragonBonesData]";};DragonBonesData.prototype._onClear=function(){for(var k in this.armatures){this.armatures[k].returnToPool();delete this.armatures[k];}if(this.userData!==null){this.userData.returnToPool();}this.autoSearch=false;this.frameRate=0;this.version="";this.name="";this.stage=null;this.frameIndices.length=0;this.cachedFrames.length=0;this.armatureNames.length=0;this.binary=null;this.intArray=null;this.floatArray=null;this.frameIntArray=null;this.frameFloatArray=null;this.frameArray=null;this.timelineArray=null;this.userData=null;};DragonBonesData.prototype.addArmature=function(value){if(value.name in this.armatures){console.warn("Same armature: "+value.name);return;}value.parent=this;this.armatures[value.name]=value;this.armatureNames.push(value.name);};DragonBonesData.prototype.getArmature=function(armatureName){return armatureName in this.armatures?this.armatures[armatureName]:null;};DragonBonesData.prototype.dispose=function(){console.warn("已废弃");this.returnToPool();};return DragonBonesData;}(dragonBones.BaseObject);dragonBones.DragonBonesData=DragonBonesData;})(dragonBones||(dragonBones={}));(function(dragonBones){var ArmatureData=function(_super){__extends(ArmatureData,_super);function ArmatureData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.aabb=new dragonBones.Rectangle();_this.animationNames=[];_this.sortedBones=[];_this.sortedSlots=[];_this.defaultActions=[];_this.actions=[];_this.bones={};_this.slots={};_this.constraints={};_this.skins={};_this.animations={};_this.canvas=null;_this.userData=null;return _this;}ArmatureData.toString=function(){return "[class dragonBones.ArmatureData]";};ArmatureData.prototype._onClear=function(){for(var _i=0,_a=this.defaultActions;_i<_a.length;_i++){var action=_a[_i];action.returnToPool();}for(var _b=0,_c=this.actions;_b<_c.length;_b++){var action=_c[_b];action.returnToPool();}for(var k in this.bones){this.bones[k].returnToPool();delete this.bones[k];}for(var k in this.slots){this.slots[k].returnToPool();delete this.slots[k];}for(var k in this.constraints){this.constraints[k].returnToPool();delete this.constraints[k];}for(var k in this.skins){this.skins[k].returnToPool();delete this.skins[k];}for(var k in this.animations){this.animations[k].returnToPool();delete this.animations[k];}if(this.canvas!==null){this.canvas.returnToPool();}if(this.userData!==null){this.userData.returnToPool();}this.type=0;this.frameRate=0;this.cacheFrameRate=0;this.scale=1.0;this.name="";this.aabb.clear();this.animationNames.length=0;this.sortedBones.length=0;this.sortedSlots.length=0;this.defaultActions.length=0;this.actions.length=0;this.defaultSkin=null;this.defaultAnimation=null;this.canvas=null;this.userData=null;this.parent=null;};ArmatureData.prototype.sortBones=function(){var total=this.sortedBones.length;if(total<=0){return;}var sortHelper=this.sortedBones.concat();var index=0;var count=0;this.sortedBones.length=0;while(count<total){var bone=sortHelper[index++];if(index>=total){index=0;}if(this.sortedBones.indexOf(bone)>=0){continue;}var flag=false;for(var k in this.constraints){var constraint=this.constraints[k];if(constraint.root===bone&&this.sortedBones.indexOf(constraint.target)<0){flag=true;break;}}if(flag){continue;}if(bone.parent!==null&&this.sortedBones.indexOf(bone.parent)<0){continue;}this.sortedBones.push(bone);count++;}};ArmatureData.prototype.cacheFrames=function(frameRate){if(this.cacheFrameRate>0){return;}this.cacheFrameRate=frameRate;for(var k in this.animations){this.animations[k].cacheFrames(this.cacheFrameRate);}};ArmatureData.prototype.setCacheFrame=function(globalTransformMatrix,transform){var dataArray=this.parent.cachedFrames;var arrayOffset=dataArray.length;dataArray.length+=10;dataArray[arrayOffset]=globalTransformMatrix.a;dataArray[arrayOffset+1]=globalTransformMatrix.b;dataArray[arrayOffset+2]=globalTransformMatrix.c;dataArray[arrayOffset+3]=globalTransformMatrix.d;dataArray[arrayOffset+4]=globalTransformMatrix.tx;dataArray[arrayOffset+5]=globalTransformMatrix.ty;dataArray[arrayOffset+6]=transform.rotation;dataArray[arrayOffset+7]=transform.skew;dataArray[arrayOffset+8]=transform.scaleX;dataArray[arrayOffset+9]=transform.scaleY;return arrayOffset;};ArmatureData.prototype.getCacheFrame=function(globalTransformMatrix,transform,arrayOffset){var dataArray=this.parent.cachedFrames;globalTransformMatrix.a=dataArray[arrayOffset];globalTransformMatrix.b=dataArray[arrayOffset+1];globalTransformMatrix.c=dataArray[arrayOffset+2];globalTransformMatrix.d=dataArray[arrayOffset+3];globalTransformMatrix.tx=dataArray[arrayOffset+4];globalTransformMatrix.ty=dataArray[arrayOffset+5];transform.rotation=dataArray[arrayOffset+6];transform.skew=dataArray[arrayOffset+7];transform.scaleX=dataArray[arrayOffset+8];transform.scaleY=dataArray[arrayOffset+9];transform.x=globalTransformMatrix.tx;transform.y=globalTransformMatrix.ty;};ArmatureData.prototype.addBone=function(value){if(value.name in this.bones){console.warn("Same bone: "+value.name);return;}this.bones[value.name]=value;this.sortedBones.push(value);};ArmatureData.prototype.addSlot=function(value){if(value.name in this.slots){console.warn("Same slot: "+value.name);return;}this.slots[value.name]=value;this.sortedSlots.push(value);};ArmatureData.prototype.addConstraint=function(value){if(value.name in this.constraints){console.warn("Same constraint: "+value.name);return;}this.constraints[value.name]=value;};ArmatureData.prototype.addSkin=function(value){if(value.name in this.skins){console.warn("Same skin: "+value.name);return;}value.parent=this;this.skins[value.name]=value;if(this.defaultSkin===null){this.defaultSkin=value;}if(value.name==="default"){this.defaultSkin=value;}};ArmatureData.prototype.addAnimation=function(value){if(value.name in this.animations){console.warn("Same animation: "+value.name);return;}value.parent=this;this.animations[value.name]=value;this.animationNames.push(value.name);if(this.defaultAnimation===null){this.defaultAnimation=value;}};ArmatureData.prototype.addAction=function(value,isDefault){if(isDefault){this.defaultActions.push(value);}else {this.actions.push(value);}};ArmatureData.prototype.getBone=function(boneName){return boneName in this.bones?this.bones[boneName]:null;};ArmatureData.prototype.getSlot=function(slotName){return slotName in this.slots?this.slots[slotName]:null;};ArmatureData.prototype.getConstraint=function(constraintName){return constraintName in this.constraints?this.constraints[constraintName]:null;};ArmatureData.prototype.getSkin=function(skinName){return skinName in this.skins?this.skins[skinName]:null;};ArmatureData.prototype.getMesh=function(skinName,slotName,meshName){var skin=this.getSkin(skinName);if(skin===null){return null;}return skin.getDisplay(slotName,meshName);};ArmatureData.prototype.getAnimation=function(animationName){return animationName in this.animations?this.animations[animationName]:null;};return ArmatureData;}(dragonBones.BaseObject);dragonBones.ArmatureData=ArmatureData;var BoneData=function(_super){__extends(BoneData,_super);function BoneData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.transform=new dragonBones.Transform();_this.userData=null;return _this;}BoneData.toString=function(){return "[class dragonBones.BoneData]";};BoneData.prototype._onClear=function(){if(this.userData!==null){this.userData.returnToPool();}this.inheritTranslation=false;this.inheritRotation=false;this.inheritScale=false;this.inheritReflection=false;this.type=0;this.length=0.0;this.name="";this.transform.identity();this.userData=null;this.parent=null;};return BoneData;}(dragonBones.BaseObject);dragonBones.BoneData=BoneData;var SurfaceData=function(_super){__extends(SurfaceData,_super);function SurfaceData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.vertices=[];return _this;}SurfaceData.toString=function(){return "[class dragonBones.SurfaceData]";};SurfaceData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=1;this.segmentX=0;this.segmentY=0;this.vertices.length=0;};return SurfaceData;}(BoneData);dragonBones.SurfaceData=SurfaceData;var SlotData=function(_super){__extends(SlotData,_super);function SlotData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.color=null;_this.userData=null;return _this;}SlotData.createColor=function(){return new dragonBones.ColorTransform();};SlotData.toString=function(){return "[class dragonBones.SlotData]";};SlotData.prototype._onClear=function(){if(this.userData!==null){this.userData.returnToPool();}this.blendMode=0;this.displayIndex=0;this.zOrder=0;this.name="";this.color=null;this.userData=null;this.parent=null;};SlotData.DEFAULT_COLOR=new dragonBones.ColorTransform();return SlotData;}(dragonBones.BaseObject);dragonBones.SlotData=SlotData;})(dragonBones||(dragonBones={}));(function(dragonBones){var ConstraintData=function(_super){__extends(ConstraintData,_super);function ConstraintData(){return _super!==null&&_super.apply(this,arguments)||this;}ConstraintData.prototype._onClear=function(){this.order=0;this.name="";this.type=0;this.target=null;this.root=null;this.bone=null;};return ConstraintData;}(dragonBones.BaseObject);dragonBones.ConstraintData=ConstraintData;var IKConstraintData=function(_super){__extends(IKConstraintData,_super);function IKConstraintData(){return _super!==null&&_super.apply(this,arguments)||this;}IKConstraintData.toString=function(){return "[class dragonBones.IKConstraintData]";};IKConstraintData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.scaleEnabled=false;this.bendPositive=false;this.weight=1.0;};return IKConstraintData;}(ConstraintData);dragonBones.IKConstraintData=IKConstraintData;var PathConstraintData=function(_super){__extends(PathConstraintData,_super);function PathConstraintData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.bones=[];return _this;}PathConstraintData.toString=function(){return "[class dragonBones.PathConstraintData]";};PathConstraintData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.pathSlot=null;this.pathDisplayData=null;this.bones.length=0;this.positionMode=0;this.spacingMode=1;this.rotateMode=1;this.position=0.0;this.spacing=0.0;this.rotateOffset=0.0;this.rotateMix=0.0;this.translateMix=0.0;};PathConstraintData.prototype.AddBone=function(value){this.bones.push(value);};return PathConstraintData;}(ConstraintData);dragonBones.PathConstraintData=PathConstraintData;})(dragonBones||(dragonBones={}));(function(dragonBones){var CanvasData=function(_super){__extends(CanvasData,_super);function CanvasData(){return _super!==null&&_super.apply(this,arguments)||this;}CanvasData.toString=function(){return "[class dragonBones.CanvasData]";};CanvasData.prototype._onClear=function(){this.hasBackground=false;this.color=0x000000;this.x=0;this.y=0;this.width=0;this.height=0;};return CanvasData;}(dragonBones.BaseObject);dragonBones.CanvasData=CanvasData;})(dragonBones||(dragonBones={}));(function(dragonBones){var SkinData=function(_super){__extends(SkinData,_super);function SkinData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.displays={};return _this;}SkinData.toString=function(){return "[class dragonBones.SkinData]";};SkinData.prototype._onClear=function(){for(var k in this.displays){var slotDisplays=this.displays[k];for(var _i=0,slotDisplays_1=slotDisplays;_i<slotDisplays_1.length;_i++){var display=slotDisplays_1[_i];if(display!==null){display.returnToPool();}}delete this.displays[k];}this.name="";this.parent=null;};SkinData.prototype.addDisplay=function(slotName,value){if(!(slotName in this.displays)){this.displays[slotName]=[];}if(value!==null){value.parent=this;}var slotDisplays=this.displays[slotName];slotDisplays.push(value);};SkinData.prototype.getDisplay=function(slotName,displayName){var slotDisplays=this.getDisplays(slotName);if(slotDisplays!==null){for(var _i=0,slotDisplays_2=slotDisplays;_i<slotDisplays_2.length;_i++){var display=slotDisplays_2[_i];if(display!==null&&display.name===displayName){return display;}}}return null;};SkinData.prototype.getDisplays=function(slotName){if(!(slotName in this.displays)){return null;}return this.displays[slotName];};return SkinData;}(dragonBones.BaseObject);dragonBones.SkinData=SkinData;})(dragonBones||(dragonBones={}));(function(dragonBones){var VerticesData=function(){function VerticesData(){this.weight=null;}VerticesData.prototype.clear=function(){if(!this.isShared&&this.weight!==null){this.weight.returnToPool();}this.isShared=false;this.inheritDeform=false;this.offset=0;this.data=null;this.weight=null;};VerticesData.prototype.shareFrom=function(value){this.isShared=true;this.offset=value.offset;this.weight=value.weight;};return VerticesData;}();dragonBones.VerticesData=VerticesData;var DisplayData=function(_super){__extends(DisplayData,_super);function DisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.transform=new dragonBones.Transform();return _this;}DisplayData.prototype._onClear=function(){this.name="";this.path="";this.transform.identity();this.parent=null;};return DisplayData;}(dragonBones.BaseObject);dragonBones.DisplayData=DisplayData;var ImageDisplayData=function(_super){__extends(ImageDisplayData,_super);function ImageDisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.pivot=new dragonBones.Point();return _this;}ImageDisplayData.toString=function(){return "[class dragonBones.ImageDisplayData]";};ImageDisplayData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=0;this.pivot.clear();this.texture=null;};return ImageDisplayData;}(DisplayData);dragonBones.ImageDisplayData=ImageDisplayData;var ArmatureDisplayData=function(_super){__extends(ArmatureDisplayData,_super);function ArmatureDisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.actions=[];return _this;}ArmatureDisplayData.toString=function(){return "[class dragonBones.ArmatureDisplayData]";};ArmatureDisplayData.prototype._onClear=function(){_super.prototype._onClear.call(this);for(var _i=0,_a=this.actions;_i<_a.length;_i++){var action=_a[_i];action.returnToPool();}this.type=1;this.inheritAnimation=false;this.actions.length=0;this.armature=null;};ArmatureDisplayData.prototype.addAction=function(value){this.actions.push(value);};return ArmatureDisplayData;}(DisplayData);dragonBones.ArmatureDisplayData=ArmatureDisplayData;var MeshDisplayData=function(_super){__extends(MeshDisplayData,_super);function MeshDisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.vertices=new VerticesData();return _this;}MeshDisplayData.toString=function(){return "[class dragonBones.MeshDisplayData]";};MeshDisplayData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=2;this.vertices.clear();this.texture=null;};return MeshDisplayData;}(DisplayData);dragonBones.MeshDisplayData=MeshDisplayData;var BoundingBoxDisplayData=function(_super){__extends(BoundingBoxDisplayData,_super);function BoundingBoxDisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.boundingBox=null;return _this;}BoundingBoxDisplayData.toString=function(){return "[class dragonBones.BoundingBoxDisplayData]";};BoundingBoxDisplayData.prototype._onClear=function(){_super.prototype._onClear.call(this);if(this.boundingBox!==null){this.boundingBox.returnToPool();}this.type=3;this.boundingBox=null;};return BoundingBoxDisplayData;}(DisplayData);dragonBones.BoundingBoxDisplayData=BoundingBoxDisplayData;var PathDisplayData=function(_super){__extends(PathDisplayData,_super);function PathDisplayData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.vertices=new VerticesData();_this.curveLengths=[];return _this;}PathDisplayData.toString=function(){return "[class dragonBones.PathDisplayData]";};PathDisplayData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=4;this.closed=false;this.constantSpeed=false;this.vertices.clear();this.curveLengths.length=0;};return PathDisplayData;}(DisplayData);dragonBones.PathDisplayData=PathDisplayData;var WeightData=function(_super){__extends(WeightData,_super);function WeightData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.bones=[];return _this;}WeightData.toString=function(){return "[class dragonBones.WeightData]";};WeightData.prototype._onClear=function(){this.count=0;this.offset=0;this.bones.length=0;};WeightData.prototype.addBone=function(value){this.bones.push(value);};return WeightData;}(dragonBones.BaseObject);dragonBones.WeightData=WeightData;})(dragonBones||(dragonBones={}));(function(dragonBones){var BoundingBoxData=function(_super){__extends(BoundingBoxData,_super);function BoundingBoxData(){return _super!==null&&_super.apply(this,arguments)||this;}BoundingBoxData.prototype._onClear=function(){this.color=0x000000;this.width=0.0;this.height=0.0;};return BoundingBoxData;}(dragonBones.BaseObject);dragonBones.BoundingBoxData=BoundingBoxData;var RectangleBoundingBoxData=function(_super){__extends(RectangleBoundingBoxData,_super);function RectangleBoundingBoxData(){return _super!==null&&_super.apply(this,arguments)||this;}RectangleBoundingBoxData.toString=function(){return "[class dragonBones.RectangleBoundingBoxData]";};RectangleBoundingBoxData._computeOutCode=function(x,y,xMin,yMin,xMax,yMax){var code=0;if(x<xMin){code|=1;}else if(x>xMax){code|=2;}if(y<yMin){code|=4;}else if(y>yMax){code|=8;}return code;};RectangleBoundingBoxData.rectangleIntersectsSegment=function(xA,yA,xB,yB,xMin,yMin,xMax,yMax,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var inSideA=xA>xMin&&xA<xMax&&yA>yMin&&yA<yMax;var inSideB=xB>xMin&&xB<xMax&&yB>yMin&&yB<yMax;if(inSideA&&inSideB){return -1;}var intersectionCount=0;var outcode0=RectangleBoundingBoxData._computeOutCode(xA,yA,xMin,yMin,xMax,yMax);var outcode1=RectangleBoundingBoxData._computeOutCode(xB,yB,xMin,yMin,xMax,yMax);while(true){if((outcode0|outcode1)===0){intersectionCount=2;break;}else if((outcode0&outcode1)!==0){break;}var x=0.0;var y=0.0;var normalRadian=0.0;var outcodeOut=outcode0!==0?outcode0:outcode1;if((outcodeOut&4)!==0){x=xA+(xB-xA)*(yMin-yA)/(yB-yA);y=yMin;if(normalRadians!==null){normalRadian=-Math.PI*0.5;}}else if((outcodeOut&8)!==0){x=xA+(xB-xA)*(yMax-yA)/(yB-yA);y=yMax;if(normalRadians!==null){normalRadian=Math.PI*0.5;}}else if((outcodeOut&2)!==0){y=yA+(yB-yA)*(xMax-xA)/(xB-xA);x=xMax;if(normalRadians!==null){normalRadian=0;}}else if((outcodeOut&1)!==0){y=yA+(yB-yA)*(xMin-xA)/(xB-xA);x=xMin;if(normalRadians!==null){normalRadian=Math.PI;}}if(outcodeOut===outcode0){xA=x;yA=y;outcode0=RectangleBoundingBoxData._computeOutCode(xA,yA,xMin,yMin,xMax,yMax);if(normalRadians!==null){normalRadians.x=normalRadian;}}else {xB=x;yB=y;outcode1=RectangleBoundingBoxData._computeOutCode(xB,yB,xMin,yMin,xMax,yMax);if(normalRadians!==null){normalRadians.y=normalRadian;}}}if(intersectionCount){if(inSideA){intersectionCount=2;if(intersectionPointA!==null){intersectionPointA.x=xB;intersectionPointA.y=yB;}if(intersectionPointB!==null){intersectionPointB.x=xB;intersectionPointB.y=xB;}if(normalRadians!==null){normalRadians.x=normalRadians.y+Math.PI;}}else if(inSideB){intersectionCount=1;if(intersectionPointA!==null){intersectionPointA.x=xA;intersectionPointA.y=yA;}if(intersectionPointB!==null){intersectionPointB.x=xA;intersectionPointB.y=yA;}if(normalRadians!==null){normalRadians.y=normalRadians.x+Math.PI;}}else {intersectionCount=3;if(intersectionPointA!==null){intersectionPointA.x=xA;intersectionPointA.y=yA;}if(intersectionPointB!==null){intersectionPointB.x=xB;intersectionPointB.y=yB;}}}return intersectionCount;};RectangleBoundingBoxData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=0;};RectangleBoundingBoxData.prototype.containsPoint=function(pX,pY){var widthH=this.width*0.5;if(pX>=-widthH&&pX<=widthH){var heightH=this.height*0.5;if(pY>=-heightH&&pY<=heightH){return true;}}return false;};RectangleBoundingBoxData.prototype.intersectsSegment=function(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var widthH=this.width*0.5;var heightH=this.height*0.5;var intersectionCount=RectangleBoundingBoxData.rectangleIntersectsSegment(xA,yA,xB,yB,-widthH,-heightH,widthH,heightH,intersectionPointA,intersectionPointB,normalRadians);return intersectionCount;};return RectangleBoundingBoxData;}(BoundingBoxData);dragonBones.RectangleBoundingBoxData=RectangleBoundingBoxData;var EllipseBoundingBoxData=function(_super){__extends(EllipseBoundingBoxData,_super);function EllipseBoundingBoxData(){return _super!==null&&_super.apply(this,arguments)||this;}EllipseBoundingBoxData.toString=function(){return "[class dragonBones.EllipseData]";};EllipseBoundingBoxData.ellipseIntersectsSegment=function(xA,yA,xB,yB,xC,yC,widthH,heightH,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var d=widthH/heightH;var dd=d*d;yA*=d;yB*=d;var dX=xB-xA;var dY=yB-yA;var lAB=Math.sqrt(dX*dX+dY*dY);var xD=dX/lAB;var yD=dY/lAB;var a=(xC-xA)*xD+(yC-yA)*yD;var aa=a*a;var ee=xA*xA+yA*yA;var rr=widthH*widthH;var dR=rr-ee+aa;var intersectionCount=0;if(dR>=0.0){var dT=Math.sqrt(dR);var sA=a-dT;var sB=a+dT;var inSideA=sA<0.0?-1:sA<=lAB?0:1;var inSideB=sB<0.0?-1:sB<=lAB?0:1;var sideAB=inSideA*inSideB;if(sideAB<0){return -1;}else if(sideAB===0){if(inSideA===-1){intersectionCount=2;xB=xA+sB*xD;yB=(yA+sB*yD)/d;if(intersectionPointA!==null){intersectionPointA.x=xB;intersectionPointA.y=yB;}if(intersectionPointB!==null){intersectionPointB.x=xB;intersectionPointB.y=yB;}if(normalRadians!==null){normalRadians.x=Math.atan2(yB/rr*dd,xB/rr);normalRadians.y=normalRadians.x+Math.PI;}}else if(inSideB===1){intersectionCount=1;xA=xA+sA*xD;yA=(yA+sA*yD)/d;if(intersectionPointA!==null){intersectionPointA.x=xA;intersectionPointA.y=yA;}if(intersectionPointB!==null){intersectionPointB.x=xA;intersectionPointB.y=yA;}if(normalRadians!==null){normalRadians.x=Math.atan2(yA/rr*dd,xA/rr);normalRadians.y=normalRadians.x+Math.PI;}}else {intersectionCount=3;if(intersectionPointA!==null){intersectionPointA.x=xA+sA*xD;intersectionPointA.y=(yA+sA*yD)/d;if(normalRadians!==null){normalRadians.x=Math.atan2(intersectionPointA.y/rr*dd,intersectionPointA.x/rr);}}if(intersectionPointB!==null){intersectionPointB.x=xA+sB*xD;intersectionPointB.y=(yA+sB*yD)/d;if(normalRadians!==null){normalRadians.y=Math.atan2(intersectionPointB.y/rr*dd,intersectionPointB.x/rr);}}}}}return intersectionCount;};EllipseBoundingBoxData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=1;};EllipseBoundingBoxData.prototype.containsPoint=function(pX,pY){var widthH=this.width*0.5;if(pX>=-widthH&&pX<=widthH){var heightH=this.height*0.5;if(pY>=-heightH&&pY<=heightH){pY*=widthH/heightH;return Math.sqrt(pX*pX+pY*pY)<=widthH;}}return false;};EllipseBoundingBoxData.prototype.intersectsSegment=function(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var intersectionCount=EllipseBoundingBoxData.ellipseIntersectsSegment(xA,yA,xB,yB,0.0,0.0,this.width*0.5,this.height*0.5,intersectionPointA,intersectionPointB,normalRadians);return intersectionCount;};return EllipseBoundingBoxData;}(BoundingBoxData);dragonBones.EllipseBoundingBoxData=EllipseBoundingBoxData;var PolygonBoundingBoxData=function(_super){__extends(PolygonBoundingBoxData,_super);function PolygonBoundingBoxData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.vertices=[];return _this;}PolygonBoundingBoxData.toString=function(){return "[class dragonBones.PolygonBoundingBoxData]";};PolygonBoundingBoxData.polygonIntersectsSegment=function(xA,yA,xB,yB,vertices,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}if(xA===xB){xA=xB+0.000001;}if(yA===yB){yA=yB+0.000001;}var count=vertices.length;var dXAB=xA-xB;var dYAB=yA-yB;var llAB=xA*yB-yA*xB;var intersectionCount=0;var xC=vertices[count-2];var yC=vertices[count-1];var dMin=0.0;var dMax=0.0;var xMin=0.0;var yMin=0.0;var xMax=0.0;var yMax=0.0;for(var i=0;i<count;i+=2){var xD=vertices[i];var yD=vertices[i+1];if(xC===xD){xC=xD+0.0001;}if(yC===yD){yC=yD+0.0001;}var dXCD=xC-xD;var dYCD=yC-yD;var llCD=xC*yD-yC*xD;var ll=dXAB*dYCD-dYAB*dXCD;var x=(llAB*dXCD-dXAB*llCD)/ll;if((x>=xC&&x<=xD||x>=xD&&x<=xC)&&(dXAB===0.0||x>=xA&&x<=xB||x>=xB&&x<=xA)){var y=(llAB*dYCD-dYAB*llCD)/ll;if((y>=yC&&y<=yD||y>=yD&&y<=yC)&&(dYAB===0.0||y>=yA&&y<=yB||y>=yB&&y<=yA)){if(intersectionPointB!==null){var d=x-xA;if(d<0.0){d=-d;}if(intersectionCount===0){dMin=d;dMax=d;xMin=x;yMin=y;xMax=x;yMax=y;if(normalRadians!==null){normalRadians.x=Math.atan2(yD-yC,xD-xC)-Math.PI*0.5;normalRadians.y=normalRadians.x;}}else {if(d<dMin){dMin=d;xMin=x;yMin=y;if(normalRadians!==null){normalRadians.x=Math.atan2(yD-yC,xD-xC)-Math.PI*0.5;}}if(d>dMax){dMax=d;xMax=x;yMax=y;if(normalRadians!==null){normalRadians.y=Math.atan2(yD-yC,xD-xC)-Math.PI*0.5;}}}intersectionCount++;}else {xMin=x;yMin=y;xMax=x;yMax=y;intersectionCount++;if(normalRadians!==null){normalRadians.x=Math.atan2(yD-yC,xD-xC)-Math.PI*0.5;normalRadians.y=normalRadians.x;}break;}}}xC=xD;yC=yD;}if(intersectionCount===1){if(intersectionPointA!==null){intersectionPointA.x=xMin;intersectionPointA.y=yMin;}if(intersectionPointB!==null){intersectionPointB.x=xMin;intersectionPointB.y=yMin;}if(normalRadians!==null){normalRadians.y=normalRadians.x+Math.PI;}}else if(intersectionCount>1){intersectionCount++;if(intersectionPointA!==null){intersectionPointA.x=xMin;intersectionPointA.y=yMin;}if(intersectionPointB!==null){intersectionPointB.x=xMax;intersectionPointB.y=yMax;}}return intersectionCount;};PolygonBoundingBoxData.prototype._onClear=function(){_super.prototype._onClear.call(this);this.type=2;this.x=0.0;this.y=0.0;this.vertices.length=0;};PolygonBoundingBoxData.prototype.containsPoint=function(pX,pY){var isInSide=false;if(pX>=this.x&&pX<=this.width&&pY>=this.y&&pY<=this.height){for(var i=0,l=this.vertices.length,iP=l-2;i<l;i+=2){var yA=this.vertices[iP+1];var yB=this.vertices[i+1];if(yB<pY&&yA>=pY||yA<pY&&yB>=pY){var xA=this.vertices[iP];var xB=this.vertices[i];if((pY-yB)*(xA-xB)/(yA-yB)+xB<pX){isInSide=!isInSide;}}iP=i;}}return isInSide;};PolygonBoundingBoxData.prototype.intersectsSegment=function(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var intersectionCount=0;if(RectangleBoundingBoxData.rectangleIntersectsSegment(xA,yA,xB,yB,this.x,this.y,this.x+this.width,this.y+this.height,null,null,null)!==0){intersectionCount=PolygonBoundingBoxData.polygonIntersectsSegment(xA,yA,xB,yB,this.vertices,intersectionPointA,intersectionPointB,normalRadians);}return intersectionCount;};return PolygonBoundingBoxData;}(BoundingBoxData);dragonBones.PolygonBoundingBoxData=PolygonBoundingBoxData;})(dragonBones||(dragonBones={}));(function(dragonBones){var AnimationData=function(_super){__extends(AnimationData,_super);function AnimationData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.cachedFrames=[];_this.boneTimelines={};_this.surfaceTimelines={};_this.slotTimelines={};_this.constraintTimelines={};_this.animationTimelines={};_this.boneCachedFrameIndices={};_this.slotCachedFrameIndices={};_this.actionTimeline=null;_this.zOrderTimeline=null;return _this;}AnimationData.toString=function(){return "[class dragonBones.AnimationData]";};AnimationData.prototype._onClear=function(){for(var k in this.boneTimelines){for(var _i=0,_a=this.boneTimelines[k];_i<_a.length;_i++){var timeline=_a[_i];timeline.returnToPool();}delete this.boneTimelines[k];}for(var k in this.surfaceTimelines){for(var _b=0,_c=this.surfaceTimelines[k];_b<_c.length;_b++){var timeline=_c[_b];timeline.returnToPool();}delete this.surfaceTimelines[k];}for(var k in this.slotTimelines){for(var _d=0,_e=this.slotTimelines[k];_d<_e.length;_d++){var timeline=_e[_d];timeline.returnToPool();}delete this.slotTimelines[k];}for(var k in this.constraintTimelines){for(var _f=0,_g=this.constraintTimelines[k];_f<_g.length;_f++){var timeline=_g[_f];timeline.returnToPool();}delete this.constraintTimelines[k];}for(var k in this.animationTimelines){for(var _h=0,_j=this.animationTimelines[k];_h<_j.length;_h++){var timeline=_j[_h];timeline.returnToPool();}delete this.animationTimelines[k];}for(var k in this.boneCachedFrameIndices){delete this.boneCachedFrameIndices[k];}for(var k in this.slotCachedFrameIndices){delete this.slotCachedFrameIndices[k];}if(this.actionTimeline!==null){this.actionTimeline.returnToPool();}if(this.zOrderTimeline!==null){this.zOrderTimeline.returnToPool();}this.frameIntOffset=0;this.frameFloatOffset=0;this.frameOffset=0;this.frameCount=0;this.playTimes=0;this.duration=0.0;this.scale=1.0;this.fadeInTime=0.0;this.cacheFrameRate=0.0;this.name="";this.cachedFrames.length=0;this.actionTimeline=null;this.zOrderTimeline=null;this.parent=null;};AnimationData.prototype.cacheFrames=function(frameRate){if(this.cacheFrameRate>0.0){return;}this.cacheFrameRate=Math.max(Math.ceil(frameRate*this.scale),1.0);var cacheFrameCount=Math.ceil(this.cacheFrameRate*this.duration)+1;this.cachedFrames.length=cacheFrameCount;for(var i=0,l=this.cacheFrames.length;i<l;++i){this.cachedFrames[i]=false;}for(var _i=0,_a=this.parent.sortedBones;_i<_a.length;_i++){var bone=_a[_i];var indices=new Array(cacheFrameCount);for(var i=0,l=indices.length;i<l;++i){indices[i]=-1;}this.boneCachedFrameIndices[bone.name]=indices;}for(var _b=0,_c=this.parent.sortedSlots;_b<_c.length;_b++){var slot=_c[_b];var indices=new Array(cacheFrameCount);for(var i=0,l=indices.length;i<l;++i){indices[i]=-1;}this.slotCachedFrameIndices[slot.name]=indices;}};AnimationData.prototype.addBoneTimeline=function(bone,timeline){var timelines=bone.name in this.boneTimelines?this.boneTimelines[bone.name]:this.boneTimelines[bone.name]=[];if(timelines.indexOf(timeline)<0){timelines.push(timeline);}};AnimationData.prototype.addSurfaceTimeline=function(surface,timeline){var timelines=surface.name in this.surfaceTimelines?this.surfaceTimelines[surface.name]:this.surfaceTimelines[surface.name]=[];if(timelines.indexOf(timeline)<0){timelines.push(timeline);}};AnimationData.prototype.addSlotTimeline=function(slot,timeline){var timelines=slot.name in this.slotTimelines?this.slotTimelines[slot.name]:this.slotTimelines[slot.name]=[];if(timelines.indexOf(timeline)<0){timelines.push(timeline);}};AnimationData.prototype.addConstraintTimeline=function(constraint,timeline){var timelines=constraint.name in this.constraintTimelines?this.constraintTimelines[constraint.name]:this.constraintTimelines[constraint.name]=[];if(timelines.indexOf(timeline)<0){timelines.push(timeline);}};AnimationData.prototype.addAnimationTimeline=function(timelineName,timeline){var timelines=timelineName in this.animationTimelines?this.animationTimelines[timelineName]:this.animationTimelines[timelineName]=[];if(timelines.indexOf(timeline)<0){timelines.push(timeline);}};AnimationData.prototype.getBoneTimelines=function(timelineName){return timelineName in this.boneTimelines?this.boneTimelines[timelineName]:null;};AnimationData.prototype.getSurfaceTimelines=function(timelineName){return timelineName in this.surfaceTimelines?this.surfaceTimelines[timelineName]:null;};AnimationData.prototype.getSlotTimelines=function(timelineName){return timelineName in this.slotTimelines?this.slotTimelines[timelineName]:null;};AnimationData.prototype.getConstraintTimelines=function(timelineName){return timelineName in this.constraintTimelines?this.constraintTimelines[timelineName]:null;};AnimationData.prototype.getAnimationTimelines=function(timelineName){return timelineName in this.animationTimelines?this.animationTimelines[timelineName]:null;};AnimationData.prototype.getBoneCachedFrameIndices=function(boneName){return boneName in this.boneCachedFrameIndices?this.boneCachedFrameIndices[boneName]:null;};AnimationData.prototype.getSlotCachedFrameIndices=function(slotName){return slotName in this.slotCachedFrameIndices?this.slotCachedFrameIndices[slotName]:null;};return AnimationData;}(dragonBones.BaseObject);dragonBones.AnimationData=AnimationData;var TimelineData=function(_super){__extends(TimelineData,_super);function TimelineData(){return _super!==null&&_super.apply(this,arguments)||this;}TimelineData.toString=function(){return "[class dragonBones.TimelineData]";};TimelineData.prototype._onClear=function(){this.type=10;this.offset=0;this.frameIndicesOffset=-1;};return TimelineData;}(dragonBones.BaseObject);dragonBones.TimelineData=TimelineData;})(dragonBones||(dragonBones={}));(function(dragonBones){var AnimationConfig=function(_super){__extends(AnimationConfig,_super);function AnimationConfig(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.boneMask=[];return _this;}AnimationConfig.toString=function(){return "[class dragonBones.AnimationConfig]";};AnimationConfig.prototype._onClear=function(){this.pauseFadeOut=true;this.fadeOutMode=4;this.fadeOutTweenType=1;this.fadeOutTime=-1.0;this.actionEnabled=true;this.additiveBlending=false;this.displayControl=true;this.pauseFadeIn=true;this.resetToPose=true;this.fadeInTweenType=1;this.playTimes=-1;this.layer=0;this.position=0.0;this.duration=-1.0;this.timeScale=-100.0;this.weight=1.0;this.fadeInTime=-1.0;this.autoFadeOutTime=-1.0;this.name="";this.animation="";this.group="";this.boneMask.length=0;};AnimationConfig.prototype.clear=function(){this._onClear();};AnimationConfig.prototype.copyFrom=function(value){this.pauseFadeOut=value.pauseFadeOut;this.fadeOutMode=value.fadeOutMode;this.autoFadeOutTime=value.autoFadeOutTime;this.fadeOutTweenType=value.fadeOutTweenType;this.actionEnabled=value.actionEnabled;this.additiveBlending=value.additiveBlending;this.displayControl=value.displayControl;this.pauseFadeIn=value.pauseFadeIn;this.resetToPose=value.resetToPose;this.playTimes=value.playTimes;this.layer=value.layer;this.position=value.position;this.duration=value.duration;this.timeScale=value.timeScale;this.fadeInTime=value.fadeInTime;this.fadeOutTime=value.fadeOutTime;this.fadeInTweenType=value.fadeInTweenType;this.weight=value.weight;this.name=value.name;this.animation=value.animation;this.group=value.group;this.boneMask.length=value.boneMask.length;for(var i=0,l=this.boneMask.length;i<l;++i){this.boneMask[i]=value.boneMask[i];}};AnimationConfig.prototype.containsBoneMask=function(boneName){return this.boneMask.length===0||this.boneMask.indexOf(boneName)>=0;};AnimationConfig.prototype.addBoneMask=function(armature,boneName,recursive){if(recursive===void 0){recursive=true;}var currentBone=armature.getBone(boneName);if(currentBone===null){return;}if(this.boneMask.indexOf(boneName)<0){this.boneMask.push(boneName);}if(recursive){for(var _i=0,_a=armature.getBones();_i<_a.length;_i++){var bone=_a[_i];if(this.boneMask.indexOf(bone.name)<0&&currentBone.contains(bone)){this.boneMask.push(bone.name);}}}};AnimationConfig.prototype.removeBoneMask=function(armature,boneName,recursive){if(recursive===void 0){recursive=true;}var index=this.boneMask.indexOf(boneName);if(index>=0){this.boneMask.splice(index,1);}if(recursive){var currentBone=armature.getBone(boneName);if(currentBone!==null){if(this.boneMask.length>0){for(var _i=0,_a=armature.getBones();_i<_a.length;_i++){var bone=_a[_i];var index_1=this.boneMask.indexOf(bone.name);if(index_1>=0&&currentBone.contains(bone)){this.boneMask.splice(index_1,1);}}}else {for(var _b=0,_c=armature.getBones();_b<_c.length;_b++){var bone=_c[_b];if(bone===currentBone){continue;}if(!currentBone.contains(bone)){this.boneMask.push(bone.name);}}}}}};return AnimationConfig;}(dragonBones.BaseObject);dragonBones.AnimationConfig=AnimationConfig;})(dragonBones||(dragonBones={}));(function(dragonBones){var TextureAtlasData=function(_super){__extends(TextureAtlasData,_super);function TextureAtlasData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.textures={};return _this;}TextureAtlasData.prototype._onClear=function(){for(var k in this.textures){this.textures[k].returnToPool();delete this.textures[k];}this.autoSearch=false;this.width=0;this.height=0;this.scale=1.0;this.name="";this.imagePath="";};TextureAtlasData.prototype.copyFrom=function(value){this.autoSearch=value.autoSearch;this.scale=value.scale;this.width=value.width;this.height=value.height;this.name=value.name;this.imagePath=value.imagePath;for(var k in this.textures){this.textures[k].returnToPool();delete this.textures[k];}for(var k in value.textures){var texture=this.createTexture();texture.copyFrom(value.textures[k]);this.textures[k]=texture;}};TextureAtlasData.prototype.addTexture=function(value){if(value.name in this.textures){console.warn("Same texture: "+value.name);return;}value.parent=this;this.textures[value.name]=value;};TextureAtlasData.prototype.getTexture=function(textureName){return textureName in this.textures?this.textures[textureName]:null;};return TextureAtlasData;}(dragonBones.BaseObject);dragonBones.TextureAtlasData=TextureAtlasData;var TextureData=function(_super){__extends(TextureData,_super);function TextureData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.region=new dragonBones.Rectangle();_this.frame=null;return _this;}TextureData.createRectangle=function(){return new dragonBones.Rectangle();};TextureData.prototype._onClear=function(){this.rotated=false;this.name="";this.region.clear();this.parent=null;this.frame=null;};TextureData.prototype.copyFrom=function(value){this.rotated=value.rotated;this.name=value.name;this.region.copyFrom(value.region);this.parent=value.parent;if(this.frame===null&&value.frame!==null){this.frame=TextureData.createRectangle();}else if(this.frame!==null&&value.frame===null){this.frame=null;}if(this.frame!==null&&value.frame!==null){this.frame.copyFrom(value.frame);}};return TextureData;}(dragonBones.BaseObject);dragonBones.TextureData=TextureData;})(dragonBones||(dragonBones={}));(function(dragonBones){var DeformVertices=function(_super){__extends(DeformVertices,_super);function DeformVertices(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.vertices=[];_this.bones=[];return _this;}DeformVertices.toString=function(){return "[class dragonBones.DeformVertices]";};DeformVertices.prototype._onClear=function(){this.verticesDirty=false;this.vertices.length=0;this.bones.length=0;this.verticesData=null;};DeformVertices.prototype.init=function(verticesDataValue,armature){this.verticesData=verticesDataValue;if(this.verticesData!==null){var vertexCount=0;if(this.verticesData.weight!==null){vertexCount=this.verticesData.weight.count*2;}else {vertexCount=this.verticesData.data.intArray[this.verticesData.offset+0]*2;}this.verticesDirty=true;this.vertices.length=vertexCount;this.bones.length=0;for(var i=0,l=this.vertices.length;i<l;++i){this.vertices[i]=0.0;}if(this.verticesData.weight!==null){for(var i=0,l=this.verticesData.weight.bones.length;i<l;++i){var bone=armature.getBone(this.verticesData.weight.bones[i].name);this.bones.push(bone);}}}else {this.verticesDirty=false;this.vertices.length=0;this.bones.length=0;this.verticesData=null;}};DeformVertices.prototype.isBonesUpdate=function(){for(var _i=0,_a=this.bones;_i<_a.length;_i++){var bone=_a[_i];if(bone!==null&&bone._childrenTransformDirty){return true;}}return false;};return DeformVertices;}(dragonBones.BaseObject);dragonBones.DeformVertices=DeformVertices;})(dragonBones||(dragonBones={}));(function(dragonBones_1){var Armature=function(_super){__extends(Armature,_super);function Armature(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._bones=[];_this._slots=[];_this._constraints=[];_this._actions=[];_this._animation=null;_this._proxy=null;_this._replaceTextureAtlasData=null;_this._clock=null;return _this;}Armature.toString=function(){return "[class dragonBones.Armature]";};Armature._onSortSlots=function(a,b){return a._zOrder>b._zOrder?1:-1;};Armature.prototype._onClear=function(){if(this._clock!==null){this._clock.remove(this);}for(var _i=0,_a=this._bones;_i<_a.length;_i++){var bone=_a[_i];bone.returnToPool();}for(var _b=0,_c=this._slots;_b<_c.length;_b++){var slot=_c[_b];slot.returnToPool();}for(var _d=0,_e=this._constraints;_d<_e.length;_d++){var constraint=_e[_d];constraint.returnToPool();}for(var _f=0,_g=this._actions;_f<_g.length;_f++){var action=_g[_f];action.returnToPool();}if(this._animation!==null){this._animation.returnToPool();}if(this._proxy!==null){this._proxy.dbClear();}if(this._replaceTextureAtlasData!==null){this._replaceTextureAtlasData.returnToPool();}this.inheritAnimation=true;this.userData=null;this._lockUpdate=false;this._slotsDirty=true;this._zOrderDirty=false;this._flipX=false;this._flipY=false;this._cacheFrameIndex=-1;this._bones.length=0;this._slots.length=0;this._constraints.length=0;this._actions.length=0;this._armatureData=null;this._animation=null;this._proxy=null;this._display=null;this._replaceTextureAtlasData=null;this._replacedTexture=null;this._dragonBones=null;this._clock=null;this._parent=null;};Armature.prototype._sortZOrder=function(slotIndices,offset){var slotDatas=this._armatureData.sortedSlots;var isOriginal=slotIndices===null;if(this._zOrderDirty||!isOriginal){for(var i=0,l=slotDatas.length;i<l;++i){var slotIndex=isOriginal?i:slotIndices[offset+i];if(slotIndex<0||slotIndex>=l){continue;}var slotData=slotDatas[slotIndex];var slot=this.getSlot(slotData.name);if(slot!==null){slot._setZorder(i);}}this._slotsDirty=true;this._zOrderDirty=!isOriginal;}};Armature.prototype._addBone=function(value){if(this._bones.indexOf(value)<0){this._bones.push(value);}};Armature.prototype._addSlot=function(value){if(this._slots.indexOf(value)<0){this._slots.push(value);}};Armature.prototype._addConstraint=function(value){if(this._constraints.indexOf(value)<0){this._constraints.push(value);}};Armature.prototype._bufferAction=function(action,append){if(this._actions.indexOf(action)<0){if(append){this._actions.push(action);}else {this._actions.unshift(action);}}};Armature.prototype.dispose=function(){if(this._armatureData!==null){this._lockUpdate=true;this._dragonBones.bufferObject(this);}};Armature.prototype.init=function(armatureData,proxy,display,dragonBones){if(this._armatureData!==null){return;}this._armatureData=armatureData;this._animation=dragonBones_1.BaseObject.borrowObject(dragonBones_1.Animation);this._proxy=proxy;this._display=display;this._dragonBones=dragonBones;this._proxy.dbInit(this);this._animation.init(this);this._animation.animations=this._armatureData.animations;};Armature.prototype.advanceTime=function(passedTime){if(this._lockUpdate){return;}if(this._armatureData===null){console.warn("The armature has been disposed.");return;}else if(this._armatureData.parent===null){console.warn("The armature data has been disposed.\nPlease make sure dispose armature before call factory.clear().");return;}var prevCacheFrameIndex=this._cacheFrameIndex;this._animation.advanceTime(passedTime);if(this._slotsDirty){this._slotsDirty=false;this._slots.sort(Armature._onSortSlots);}if(this._cacheFrameIndex<0||this._cacheFrameIndex!==prevCacheFrameIndex){var i=0,l=0;for(i=0,l=this._bones.length;i<l;++i){this._bones[i].update(this._cacheFrameIndex);}for(i=0,l=this._slots.length;i<l;++i){this._slots[i].update(this._cacheFrameIndex);}}if(this._actions.length>0){this._lockUpdate=true;for(var _i=0,_a=this._actions;_i<_a.length;_i++){var action=_a[_i];var actionData=action.actionData;if(actionData!==null){if(actionData.type===0){if(action.slot!==null){var childArmature=action.slot.childArmature;if(childArmature!==null){childArmature.animation.fadeIn(actionData.name);}}else if(action.bone!==null){for(var _b=0,_c=this.getSlots();_b<_c.length;_b++){var slot=_c[_b];if(slot.parent===action.bone){var childArmature=slot.childArmature;if(childArmature!==null){childArmature.animation.fadeIn(actionData.name);}}}}else {this._animation.fadeIn(actionData.name);}}}action.returnToPool();}this._actions.length=0;this._lockUpdate=false;}this._proxy.dbUpdate();};Armature.prototype.invalidUpdate=function(boneName,updateSlot){if(boneName===void 0){boneName=null;}if(updateSlot===void 0){updateSlot=false;}if(boneName!==null&&boneName.length>0){var bone=this.getBone(boneName);if(bone!==null){bone.invalidUpdate();if(updateSlot){for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];if(slot.parent===bone){slot.invalidUpdate();}}}}}else {for(var _b=0,_c=this._bones;_b<_c.length;_b++){var bone=_c[_b];bone.invalidUpdate();}if(updateSlot){for(var _d=0,_e=this._slots;_d<_e.length;_d++){var slot=_e[_d];slot.invalidUpdate();}}}};Armature.prototype.containsPoint=function(x,y){for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];if(slot.containsPoint(x,y)){return slot;}}return null;};Armature.prototype.intersectsSegment=function(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}var isV=xA===xB;var dMin=0.0;var dMax=0.0;var intXA=0.0;var intYA=0.0;var intXB=0.0;var intYB=0.0;var intAN=0.0;var intBN=0.0;var intSlotA=null;var intSlotB=null;for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];var intersectionCount=slot.intersectsSegment(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians);if(intersectionCount>0){if(intersectionPointA!==null||intersectionPointB!==null){if(intersectionPointA!==null){var d=isV?intersectionPointA.y-yA:intersectionPointA.x-xA;if(d<0.0){d=-d;}if(intSlotA===null||d<dMin){dMin=d;intXA=intersectionPointA.x;intYA=intersectionPointA.y;intSlotA=slot;if(normalRadians){intAN=normalRadians.x;}}}if(intersectionPointB!==null){var d=intersectionPointB.x-xA;if(d<0.0){d=-d;}if(intSlotB===null||d>dMax){dMax=d;intXB=intersectionPointB.x;intYB=intersectionPointB.y;intSlotB=slot;if(normalRadians!==null){intBN=normalRadians.y;}}}}else {intSlotA=slot;break;}}}if(intSlotA!==null&&intersectionPointA!==null){intersectionPointA.x=intXA;intersectionPointA.y=intYA;if(normalRadians!==null){normalRadians.x=intAN;}}if(intSlotB!==null&&intersectionPointB!==null){intersectionPointB.x=intXB;intersectionPointB.y=intYB;if(normalRadians!==null){normalRadians.y=intBN;}}return intSlotA;};Armature.prototype.getBone=function(name){for(var _i=0,_a=this._bones;_i<_a.length;_i++){var bone=_a[_i];if(bone.name===name){return bone;}}return null;};Armature.prototype.getBoneByDisplay=function(display){var slot=this.getSlotByDisplay(display);return slot!==null?slot.parent:null;};Armature.prototype.getSlot=function(name){for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];if(slot.name===name){return slot;}}return null;};Armature.prototype.getSlotByDisplay=function(display){if(display!==null){for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];if(slot.display===display){return slot;}}}return null;};Armature.prototype.getBones=function(){return this._bones;};Armature.prototype.getSlots=function(){return this._slots;};Object.defineProperty(Armature.prototype,"flipX",{get:function get(){return this._flipX;},set:function set(value){if(this._flipX===value){return;}this._flipX=value;this.invalidUpdate();},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"flipY",{get:function get(){return this._flipY;},set:function set(value){if(this._flipY===value){return;}this._flipY=value;this.invalidUpdate();},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"cacheFrameRate",{get:function get(){return this._armatureData.cacheFrameRate;},set:function set(value){if(this._armatureData.cacheFrameRate!==value){this._armatureData.cacheFrames(value);for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];var childArmature=slot.childArmature;if(childArmature!==null){childArmature.cacheFrameRate=value;}}}},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"name",{get:function get(){return this._armatureData.name;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"armatureData",{get:function get(){return this._armatureData;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"animation",{get:function get(){return this._animation;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"proxy",{get:function get(){return this._proxy;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"eventDispatcher",{get:function get(){return this._proxy;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"display",{get:function get(){return this._display;},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"replacedTexture",{get:function get(){return this._replacedTexture;},set:function set(value){if(this._replacedTexture===value){return;}if(this._replaceTextureAtlasData!==null){this._replaceTextureAtlasData.returnToPool();this._replaceTextureAtlasData=null;}this._replacedTexture=value;for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];slot.invalidUpdate();slot.update(-1);}},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"clock",{get:function get(){return this._clock;},set:function set(value){if(this._clock===value){return;}if(this._clock!==null){this._clock.remove(this);}this._clock=value;if(this._clock){this._clock.add(this);}for(var _i=0,_a=this._slots;_i<_a.length;_i++){var slot=_a[_i];var childArmature=slot.childArmature;if(childArmature!==null){childArmature.clock=this._clock;}}},enumerable:true,configurable:true});Object.defineProperty(Armature.prototype,"parent",{get:function get(){return this._parent;},enumerable:true,configurable:true});Armature.prototype.replaceTexture=function(texture){this.replacedTexture=texture;};Armature.prototype.hasEventListener=function(type){return this._proxy.hasDBEventListener(type);};Armature.prototype.addEventListener=function(type,listener,target){this._proxy.addDBEventListener(type,listener,target);};Armature.prototype.removeEventListener=function(type,listener,target){this._proxy.removeDBEventListener(type,listener,target);};Armature.prototype.enableAnimationCache=function(frameRate){console.warn("Deprecated.");this.cacheFrameRate=frameRate;};Armature.prototype.getDisplay=function(){return this._display;};return Armature;}(dragonBones_1.BaseObject);dragonBones_1.Armature=Armature;})(dragonBones||(dragonBones={}));(function(dragonBones){var TransformObject=function(_super){__extends(TransformObject,_super);function TransformObject(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.globalTransformMatrix=new dragonBones.Matrix();_this.global=new dragonBones.Transform();_this.offset=new dragonBones.Transform();return _this;}TransformObject.prototype._onClear=function(){this.globalTransformMatrix.identity();this.global.identity();this.offset.identity();this.origin=null;this.userData=null;this._globalDirty=false;this._armature=null;};TransformObject.prototype.updateGlobalTransform=function(){if(this._globalDirty){this._globalDirty=false;this.global.fromMatrix(this.globalTransformMatrix);}};Object.defineProperty(TransformObject.prototype,"armature",{get:function get(){return this._armature;},enumerable:true,configurable:true});TransformObject._helpMatrix=new dragonBones.Matrix();TransformObject._helpTransform=new dragonBones.Transform();TransformObject._helpPoint=new dragonBones.Point();return TransformObject;}(dragonBones.BaseObject);dragonBones.TransformObject=TransformObject;})(dragonBones||(dragonBones={}));(function(dragonBones){var Bone=function(_super){__extends(Bone,_super);function Bone(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.animationPose=new dragonBones.Transform();_this._blendState=new dragonBones.BlendState();return _this;}Bone.toString=function(){return "[class dragonBones.Bone]";};Bone.prototype._onClear=function(){_super.prototype._onClear.call(this);this.offsetMode=1;this.animationPose.identity();this._transformDirty=false;this._childrenTransformDirty=false;this._localDirty=true;this._hasConstraint=false;this._visible=true;this._cachedFrameIndex=-1;this._blendState.clear();this._boneData=null;this._parent=null;this._cachedFrameIndices=null;};Bone.prototype._updateGlobalTransformMatrix=function(isCache){var boneData=this._boneData;var global=this.global;var globalTransformMatrix=this.globalTransformMatrix;var origin=this.origin;var offset=this.offset;var animationPose=this.animationPose;var parent=this._parent;var flipX=this._armature.flipX;var flipY=this._armature.flipY===dragonBones.DragonBones.yDown;var inherit=parent!==null;var rotation=0.0;if(this.offsetMode===1){if(origin!==null){global.x=origin.x+offset.x+animationPose.x;global.scaleX=origin.scaleX*offset.scaleX*animationPose.scaleX;global.scaleY=origin.scaleY*offset.scaleY*animationPose.scaleY;if(dragonBones.DragonBones.yDown){global.y=origin.y+offset.y+animationPose.y;global.skew=origin.skew+offset.skew+animationPose.skew;global.rotation=origin.rotation+offset.rotation+animationPose.rotation;}else {global.y=origin.y-offset.y+animationPose.y;global.skew=origin.skew-offset.skew+animationPose.skew;global.rotation=origin.rotation-offset.rotation+animationPose.rotation;}}else {global.copyFrom(offset);if(!dragonBones.DragonBones.yDown){global.y=-global.y;global.skew=-global.skew;global.rotation=-global.rotation;}global.add(animationPose);}}else if(this.offsetMode===0){if(origin!==null){global.copyFrom(origin).add(animationPose);}else {global.copyFrom(animationPose);}}else {inherit=false;global.copyFrom(offset);if(!dragonBones.DragonBones.yDown){global.y=-global.y;global.skew=-global.skew;global.rotation=-global.rotation;}}if(inherit){var parentMatrix=parent._boneData.type===0?parent.globalTransformMatrix:parent._getGlobalTransformMatrix(global.x,global.y);if(boneData.inheritScale){if(!boneData.inheritRotation){parent.updateGlobalTransform();if(flipX&&flipY){rotation=global.rotation-(parent.global.rotation+Math.PI);}else if(flipX){rotation=global.rotation+parent.global.rotation+Math.PI;}else if(flipY){rotation=global.rotation+parent.global.rotation;}else {rotation=global.rotation-parent.global.rotation;}global.rotation=rotation;}global.toMatrix(globalTransformMatrix);globalTransformMatrix.concat(parentMatrix);if(boneData.inheritTranslation){global.x=globalTransformMatrix.tx;global.y=globalTransformMatrix.ty;}else {globalTransformMatrix.tx=global.x;globalTransformMatrix.ty=global.y;}if(isCache){global.fromMatrix(globalTransformMatrix);}else {this._globalDirty=true;}}else {if(boneData.inheritTranslation){var x=global.x;var y=global.y;global.x=parentMatrix.a*x+parentMatrix.c*y+parentMatrix.tx;global.y=parentMatrix.b*x+parentMatrix.d*y+parentMatrix.ty;}else {if(flipX){global.x=-global.x;}if(flipY){global.y=-global.y;}}if(boneData.inheritRotation){parent.updateGlobalTransform();if(parent.global.scaleX<0.0){rotation=global.rotation+parent.global.rotation+Math.PI;}else {rotation=global.rotation+parent.global.rotation;}if(parentMatrix.a*parentMatrix.d-parentMatrix.b*parentMatrix.c<0.0){rotation-=global.rotation*2.0;if(flipX!==flipY||boneData.inheritReflection){global.skew+=Math.PI;}if(!dragonBones.DragonBones.yDown){global.skew=-global.skew;}}global.rotation=rotation;}else if(flipX||flipY){if(flipX&&flipY){rotation=global.rotation+Math.PI;}else {if(flipX){rotation=Math.PI-global.rotation;}else {rotation=-global.rotation;}global.skew+=Math.PI;}global.rotation=rotation;}global.toMatrix(globalTransformMatrix);}}else {if(flipX||flipY){if(flipX){global.x=-global.x;}if(flipY){global.y=-global.y;}if(flipX&&flipY){rotation=global.rotation+Math.PI;}else {if(flipX){rotation=Math.PI-global.rotation;}else {rotation=-global.rotation;}global.skew+=Math.PI;}global.rotation=rotation;}global.toMatrix(globalTransformMatrix);}};Bone.prototype.init=function(boneData,armatureValue){if(this._boneData!==null){return;}this._boneData=boneData;this._armature=armatureValue;if(this._boneData.parent!==null){this._parent=this._armature.getBone(this._boneData.parent.name);}this._armature._addBone(this);this.origin=this._boneData.transform;};Bone.prototype.update=function(cacheFrameIndex){this._blendState.dirty=false;if(cacheFrameIndex>=0&&this._cachedFrameIndices!==null){var cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex];if(cachedFrameIndex>=0&&this._cachedFrameIndex===cachedFrameIndex){this._transformDirty=false;}else if(cachedFrameIndex>=0){this._transformDirty=true;this._cachedFrameIndex=cachedFrameIndex;}else {if(this._hasConstraint){for(var _i=0,_a=this._armature._constraints;_i<_a.length;_i++){var constraint=_a[_i];if(constraint._root===this){constraint.update();}}}if(this._transformDirty||this._parent!==null&&this._parent._childrenTransformDirty){this._transformDirty=true;this._cachedFrameIndex=-1;}else if(this._cachedFrameIndex>=0){this._transformDirty=false;this._cachedFrameIndices[cacheFrameIndex]=this._cachedFrameIndex;}else {this._transformDirty=true;this._cachedFrameIndex=-1;}}}else {if(this._hasConstraint){for(var _b=0,_c=this._armature._constraints;_b<_c.length;_b++){var constraint=_c[_b];if(constraint._root===this){constraint.update();}}}if(this._transformDirty||this._parent!==null&&this._parent._childrenTransformDirty){cacheFrameIndex=-1;this._transformDirty=true;this._cachedFrameIndex=-1;}}if(this._transformDirty){this._transformDirty=false;this._childrenTransformDirty=true;if(this._cachedFrameIndex<0){var isCache=cacheFrameIndex>=0;if(this._localDirty){this._updateGlobalTransformMatrix(isCache);}if(isCache&&this._cachedFrameIndices!==null){this._cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex]=this._armature._armatureData.setCacheFrame(this.globalTransformMatrix,this.global);}}else {this._armature._armatureData.getCacheFrame(this.globalTransformMatrix,this.global,this._cachedFrameIndex);}}else if(this._childrenTransformDirty){this._childrenTransformDirty=false;}this._localDirty=true;};Bone.prototype.updateByConstraint=function(){if(this._localDirty){this._localDirty=false;if(this._transformDirty||this._parent!==null&&this._parent._childrenTransformDirty){this._updateGlobalTransformMatrix(true);}this._transformDirty=true;}};Bone.prototype.invalidUpdate=function(){this._transformDirty=true;};Bone.prototype.contains=function(value){if(value===this){return false;}var ancestor=value;while(ancestor!==this&&ancestor!==null){ancestor=ancestor.parent;}return ancestor===this;};Object.defineProperty(Bone.prototype,"boneData",{get:function get(){return this._boneData;},enumerable:true,configurable:true});Object.defineProperty(Bone.prototype,"visible",{get:function get(){return this._visible;},set:function set(value){if(this._visible===value){return;}this._visible=value;for(var _i=0,_a=this._armature.getSlots();_i<_a.length;_i++){var slot=_a[_i];if(slot.parent===this){slot._updateVisible();}}},enumerable:true,configurable:true});Object.defineProperty(Bone.prototype,"name",{get:function get(){return this._boneData.name;},enumerable:true,configurable:true});Object.defineProperty(Bone.prototype,"parent",{get:function get(){return this._parent;},enumerable:true,configurable:true});Bone.prototype.getBones=function(){console.warn("Deprecated.");var bones=new Array();for(var _i=0,_a=this._armature.getBones();_i<_a.length;_i++){var bone=_a[_i];if(bone.parent===this){bones.push(bone);}}return bones;};Bone.prototype.getSlots=function(){console.warn("Deprecated.");var slots=new Array();for(var _i=0,_a=this._armature.getSlots();_i<_a.length;_i++){var slot=_a[_i];if(slot.parent===this){slots.push(slot);}}return slots;};Object.defineProperty(Bone.prototype,"slot",{get:function get(){console.warn("Deprecated.");for(var _i=0,_a=this._armature.getSlots();_i<_a.length;_i++){var slot=_a[_i];if(slot.parent===this){return slot;}}return null;},enumerable:true,configurable:true});return Bone;}(dragonBones.TransformObject);dragonBones.Bone=Bone;})(dragonBones||(dragonBones={}));(function(dragonBones){var Surface=function(_super){__extends(Surface,_super);function Surface(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._vertices=[];_this._deformVertices=[];_this._hullCache=[];_this._matrixCahce=[];return _this;}Surface.toString=function(){return "[class dragonBones.Surface]";};Surface.prototype._onClear=function(){_super.prototype._onClear.call(this);this._dX=0.0;this._dY=0.0;this._k=0.0;this._kX=0.0;this._kY=0.0;this._vertices.length=0;this._deformVertices.length=0;this._matrixCahce.length=0;this._hullCache.length=0;};Surface.prototype._getAffineTransform=function(x,y,lX,lY,aX,aY,bX,bY,cX,cY,transform,matrix,isDown){var dabX=bX-aX;var dabY=bY-aY;var dacX=cX-aX;var dacY=cY-aY;transform.rotation=Math.atan2(dabY,dabX);transform.skew=Math.atan2(dacY,dacX)-Math.PI*0.5-transform.rotation;if(isDown){transform.rotation+=Math.PI;}transform.scaleX=Math.sqrt(dabX*dabX+dabY*dabY)/lX;transform.scaleY=Math.sqrt(dacX*dacX+dacY*dacY)/lY;transform.toMatrix(matrix);transform.x=matrix.tx=aX-(matrix.a*x+matrix.c*y);transform.y=matrix.ty=aY-(matrix.b*x+matrix.d*y);};Surface.prototype._updateVertices=function(){var originalVertices=this._boneData.vertices;var vertices=this._vertices;var animationVertices=this._deformVertices;if(this._parent!==null){if(this._parent._boneData.type===1){for(var i=0,l=originalVertices.length;i<l;i+=2){var x=originalVertices[i]+animationVertices[i];var y=originalVertices[i+1]+animationVertices[i];var matrix=this._parent._getGlobalTransformMatrix(x,y);vertices[i]=matrix.a*x+matrix.c*y+matrix.tx;vertices[i+1]=matrix.b*x+matrix.d*y+matrix.ty;}}else {var parentMatrix=this._parent.globalTransformMatrix;for(var i=0,l=originalVertices.length;i<l;i+=2){var x=originalVertices[i]+animationVertices[i];var y=originalVertices[i+1]+animationVertices[i+1];vertices[i]=parentMatrix.a*x+parentMatrix.c*y+parentMatrix.tx;vertices[i+1]=parentMatrix.b*x+parentMatrix.d*y+parentMatrix.ty;}}}else {for(var i=0,l=originalVertices.length;i<l;i+=2){vertices[i]=originalVertices[i]+animationVertices[i];vertices[i+1]=originalVertices[i+1]+animationVertices[i+1];}}};Surface.prototype._updateGlobalTransformMatrix=function(isCache){var segmentXD=this._boneData.segmentX*2;var lastIndex=this._vertices.length-2;var lA=200.0;var raX=this._vertices[0];var raY=this._vertices[1];var rbX=this._vertices[segmentXD];var rbY=this._vertices[segmentXD+1];var rcX=this._vertices[lastIndex];var rcY=this._vertices[lastIndex+1];var rdX=this._vertices[lastIndex-segmentXD];var rdY=this._vertices[lastIndex-segmentXD+1];var dacX=raX+(rcX-raX)*0.5;var dacY=raY+(rcY-raY)*0.5;var dbdX=rbX+(rdX-rbX)*0.5;var dbdY=rbY+(rdY-rbY)*0.5;var aX=dacX+(dbdX-dacX)*0.5;var aY=dacY+(dbdY-dacY)*0.5;var bX=rbX+(rcX-rbX)*0.5;var bY=rbY+(rcY-rbY)*0.5;var cX=rdX+(rcX-rdX)*0.5;var cY=rdY+(rcY-rdY)*0.5;this._globalDirty=false;this._getAffineTransform(0.0,0.0,lA,lA,aX,aY,bX,bY,cX,cY,this.global,this.globalTransformMatrix,false);};Surface.prototype._getGlobalTransformMatrix=function(x,y){var lB=1000.0;if(x<-lB||lB<x||y<-lB||lB<y){return this.globalTransformMatrix;}var isDown=false;var lA=200.0;var surfaceData=this._boneData;var segmentX=surfaceData.segmentX;var segmentY=surfaceData.segmentY;var segmentXD=surfaceData.segmentX*2;var dX=this._dX;var dY=this._dY;var indexX=Math.floor((x+lA)/dX);var indexY=Math.floor((y+lA)/dY);var matrixIndex=0;var pX=indexX*dX-lA;var pY=indexY*dY-lA;var matrices=this._matrixCahce;var helpMatrix=Surface._helpMatrix;if(x<-lA){if(y<-lA||y>=lA){return this.globalTransformMatrix;}isDown=y>this._kX*(x+lA)+pY;matrixIndex=((segmentX*(segmentY+1)+segmentX*2+segmentY+indexY)*2+(isDown?1:0))*7;if(this._matrixCahce[matrixIndex]>0.0){helpMatrix.copyFromArray(matrices,matrixIndex+1);}else {var vertexIndex=indexY*(segmentXD+2);var ddX=this._hullCache[4];var ddY=this._hullCache[5];var sX=this._hullCache[2]-(segmentY-indexY)*ddX;var sY=this._hullCache[3]-(segmentY-indexY)*ddY;var vertices=this._vertices;if(isDown){this._getAffineTransform(-lA,pY+dY,lB-lA,dY,vertices[vertexIndex+segmentXD+2],vertices[vertexIndex+segmentXD+3],sX+ddX,sY+ddY,vertices[vertexIndex],vertices[vertexIndex+1],Surface._helpTransform,helpMatrix,true);}else {this._getAffineTransform(-lB,pY,lB-lA,dY,sX,sY,vertices[vertexIndex],vertices[vertexIndex+1],sX+ddX,sY+ddY,Surface._helpTransform,helpMatrix,false);}matrices[matrixIndex]=1.0;matrices[matrixIndex+1]=helpMatrix.a;matrices[matrixIndex+2]=helpMatrix.b;matrices[matrixIndex+3]=helpMatrix.c;matrices[matrixIndex+4]=helpMatrix.d;matrices[matrixIndex+5]=helpMatrix.tx;matrices[matrixIndex+6]=helpMatrix.ty;}}else if(x>=lA){if(y<-lA||y>=lA){return this.globalTransformMatrix;}isDown=y>this._kX*(x-lB)+pY;matrixIndex=((segmentX*(segmentY+1)+segmentX+indexY)*2+(isDown?1:0))*7;if(this._matrixCahce[matrixIndex]>0.0){helpMatrix.copyFromArray(matrices,matrixIndex+1);}else {var vertexIndex=(indexY+1)*(segmentXD+2)-2;var ddX=this._hullCache[4];var ddY=this._hullCache[5];var sX=this._hullCache[0]+indexY*ddX;var sY=this._hullCache[1]+indexY*ddY;var vertices=this._vertices;if(isDown){this._getAffineTransform(lB,pY+dY,lB-lA,dY,sX+ddX,sY+ddY,vertices[vertexIndex+segmentXD+2],vertices[vertexIndex+segmentXD+3],sX,sY,Surface._helpTransform,helpMatrix,true);}else {this._getAffineTransform(lA,pY,lB-lA,dY,vertices[vertexIndex],vertices[vertexIndex+1],sX,sY,vertices[vertexIndex+segmentXD+2],vertices[vertexIndex+segmentXD+3],Surface._helpTransform,helpMatrix,false);}matrices[matrixIndex]=1.0;matrices[matrixIndex+1]=helpMatrix.a;matrices[matrixIndex+2]=helpMatrix.b;matrices[matrixIndex+3]=helpMatrix.c;matrices[matrixIndex+4]=helpMatrix.d;matrices[matrixIndex+5]=helpMatrix.tx;matrices[matrixIndex+6]=helpMatrix.ty;}}else if(y<-lA){if(x<-lA||x>=lA){return this.globalTransformMatrix;}isDown=y>this._kY*(x-pX-dX)-lB;matrixIndex=(segmentX*(segmentY+1)+indexX*2+(isDown?1:0))*7;if(this._matrixCahce[matrixIndex]>0.0){helpMatrix.copyFromArray(matrices,matrixIndex+1);}else {var vertexIndex=indexX*2;var ddX=this._hullCache[10];var ddY=this._hullCache[11];var sX=this._hullCache[8]+indexX*ddX;var sY=this._hullCache[9]+indexX*ddY;var vertices=this._vertices;if(isDown){this._getAffineTransform(pX+dX,-lA,dX,lB-lA,vertices[vertexIndex+2],vertices[vertexIndex+3],vertices[vertexIndex],vertices[vertexIndex+1],sX+ddX,sY+ddY,Surface._helpTransform,helpMatrix,true);}else {this._getAffineTransform(pX,-lB,dX,lB-lA,sX,sY,sX+ddX,sY+ddY,vertices[vertexIndex],vertices[vertexIndex+1],Surface._helpTransform,helpMatrix,false);}matrices[matrixIndex]=1.0;matrices[matrixIndex+1]=helpMatrix.a;matrices[matrixIndex+2]=helpMatrix.b;matrices[matrixIndex+3]=helpMatrix.c;matrices[matrixIndex+4]=helpMatrix.d;matrices[matrixIndex+5]=helpMatrix.tx;matrices[matrixIndex+6]=helpMatrix.ty;}}else if(y>=lA){if(x<-lA||x>=lA){return this.globalTransformMatrix;}isDown=y>this._kY*(x-pX-dX)+lA;matrixIndex=((segmentX*(segmentY+1)+segmentX+segmentY+indexY)*2+(isDown?1:0))*7;if(this._matrixCahce[matrixIndex]>0.0){helpMatrix.copyFromArray(matrices,matrixIndex+1);}else {var vertexIndex=segmentY*(segmentXD+2)+indexX*2;var ddX=this._hullCache[10];var ddY=this._hullCache[11];var sX=this._hullCache[6]-(segmentX-indexX)*ddX;var sY=this._hullCache[7]-(segmentX-indexX)*ddY;var vertices=this._vertices;if(isDown){this._getAffineTransform(pX+dX,lB,dX,lB-lA,sX+ddX,sY+ddY,sX,sY,vertices[vertexIndex+2],vertices[vertexIndex+3],Surface._helpTransform,helpMatrix,true);}else {this._getAffineTransform(pX,lA,dX,lB-lA,vertices[vertexIndex],vertices[vertexIndex+1],vertices[vertexIndex+2],vertices[vertexIndex+3],sX,sY,Surface._helpTransform,helpMatrix,false);}matrices[matrixIndex]=1.0;matrices[matrixIndex+1]=helpMatrix.a;matrices[matrixIndex+2]=helpMatrix.b;matrices[matrixIndex+3]=helpMatrix.c;matrices[matrixIndex+4]=helpMatrix.d;matrices[matrixIndex+5]=helpMatrix.tx;matrices[matrixIndex+6]=helpMatrix.ty;}}else {isDown=y>this._k*(x-pX-dX)+pY;matrixIndex=((segmentX*indexY+indexX)*2+(isDown?1:0))*7;if(this._matrixCahce[matrixIndex]>0.0){helpMatrix.copyFromArray(matrices,matrixIndex+1);}else {var vertexIndex=indexX*2+indexY*(segmentXD+2);var vertices=this._vertices;if(isDown){this._getAffineTransform(pX+dX,pY+dY,dX,dY,vertices[vertexIndex+segmentXD+4],vertices[vertexIndex+segmentXD+5],vertices[vertexIndex+segmentXD+2],vertices[vertexIndex+segmentXD+3],vertices[vertexIndex+2],vertices[vertexIndex+3],Surface._helpTransform,helpMatrix,true);}else {this._getAffineTransform(pX,pY,dX,dY,vertices[vertexIndex],vertices[vertexIndex+1],vertices[vertexIndex+2],vertices[vertexIndex+3],vertices[vertexIndex+segmentXD+2],vertices[vertexIndex+segmentXD+3],Surface._helpTransform,helpMatrix,false);}matrices[matrixIndex]=1.0;matrices[matrixIndex+1]=helpMatrix.a;matrices[matrixIndex+2]=helpMatrix.b;matrices[matrixIndex+3]=helpMatrix.c;matrices[matrixIndex+4]=helpMatrix.d;matrices[matrixIndex+5]=helpMatrix.tx;matrices[matrixIndex+6]=helpMatrix.ty;}}return helpMatrix;};Surface.prototype.init=function(surfaceData,armatureValue){if(this._boneData!==null){return;}_super.prototype.init.call(this,surfaceData,armatureValue);var segmentX=surfaceData.segmentX;var segmentY=surfaceData.segmentY;var vertexCount=surfaceData.vertices.length;var lB=1000.0;var lA=200.0;this._dX=lA*2.0/segmentX;this._dY=lA*2.0/segmentY;this._k=-this._dY/this._dX;this._kX=-this._dY/(lB-lA);this._kY=-(lB-lA)/this._dX;this._vertices.length=vertexCount;this._deformVertices.length=vertexCount;this._matrixCahce.length=(segmentX*segmentY+segmentX*2+segmentY*2)*2*7;this._hullCache.length=10;for(var i=0;i<vertexCount;++i){this._deformVertices[i]=0.0;}};Surface.prototype.update=function(cacheFrameIndex){this._blendState.dirty=false;if(cacheFrameIndex>=0&&this._cachedFrameIndices!==null){var cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex];if(cachedFrameIndex>=0&&this._cachedFrameIndex===cachedFrameIndex){this._transformDirty=false;}else if(cachedFrameIndex>=0){this._transformDirty=true;this._cachedFrameIndex=cachedFrameIndex;}else {if(this._hasConstraint){for(var _i=0,_a=this._armature._constraints;_i<_a.length;_i++){var constraint=_a[_i];if(constraint._root===this){constraint.update();}}}if(this._transformDirty||this._parent!==null&&this._parent._childrenTransformDirty){this._transformDirty=true;this._cachedFrameIndex=-1;}else if(this._cachedFrameIndex>=0){this._transformDirty=false;this._cachedFrameIndices[cacheFrameIndex]=this._cachedFrameIndex;}else {this._transformDirty=true;this._cachedFrameIndex=-1;}}}else {if(this._hasConstraint){for(var _b=0,_c=this._armature._constraints;_b<_c.length;_b++){var constraint=_c[_b];if(constraint._root===this){constraint.update();}}}if(this._transformDirty||this._parent!==null&&this._parent._childrenTransformDirty){cacheFrameIndex=-1;this._transformDirty=true;this._cachedFrameIndex=-1;}}if(this._transformDirty){this._transformDirty=false;this._childrenTransformDirty=true;for(var i=0,l=this._matrixCahce.length;i<l;i+=7){this._matrixCahce[i]=-1.0;}this._updateVertices();if(this._cachedFrameIndex<0){var isCache=cacheFrameIndex>=0;if(this._localDirty){this._updateGlobalTransformMatrix(isCache);}if(isCache&&this._cachedFrameIndices!==null){this._cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex]=this._armature._armatureData.setCacheFrame(this.globalTransformMatrix,this.global);}}else {this._armature._armatureData.getCacheFrame(this.globalTransformMatrix,this.global,this._cachedFrameIndex);}var lB=1000.0;var lA=200.0;var ddX=2*this.global.x;var ddY=2*this.global.y;var helpPoint=Surface._helpPoint;this.globalTransformMatrix.transformPoint(lB,-lA,helpPoint);this._hullCache[0]=helpPoint.x;this._hullCache[1]=helpPoint.y;this._hullCache[2]=ddX-helpPoint.x;this._hullCache[3]=ddY-helpPoint.y;this.globalTransformMatrix.transformPoint(0.0,this._dY,helpPoint,true);this._hullCache[4]=helpPoint.x;this._hullCache[5]=helpPoint.y;this.globalTransformMatrix.transformPoint(lA,lB,helpPoint);this._hullCache[6]=helpPoint.x;this._hullCache[7]=helpPoint.y;this._hullCache[8]=ddX-helpPoint.x;this._hullCache[9]=ddY-helpPoint.y;this.globalTransformMatrix.transformPoint(this._dX,0.0,helpPoint,true);this._hullCache[10]=helpPoint.x;this._hullCache[11]=helpPoint.y;}else if(this._childrenTransformDirty){this._childrenTransformDirty=false;}this._localDirty=true;};return Surface;}(dragonBones.Bone);dragonBones.Surface=Surface;})(dragonBones||(dragonBones={}));(function(dragonBones){var Slot=function(_super){__extends(Slot,_super);function Slot(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._localMatrix=new dragonBones.Matrix();_this._colorTransform=new dragonBones.ColorTransform();_this._displayDatas=[];_this._displayList=[];_this._deformVertices=null;_this._rawDisplay=null;_this._meshDisplay=null;return _this;}Slot.prototype._onClear=function(){_super.prototype._onClear.call(this);var disposeDisplayList=[];for(var _i=0,_a=this._displayList;_i<_a.length;_i++){var eachDisplay=_a[_i];if(eachDisplay!==null&&eachDisplay!==this._rawDisplay&&eachDisplay!==this._meshDisplay&&disposeDisplayList.indexOf(eachDisplay)<0){disposeDisplayList.push(eachDisplay);}}for(var _b=0,disposeDisplayList_1=disposeDisplayList;_b<disposeDisplayList_1.length;_b++){var eachDisplay=disposeDisplayList_1[_b];if(eachDisplay instanceof dragonBones.Armature){eachDisplay.dispose();}else {this._disposeDisplay(eachDisplay,true);}}if(this._deformVertices!==null){this._deformVertices.returnToPool();}if(this._meshDisplay!==null&&this._meshDisplay!==this._rawDisplay){this._disposeDisplay(this._meshDisplay,false);}if(this._rawDisplay!==null){this._disposeDisplay(this._rawDisplay,false);}this.displayController=null;this._displayDirty=false;this._zOrderDirty=false;this._blendModeDirty=false;this._colorDirty=false;this._transformDirty=false;this._visible=true;this._blendMode=0;this._displayIndex=-1;this._animationDisplayIndex=-1;this._zOrder=0;this._cachedFrameIndex=-1;this._pivotX=0.0;this._pivotY=0.0;this._localMatrix.identity();this._colorTransform.identity();this._displayList.length=0;this._displayDatas.length=0;this._slotData=null;this._rawDisplayDatas=null;this._displayData=null;this._boundingBoxData=null;this._textureData=null;this._deformVertices=null;this._rawDisplay=null;this._meshDisplay=null;this._display=null;this._childArmature=null;this._parent=null;this._cachedFrameIndices=null;};Slot.prototype._getDefaultRawDisplayData=function(displayIndex){var defaultSkin=this._armature._armatureData.defaultSkin;if(defaultSkin!==null){var defaultRawDisplayDatas=defaultSkin.getDisplays(this._slotData.name);if(defaultRawDisplayDatas!==null){return displayIndex<defaultRawDisplayDatas.length?defaultRawDisplayDatas[displayIndex]:null;}}return null;};Slot.prototype._updateDisplayData=function(){var prevDisplayData=this._displayData;var prevVerticesData=this._deformVertices!==null?this._deformVertices.verticesData:null;var prevTextureData=this._textureData;var rawDisplayData=null;var currentVerticesData=null;this._displayData=null;this._boundingBoxData=null;this._textureData=null;if(this._displayIndex>=0){if(this._rawDisplayDatas!==null){rawDisplayData=this._displayIndex<this._rawDisplayDatas.length?this._rawDisplayDatas[this._displayIndex]:null;}if(rawDisplayData===null){rawDisplayData=this._getDefaultRawDisplayData(this._displayIndex);}if(this._displayIndex<this._displayDatas.length){this._displayData=this._displayDatas[this._displayIndex];}}if(this._displayData!==null){if(this._displayData.type===2){currentVerticesData=this._displayData.vertices;}else if(this._displayData.type===4){currentVerticesData=this._displayData.vertices;}else if(rawDisplayData!==null){if(rawDisplayData.type===2){currentVerticesData=rawDisplayData.vertices;}else if(rawDisplayData.type===4){currentVerticesData=rawDisplayData.vertices;}}if(this._displayData.type===3){this._boundingBoxData=this._displayData.boundingBox;}else if(rawDisplayData!==null){if(rawDisplayData.type===3){this._boundingBoxData=rawDisplayData.boundingBox;}}if(this._displayData.type===0){this._textureData=this._displayData.texture;}else if(this._displayData.type===2){this._textureData=this._displayData.texture;}}if(this._displayData!==prevDisplayData||currentVerticesData!==prevVerticesData||this._textureData!==prevTextureData){if(currentVerticesData===null&&this._textureData!==null){var imageDisplayData=this._displayData;var scale=this._textureData.parent.scale*this._armature._armatureData.scale;var frame=this._textureData.frame;this._pivotX=imageDisplayData.pivot.x;this._pivotY=imageDisplayData.pivot.y;var rect=frame!==null?frame:this._textureData.region;var width=rect.width;var height=rect.height;if(this._textureData.rotated&&frame===null){width=rect.height;height=rect.width;}this._pivotX*=width*scale;this._pivotY*=height*scale;if(frame!==null){this._pivotX+=frame.x*scale;this._pivotY+=frame.y*scale;}if(this._displayData!==null&&rawDisplayData!==null&&this._displayData!==rawDisplayData){rawDisplayData.transform.toMatrix(Slot._helpMatrix);Slot._helpMatrix.invert();Slot._helpMatrix.transformPoint(0.0,0.0,Slot._helpPoint);this._pivotX-=Slot._helpPoint.x;this._pivotY-=Slot._helpPoint.y;this._displayData.transform.toMatrix(Slot._helpMatrix);Slot._helpMatrix.invert();Slot._helpMatrix.transformPoint(0.0,0.0,Slot._helpPoint);this._pivotX+=Slot._helpPoint.x;this._pivotY+=Slot._helpPoint.y;}if(!dragonBones.DragonBones.yDown){this._pivotY=(this._textureData.rotated?this._textureData.region.width:this._textureData.region.height)*scale-this._pivotY;}}else {this._pivotX=0.0;this._pivotY=0.0;}if(rawDisplayData!==null){this.origin=rawDisplayData.transform;}else if(this._displayData!==null){this.origin=this._displayData.transform;}else {this.origin=null;}if(currentVerticesData!==prevVerticesData){if(this._deformVertices===null){this._deformVertices=dragonBones.BaseObject.borrowObject(dragonBones.DeformVertices);}this._deformVertices.init(currentVerticesData,this._armature);}else if(this._deformVertices!==null&&this._textureData!==prevTextureData){this._deformVertices.verticesDirty=true;}this._displayDirty=true;this._transformDirty=true;}};Slot.prototype._updateDisplay=function(){var prevDisplay=this._display!==null?this._display:this._rawDisplay;var prevChildArmature=this._childArmature;if(this._displayIndex>=0&&this._displayIndex<this._displayList.length){this._display=this._displayList[this._displayIndex];if(this._display!==null&&this._display instanceof dragonBones.Armature){this._childArmature=this._display;this._display=this._childArmature.display;}else {this._childArmature=null;}}else {this._display=null;this._childArmature=null;}var currentDisplay=this._display!==null?this._display:this._rawDisplay;if(currentDisplay!==prevDisplay){this._onUpdateDisplay();this._replaceDisplay(prevDisplay);this._transformDirty=true;this._visibleDirty=true;this._blendModeDirty=true;this._colorDirty=true;}if(currentDisplay===this._rawDisplay||currentDisplay===this._meshDisplay){this._updateFrame();}if(this._childArmature!==prevChildArmature){if(prevChildArmature!==null){prevChildArmature._parent=null;prevChildArmature.clock=null;if(prevChildArmature.inheritAnimation){prevChildArmature.animation.reset();}}if(this._childArmature!==null){this._childArmature._parent=this;this._childArmature.clock=this._armature.clock;if(this._childArmature.inheritAnimation){if(this._childArmature.cacheFrameRate===0){var cacheFrameRate=this._armature.cacheFrameRate;if(cacheFrameRate!==0){this._childArmature.cacheFrameRate=cacheFrameRate;}}var actions=null;if(this._displayData!==null&&this._displayData.type===1){actions=this._displayData.actions;}else if(this._displayIndex>=0&&this._rawDisplayDatas!==null){var rawDisplayData=this._displayIndex<this._rawDisplayDatas.length?this._rawDisplayDatas[this._displayIndex]:null;if(rawDisplayData===null){rawDisplayData=this._getDefaultRawDisplayData(this._displayIndex);}if(rawDisplayData!==null&&rawDisplayData.type===1){actions=rawDisplayData.actions;}}if(actions!==null&&actions.length>0){for(var _i=0,actions_1=actions;_i<actions_1.length;_i++){var action=actions_1[_i];var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);dragonBones.EventObject.actionDataToInstance(action,eventObject,this._armature);eventObject.slot=this;this._armature._bufferAction(eventObject,false);}}else {this._childArmature.animation.play();}}}}};Slot.prototype._updateGlobalTransformMatrix=function(isCache){var parentMatrix=this._parent._boneData.type===0?this._parent.globalTransformMatrix:this._parent._getGlobalTransformMatrix(this.global.x,this.global.y);this.globalTransformMatrix.copyFrom(this._localMatrix);this.globalTransformMatrix.concat(parentMatrix);if(isCache){this.global.fromMatrix(this.globalTransformMatrix);}else {this._globalDirty=true;}};Slot.prototype._setDisplayIndex=function(value,isAnimation){if(isAnimation===void 0){isAnimation=false;}if(isAnimation){if(this._animationDisplayIndex===value){return false;}this._animationDisplayIndex=value;}if(this._displayIndex===value){return false;}this._displayIndex=value;this._displayDirty=true;this._updateDisplayData();return this._displayDirty;};Slot.prototype._setZorder=function(value){if(this._zOrder===value);this._zOrder=value;this._zOrderDirty=true;return this._zOrderDirty;};Slot.prototype._setColor=function(value){this._colorTransform.copyFrom(value);this._colorDirty=true;return this._colorDirty;};Slot.prototype._setDisplayList=function(value){if(value!==null&&value.length>0){if(this._displayList.length!==value.length){this._displayList.length=value.length;}for(var i=0,l=value.length;i<l;++i){var eachDisplay=value[i];if(eachDisplay!==null&&eachDisplay!==this._rawDisplay&&eachDisplay!==this._meshDisplay&&!(eachDisplay instanceof dragonBones.Armature)&&this._displayList.indexOf(eachDisplay)<0){this._initDisplay(eachDisplay,true);}this._displayList[i]=eachDisplay;}}else if(this._displayList.length>0){this._displayList.length=0;}if(this._displayIndex>=0&&this._displayIndex<this._displayList.length){this._displayDirty=this._display!==this._displayList[this._displayIndex];}else {this._displayDirty=this._display!==null;}this._updateDisplayData();return this._displayDirty;};Slot.prototype.init=function(slotData,armatureValue,rawDisplay,meshDisplay){if(this._slotData!==null){return;}this._slotData=slotData;this._isFromCache=false;this._visibleDirty=true;this._blendModeDirty=true;this._colorDirty=true;this._blendMode=this._slotData.blendMode;this._zOrder=this._slotData.zOrder;this._colorTransform.copyFrom(this._slotData.color);this._rawDisplay=rawDisplay;this._meshDisplay=meshDisplay;this._armature=armatureValue;var slotParent=this._armature.getBone(this._slotData.parent.name);if(slotParent!==null){this._parent=slotParent;}this._armature._addSlot(this);this._initDisplay(this._rawDisplay,false);if(this._rawDisplay!==this._meshDisplay){this._initDisplay(this._meshDisplay,false);}this._onUpdateDisplay();this._addDisplay();};Slot.prototype.update=function(cacheFrameIndex){this._isFromCache=false;if(this._displayDirty){this._displayDirty=false;this._updateDisplay();if(this._transformDirty){if(this.origin!==null){this.global.copyFrom(this.origin).add(this.offset).toMatrix(this._localMatrix);}else {this.global.copyFrom(this.offset).toMatrix(this._localMatrix);}}}if(this._zOrderDirty){this._zOrderDirty=false;this._updateZOrder();}if(cacheFrameIndex>=0&&this._cachedFrameIndices!==null){var cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex];if(cachedFrameIndex>=0&&this._cachedFrameIndex===cachedFrameIndex){this._transformDirty=false;}else if(cachedFrameIndex>=0){this._transformDirty=true;this._cachedFrameIndex=cachedFrameIndex;}else if(this._transformDirty||this._parent._childrenTransformDirty){this._transformDirty=true;this._cachedFrameIndex=-1;}else if(this._cachedFrameIndex>=0){this._transformDirty=false;this._cachedFrameIndices[cacheFrameIndex]=this._cachedFrameIndex;}else {this._transformDirty=true;this._cachedFrameIndex=-1;}}else if(this._transformDirty||this._parent._childrenTransformDirty){cacheFrameIndex=-1;this._transformDirty=true;this._cachedFrameIndex=-1;}if(this._display===null){return;}if(this._visibleDirty){this._visibleDirty=false;this._updateVisible();}if(this._blendModeDirty){this._blendModeDirty=false;this._updateBlendMode();}if(this._colorDirty){this._colorDirty=false;this._updateColor();}if(this._deformVertices!==null&&this._deformVertices.verticesData!==null&&this._display===this._meshDisplay){var isSkinned=this._deformVertices.verticesData.weight!==null;var isSurface=this._parent._boneData.type!==0;if(this._deformVertices.verticesDirty||isSkinned&&this._deformVertices.isBonesUpdate()||isSurface&&this._parent._childrenTransformDirty){this._deformVertices.verticesDirty=false;this._updateMesh();}if(isSkinned||isSurface){return;}}if(this._transformDirty){this._transformDirty=false;if(this._cachedFrameIndex<0){var isCache=cacheFrameIndex>=0;this._updateGlobalTransformMatrix(isCache);if(isCache&&this._cachedFrameIndices!==null){this._cachedFrameIndex=this._cachedFrameIndices[cacheFrameIndex]=this._armature._armatureData.setCacheFrame(this.globalTransformMatrix,this.global);}}else {this._isFromCache=true;this._armature._armatureData.getCacheFrame(this.globalTransformMatrix,this.global,this._cachedFrameIndex);}this._updateTransform();}};Slot.prototype.updateTransformAndMatrix=function(){if(this._transformDirty){this._transformDirty=false;this._updateGlobalTransformMatrix(false);}};Slot.prototype.replaceDisplayData=function(value,displayIndex){if(displayIndex===void 0){displayIndex=-1;}if(displayIndex<0){if(this._displayIndex<0){displayIndex=0;}else {displayIndex=this._displayIndex;}}if(this._displayDatas.length<=displayIndex){this._displayDatas.length=displayIndex+1;for(var i=0,l=this._displayDatas.length;i<l;++i){if(!this._displayDatas[i]){this._displayDatas[i]=null;}}}this._displayDatas[displayIndex]=value;};Slot.prototype.containsPoint=function(x,y){if(this._boundingBoxData===null){return false;}this.updateTransformAndMatrix();Slot._helpMatrix.copyFrom(this.globalTransformMatrix);Slot._helpMatrix.invert();Slot._helpMatrix.transformPoint(x,y,Slot._helpPoint);return this._boundingBoxData.containsPoint(Slot._helpPoint.x,Slot._helpPoint.y);};Slot.prototype.intersectsSegment=function(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians){if(intersectionPointA===void 0){intersectionPointA=null;}if(intersectionPointB===void 0){intersectionPointB=null;}if(normalRadians===void 0){normalRadians=null;}if(this._boundingBoxData===null){return 0;}this.updateTransformAndMatrix();Slot._helpMatrix.copyFrom(this.globalTransformMatrix);Slot._helpMatrix.invert();Slot._helpMatrix.transformPoint(xA,yA,Slot._helpPoint);xA=Slot._helpPoint.x;yA=Slot._helpPoint.y;Slot._helpMatrix.transformPoint(xB,yB,Slot._helpPoint);xB=Slot._helpPoint.x;yB=Slot._helpPoint.y;var intersectionCount=this._boundingBoxData.intersectsSegment(xA,yA,xB,yB,intersectionPointA,intersectionPointB,normalRadians);if(intersectionCount>0){if(intersectionCount===1||intersectionCount===2){if(intersectionPointA!==null){this.globalTransformMatrix.transformPoint(intersectionPointA.x,intersectionPointA.y,intersectionPointA);if(intersectionPointB!==null){intersectionPointB.x=intersectionPointA.x;intersectionPointB.y=intersectionPointA.y;}}else if(intersectionPointB!==null){this.globalTransformMatrix.transformPoint(intersectionPointB.x,intersectionPointB.y,intersectionPointB);}}else {if(intersectionPointA!==null){this.globalTransformMatrix.transformPoint(intersectionPointA.x,intersectionPointA.y,intersectionPointA);}if(intersectionPointB!==null){this.globalTransformMatrix.transformPoint(intersectionPointB.x,intersectionPointB.y,intersectionPointB);}}if(normalRadians!==null){this.globalTransformMatrix.transformPoint(Math.cos(normalRadians.x),Math.sin(normalRadians.x),Slot._helpPoint,true);normalRadians.x=Math.atan2(Slot._helpPoint.y,Slot._helpPoint.x);this.globalTransformMatrix.transformPoint(Math.cos(normalRadians.y),Math.sin(normalRadians.y),Slot._helpPoint,true);normalRadians.y=Math.atan2(Slot._helpPoint.y,Slot._helpPoint.x);}}return intersectionCount;};Slot.prototype.invalidUpdate=function(){this._displayDirty=true;this._transformDirty=true;};Object.defineProperty(Slot.prototype,"visible",{get:function get(){return this._visible;},set:function set(value){if(this._visible===value){return;}this._visible=value;this._updateVisible();},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"displayIndex",{get:function get(){return this._displayIndex;},set:function set(value){if(this._setDisplayIndex(value)){this.update(-1);}},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"name",{get:function get(){return this._slotData.name;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"displayList",{get:function get(){return this._displayList.concat();},set:function set(value){var backupDisplayList=this._displayList.concat();var disposeDisplayList=new Array();if(this._setDisplayList(value)){this.update(-1);}for(var _i=0,backupDisplayList_1=backupDisplayList;_i<backupDisplayList_1.length;_i++){var eachDisplay=backupDisplayList_1[_i];if(eachDisplay!==null&&eachDisplay!==this._rawDisplay&&eachDisplay!==this._meshDisplay&&this._displayList.indexOf(eachDisplay)<0&&disposeDisplayList.indexOf(eachDisplay)<0){disposeDisplayList.push(eachDisplay);}}for(var _a=0,disposeDisplayList_2=disposeDisplayList;_a<disposeDisplayList_2.length;_a++){var eachDisplay=disposeDisplayList_2[_a];if(eachDisplay instanceof dragonBones.Armature);else {this._disposeDisplay(eachDisplay,true);}}},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"slotData",{get:function get(){return this._slotData;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"rawDisplayDatas",{get:function get(){return this._rawDisplayDatas;},set:function set(value){if(this._rawDisplayDatas===value){return;}this._displayDirty=true;this._rawDisplayDatas=value;if(this._rawDisplayDatas!==null){this._displayDatas.length=this._rawDisplayDatas.length;for(var i=0,l=this._displayDatas.length;i<l;++i){var rawDisplayData=this._rawDisplayDatas[i];if(rawDisplayData===null){rawDisplayData=this._getDefaultRawDisplayData(i);}this._displayDatas[i]=rawDisplayData;}}else {this._displayDatas.length=0;}},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"displayData",{get:function get(){return this._displayData;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"boundingBoxData",{get:function get(){return this._boundingBoxData;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"rawDisplay",{get:function get(){return this._rawDisplay;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"meshDisplay",{get:function get(){return this._meshDisplay;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"display",{get:function get(){return this._display;},set:function set(value){if(this._display===value){return;}var displayListLength=this._displayList.length;if(this._displayIndex<0&&displayListLength===0){this._displayIndex=0;}if(this._displayIndex<0){return;}else {var replaceDisplayList=this.displayList;if(displayListLength<=this._displayIndex){replaceDisplayList.length=this._displayIndex+1;}replaceDisplayList[this._displayIndex]=value;this.displayList=replaceDisplayList;}},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"childArmature",{get:function get(){return this._childArmature;},set:function set(value){if(this._childArmature===value){return;}this.display=value;},enumerable:true,configurable:true});Object.defineProperty(Slot.prototype,"parent",{get:function get(){return this._parent;},enumerable:true,configurable:true});Slot.prototype.getDisplay=function(){return this._display;};Slot.prototype.setDisplay=function(value){this.display=value;};return Slot;}(dragonBones.TransformObject);dragonBones.Slot=Slot;})(dragonBones||(dragonBones={}));(function(dragonBones){var Constraint=function(_super){__extends(Constraint,_super);function Constraint(){return _super!==null&&_super.apply(this,arguments)||this;}Constraint.prototype._onClear=function(){this._armature=null;this._target=null;this._root=null;this._bone=null;};Object.defineProperty(Constraint.prototype,"name",{get:function get(){return this._constraintData.name;},enumerable:true,configurable:true});Constraint._helpMatrix=new dragonBones.Matrix();Constraint._helpTransform=new dragonBones.Transform();Constraint._helpPoint=new dragonBones.Point();return Constraint;}(dragonBones.BaseObject);dragonBones.Constraint=Constraint;var IKConstraint=function(_super){__extends(IKConstraint,_super);function IKConstraint(){return _super!==null&&_super.apply(this,arguments)||this;}IKConstraint.toString=function(){return "[class dragonBones.IKConstraint]";};IKConstraint.prototype._onClear=function(){_super.prototype._onClear.call(this);this._scaleEnabled=false;this._bendPositive=false;this._weight=1.0;this._constraintData=null;};IKConstraint.prototype._computeA=function(){var ikGlobal=this._target.global;var global=this._root.global;var globalTransformMatrix=this._root.globalTransformMatrix;var radian=Math.atan2(ikGlobal.y-global.y,ikGlobal.x-global.x);if(global.scaleX<0.0){radian+=Math.PI;}global.rotation+=dragonBones.Transform.normalizeRadian(radian-global.rotation)*this._weight;global.toMatrix(globalTransformMatrix);};IKConstraint.prototype._computeB=function(){var boneLength=this._bone._boneData.length;var parent=this._root;var ikGlobal=this._target.global;var parentGlobal=parent.global;var global=this._bone.global;var globalTransformMatrix=this._bone.globalTransformMatrix;var x=globalTransformMatrix.a*boneLength;var y=globalTransformMatrix.b*boneLength;var lLL=x*x+y*y;var lL=Math.sqrt(lLL);var dX=global.x-parentGlobal.x;var dY=global.y-parentGlobal.y;var lPP=dX*dX+dY*dY;var lP=Math.sqrt(lPP);var rawRadian=global.rotation;var rawParentRadian=parentGlobal.rotation;var rawRadianA=Math.atan2(dY,dX);dX=ikGlobal.x-parentGlobal.x;dY=ikGlobal.y-parentGlobal.y;var lTT=dX*dX+dY*dY;var lT=Math.sqrt(lTT);var radianA=0.0;if(lL+lP<=lT||lT+lL<=lP||lT+lP<=lL){radianA=Math.atan2(ikGlobal.y-parentGlobal.y,ikGlobal.x-parentGlobal.x);if(lL+lP<=lT);else if(lP<lL){radianA+=Math.PI;}}else {var h=(lPP-lLL+lTT)/(2.0*lTT);var r=Math.sqrt(lPP-h*h*lTT)/lT;var hX=parentGlobal.x+dX*h;var hY=parentGlobal.y+dY*h;var rX=-dY*r;var rY=dX*r;var isPPR=false;var parentParent=parent.parent;if(parentParent!==null){var parentParentMatrix=parentParent.globalTransformMatrix;isPPR=parentParentMatrix.a*parentParentMatrix.d-parentParentMatrix.b*parentParentMatrix.c<0.0;}if(isPPR!==this._bendPositive){global.x=hX-rX;global.y=hY-rY;}else {global.x=hX+rX;global.y=hY+rY;}radianA=Math.atan2(global.y-parentGlobal.y,global.x-parentGlobal.x);}var dR=dragonBones.Transform.normalizeRadian(radianA-rawRadianA);parentGlobal.rotation=rawParentRadian+dR*this._weight;parentGlobal.toMatrix(parent.globalTransformMatrix);var currentRadianA=rawRadianA+dR*this._weight;global.x=parentGlobal.x+Math.cos(currentRadianA)*lP;global.y=parentGlobal.y+Math.sin(currentRadianA)*lP;var radianB=Math.atan2(ikGlobal.y-global.y,ikGlobal.x-global.x);if(global.scaleX<0.0){radianB+=Math.PI;}global.rotation=parentGlobal.rotation+rawRadian-rawParentRadian+dragonBones.Transform.normalizeRadian(radianB-dR-rawRadian)*this._weight;global.toMatrix(globalTransformMatrix);};IKConstraint.prototype.init=function(constraintData,armature){if(this._constraintData!==null){return;}this._constraintData=constraintData;this._armature=armature;this._target=this._armature.getBone(this._constraintData.target.name);this._root=this._armature.getBone(this._constraintData.root.name);this._bone=this._constraintData.bone!==null?this._armature.getBone(this._constraintData.bone.name):null;{var ikConstraintData=this._constraintData;this._scaleEnabled=ikConstraintData.scaleEnabled;this._bendPositive=ikConstraintData.bendPositive;this._weight=ikConstraintData.weight;}this._root._hasConstraint=true;};IKConstraint.prototype.update=function(){this._root.updateByConstraint();if(this._bone!==null){this._bone.updateByConstraint();this._computeB();}else {this._computeA();}};IKConstraint.prototype.invalidUpdate=function(){this._root.invalidUpdate();if(this._bone!==null){this._bone.invalidUpdate();}};return IKConstraint;}(Constraint);dragonBones.IKConstraint=IKConstraint;var PathConstraint=function(_super){__extends(PathConstraint,_super);function PathConstraint(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._bones=[];_this._spaces=[];_this._positions=[];_this._curves=[];_this._boneLengths=[];_this._pathGlobalVertices=[];_this._segments=[10];return _this;}PathConstraint.toString=function(){return "[class dragonBones.PathConstraint]";};PathConstraint.prototype._onClear=function(){_super.prototype._onClear.call(this);this.dirty=false;this.pathOffset=0;this.position=0.0;this.spacing=0.0;this.rotateOffset=0.0;this.rotateMix=1.0;this.translateMix=1.0;this._pathSlot=null;this._bones.length=0;this._spaces.length=0;this._positions.length=0;this._curves.length=0;this._boneLengths.length=0;this._pathGlobalVertices.length=0;};PathConstraint.prototype._updatePathVertices=function(verticesData){var armature=this._armature;var dragonBonesData=armature.armatureData.parent;var scale=armature.armatureData.scale;var intArray=dragonBonesData.intArray;var floatArray=dragonBonesData.floatArray;var pathOffset=verticesData.offset;var pathVertexCount=intArray[pathOffset+0];var pathVertexOffset=intArray[pathOffset+2];this._pathGlobalVertices.length=pathVertexCount*2;var weightData=verticesData.weight;if(weightData===null){var parentBone=this._pathSlot.parent;parentBone.updateByConstraint();var matrix=parentBone.globalTransformMatrix;for(var i=0,iV_1=pathVertexOffset;i<pathVertexCount;i+=2){var vx=floatArray[iV_1++]*scale;var vy=floatArray[iV_1++]*scale;var x=matrix.a*vx+matrix.c*vy+matrix.tx;var y=matrix.b*vx+matrix.d*vy+matrix.ty;this._pathGlobalVertices[i]=x;this._pathGlobalVertices[i+1]=y;}return;}var bones=this._pathSlot._deformVertices.bones;var weightBoneCount=weightData.bones.length;var weightOffset=weightData.offset;var floatOffset=intArray[weightOffset+1];var iV=floatOffset;var iB=weightOffset+2+weightBoneCount;for(var i=0,iW=0;i<pathVertexCount;i++){var vertexBoneCount=intArray[iB++];var xG=0.0,yG=0.0;for(var ii=0,ll=vertexBoneCount;ii<ll;ii++){var boneIndex=intArray[iB++];var bone=bones[boneIndex];if(bone===null){continue;}bone.updateByConstraint();var matrix=bone.globalTransformMatrix;var weight=floatArray[iV++];var vx=floatArray[iV++]*scale;var vy=floatArray[iV++]*scale;xG+=(matrix.a*vx+matrix.c*vy+matrix.tx)*weight;yG+=(matrix.b*vx+matrix.d*vy+matrix.ty)*weight;}this._pathGlobalVertices[iW++]=xG;this._pathGlobalVertices[iW++]=yG;}};PathConstraint.prototype._computeVertices=function(start,count,offset,out){for(var i=offset,iW=start;i<count;i+=2){out[i]=this._pathGlobalVertices[iW++];out[i+1]=this._pathGlobalVertices[iW++];}};PathConstraint.prototype._computeBezierCurve=function(pathDisplayDta,spaceCount,tangents,percentPosition,percentSpacing){var armature=this._armature;var intArray=armature.armatureData.parent.intArray;var vertexCount=intArray[pathDisplayDta.vertices.offset+0];var positions=this._positions;var spaces=this._spaces;var isClosed=pathDisplayDta.closed;var curveVertices=Array();var verticesLength=vertexCount*2;var curveCount=verticesLength/6;var preCurve=-1;var position=this.position;positions.length=spaceCount*3+2;var pathLength=0.0;if(!pathDisplayDta.constantSpeed){var lenghts=pathDisplayDta.curveLengths;curveCount-=isClosed?1:2;pathLength=lenghts[curveCount];if(percentPosition){position*=pathLength;}if(percentSpacing){for(var i=0;i<spaceCount;i++){spaces[i]*=pathLength;}}curveVertices.length=8;for(var i=0,o=0,curve=0;i<spaceCount;i++,o+=3){var space=spaces[i];position+=space;if(isClosed){position%=pathLength;if(position<0){position+=pathLength;}curve=0;}else if(position<0){continue;}else if(position>pathLength){continue;}var percent=0.0;for(;;curve++){var len=lenghts[curve];if(position>len){continue;}if(curve===0){percent=position/len;}else {var preLen=lenghts[curve-1];percent=(position-preLen)/(len-preLen);}break;}if(curve!==preCurve){preCurve=curve;if(isClosed&&curve===curveCount){this._computeVertices(verticesLength-4,4,0,curveVertices);this._computeVertices(0,4,4,curveVertices);}else {this._computeVertices(curve*6+2,8,0,curveVertices);}}this.addCurvePosition(percent,curveVertices[0],curveVertices[1],curveVertices[2],curveVertices[3],curveVertices[4],curveVertices[5],curveVertices[6],curveVertices[7],positions,o,tangents);}return;}if(isClosed){verticesLength+=2;curveVertices.length=vertexCount;this._computeVertices(2,verticesLength-4,0,curveVertices);this._computeVertices(0,2,verticesLength-4,curveVertices);curveVertices[verticesLength-2]=curveVertices[0];curveVertices[verticesLength-1]=curveVertices[1];}else {curveCount--;verticesLength-=4;curveVertices.length=verticesLength;this._computeVertices(2,verticesLength,0,curveVertices);}var curves=new Array(curveCount);pathLength=0;var x1=curveVertices[0],y1=curveVertices[1],cx1=0,cy1=0,cx2=0,cy2=0,x2=0,y2=0;var tmpx,tmpy,dddfx,dddfy,ddfx,ddfy,dfx,dfy;for(var i=0,w=2;i<curveCount;i++,w+=6){cx1=curveVertices[w];cy1=curveVertices[w+1];cx2=curveVertices[w+2];cy2=curveVertices[w+3];x2=curveVertices[w+4];y2=curveVertices[w+5];tmpx=(x1-cx1*2+cx2)*0.1875;tmpy=(y1-cy1*2+cy2)*0.1875;dddfx=((cx1-cx2)*3-x1+x2)*0.09375;dddfy=((cy1-cy2)*3-y1+y2)*0.09375;ddfx=tmpx*2+dddfx;ddfy=tmpy*2+dddfy;dfx=(cx1-x1)*0.75+tmpx+dddfx*0.16666667;dfy=(cy1-y1)*0.75+tmpy+dddfy*0.16666667;pathLength+=Math.sqrt(dfx*dfx+dfy*dfy);dfx+=ddfx;dfy+=ddfy;ddfx+=dddfx;ddfy+=dddfy;pathLength+=Math.sqrt(dfx*dfx+dfy*dfy);dfx+=ddfx;dfy+=ddfy;pathLength+=Math.sqrt(dfx*dfx+dfy*dfy);dfx+=ddfx+dddfx;dfy+=ddfy+dddfy;pathLength+=Math.sqrt(dfx*dfx+dfy*dfy);curves[i]=pathLength;x1=x2;y1=y2;}if(percentPosition){position*=pathLength;}if(percentSpacing){for(var i=0;i<spaceCount;i++){spaces[i]*=pathLength;}}var segments=this._segments;var curveLength=0;for(var i=0,o=0,curve=0,segment=0;i<spaceCount;i++,o+=3){var space=spaces[i];position+=space;var p=position;if(isClosed){p%=pathLength;if(p<0)p+=pathLength;curve=0;}else if(p<0){continue;}else if(p>pathLength){continue;}for(;;curve++){var length_1=curves[curve];if(p>length_1)continue;if(curve===0)p/=length_1;else {var prev=curves[curve-1];p=(p-prev)/(length_1-prev);}break;}if(curve!==preCurve){preCurve=curve;var ii=curve*6;x1=curveVertices[ii];y1=curveVertices[ii+1];cx1=curveVertices[ii+2];cy1=curveVertices[ii+3];cx2=curveVertices[ii+4];cy2=curveVertices[ii+5];x2=curveVertices[ii+6];y2=curveVertices[ii+7];tmpx=(x1-cx1*2+cx2)*0.03;tmpy=(y1-cy1*2+cy2)*0.03;dddfx=((cx1-cx2)*3-x1+x2)*0.006;dddfy=((cy1-cy2)*3-y1+y2)*0.006;ddfx=tmpx*2+dddfx;ddfy=tmpy*2+dddfy;dfx=(cx1-x1)*0.3+tmpx+dddfx*0.16666667;dfy=(cy1-y1)*0.3+tmpy+dddfy*0.16666667;curveLength=Math.sqrt(dfx*dfx+dfy*dfy);segments[0]=curveLength;for(ii=1;ii<8;ii++){dfx+=ddfx;dfy+=ddfy;ddfx+=dddfx;ddfy+=dddfy;curveLength+=Math.sqrt(dfx*dfx+dfy*dfy);segments[ii]=curveLength;}dfx+=ddfx;dfy+=ddfy;curveLength+=Math.sqrt(dfx*dfx+dfy*dfy);segments[8]=curveLength;dfx+=ddfx+dddfx;dfy+=ddfy+dddfy;curveLength+=Math.sqrt(dfx*dfx+dfy*dfy);segments[9]=curveLength;segment=0;}p*=curveLength;for(;;segment++){var length_2=segments[segment];if(p>length_2)continue;if(segment===0)p/=length_2;else {var prev=segments[segment-1];p=segment+(p-prev)/(length_2-prev);}break;}this.addCurvePosition(p*0.1,x1,y1,cx1,cy1,cx2,cy2,x2,y2,positions,o,tangents);}};PathConstraint.prototype.addCurvePosition=function(t,x1,y1,cx1,cy1,cx2,cy2,x2,y2,out,offset,tangents){if(t===0){out[offset]=x1;out[offset+1]=y1;out[offset+2]=0;return;}if(t===1){out[offset]=x2;out[offset+1]=y2;out[offset+2]=0;return;}var mt=1-t;var mt2=mt*mt;var t2=t*t;var a=mt2*mt;var b=mt2*t*3;var c=mt*t2*3;var d=t*t2;var x=a*x1+b*cx1+c*cx2+d*x2;var y=a*y1+b*cy1+c*cy2+d*y2;out[offset]=x;out[offset+1]=y;if(tangents){out[offset+2]=Math.atan2(y-(a*y1+b*cy1+c*cy2),x-(a*x1+b*cx1+c*cx2));}else {out[offset+2]=0;}};PathConstraint.prototype.init=function(constraintData,armature){this._constraintData=constraintData;this._armature=armature;var data=constraintData;this.pathOffset=data.pathDisplayData.vertices.offset;this.position=data.position;this.spacing=data.spacing;this.rotateOffset=data.rotateOffset;this.rotateMix=data.rotateMix;this.translateMix=data.translateMix;this._root=this._armature.getBone(data.root.name);this._target=this._armature.getBone(data.target.name);this._pathSlot=this._armature.getSlot(data.pathSlot.name);for(var i=0,l=data.bones.length;i<l;i++){var bone=this._armature.getBone(data.bones[i].name);if(bone!==null){this._bones.push(bone);}}if(data.rotateMode===2){this._boneLengths.length=this._bones.length;}this._root._hasConstraint=true;};PathConstraint.prototype.update=function(){var pathSlot=this._pathSlot;if(pathSlot._deformVertices===null||pathSlot._deformVertices.verticesData===null||pathSlot._deformVertices.verticesData.offset!==this.pathOffset){return;}var constraintData=this._constraintData;var pathDisplayData=pathSlot._displayData;var isPathVerticeDirty=false;var deformVertices=pathSlot._deformVertices;if(this._root._childrenTransformDirty){this._updatePathVertices(pathDisplayData.vertices);isPathVerticeDirty=true;}else if(deformVertices!==null&&(deformVertices.verticesDirty||deformVertices.isBonesUpdate())){this._updatePathVertices(pathDisplayData.vertices);deformVertices.verticesDirty=false;isPathVerticeDirty=true;}if(!isPathVerticeDirty&&!this.dirty){return;}var positionMode=constraintData.positionMode;var spacingMode=constraintData.spacingMode;var rotateMode=constraintData.rotateMode;var bones=this._bones;var isLengthMode=spacingMode===0;var isChainScaleMode=rotateMode===2;var isTangentMode=rotateMode===0;var boneCount=bones.length;var spacesCount=isTangentMode?boneCount:boneCount+1;var spacing=this.spacing;var spaces=this._spaces;spaces.length=spacesCount;if(isChainScaleMode||isLengthMode){spaces[0]=0;for(var i=0,l=spacesCount-1;i<l;i++){var bone=bones[i];bone.updateByConstraint();var boneLength=bone._boneData.length;var matrix=bone.globalTransformMatrix;var x=boneLength*matrix.a;var y=boneLength*matrix.b;var len=Math.sqrt(x*x+y*y);if(isChainScaleMode){this._boneLengths[i]=len;}spaces[i+1]=(boneLength+spacing)*len/boneLength;}}else {for(var i=0;i<spacesCount;i++){spaces[i]=spacing;}}this._computeBezierCurve(pathDisplayData,spacesCount,isTangentMode,positionMode===1,spacingMode===2);var positions=this._positions;var rotateOffset=this.rotateOffset;var boneX=positions[0],boneY=positions[1];var tip;if(rotateOffset===0){tip=rotateMode===1;}else {tip=false;var bone=pathSlot.parent;if(bone!==null){var matrix=bone.globalTransformMatrix;rotateOffset*=matrix.a*matrix.d-matrix.b*matrix.c>0?dragonBones.Transform.DEG_RAD:-dragonBones.Transform.DEG_RAD;}}var rotateMix=this.rotateMix;var translateMix=this.translateMix;for(var i=0,p=3;i<boneCount;i++,p+=3){var bone=bones[i];bone.updateByConstraint();var matrix=bone.globalTransformMatrix;matrix.tx+=(boneX-matrix.tx)*translateMix;matrix.ty+=(boneY-matrix.ty)*translateMix;var x=positions[p],y=positions[p+1];var dx=x-boneX,dy=y-boneY;if(isChainScaleMode){var lenght=this._boneLengths[i];var s=(Math.sqrt(dx*dx+dy*dy)/lenght-1)*rotateMix+1;matrix.a*=s;matrix.b*=s;}boneX=x;boneY=y;if(rotateMix>0){var a=matrix.a,b=matrix.b,c=matrix.c,d=matrix.d,r=void 0,cos=void 0,sin=void 0;if(isTangentMode){r=positions[p-1];}else {r=Math.atan2(dy,dx);}r-=Math.atan2(b,a);if(tip){cos=Math.cos(r);sin=Math.sin(r);var length_3=bone._boneData.length;boneX+=(length_3*(cos*a-sin*b)-dx)*rotateMix;boneY+=(length_3*(sin*a+cos*b)-dy)*rotateMix;}else {r+=rotateOffset;}if(r>dragonBones.Transform.PI){r-=dragonBones.Transform.PI_D;}else if(r<-dragonBones.Transform.PI){r+=dragonBones.Transform.PI_D;}r*=rotateMix;cos=Math.cos(r);sin=Math.sin(r);matrix.a=cos*a-sin*b;matrix.b=sin*a+cos*b;matrix.c=cos*c-sin*d;matrix.d=sin*c+cos*d;}bone.global.fromMatrix(matrix);}this.dirty=false;};PathConstraint.prototype.invalidUpdate=function(){};return PathConstraint;}(Constraint);dragonBones.PathConstraint=PathConstraint;})(dragonBones||(dragonBones={}));(function(dragonBones){var WorldClock=function(){function WorldClock(time){if(time===void 0){time=0.0;}this.time=0.0;this.timeScale=1.0;this._systemTime=0.0;this._animatebles=[];this._clock=null;this.time=time;this._systemTime=new Date().getTime()*0.001;}WorldClock.prototype.advanceTime=function(passedTime){if(passedTime!==passedTime){passedTime=0.0;}var currentTime=Date.now()*0.001;if(passedTime<0.0){passedTime=currentTime-this._systemTime;}this._systemTime=currentTime;if(this.timeScale!==1.0){passedTime*=this.timeScale;}if(passedTime===0.0){return;}if(passedTime<0.0){this.time-=passedTime;}else {this.time+=passedTime;}var i=0,r=0,l=this._animatebles.length;for(;i<l;++i){var animatable=this._animatebles[i];if(animatable!==null){if(r>0){this._animatebles[i-r]=animatable;this._animatebles[i]=null;}animatable.advanceTime(passedTime);}else {r++;}}if(r>0){l=this._animatebles.length;for(;i<l;++i){var animateble=this._animatebles[i];if(animateble!==null){this._animatebles[i-r]=animateble;}else {r++;}}this._animatebles.length-=r;}};WorldClock.prototype.contains=function(value){if(value===this){return false;}var ancestor=value;while(ancestor!==this&&ancestor!==null){ancestor=ancestor.clock;}return ancestor===this;};WorldClock.prototype.add=function(value){if(this._animatebles.indexOf(value)<0){this._animatebles.push(value);value.clock=this;}};WorldClock.prototype.remove=function(value){var index=this._animatebles.indexOf(value);if(index>=0){this._animatebles[index]=null;value.clock=null;}};WorldClock.prototype.clear=function(){for(var _i=0,_a=this._animatebles;_i<_a.length;_i++){var animatable=_a[_i];if(animatable!==null){animatable.clock=null;}}};Object.defineProperty(WorldClock.prototype,"clock",{get:function get(){return this._clock;},set:function set(value){if(this._clock===value){return;}if(this._clock!==null){this._clock.remove(this);}this._clock=value;if(this._clock!==null){this._clock.add(this);}},enumerable:true,configurable:true});WorldClock.clock=new WorldClock();return WorldClock;}();dragonBones.WorldClock=WorldClock;})(dragonBones||(dragonBones={}));(function(dragonBones){var Animation=function(_super){__extends(Animation,_super);function Animation(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._animationNames=[];_this._animationStates=[];_this._animations={};_this._animationConfig=null;return _this;}Animation.toString=function(){return "[class dragonBones.Animation]";};Animation.prototype._onClear=function(){for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];animationState.returnToPool();}for(var k in this._animations){delete this._animations[k];}if(this._animationConfig!==null){this._animationConfig.returnToPool();}this.timeScale=1.0;this._lockUpdate=false;this._animationDirty=false;this._inheritTimeScale=1.0;this._animationNames.length=0;this._animationStates.length=0;this._armature=null;this._animationConfig=null;this._lastAnimationState=null;};Animation.prototype._fadeOut=function(animationConfig){switch(animationConfig.fadeOutMode){case 1:for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];if(animationState._parent!==null){continue;}if(animationState.layer===animationConfig.layer){animationState.fadeOut(animationConfig.fadeOutTime,animationConfig.pauseFadeOut);}}break;case 2:for(var _b=0,_c=this._animationStates;_b<_c.length;_b++){var animationState=_c[_b];if(animationState._parent!==null){continue;}if(animationState.group===animationConfig.group){animationState.fadeOut(animationConfig.fadeOutTime,animationConfig.pauseFadeOut);}}break;case 3:for(var _d=0,_e=this._animationStates;_d<_e.length;_d++){var animationState=_e[_d];if(animationState._parent!==null){continue;}if(animationState.layer===animationConfig.layer&&animationState.group===animationConfig.group){animationState.fadeOut(animationConfig.fadeOutTime,animationConfig.pauseFadeOut);}}break;case 4:for(var _f=0,_g=this._animationStates;_f<_g.length;_f++){var animationState=_g[_f];if(animationState._parent!==null){continue;}animationState.fadeOut(animationConfig.fadeOutTime,animationConfig.pauseFadeOut);}break;}};Animation.prototype.init=function(armature){if(this._armature!==null){return;}this._armature=armature;this._animationConfig=dragonBones.BaseObject.borrowObject(dragonBones.AnimationConfig);};Animation.prototype.advanceTime=function(passedTime){if(passedTime<0.0){passedTime=-passedTime;}if(this._armature.inheritAnimation&&this._armature._parent!==null){this._inheritTimeScale=this._armature._parent._armature.animation._inheritTimeScale*this.timeScale;}else {this._inheritTimeScale=this.timeScale;}if(this._inheritTimeScale!==1.0){passedTime*=this._inheritTimeScale;}var animationStateCount=this._animationStates.length;if(animationStateCount===1){var animationState=this._animationStates[0];if(animationState._fadeState>0&&animationState._subFadeState>0){this._armature._dragonBones.bufferObject(animationState);this._animationStates.length=0;this._lastAnimationState=null;}else {var animationData=animationState._animationData;var cacheFrameRate=animationData.cacheFrameRate;if(this._animationDirty&&cacheFrameRate>0.0){this._animationDirty=false;for(var _i=0,_a=this._armature.getBones();_i<_a.length;_i++){var bone=_a[_i];bone._cachedFrameIndices=animationData.getBoneCachedFrameIndices(bone.name);}for(var _b=0,_c=this._armature.getSlots();_b<_c.length;_b++){var slot=_c[_b];var rawDisplayDatas=slot.rawDisplayDatas;if(rawDisplayDatas!==null&&rawDisplayDatas.length>0){var rawDsplayData=rawDisplayDatas[0];if(rawDsplayData!==null){if(rawDsplayData.parent===this._armature.armatureData.defaultSkin){slot._cachedFrameIndices=animationData.getSlotCachedFrameIndices(slot.name);continue;}}}slot._cachedFrameIndices=null;}}animationState.advanceTime(passedTime,cacheFrameRate);}}else if(animationStateCount>1){for(var i=0,r=0;i<animationStateCount;++i){var animationState=this._animationStates[i];if(animationState._fadeState>0&&animationState._subFadeState>0){r++;this._armature._dragonBones.bufferObject(animationState);this._animationDirty=true;if(this._lastAnimationState===animationState){this._lastAnimationState=null;}}else {if(r>0){this._animationStates[i-r]=animationState;}animationState.advanceTime(passedTime,0.0);}if(i===animationStateCount-1&&r>0){this._animationStates.length-=r;if(this._lastAnimationState===null&&this._animationStates.length>0){this._lastAnimationState=this._animationStates[this._animationStates.length-1];}}}this._armature._cacheFrameIndex=-1;}else {this._armature._cacheFrameIndex=-1;}};Animation.prototype.reset=function(){for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];animationState.returnToPool();}this._animationDirty=false;this._animationConfig.clear();this._animationStates.length=0;this._lastAnimationState=null;};Animation.prototype.stop=function(animationName){if(animationName===void 0){animationName=null;}if(animationName!==null){var animationState=this.getState(animationName);if(animationState!==null){animationState.stop();}}else {for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];animationState.stop();}}};Animation.prototype.playConfig=function(animationConfig){var animationName=animationConfig.animation;if(!(animationName in this._animations)){console.warn("Non-existent animation.\n","DragonBones name: "+this._armature.armatureData.parent.name,"Armature name: "+this._armature.name,"Animation name: "+animationName);return null;}var animationData=this._animations[animationName];if(animationConfig.fadeOutMode===5){for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState_1=_a[_i];if(animationState_1._animationData===animationData){return animationState_1;}}}if(this._animationStates.length===0){animationConfig.fadeInTime=0.0;}else if(animationConfig.fadeInTime<0.0){animationConfig.fadeInTime=animationData.fadeInTime;}if(animationConfig.fadeOutTime<0.0){animationConfig.fadeOutTime=animationConfig.fadeInTime;}if(animationConfig.timeScale<=-100.0){animationConfig.timeScale=1.0/animationData.scale;}if(animationData.frameCount>1){if(animationConfig.position<0.0){animationConfig.position%=animationData.duration;animationConfig.position=animationData.duration-animationConfig.position;}else if(animationConfig.position===animationData.duration){animationConfig.position-=0.000001;}else if(animationConfig.position>animationData.duration){animationConfig.position%=animationData.duration;}if(animationConfig.duration>0.0&&animationConfig.position+animationConfig.duration>animationData.duration){animationConfig.duration=animationData.duration-animationConfig.position;}if(animationConfig.playTimes<0){animationConfig.playTimes=animationData.playTimes;}}else {animationConfig.playTimes=1;animationConfig.position=0.0;if(animationConfig.duration>0.0){animationConfig.duration=0.0;}}if(animationConfig.duration===0.0){animationConfig.duration=-1.0;}this._fadeOut(animationConfig);var animationState=dragonBones.BaseObject.borrowObject(dragonBones.AnimationState);animationState.init(this._armature,animationData,animationConfig);this._animationDirty=true;this._armature._cacheFrameIndex=-1;if(this._animationStates.length>0){var added=false;for(var i=0,l=this._animationStates.length;i<l;++i){if(animationState.layer>this._animationStates[i].layer){added=true;this._animationStates.splice(i,0,animationState);break;}else if(i!==l-1&&animationState.layer>this._animationStates[i+1].layer){added=true;this._animationStates.splice(i+1,0,animationState);break;}}if(!added){this._animationStates.push(animationState);}}else {this._animationStates.push(animationState);}for(var _b=0,_c=this._armature.getSlots();_b<_c.length;_b++){var slot=_c[_b];var childArmature=slot.childArmature;if(childArmature!==null&&childArmature.inheritAnimation&&childArmature.animation.hasAnimation(animationName)&&childArmature.animation.getState(animationName)===null){childArmature.animation.fadeIn(animationName);}}var isLocked=false;for(var k in animationData.animationTimelines){if(!this._lockUpdate){isLocked=true;this._lockUpdate=true;}var childAnimatiionState=this.fadeIn(k,animationConfig.fadeInTime,1,animationState.layer,null,0);if(childAnimatiionState!==null){childAnimatiionState.resetToPose=false;childAnimatiionState._parent=animationState;childAnimatiionState.stop();}}if(isLocked){this._lockUpdate=false;}if(!this._lockUpdate){if(animationConfig.fadeInTime<=0.0){this._armature.advanceTime(0.0);}this._lastAnimationState=animationState;}return animationState;};Animation.prototype.play=function(animationName,playTimes){if(animationName===void 0){animationName=null;}if(playTimes===void 0){playTimes=-1;}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=playTimes;this._animationConfig.fadeInTime=0.0;this._animationConfig.animation=animationName!==null?animationName:"";if(animationName!==null&&animationName.length>0){this.playConfig(this._animationConfig);}else if(this._lastAnimationState===null){var defaultAnimation=this._armature.armatureData.defaultAnimation;if(defaultAnimation!==null){this._animationConfig.animation=defaultAnimation.name;this.playConfig(this._animationConfig);}}else if(!this._lastAnimationState.isPlaying&&!this._lastAnimationState.isCompleted){this._lastAnimationState.play();}else {this._animationConfig.animation=this._lastAnimationState.name;this.playConfig(this._animationConfig);}return this._lastAnimationState;};Animation.prototype.fadeIn=function(animationName,fadeInTime,playTimes,layer,group,fadeOutMode){if(fadeInTime===void 0){fadeInTime=-1.0;}if(playTimes===void 0){playTimes=-1;}if(layer===void 0){layer=0;}if(group===void 0){group=null;}if(fadeOutMode===void 0){fadeOutMode=3;}this._animationConfig.clear();this._animationConfig.fadeOutMode=fadeOutMode;this._animationConfig.playTimes=playTimes;this._animationConfig.layer=layer;this._animationConfig.fadeInTime=fadeInTime;this._animationConfig.animation=animationName;this._animationConfig.group=group!==null?group:"";return this.playConfig(this._animationConfig);};Animation.prototype.gotoAndPlayByTime=function(animationName,time,playTimes){if(time===void 0){time=0.0;}if(playTimes===void 0){playTimes=-1;}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=playTimes;this._animationConfig.position=time;this._animationConfig.fadeInTime=0.0;this._animationConfig.animation=animationName;return this.playConfig(this._animationConfig);};Animation.prototype.gotoAndPlayByFrame=function(animationName,frame,playTimes){if(frame===void 0){frame=0;}if(playTimes===void 0){playTimes=-1;}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=playTimes;this._animationConfig.fadeInTime=0.0;this._animationConfig.animation=animationName;var animationData=animationName in this._animations?this._animations[animationName]:null;if(animationData!==null){this._animationConfig.position=animationData.duration*frame/animationData.frameCount;}return this.playConfig(this._animationConfig);};Animation.prototype.gotoAndPlayByProgress=function(animationName,progress,playTimes){if(progress===void 0){progress=0.0;}if(playTimes===void 0){playTimes=-1;}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=playTimes;this._animationConfig.fadeInTime=0.0;this._animationConfig.animation=animationName;var animationData=animationName in this._animations?this._animations[animationName]:null;if(animationData!==null){this._animationConfig.position=animationData.duration*(progress>0.0?progress:0.0);}return this.playConfig(this._animationConfig);};Animation.prototype.gotoAndStopByTime=function(animationName,time){if(time===void 0){time=0.0;}var animationState=this.gotoAndPlayByTime(animationName,time,1);if(animationState!==null){animationState.stop();}return animationState;};Animation.prototype.gotoAndStopByFrame=function(animationName,frame){if(frame===void 0){frame=0;}var animationState=this.gotoAndPlayByFrame(animationName,frame,1);if(animationState!==null){animationState.stop();}return animationState;};Animation.prototype.gotoAndStopByProgress=function(animationName,progress){if(progress===void 0){progress=0.0;}var animationState=this.gotoAndPlayByProgress(animationName,progress,1);if(animationState!==null){animationState.stop();}return animationState;};Animation.prototype.getState=function(animationName){var i=this._animationStates.length;while(i--){var animationState=this._animationStates[i];if(animationState.name===animationName){return animationState;}}return null;};Animation.prototype.hasAnimation=function(animationName){return animationName in this._animations;};Animation.prototype.getStates=function(){return this._animationStates;};Object.defineProperty(Animation.prototype,"isPlaying",{get:function get(){for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];if(animationState.isPlaying){return true;}}return false;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"isCompleted",{get:function get(){for(var _i=0,_a=this._animationStates;_i<_a.length;_i++){var animationState=_a[_i];if(!animationState.isCompleted){return false;}}return this._animationStates.length>0;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"lastAnimationName",{get:function get(){return this._lastAnimationState!==null?this._lastAnimationState.name:"";},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"animationNames",{get:function get(){return this._animationNames;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"animations",{get:function get(){return this._animations;},set:function set(value){if(this._animations===value){return;}this._animationNames.length=0;for(var k in this._animations){delete this._animations[k];}for(var k in value){this._animationNames.push(k);this._animations[k]=value[k];}},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"animationConfig",{get:function get(){this._animationConfig.clear();return this._animationConfig;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"lastAnimationState",{get:function get(){return this._lastAnimationState;},enumerable:true,configurable:true});Animation.prototype.gotoAndPlay=function(animationName,fadeInTime,duration,playTimes,layer,group,fadeOutMode,pauseFadeOut,pauseFadeIn){if(fadeInTime===void 0){fadeInTime=-1;}if(duration===void 0){duration=-1;}if(playTimes===void 0){playTimes=-1;}if(layer===void 0){layer=0;}if(group===void 0){group=null;}if(fadeOutMode===void 0){fadeOutMode=3;}console.warn("Deprecated.");this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.fadeOutMode=fadeOutMode;this._animationConfig.playTimes=playTimes;this._animationConfig.layer=layer;this._animationConfig.fadeInTime=fadeInTime;this._animationConfig.animation=animationName;this._animationConfig.group=group!==null?group:"";var animationData=this._animations[animationName];if(animationData&&duration>0.0){this._animationConfig.timeScale=animationData.duration/duration;}return this.playConfig(this._animationConfig);};Animation.prototype.gotoAndStop=function(animationName,time){if(time===void 0){time=0;}console.warn("Deprecated.");return this.gotoAndStopByTime(animationName,time);};Object.defineProperty(Animation.prototype,"animationList",{get:function get(){console.warn("Deprecated.");return this._animationNames;},enumerable:true,configurable:true});Object.defineProperty(Animation.prototype,"animationDataList",{get:function get(){console.warn("Deprecated.");var list=[];for(var i=0,l=this._animationNames.length;i<l;++i){list.push(this._animations[this._animationNames[i]]);}return list;},enumerable:true,configurable:true});return Animation;}(dragonBones.BaseObject);dragonBones.Animation=Animation;})(dragonBones||(dragonBones={}));(function(dragonBones){var AnimationState=function(_super){__extends(AnimationState,_super);function AnimationState(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._blendState=new BlendState();_this._boneMask=[];_this._boneTimelines=[];_this._surfaceTimelines=[];_this._slotTimelines=[];_this._constraintTimelines=[];_this._animationTimelines=[];_this._poseTimelines=[];_this._bonePoses={};_this._actionTimeline=null;_this._zOrderTimeline=null;_this._parent=null;return _this;}AnimationState.toString=function(){return "[class dragonBones.AnimationState]";};AnimationState.prototype._onClear=function(){for(var _i=0,_a=this._boneTimelines;_i<_a.length;_i++){var timeline=_a[_i];timeline.returnToPool();}for(var _b=0,_c=this._surfaceTimelines;_b<_c.length;_b++){var timeline=_c[_b];timeline.returnToPool();}for(var _d=0,_e=this._slotTimelines;_d<_e.length;_d++){var timeline=_e[_d];timeline.returnToPool();}for(var _f=0,_g=this._constraintTimelines;_f<_g.length;_f++){var timeline=_g[_f];timeline.returnToPool();}for(var _h=0,_j=this._animationTimelines;_h<_j.length;_h++){var timeline=_j[_h];timeline.returnToPool();}for(var k in this._bonePoses){this._bonePoses[k].returnToPool();delete this._bonePoses[k];}if(this._actionTimeline!==null){this._actionTimeline.returnToPool();}if(this._zOrderTimeline!==null){this._zOrderTimeline.returnToPool();}this.actionEnabled=false;this.additiveBlending=false;this.displayControl=false;this.resetToPose=false;this.playTimes=1;this.layer=0;this.timeScale=1.0;this.weight=1.0;this.autoFadeOutTime=0.0;this.fadeTotalTime=0.0;this.name="";this.group="";this._timelineDirty=2;this._playheadState=0;this._fadeState=-1;this._subFadeState=-1;this._position=0.0;this._duration=0.0;this._fadeTime=0.0;this._time=0.0;this._fadeProgress=0.0;this._weightResult=0.0;this._blendState.clear();this._boneMask.length=0;this._boneTimelines.length=0;this._surfaceTimelines.length=0;this._slotTimelines.length=0;this._constraintTimelines.length=0;this._animationTimelines.length=0;this._poseTimelines.length=0;this._animationData=null;this._armature=null;this._actionTimeline=null;this._zOrderTimeline=null;this._parent=null;};AnimationState.prototype._updateTimelines=function(){{for(var _i=0,_a=this._armature._constraints;_i<_a.length;_i++){var constraint=_a[_i];var timelineDatas=this._animationData.getConstraintTimelines(constraint.name);if(timelineDatas!==null){for(var _b=0,timelineDatas_1=timelineDatas;_b<timelineDatas_1.length;_b++){var timelineData=timelineDatas_1[_b];switch(timelineData.type){case 30:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.IKConstraintTimelineState);timeline.constraint=constraint;timeline.init(this._armature,this,timelineData);this._constraintTimelines.push(timeline);break;}}}}else if(this.resetToPose){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.IKConstraintTimelineState);timeline.constraint=constraint;timeline.init(this._armature,this,null);this._constraintTimelines.push(timeline);this._poseTimelines.push(timeline);}}}{for(var _c=0,_d=this._armature.animation.getStates();_c<_d.length;_c++){var animationState=_d[_c];if(animationState._parent!==this){continue;}var timelineDatas=this._animationData.getAnimationTimelines(animationState.name);if(timelineDatas===null){continue;}for(var _e=0,timelineDatas_2=timelineDatas;_e<timelineDatas_2.length;_e++){var timelineData=timelineDatas_2[_e];switch(timelineData.type){case 40:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.AnimationTimelineState);timeline.animationState=animationState;timeline.init(this._armature,this,timelineData);this._animationTimelines.push(timeline);break;}}}}}};AnimationState.prototype._updateBoneAndSlotTimelines=function(){{var boneTimelines={};for(var _i=0,_a=this._boneTimelines;_i<_a.length;_i++){var timeline=_a[_i];var timelineName=timeline.bone.name;if(!(timelineName in boneTimelines)){boneTimelines[timelineName]=[];}boneTimelines[timelineName].push(timeline);}for(var _b=0,_c=this._armature.getBones();_b<_c.length;_b++){var bone=_c[_b];var timelineName=bone.name;if(!this.containsBoneMask(timelineName)){continue;}if(timelineName in boneTimelines){delete boneTimelines[timelineName];}else if(bone._boneData.type===0){var timelineDatas=this._animationData.getBoneTimelines(timelineName);var bonePose=timelineName in this._bonePoses?this._bonePoses[timelineName]:this._bonePoses[timelineName]=dragonBones.BaseObject.borrowObject(BonePose);if(timelineDatas!==null){for(var _d=0,timelineDatas_3=timelineDatas;_d<timelineDatas_3.length;_d++){var timelineData=timelineDatas_3[_d];switch(timelineData.type){case 10:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.BoneAllTimelineState);timeline.bone=bone;timeline.bonePose=bonePose;timeline.init(this._armature,this,timelineData);this._boneTimelines.push(timeline);break;}case 11:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.BoneTranslateTimelineState);timeline.bone=bone;timeline.bonePose=bonePose;timeline.init(this._armature,this,timelineData);this._boneTimelines.push(timeline);break;}case 12:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.BoneRotateTimelineState);timeline.bone=bone;timeline.bonePose=bonePose;timeline.init(this._armature,this,timelineData);this._boneTimelines.push(timeline);break;}case 13:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.BoneScaleTimelineState);timeline.bone=bone;timeline.bonePose=bonePose;timeline.init(this._armature,this,timelineData);this._boneTimelines.push(timeline);break;}}}}else if(this.resetToPose){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.BoneAllTimelineState);timeline.bone=bone;timeline.bonePose=bonePose;timeline.init(this._armature,this,null);this._boneTimelines.push(timeline);this._poseTimelines.push(timeline);}}else if(bone._boneData.type===1){var timelineDatas=this._animationData.getSurfaceTimelines(timelineName);if(timelineDatas!==null){for(var _e=0,timelineDatas_4=timelineDatas;_e<timelineDatas_4.length;_e++){var timelineData=timelineDatas_4[_e];switch(timelineData.type){case 50:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SurfaceTimelineState);timeline.surface=bone;timeline.init(this._armature,this,timelineData);this._surfaceTimelines.push(timeline);break;}}}}else if(this.resetToPose){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SurfaceTimelineState);timeline.surface=bone;timeline.init(this._armature,this,null);this._surfaceTimelines.push(timeline);this._poseTimelines.push(timeline);}}}for(var k in boneTimelines){for(var _f=0,_g=boneTimelines[k];_f<_g.length;_f++){var timeline=_g[_f];this._boneTimelines.splice(this._boneTimelines.indexOf(timeline),1);timeline.returnToPool();}}}{var slotTimelines={};var ffdFlags=[];for(var _h=0,_j=this._slotTimelines;_h<_j.length;_h++){var timeline=_j[_h];var timelineName=timeline.slot.name;if(!(timelineName in slotTimelines)){slotTimelines[timelineName]=[];}slotTimelines[timelineName].push(timeline);}for(var _k=0,_l=this._armature.getSlots();_k<_l.length;_k++){var slot=_l[_k];var boneName=slot.parent.name;if(!this.containsBoneMask(boneName)){continue;}var timelineName=slot.name;var timelineDatas=this._animationData.getSlotTimelines(timelineName);if(timelineName in slotTimelines){delete slotTimelines[timelineName];}else {var displayIndexFlag=false;var colorFlag=false;ffdFlags.length=0;if(timelineDatas!==null){for(var _m=0,timelineDatas_5=timelineDatas;_m<timelineDatas_5.length;_m++){var timelineData=timelineDatas_5[_m];switch(timelineData.type){case 20:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SlotDislayTimelineState);timeline.slot=slot;timeline.init(this._armature,this,timelineData);this._slotTimelines.push(timeline);displayIndexFlag=true;break;}case 21:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SlotColorTimelineState);timeline.slot=slot;timeline.init(this._armature,this,timelineData);this._slotTimelines.push(timeline);colorFlag=true;break;}case 22:{var timeline=dragonBones.BaseObject.borrowObject(dragonBones.DeformTimelineState);timeline.slot=slot;timeline.init(this._armature,this,timelineData);this._slotTimelines.push(timeline);ffdFlags.push(timeline.vertexOffset);break;}}}}if(this.resetToPose){if(!displayIndexFlag){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SlotDislayTimelineState);timeline.slot=slot;timeline.init(this._armature,this,null);this._slotTimelines.push(timeline);this._poseTimelines.push(timeline);}if(!colorFlag){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.SlotColorTimelineState);timeline.slot=slot;timeline.init(this._armature,this,null);this._slotTimelines.push(timeline);this._poseTimelines.push(timeline);}if(slot.rawDisplayDatas!==null){for(var _o=0,_p=slot.rawDisplayDatas;_o<_p.length;_o++){var displayData=_p[_o];if(displayData!==null&&displayData.type===2){var meshOffset=displayData.vertices.offset;if(ffdFlags.indexOf(meshOffset)<0){var timeline=dragonBones.BaseObject.borrowObject(dragonBones.DeformTimelineState);timeline.vertexOffset=meshOffset;timeline.slot=slot;timeline.init(this._armature,this,null);this._slotTimelines.push(timeline);this._poseTimelines.push(timeline);}}}}}}}for(var k in slotTimelines){for(var _q=0,_r=slotTimelines[k];_q<_r.length;_q++){var timeline=_r[_q];this._slotTimelines.splice(this._slotTimelines.indexOf(timeline),1);timeline.returnToPool();}}}};AnimationState.prototype._advanceFadeTime=function(passedTime){var isFadeOut=this._fadeState>0;if(this._subFadeState<0){this._subFadeState=0;var eventType=isFadeOut?dragonBones.EventObject.FADE_OUT:dragonBones.EventObject.FADE_IN;if(this._armature.eventDispatcher.hasDBEventListener(eventType)){var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);eventObject.type=eventType;eventObject.armature=this._armature;eventObject.animationState=this;this._armature._dragonBones.bufferEvent(eventObject);}}if(passedTime<0.0){passedTime=-passedTime;}this._fadeTime+=passedTime;if(this._fadeTime>=this.fadeTotalTime){this._subFadeState=1;this._fadeProgress=isFadeOut?0.0:1.0;}else if(this._fadeTime>0.0){this._fadeProgress=isFadeOut?1.0-this._fadeTime/this.fadeTotalTime:this._fadeTime/this.fadeTotalTime;}else {this._fadeProgress=isFadeOut?1.0:0.0;}if(this._subFadeState>0){if(!isFadeOut){this._playheadState|=1;this._fadeState=0;}var eventType=isFadeOut?dragonBones.EventObject.FADE_OUT_COMPLETE:dragonBones.EventObject.FADE_IN_COMPLETE;if(this._armature.eventDispatcher.hasDBEventListener(eventType)){var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);eventObject.type=eventType;eventObject.armature=this._armature;eventObject.animationState=this;this._armature._dragonBones.bufferEvent(eventObject);}}};AnimationState.prototype.init=function(armature,animationData,animationConfig){if(this._armature!==null){return;}this._armature=armature;this._animationData=animationData;this.resetToPose=animationConfig.resetToPose;this.additiveBlending=animationConfig.additiveBlending;this.displayControl=animationConfig.displayControl;this.actionEnabled=animationConfig.actionEnabled;this.layer=animationConfig.layer;this.playTimes=animationConfig.playTimes;this.timeScale=animationConfig.timeScale;this.fadeTotalTime=animationConfig.fadeInTime;this.autoFadeOutTime=animationConfig.autoFadeOutTime;this.weight=animationConfig.weight;this.name=animationConfig.name.length>0?animationConfig.name:animationConfig.animation;this.group=animationConfig.group;if(animationConfig.pauseFadeIn){this._playheadState=2;}else {this._playheadState=3;}if(animationConfig.duration<0.0){this._position=0.0;this._duration=this._animationData.duration;if(animationConfig.position!==0.0){if(this.timeScale>=0.0){this._time=animationConfig.position;}else {this._time=animationConfig.position-this._duration;}}else {this._time=0.0;}}else {this._position=animationConfig.position;this._duration=animationConfig.duration;this._time=0.0;}if(this.timeScale<0.0&&this._time===0.0){this._time=-0.000001;}if(this.fadeTotalTime<=0.0){this._fadeProgress=0.999999;}if(animationConfig.boneMask.length>0){this._boneMask.length=animationConfig.boneMask.length;for(var i=0,l=this._boneMask.length;i<l;++i){this._boneMask[i]=animationConfig.boneMask[i];}}this._actionTimeline=dragonBones.BaseObject.borrowObject(dragonBones.ActionTimelineState);this._actionTimeline.init(this._armature,this,this._animationData.actionTimeline);this._actionTimeline.currentTime=this._time;if(this._actionTimeline.currentTime<0.0){this._actionTimeline.currentTime=this._duration-this._actionTimeline.currentTime;}if(this._animationData.zOrderTimeline!==null){this._zOrderTimeline=dragonBones.BaseObject.borrowObject(dragonBones.ZOrderTimelineState);this._zOrderTimeline.init(this._armature,this,this._animationData.zOrderTimeline);}};AnimationState.prototype.advanceTime=function(passedTime,cacheFrameRate){this._blendState.dirty=false;if(this._fadeState!==0||this._subFadeState!==0){this._advanceFadeTime(passedTime);}if(this._playheadState===3){if(this.timeScale!==1.0){passedTime*=this.timeScale;}this._time+=passedTime;}if(this._timelineDirty!==0){if(this._timelineDirty===2){this._updateTimelines();}this._timelineDirty=0;this._updateBoneAndSlotTimelines();}if(this.weight===0.0){return;}var isCacheEnabled=this._fadeState===0&&cacheFrameRate>0.0;var isUpdateTimeline=true;var isUpdateBoneTimeline=true;var time=this._time;this._weightResult=this.weight*this._fadeProgress;if(this._parent!==null){this._weightResult*=this._parent._weightResult/this._parent._fadeProgress;}if(this._actionTimeline.playState<=0){this._actionTimeline.update(time);}if(isCacheEnabled){var internval=cacheFrameRate*2.0;this._actionTimeline.currentTime=Math.floor(this._actionTimeline.currentTime*internval)/internval;}if(this._zOrderTimeline!==null&&this._zOrderTimeline.playState<=0){this._zOrderTimeline.update(time);}if(isCacheEnabled){var cacheFrameIndex=Math.floor(this._actionTimeline.currentTime*cacheFrameRate);if(this._armature._cacheFrameIndex===cacheFrameIndex){isUpdateTimeline=false;isUpdateBoneTimeline=false;}else {this._armature._cacheFrameIndex=cacheFrameIndex;if(this._animationData.cachedFrames[cacheFrameIndex]){isUpdateBoneTimeline=false;}else {this._animationData.cachedFrames[cacheFrameIndex]=true;}}}if(isUpdateTimeline){if(isUpdateBoneTimeline){for(var i=0,l=this._boneTimelines.length;i<l;++i){var timeline=this._boneTimelines[i];if(timeline.playState<=0){timeline.update(time);}if(i===l-1||timeline.bone!==this._boneTimelines[i+1].bone){var state=timeline.bone._blendState.update(this._weightResult,this.layer);if(state!==0){timeline.blend(state);}}}}for(var i=0,l=this._surfaceTimelines.length;i<l;++i){var timeline=this._surfaceTimelines[i];var state=timeline.surface._blendState.update(this._weightResult,this.layer);if(timeline.playState<=0){timeline.update(time);}if(state!==0){timeline.blend(state);}}if(this.displayControl){for(var i=0,l=this._slotTimelines.length;i<l;++i){var timeline=this._slotTimelines[i];var displayController=timeline.slot.displayController;if(displayController===null||displayController===this.name||displayController===this.group){if(timeline.playState<=0){timeline.update(time);}}}}for(var i=0,l=this._constraintTimelines.length;i<l;++i){var timeline=this._constraintTimelines[i];if(timeline.playState<=0){timeline.update(time);}}for(var i=0,l=this._animationTimelines.length;i<l;++i){var timeline=this._animationTimelines[i];var state=timeline.animationState._blendState.update(this._weightResult,this.layer);if(timeline.playState<=0){timeline.update(time);}if(state!==0){timeline.blend(state);}}}if(this._fadeState===0){if(this._subFadeState>0){this._subFadeState=0;if(this._poseTimelines.length>0){for(var _i=0,_a=this._poseTimelines;_i<_a.length;_i++){var timeline=_a[_i];if(timeline instanceof dragonBones.BoneTimelineState){this._boneTimelines.splice(this._boneTimelines.indexOf(timeline),1);}else if(timeline instanceof dragonBones.SurfaceTimelineState){this._surfaceTimelines.splice(this._surfaceTimelines.indexOf(timeline),1);}else if(timeline instanceof dragonBones.SlotTimelineState){this._slotTimelines.splice(this._slotTimelines.indexOf(timeline),1);}else if(timeline instanceof dragonBones.ConstraintTimelineState){this._constraintTimelines.splice(this._constraintTimelines.indexOf(timeline),1);}timeline.returnToPool();}this._poseTimelines.length=0;}}if(this._actionTimeline.playState>0){if(this.autoFadeOutTime>=0.0){this.fadeOut(this.autoFadeOutTime);}}}};AnimationState.prototype.play=function(){this._playheadState=3;};AnimationState.prototype.stop=function(){this._playheadState&=1;};AnimationState.prototype.fadeOut=function(fadeOutTime,pausePlayhead){if(pausePlayhead===void 0){pausePlayhead=true;}if(fadeOutTime<0.0){fadeOutTime=0.0;}if(pausePlayhead){this._playheadState&=2;}if(this._fadeState>0){if(fadeOutTime>this.fadeTotalTime-this._fadeTime){return;}}else {this._fadeState=1;this._subFadeState=-1;if(fadeOutTime<=0.0||this._fadeProgress<=0.0){this._fadeProgress=0.000001;}for(var _i=0,_a=this._boneTimelines;_i<_a.length;_i++){var timeline=_a[_i];timeline.fadeOut();}for(var _b=0,_c=this._surfaceTimelines;_b<_c.length;_b++){var timeline=_c[_b];timeline.fadeOut();}for(var _d=0,_e=this._slotTimelines;_d<_e.length;_d++){var timeline=_e[_d];timeline.fadeOut();}for(var _f=0,_g=this._constraintTimelines;_f<_g.length;_f++){var timeline=_g[_f];timeline.fadeOut();}for(var _h=0,_j=this._animationTimelines;_h<_j.length;_h++){var timeline=_j[_h];timeline.animationState.fadeOut(fadeOutTime,pausePlayhead);timeline.fadeOut();}}this.displayControl=false;this.fadeTotalTime=this._fadeProgress>0.000001?fadeOutTime/this._fadeProgress:0.0;this._fadeTime=this.fadeTotalTime*(1.0-this._fadeProgress);};AnimationState.prototype.containsBoneMask=function(boneName){return this._boneMask.length===0||this._boneMask.indexOf(boneName)>=0;};AnimationState.prototype.addBoneMask=function(boneName,recursive){if(recursive===void 0){recursive=true;}var currentBone=this._armature.getBone(boneName);if(currentBone===null){return;}if(this._boneMask.indexOf(boneName)<0){this._boneMask.push(boneName);}if(recursive){for(var _i=0,_a=this._armature.getBones();_i<_a.length;_i++){var bone=_a[_i];if(this._boneMask.indexOf(bone.name)<0&&currentBone.contains(bone)){this._boneMask.push(bone.name);}}}this._timelineDirty=1;};AnimationState.prototype.removeBoneMask=function(boneName,recursive){if(recursive===void 0){recursive=true;}var index=this._boneMask.indexOf(boneName);if(index>=0){this._boneMask.splice(index,1);}if(recursive){var currentBone=this._armature.getBone(boneName);if(currentBone!==null){var bones=this._armature.getBones();if(this._boneMask.length>0){for(var _i=0,bones_1=bones;_i<bones_1.length;_i++){var bone=bones_1[_i];var index_2=this._boneMask.indexOf(bone.name);if(index_2>=0&&currentBone.contains(bone)){this._boneMask.splice(index_2,1);}}}else {for(var _a=0,bones_2=bones;_a<bones_2.length;_a++){var bone=bones_2[_a];if(bone===currentBone){continue;}if(!currentBone.contains(bone)){this._boneMask.push(bone.name);}}}}}this._timelineDirty=1;};AnimationState.prototype.removeAllBoneMask=function(){this._boneMask.length=0;this._timelineDirty=1;};Object.defineProperty(AnimationState.prototype,"isFadeIn",{get:function get(){return this._fadeState<0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isFadeOut",{get:function get(){return this._fadeState>0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isFadeComplete",{get:function get(){return this._fadeState===0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isPlaying",{get:function get(){return (this._playheadState&2)!==0&&this._actionTimeline.playState<=0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"isCompleted",{get:function get(){return this._actionTimeline.playState>0;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"currentPlayTimes",{get:function get(){return this._actionTimeline.currentPlayTimes;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"totalTime",{get:function get(){return this._duration;},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"currentTime",{get:function get(){return this._actionTimeline.currentTime;},set:function set(value){var currentPlayTimes=this._actionTimeline.currentPlayTimes-(this._actionTimeline.playState>0?1:0);if(value<0||this._duration<value){value=value%this._duration+currentPlayTimes*this._duration;if(value<0){value+=this._duration;}}if(this.playTimes>0&&currentPlayTimes===this.playTimes-1&&value===this._duration){value=this._duration-0.000001;}if(this._time===value){return;}this._time=value;this._actionTimeline.setCurrentTime(this._time);if(this._zOrderTimeline!==null){this._zOrderTimeline.playState=-1;}for(var _i=0,_a=this._boneTimelines;_i<_a.length;_i++){var timeline=_a[_i];timeline.playState=-1;}for(var _b=0,_c=this._slotTimelines;_b<_c.length;_b++){var timeline=_c[_b];timeline.playState=-1;}},enumerable:true,configurable:true});Object.defineProperty(AnimationState.prototype,"animationData",{get:function get(){return this._animationData;},enumerable:true,configurable:true});return AnimationState;}(dragonBones.BaseObject);dragonBones.AnimationState=AnimationState;var BonePose=function(_super){__extends(BonePose,_super);function BonePose(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.current=new dragonBones.Transform();_this.delta=new dragonBones.Transform();_this.result=new dragonBones.Transform();return _this;}BonePose.toString=function(){return "[class dragonBones.BonePose]";};BonePose.prototype._onClear=function(){this.current.identity();this.delta.identity();this.result.identity();};return BonePose;}(dragonBones.BaseObject);dragonBones.BonePose=BonePose;var BlendState=function(){function BlendState(){}BlendState.prototype.update=function(weight,p_layer){if(this.dirty){if(this.leftWeight>0.0){if(this.layer!==p_layer){if(this.layerWeight>=this.leftWeight){this.leftWeight=0.0;return 0;}else {this.layer=p_layer;this.leftWeight-=this.layerWeight;this.layerWeight=0.0;}}}else {return 0;}weight*=this.leftWeight;this.layerWeight+=weight;this.blendWeight=weight;return 2;}this.dirty=true;this.layer=p_layer;this.layerWeight=weight;this.leftWeight=1.0;this.blendWeight=weight;return 1;};BlendState.prototype.clear=function(){this.dirty=false;this.layer=0;this.leftWeight=0.0;this.layerWeight=0.0;this.blendWeight=0.0;};return BlendState;}();dragonBones.BlendState=BlendState;})(dragonBones||(dragonBones={}));(function(dragonBones){var TimelineState=function(_super){__extends(TimelineState,_super);function TimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}TimelineState.prototype._onClear=function(){this.playState=-1;this.currentPlayTimes=-1;this.currentTime=-1.0;this._tweenState=0;this._frameRate=0;this._frameValueOffset=0;this._frameCount=0;this._frameOffset=0;this._frameIndex=-1;this._frameRateR=0.0;this._position=0.0;this._duration=0.0;this._timeScale=1.0;this._timeOffset=0.0;this._dragonBonesData=null;this._animationData=null;this._timelineData=null;this._armature=null;this._animationState=null;this._actionTimeline=null;this._frameArray=null;this._frameIntArray=null;this._frameFloatArray=null;this._timelineArray=null;this._frameIndices=null;};TimelineState.prototype._setCurrentTime=function(passedTime){var prevState=this.playState;var prevPlayTimes=this.currentPlayTimes;var prevTime=this.currentTime;if(this._actionTimeline!==null&&this._frameCount<=1){this.playState=this._actionTimeline.playState>=0?1:-1;this.currentPlayTimes=1;this.currentTime=this._actionTimeline.currentTime;}else if(this._actionTimeline===null||this._timeScale!==1.0||this._timeOffset!==0.0){var playTimes=this._animationState.playTimes;var totalTime=playTimes*this._duration;passedTime*=this._timeScale;if(this._timeOffset!==0.0){passedTime+=this._timeOffset*this._animationData.duration;}if(playTimes>0&&(passedTime>=totalTime||passedTime<=-totalTime)){if(this.playState<=0&&this._animationState._playheadState===3){this.playState=1;}this.currentPlayTimes=playTimes;if(passedTime<0.0){this.currentTime=0.0;}else {this.currentTime=this._duration+0.000001;}}else {if(this.playState!==0&&this._animationState._playheadState===3){this.playState=0;}if(passedTime<0.0){passedTime=-passedTime;this.currentPlayTimes=Math.floor(passedTime/this._duration);this.currentTime=this._duration-passedTime%this._duration;}else {this.currentPlayTimes=Math.floor(passedTime/this._duration);this.currentTime=passedTime%this._duration;}}this.currentTime+=this._position;}else {this.playState=this._actionTimeline.playState;this.currentPlayTimes=this._actionTimeline.currentPlayTimes;this.currentTime=this._actionTimeline.currentTime;}if(this.currentPlayTimes===prevPlayTimes&&this.currentTime===prevTime){return false;}if(prevState<0&&this.playState!==prevState||this.playState<=0&&this.currentPlayTimes!==prevPlayTimes){this._frameIndex=-1;}return true;};TimelineState.prototype.init=function(armature,animationState,timelineData){this._armature=armature;this._animationState=animationState;this._timelineData=timelineData;this._actionTimeline=this._animationState._actionTimeline;if(this===this._actionTimeline){this._actionTimeline=null;}this._animationData=this._animationState._animationData;this._frameRate=this._animationData.parent.frameRate;this._frameRateR=1.0/this._frameRate;this._position=this._animationState._position;this._duration=this._animationState._duration;this._dragonBonesData=this._animationData.parent.parent;if(this._timelineData!==null){this._frameIntArray=this._dragonBonesData.frameIntArray;this._frameFloatArray=this._dragonBonesData.frameFloatArray;this._frameArray=this._dragonBonesData.frameArray;this._timelineArray=this._dragonBonesData.timelineArray;this._frameIndices=this._dragonBonesData.frameIndices;this._frameCount=this._timelineArray[this._timelineData.offset+2];this._frameValueOffset=this._timelineArray[this._timelineData.offset+4];this._timeScale=100.0/this._timelineArray[this._timelineData.offset+0];this._timeOffset=this._timelineArray[this._timelineData.offset+1]*0.01;}};TimelineState.prototype.fadeOut=function(){};TimelineState.prototype.update=function(passedTime){if(this._setCurrentTime(passedTime)){if(this._frameCount>1){var timelineFrameIndex=Math.floor(this.currentTime*this._frameRate);var frameIndex=this._frameIndices[this._timelineData.frameIndicesOffset+timelineFrameIndex];if(this._frameIndex!==frameIndex){this._frameIndex=frameIndex;this._frameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5+this._frameIndex];this._onArriveAtFrame();}}else if(this._frameIndex<0){this._frameIndex=0;if(this._timelineData!==null){this._frameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5];}this._onArriveAtFrame();}if(this._tweenState!==0){this._onUpdateFrame();}}};return TimelineState;}(dragonBones.BaseObject);dragonBones.TimelineState=TimelineState;var TweenTimelineState=function(_super){__extends(TweenTimelineState,_super);function TweenTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}TweenTimelineState._getEasingValue=function(tweenType,progress,easing){var value=progress;switch(tweenType){case 3:value=Math.pow(progress,2.0);break;case 4:value=1.0-Math.pow(1.0-progress,2.0);break;case 5:value=0.5*(1.0-Math.cos(progress*Math.PI));break;}return (value-progress)*easing+progress;};TweenTimelineState._getEasingCurveValue=function(progress,samples,count,offset){if(progress<=0.0){return 0.0;}else if(progress>=1.0){return 1.0;}var segmentCount=count+1;var valueIndex=Math.floor(progress*segmentCount);var fromValue=valueIndex===0?0.0:samples[offset+valueIndex-1];var toValue=valueIndex===segmentCount-1?10000.0:samples[offset+valueIndex];return (fromValue+(toValue-fromValue)*(progress*segmentCount-valueIndex))*0.0001;};TweenTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this._tweenType=0;this._curveCount=0;this._framePosition=0.0;this._frameDurationR=0.0;this._tweenProgress=0.0;this._tweenEasing=0.0;};TweenTimelineState.prototype._onArriveAtFrame=function(){if(this._frameCount>1&&(this._frameIndex!==this._frameCount-1||this._animationState.playTimes===0||this._animationState.currentPlayTimes<this._animationState.playTimes-1)){this._tweenType=this._frameArray[this._frameOffset+1];this._tweenState=this._tweenType===0?1:2;if(this._tweenType===2){this._curveCount=this._frameArray[this._frameOffset+2];}else if(this._tweenType!==0&&this._tweenType!==1){this._tweenEasing=this._frameArray[this._frameOffset+2]*0.01;}this._framePosition=this._frameArray[this._frameOffset]*this._frameRateR;if(this._frameIndex===this._frameCount-1){this._frameDurationR=1.0/(this._animationData.duration-this._framePosition);}else {var nextFrameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5+this._frameIndex+1];var frameDuration=this._frameArray[nextFrameOffset]*this._frameRateR-this._framePosition;if(frameDuration>0){this._frameDurationR=1.0/frameDuration;}else {this._frameDurationR=0.0;}}}else {this._tweenState=1;}};TweenTimelineState.prototype._onUpdateFrame=function(){if(this._tweenState===2){this._tweenProgress=(this.currentTime-this._framePosition)*this._frameDurationR;if(this._tweenType===2){this._tweenProgress=TweenTimelineState._getEasingCurveValue(this._tweenProgress,this._frameArray,this._curveCount,this._frameOffset+3);}else if(this._tweenType!==1){this._tweenProgress=TweenTimelineState._getEasingValue(this._tweenType,this._tweenProgress,this._tweenEasing);}}else {this._tweenProgress=0.0;}};return TweenTimelineState;}(TimelineState);dragonBones.TweenTimelineState=TweenTimelineState;var BoneTimelineState=function(_super){__extends(BoneTimelineState,_super);function BoneTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}BoneTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.bone=null;this.bonePose=null;};BoneTimelineState.prototype.blend=function(state){var blendWeight=this.bone._blendState.blendWeight;var animationPose=this.bone.animationPose;var result=this.bonePose.result;if(state===2){animationPose.x+=result.x*blendWeight;animationPose.y+=result.y*blendWeight;animationPose.rotation+=result.rotation*blendWeight;animationPose.skew+=result.skew*blendWeight;animationPose.scaleX+=(result.scaleX-1.0)*blendWeight;animationPose.scaleY+=(result.scaleY-1.0)*blendWeight;}else if(blendWeight!==1.0){animationPose.x=result.x*blendWeight;animationPose.y=result.y*blendWeight;animationPose.rotation=result.rotation*blendWeight;animationPose.skew=result.skew*blendWeight;animationPose.scaleX=(result.scaleX-1.0)*blendWeight+1.0;animationPose.scaleY=(result.scaleY-1.0)*blendWeight+1.0;}else {animationPose.x=result.x;animationPose.y=result.y;animationPose.rotation=result.rotation;animationPose.skew=result.skew;animationPose.scaleX=result.scaleX;animationPose.scaleY=result.scaleY;}if(this._animationState._fadeState!==0||this._animationState._subFadeState!==0){this.bone._transformDirty=true;}};return BoneTimelineState;}(TweenTimelineState);dragonBones.BoneTimelineState=BoneTimelineState;var SlotTimelineState=function(_super){__extends(SlotTimelineState,_super);function SlotTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}SlotTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.slot=null;};return SlotTimelineState;}(TweenTimelineState);dragonBones.SlotTimelineState=SlotTimelineState;var ConstraintTimelineState=function(_super){__extends(ConstraintTimelineState,_super);function ConstraintTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}ConstraintTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.constraint=null;};return ConstraintTimelineState;}(TweenTimelineState);dragonBones.ConstraintTimelineState=ConstraintTimelineState;})(dragonBones||(dragonBones={}));(function(dragonBones){var ActionTimelineState=function(_super){__extends(ActionTimelineState,_super);function ActionTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}ActionTimelineState.toString=function(){return "[class dragonBones.ActionTimelineState]";};ActionTimelineState.prototype._onCrossFrame=function(frameIndex){var eventDispatcher=this._armature.eventDispatcher;if(this._animationState.actionEnabled){var frameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5+frameIndex];var actionCount=this._frameArray[frameOffset+1];var actions=this._animationData.parent.actions;for(var i=0;i<actionCount;++i){var actionIndex=this._frameArray[frameOffset+2+i];var action=actions[actionIndex];if(action.type===0){var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);eventObject.time=this._frameArray[frameOffset]/this._frameRate;eventObject.animationState=this._animationState;dragonBones.EventObject.actionDataToInstance(action,eventObject,this._armature);this._armature._bufferAction(eventObject,true);}else {var eventType=action.type===10?dragonBones.EventObject.FRAME_EVENT:dragonBones.EventObject.SOUND_EVENT;if(action.type===11||eventDispatcher.hasDBEventListener(eventType)){var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);eventObject.time=this._frameArray[frameOffset]/this._frameRate;eventObject.animationState=this._animationState;dragonBones.EventObject.actionDataToInstance(action,eventObject,this._armature);this._armature._dragonBones.bufferEvent(eventObject);}}}}};ActionTimelineState.prototype._onArriveAtFrame=function(){};ActionTimelineState.prototype._onUpdateFrame=function(){};ActionTimelineState.prototype.update=function(passedTime){var prevState=this.playState;var prevPlayTimes=this.currentPlayTimes;var prevTime=this.currentTime;if(this._setCurrentTime(passedTime)){var eventDispatcher=this._armature.eventDispatcher;if(prevState<0){if(this.playState!==prevState){if(this._animationState.displayControl&&this._animationState.resetToPose){this._armature._sortZOrder(null,0);}prevPlayTimes=this.currentPlayTimes;if(eventDispatcher.hasDBEventListener(dragonBones.EventObject.START)){var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);eventObject.type=dragonBones.EventObject.START;eventObject.armature=this._armature;eventObject.animationState=this._animationState;this._armature._dragonBones.bufferEvent(eventObject);}}else {return;}}var isReverse=this._animationState.timeScale<0.0;var loopCompleteEvent=null;var completeEvent=null;if(this.currentPlayTimes!==prevPlayTimes){if(eventDispatcher.hasDBEventListener(dragonBones.EventObject.LOOP_COMPLETE)){loopCompleteEvent=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);loopCompleteEvent.type=dragonBones.EventObject.LOOP_COMPLETE;loopCompleteEvent.armature=this._armature;loopCompleteEvent.animationState=this._animationState;}if(this.playState>0){if(eventDispatcher.hasDBEventListener(dragonBones.EventObject.COMPLETE)){completeEvent=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);completeEvent.type=dragonBones.EventObject.COMPLETE;completeEvent.armature=this._armature;completeEvent.animationState=this._animationState;}}}if(this._frameCount>1){var timelineData=this._timelineData;var timelineFrameIndex=Math.floor(this.currentTime*this._frameRate);var frameIndex=this._frameIndices[timelineData.frameIndicesOffset+timelineFrameIndex];if(this._frameIndex!==frameIndex){var crossedFrameIndex=this._frameIndex;this._frameIndex=frameIndex;if(this._timelineArray!==null){this._frameOffset=this._animationData.frameOffset+this._timelineArray[timelineData.offset+5+this._frameIndex];if(isReverse){if(crossedFrameIndex<0){var prevFrameIndex=Math.floor(prevTime*this._frameRate);crossedFrameIndex=this._frameIndices[timelineData.frameIndicesOffset+prevFrameIndex];if(this.currentPlayTimes===prevPlayTimes){if(crossedFrameIndex===frameIndex){crossedFrameIndex=-1;}}}while(crossedFrameIndex>=0){var frameOffset=this._animationData.frameOffset+this._timelineArray[timelineData.offset+5+crossedFrameIndex];var framePosition=this._frameArray[frameOffset]/this._frameRate;if(this._position<=framePosition&&framePosition<=this._position+this._duration){this._onCrossFrame(crossedFrameIndex);}if(loopCompleteEvent!==null&&crossedFrameIndex===0){this._armature._dragonBones.bufferEvent(loopCompleteEvent);loopCompleteEvent=null;}if(crossedFrameIndex>0){crossedFrameIndex--;}else {crossedFrameIndex=this._frameCount-1;}if(crossedFrameIndex===frameIndex){break;}}}else {if(crossedFrameIndex<0){var prevFrameIndex=Math.floor(prevTime*this._frameRate);crossedFrameIndex=this._frameIndices[timelineData.frameIndicesOffset+prevFrameIndex];var frameOffset=this._animationData.frameOffset+this._timelineArray[timelineData.offset+5+crossedFrameIndex];var framePosition=this._frameArray[frameOffset]/this._frameRate;if(this.currentPlayTimes===prevPlayTimes){if(prevTime<=framePosition){if(crossedFrameIndex>0){crossedFrameIndex--;}else {crossedFrameIndex=this._frameCount-1;}}else if(crossedFrameIndex===frameIndex){crossedFrameIndex=-1;}}}while(crossedFrameIndex>=0){if(crossedFrameIndex<this._frameCount-1){crossedFrameIndex++;}else {crossedFrameIndex=0;}var frameOffset=this._animationData.frameOffset+this._timelineArray[timelineData.offset+5+crossedFrameIndex];var framePosition=this._frameArray[frameOffset]/this._frameRate;if(this._position<=framePosition&&framePosition<=this._position+this._duration){this._onCrossFrame(crossedFrameIndex);}if(loopCompleteEvent!==null&&crossedFrameIndex===0){this._armature._dragonBones.bufferEvent(loopCompleteEvent);loopCompleteEvent=null;}if(crossedFrameIndex===frameIndex){break;}}}}}}else if(this._frameIndex<0){this._frameIndex=0;if(this._timelineData!==null){this._frameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5];var framePosition=this._frameArray[this._frameOffset]/this._frameRate;if(this.currentPlayTimes===prevPlayTimes){if(prevTime<=framePosition){this._onCrossFrame(this._frameIndex);}}else if(this._position<=framePosition){if(!isReverse&&loopCompleteEvent!==null){this._armature._dragonBones.bufferEvent(loopCompleteEvent);loopCompleteEvent=null;}this._onCrossFrame(this._frameIndex);}}}if(loopCompleteEvent!==null){this._armature._dragonBones.bufferEvent(loopCompleteEvent);}if(completeEvent!==null){this._armature._dragonBones.bufferEvent(completeEvent);}}};ActionTimelineState.prototype.setCurrentTime=function(value){this._setCurrentTime(value);this._frameIndex=-1;};return ActionTimelineState;}(dragonBones.TimelineState);dragonBones.ActionTimelineState=ActionTimelineState;var ZOrderTimelineState=function(_super){__extends(ZOrderTimelineState,_super);function ZOrderTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}ZOrderTimelineState.toString=function(){return "[class dragonBones.ZOrderTimelineState]";};ZOrderTimelineState.prototype._onArriveAtFrame=function(){if(this.playState>=0){var count=this._frameArray[this._frameOffset+1];if(count>0){this._armature._sortZOrder(this._frameArray,this._frameOffset+2);}else {this._armature._sortZOrder(null,0);}}};ZOrderTimelineState.prototype._onUpdateFrame=function(){};return ZOrderTimelineState;}(dragonBones.TimelineState);dragonBones.ZOrderTimelineState=ZOrderTimelineState;var BoneAllTimelineState=function(_super){__extends(BoneAllTimelineState,_super);function BoneAllTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}BoneAllTimelineState.toString=function(){return "[class dragonBones.BoneAllTimelineState]";};BoneAllTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*6;var scale=this._armature._armatureData.scale;var frameFloatArray=this._frameFloatArray;var current=this.bonePose.current;var delta=this.bonePose.delta;current.x=frameFloatArray[valueOffset++]*scale;current.y=frameFloatArray[valueOffset++]*scale;current.rotation=frameFloatArray[valueOffset++];current.skew=frameFloatArray[valueOffset++];current.scaleX=frameFloatArray[valueOffset++];current.scaleY=frameFloatArray[valueOffset++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;}delta.x=frameFloatArray[valueOffset++]*scale-current.x;delta.y=frameFloatArray[valueOffset++]*scale-current.y;delta.rotation=frameFloatArray[valueOffset++]-current.rotation;delta.skew=frameFloatArray[valueOffset++]-current.skew;delta.scaleX=frameFloatArray[valueOffset++]-current.scaleX;delta.scaleY=frameFloatArray[valueOffset++]-current.scaleY;}else {delta.x=0.0;delta.y=0.0;delta.rotation=0.0;delta.skew=0.0;delta.scaleX=0.0;delta.scaleY=0.0;}}else {var current=this.bonePose.current;var delta=this.bonePose.delta;current.x=0.0;current.y=0.0;current.rotation=0.0;current.skew=0.0;current.scaleX=1.0;current.scaleY=1.0;delta.x=0.0;delta.y=0.0;delta.rotation=0.0;delta.skew=0.0;delta.scaleX=0.0;delta.scaleY=0.0;}};BoneAllTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);var current=this.bonePose.current;var delta=this.bonePose.delta;var result=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0;}result.x=current.x+delta.x*this._tweenProgress;result.y=current.y+delta.y*this._tweenProgress;result.rotation=current.rotation+delta.rotation*this._tweenProgress;result.skew=current.skew+delta.skew*this._tweenProgress;result.scaleX=current.scaleX+delta.scaleX*this._tweenProgress;result.scaleY=current.scaleY+delta.scaleY*this._tweenProgress;};BoneAllTimelineState.prototype.fadeOut=function(){var result=this.bonePose.result;result.rotation=dragonBones.Transform.normalizeRadian(result.rotation);result.skew=dragonBones.Transform.normalizeRadian(result.skew);};return BoneAllTimelineState;}(dragonBones.BoneTimelineState);dragonBones.BoneAllTimelineState=BoneAllTimelineState;var BoneTranslateTimelineState=function(_super){__extends(BoneTranslateTimelineState,_super);function BoneTranslateTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}BoneTranslateTimelineState.toString=function(){return "[class dragonBones.BoneTranslateTimelineState]";};BoneTranslateTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*2;var scale=this._armature._armatureData.scale;var frameFloatArray=this._frameFloatArray;var current=this.bonePose.current;var delta=this.bonePose.delta;current.x=frameFloatArray[valueOffset++]*scale;current.y=frameFloatArray[valueOffset++]*scale;if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;}delta.x=frameFloatArray[valueOffset++]*scale-current.x;delta.y=frameFloatArray[valueOffset++]*scale-current.y;}else {delta.x=0.0;delta.y=0.0;}}else {var current=this.bonePose.current;var delta=this.bonePose.delta;current.x=0.0;current.y=0.0;delta.x=0.0;delta.y=0.0;}};BoneTranslateTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);var current=this.bonePose.current;var delta=this.bonePose.delta;var result=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0;}result.x=current.x+delta.x*this._tweenProgress;result.y=current.y+delta.y*this._tweenProgress;};return BoneTranslateTimelineState;}(dragonBones.BoneTimelineState);dragonBones.BoneTranslateTimelineState=BoneTranslateTimelineState;var BoneRotateTimelineState=function(_super){__extends(BoneRotateTimelineState,_super);function BoneRotateTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}BoneRotateTimelineState.toString=function(){return "[class dragonBones.BoneRotateTimelineState]";};BoneRotateTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*2;var frameFloatArray=this._frameFloatArray;var current=this.bonePose.current;var delta=this.bonePose.delta;current.rotation=frameFloatArray[valueOffset++];current.skew=frameFloatArray[valueOffset++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;delta.rotation=dragonBones.Transform.normalizeRadian(frameFloatArray[valueOffset++]-current.rotation);}else {delta.rotation=frameFloatArray[valueOffset++]-current.rotation;}delta.skew=frameFloatArray[valueOffset++]-current.skew;}else {delta.rotation=0.0;delta.skew=0.0;}}else {var current=this.bonePose.current;var delta=this.bonePose.delta;current.rotation=0.0;current.skew=0.0;delta.rotation=0.0;delta.skew=0.0;}};BoneRotateTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);var current=this.bonePose.current;var delta=this.bonePose.delta;var result=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0;}result.rotation=current.rotation+delta.rotation*this._tweenProgress;result.skew=current.skew+delta.skew*this._tweenProgress;};BoneRotateTimelineState.prototype.fadeOut=function(){var result=this.bonePose.result;result.rotation=dragonBones.Transform.normalizeRadian(result.rotation);result.skew=dragonBones.Transform.normalizeRadian(result.skew);};return BoneRotateTimelineState;}(dragonBones.BoneTimelineState);dragonBones.BoneRotateTimelineState=BoneRotateTimelineState;var BoneScaleTimelineState=function(_super){__extends(BoneScaleTimelineState,_super);function BoneScaleTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}BoneScaleTimelineState.toString=function(){return "[class dragonBones.BoneScaleTimelineState]";};BoneScaleTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*2;var frameFloatArray=this._frameFloatArray;var current=this.bonePose.current;var delta=this.bonePose.delta;current.scaleX=frameFloatArray[valueOffset++];current.scaleY=frameFloatArray[valueOffset++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;}delta.scaleX=frameFloatArray[valueOffset++]-current.scaleX;delta.scaleY=frameFloatArray[valueOffset++]-current.scaleY;}else {delta.scaleX=0.0;delta.scaleY=0.0;}}else {var current=this.bonePose.current;var delta=this.bonePose.delta;current.scaleX=1.0;current.scaleY=1.0;delta.scaleX=0.0;delta.scaleY=0.0;}};BoneScaleTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);var current=this.bonePose.current;var delta=this.bonePose.delta;var result=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0;}result.scaleX=current.scaleX+delta.scaleX*this._tweenProgress;result.scaleY=current.scaleY+delta.scaleY*this._tweenProgress;};return BoneScaleTimelineState;}(dragonBones.BoneTimelineState);dragonBones.BoneScaleTimelineState=BoneScaleTimelineState;var SurfaceTimelineState=function(_super){__extends(SurfaceTimelineState,_super);function SurfaceTimelineState(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._current=[];_this._delta=[];_this._result=[];return _this;}SurfaceTimelineState.toString=function(){return "[class dragonBones.SurfaceTimelineState]";};SurfaceTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.surface=null;this._frameFloatOffset=0;this._valueCount=0;this._deformCount=0;this._valueOffset=0;this._current.length=0;this._delta.length=0;this._result.length=0;};SurfaceTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*this._valueCount;var scale=this._armature._armatureData.scale;var frameFloatArray=this._frameFloatArray;if(this._tweenState===2){var nextValueOffset=valueOffset+this._valueCount;if(this._frameIndex===this._frameCount-1){nextValueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;}for(var i=0;i<this._valueCount;++i){this._delta[i]=frameFloatArray[nextValueOffset+i]*scale-(this._current[i]=frameFloatArray[valueOffset+i]*scale);}}else {for(var i=0;i<this._valueCount;++i){this._current[i]=frameFloatArray[valueOffset+i]*scale;}}}else {for(var i=0;i<this._valueCount;++i){this._current[i]=0.0;}}};SurfaceTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);this.surface._transformDirty=true;if(this._tweenState!==2){this._tweenState=0;}for(var i=0;i<this._valueCount;++i){this._result[i]=this._current[i]+this._delta[i]*this._tweenProgress;}};SurfaceTimelineState.prototype.init=function(armature,animationState,timelineData){_super.prototype.init.call(this,armature,animationState,timelineData);if(this._timelineData!==null){var frameIntOffset=this._animationData.frameIntOffset+this._timelineArray[this._timelineData.offset+3];this._deformCount=this._frameIntArray[frameIntOffset+1];this._valueCount=this._frameIntArray[frameIntOffset+2];this._valueOffset=this._frameIntArray[frameIntOffset+3];this._frameFloatOffset=this._frameIntArray[frameIntOffset+4]+this._animationData.frameFloatOffset;}else {this._deformCount=this.surface._deformVertices.length;this._valueCount=this._deformCount;this._valueOffset=0;this._frameFloatOffset=0;}this._current.length=this._valueCount;this._delta.length=this._valueCount;this._result.length=this._valueCount;for(var i=0;i<this._valueCount;++i){this._delta[i]=0.0;}};SurfaceTimelineState.prototype.blend=function(state){var blendWeight=this.surface._blendState.blendWeight;var result=this.surface._deformVertices;for(var i=0;i<this._deformCount;++i){var value=0.0;if(i<this._valueOffset){value=this._frameFloatArray[this._frameFloatOffset+i];}else if(i<this._valueOffset+this._valueCount){value=this._result[i-this._valueOffset];}else {value=this._frameFloatArray[this._frameFloatOffset+i-this._valueCount];}if(state===2){result[i]+=value*blendWeight;}else if(blendWeight!==1.0){result[i]=value*blendWeight;}else {result[i]=value;}}if(this._animationState._fadeState!==0||this._animationState._subFadeState!==0){this.surface._transformDirty=true;}};return SurfaceTimelineState;}(dragonBones.TweenTimelineState);dragonBones.SurfaceTimelineState=SurfaceTimelineState;var SlotDislayTimelineState=function(_super){__extends(SlotDislayTimelineState,_super);function SlotDislayTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}SlotDislayTimelineState.toString=function(){return "[class dragonBones.SlotDislayTimelineState]";};SlotDislayTimelineState.prototype._onArriveAtFrame=function(){if(this.playState>=0){var displayIndex=this._timelineData!==null?this._frameArray[this._frameOffset+1]:this.slot._slotData.displayIndex;if(this.slot.displayIndex!==displayIndex){this.slot._setDisplayIndex(displayIndex,true);}}};return SlotDislayTimelineState;}(dragonBones.SlotTimelineState);dragonBones.SlotDislayTimelineState=SlotDislayTimelineState;var SlotColorTimelineState=function(_super){__extends(SlotColorTimelineState,_super);function SlotColorTimelineState(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._current=[0,0,0,0,0,0,0,0];_this._delta=[0,0,0,0,0,0,0,0];_this._result=[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0];return _this;}SlotColorTimelineState.toString=function(){return "[class dragonBones.SlotColorTimelineState]";};SlotColorTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this._dirty=false;};SlotColorTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var intArray=this._dragonBonesData.intArray;var frameIntArray=this._frameIntArray;var valueOffset=this._animationData.frameIntOffset+this._frameValueOffset+this._frameIndex*1;var colorOffset=frameIntArray[valueOffset];if(colorOffset<0){colorOffset+=65536;}this._current[0]=intArray[colorOffset++];this._current[1]=intArray[colorOffset++];this._current[2]=intArray[colorOffset++];this._current[3]=intArray[colorOffset++];this._current[4]=intArray[colorOffset++];this._current[5]=intArray[colorOffset++];this._current[6]=intArray[colorOffset++];this._current[7]=intArray[colorOffset++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){colorOffset=frameIntArray[this._animationData.frameIntOffset+this._frameValueOffset];}else {colorOffset=frameIntArray[valueOffset+1*1];}if(colorOffset<0){colorOffset+=65536;}this._delta[0]=intArray[colorOffset++]-this._current[0];this._delta[1]=intArray[colorOffset++]-this._current[1];this._delta[2]=intArray[colorOffset++]-this._current[2];this._delta[3]=intArray[colorOffset++]-this._current[3];this._delta[4]=intArray[colorOffset++]-this._current[4];this._delta[5]=intArray[colorOffset++]-this._current[5];this._delta[6]=intArray[colorOffset++]-this._current[6];this._delta[7]=intArray[colorOffset++]-this._current[7];}}else {var color=this.slot._slotData.color;this._current[0]=color.alphaMultiplier*100.0;this._current[1]=color.redMultiplier*100.0;this._current[2]=color.greenMultiplier*100.0;this._current[3]=color.blueMultiplier*100.0;this._current[4]=color.alphaOffset;this._current[5]=color.redOffset;this._current[6]=color.greenOffset;this._current[7]=color.blueOffset;}};SlotColorTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);this._dirty=true;if(this._tweenState!==2){this._tweenState=0;}this._result[0]=(this._current[0]+this._delta[0]*this._tweenProgress)*0.01;this._result[1]=(this._current[1]+this._delta[1]*this._tweenProgress)*0.01;this._result[2]=(this._current[2]+this._delta[2]*this._tweenProgress)*0.01;this._result[3]=(this._current[3]+this._delta[3]*this._tweenProgress)*0.01;this._result[4]=this._current[4]+this._delta[4]*this._tweenProgress;this._result[5]=this._current[5]+this._delta[5]*this._tweenProgress;this._result[6]=this._current[6]+this._delta[6]*this._tweenProgress;this._result[7]=this._current[7]+this._delta[7]*this._tweenProgress;};SlotColorTimelineState.prototype.fadeOut=function(){this._tweenState=0;this._dirty=false;};SlotColorTimelineState.prototype.update=function(passedTime){_super.prototype.update.call(this,passedTime);if(this._tweenState!==0||this._dirty){var result=this.slot._colorTransform;if(this._animationState._fadeState!==0||this._animationState._subFadeState!==0){if(result.alphaMultiplier!==this._result[0]||result.redMultiplier!==this._result[1]||result.greenMultiplier!==this._result[2]||result.blueMultiplier!==this._result[3]||result.alphaOffset!==this._result[4]||result.redOffset!==this._result[5]||result.greenOffset!==this._result[6]||result.blueOffset!==this._result[7]){var fadeProgress=Math.pow(this._animationState._fadeProgress,4);result.alphaMultiplier+=(this._result[0]-result.alphaMultiplier)*fadeProgress;result.redMultiplier+=(this._result[1]-result.redMultiplier)*fadeProgress;result.greenMultiplier+=(this._result[2]-result.greenMultiplier)*fadeProgress;result.blueMultiplier+=(this._result[3]-result.blueMultiplier)*fadeProgress;result.alphaOffset+=(this._result[4]-result.alphaOffset)*fadeProgress;result.redOffset+=(this._result[5]-result.redOffset)*fadeProgress;result.greenOffset+=(this._result[6]-result.greenOffset)*fadeProgress;result.blueOffset+=(this._result[7]-result.blueOffset)*fadeProgress;this.slot._colorDirty=true;}}else if(this._dirty){this._dirty=false;if(result.alphaMultiplier!==this._result[0]||result.redMultiplier!==this._result[1]||result.greenMultiplier!==this._result[2]||result.blueMultiplier!==this._result[3]||result.alphaOffset!==this._result[4]||result.redOffset!==this._result[5]||result.greenOffset!==this._result[6]||result.blueOffset!==this._result[7]){result.alphaMultiplier=this._result[0];result.redMultiplier=this._result[1];result.greenMultiplier=this._result[2];result.blueMultiplier=this._result[3];result.alphaOffset=this._result[4];result.redOffset=this._result[5];result.greenOffset=this._result[6];result.blueOffset=this._result[7];this.slot._colorDirty=true;}}}};return SlotColorTimelineState;}(dragonBones.SlotTimelineState);dragonBones.SlotColorTimelineState=SlotColorTimelineState;var DeformTimelineState=function(_super){__extends(DeformTimelineState,_super);function DeformTimelineState(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._current=[];_this._delta=[];_this._result=[];return _this;}DeformTimelineState.toString=function(){return "[class dragonBones.DeformTimelineState]";};DeformTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.vertexOffset=0;this._dirty=false;this._frameFloatOffset=0;this._valueCount=0;this._deformCount=0;this._valueOffset=0;this._current.length=0;this._delta.length=0;this._result.length=0;};DeformTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var valueOffset=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*this._valueCount;var scale=this._armature._armatureData.scale;var frameFloatArray=this._frameFloatArray;if(this._tweenState===2){var nextValueOffset=valueOffset+this._valueCount;if(this._frameIndex===this._frameCount-1){nextValueOffset=this._animationData.frameFloatOffset+this._frameValueOffset;}for(var i=0;i<this._valueCount;++i){this._delta[i]=frameFloatArray[nextValueOffset+i]*scale-(this._current[i]=frameFloatArray[valueOffset+i]*scale);}}else {for(var i=0;i<this._valueCount;++i){this._current[i]=frameFloatArray[valueOffset+i]*scale;}}}else {for(var i=0;i<this._valueCount;++i){this._current[i]=0.0;}}};DeformTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);this._dirty=true;if(this._tweenState!==2){this._tweenState=0;}for(var i=0;i<this._valueCount;++i){this._result[i]=this._current[i]+this._delta[i]*this._tweenProgress;}};DeformTimelineState.prototype.init=function(armature,animationState,timelineData){_super.prototype.init.call(this,armature,animationState,timelineData);if(this._timelineData!==null){var frameIntOffset=this._animationData.frameIntOffset+this._timelineArray[this._timelineData.offset+3];this.vertexOffset=this._frameIntArray[frameIntOffset+0];if(this.vertexOffset<0){this.vertexOffset+=65536;}this._deformCount=this._frameIntArray[frameIntOffset+1];this._valueCount=this._frameIntArray[frameIntOffset+2];this._valueOffset=this._frameIntArray[frameIntOffset+3];this._frameFloatOffset=this._frameIntArray[frameIntOffset+4]+this._animationData.frameFloatOffset;}else {var deformVertices=this.slot._deformVertices;this._deformCount=deformVertices!==null?deformVertices.vertices.length:0;this._valueCount=this._deformCount;this._valueOffset=0;this._frameFloatOffset=0;}this._current.length=this._valueCount;this._delta.length=this._valueCount;this._result.length=this._valueCount;for(var i=0;i<this._valueCount;++i){this._delta[i]=0.0;}};DeformTimelineState.prototype.fadeOut=function(){this._tweenState=0;this._dirty=false;};DeformTimelineState.prototype.update=function(passedTime){var deformVertices=this.slot._deformVertices;if(deformVertices===null||deformVertices.verticesData===null||deformVertices.verticesData.offset!==this.vertexOffset){return;}_super.prototype.update.call(this,passedTime);if(this._tweenState!==0||this._dirty){var result=deformVertices.vertices;if(this._animationState._fadeState!==0||this._animationState._subFadeState!==0){var fadeProgress=Math.pow(this._animationState._fadeProgress,2);for(var i=0;i<this._deformCount;++i){if(i<this._valueOffset){result[i]+=(this._frameFloatArray[this._frameFloatOffset+i]-result[i])*fadeProgress;}else if(i<this._valueOffset+this._valueCount){result[i]+=(this._result[i-this._valueOffset]-result[i])*fadeProgress;}else {result[i]+=(this._frameFloatArray[this._frameFloatOffset+i-this._valueCount]-result[i])*fadeProgress;}}deformVertices.verticesDirty=true;}else if(this._dirty){this._dirty=false;for(var i=0;i<this._deformCount;++i){if(i<this._valueOffset){result[i]=this._frameFloatArray[this._frameFloatOffset+i];}else if(i<this._valueOffset+this._valueCount){result[i]=this._result[i-this._valueOffset];}else {result[i]=this._frameFloatArray[this._frameFloatOffset+i-this._valueCount];}}deformVertices.verticesDirty=true;}}};return DeformTimelineState;}(dragonBones.SlotTimelineState);dragonBones.DeformTimelineState=DeformTimelineState;var IKConstraintTimelineState=function(_super){__extends(IKConstraintTimelineState,_super);function IKConstraintTimelineState(){return _super!==null&&_super.apply(this,arguments)||this;}IKConstraintTimelineState.toString=function(){return "[class dragonBones.IKConstraintTimelineState]";};IKConstraintTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this._current=0.0;this._delta=0.0;};IKConstraintTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);var ikConstraint=this.constraint;if(this._timelineData!==null){var valueOffset=this._animationData.frameIntOffset+this._frameValueOffset+this._frameIndex*2;var frameIntArray=this._frameIntArray;var bendPositive=frameIntArray[valueOffset++]!==0;this._current=frameIntArray[valueOffset++]*0.01;if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameIntOffset+this._frameValueOffset;}this._delta=frameIntArray[valueOffset+1]*0.01-this._current;}else {this._delta=0.0;}ikConstraint._bendPositive=bendPositive;}else {var ikConstraintData=ikConstraint._constraintData;this._current=ikConstraintData.weight;this._delta=0.0;ikConstraint._bendPositive=ikConstraintData.bendPositive;}ikConstraint.invalidUpdate();};IKConstraintTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);if(this._tweenState!==2){this._tweenState=0;}var ikConstraint=this.constraint;ikConstraint._weight=this._current+this._delta*this._tweenProgress;ikConstraint.invalidUpdate();};return IKConstraintTimelineState;}(dragonBones.ConstraintTimelineState);dragonBones.IKConstraintTimelineState=IKConstraintTimelineState;var AnimationTimelineState=function(_super){__extends(AnimationTimelineState,_super);function AnimationTimelineState(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._floats=[0.0,0.0,0.0,0.0,0.0,0.0];return _this;}AnimationTimelineState.toString=function(){return "[class dragonBones.AnimationTimelineState]";};AnimationTimelineState.prototype._onClear=function(){_super.prototype._onClear.call(this);this.animationState=null;};AnimationTimelineState.prototype._onArriveAtFrame=function(){_super.prototype._onArriveAtFrame.call(this);if(this._timelineData===null){return;}var valueOffset=this._animationData.frameIntOffset+this._frameValueOffset+this._frameIndex*2;var frameRateR=1.0/this.animationState._animationData.parent.frameRate;var frameIntArray=this._frameIntArray;this._floats[0]=frameIntArray[valueOffset++]*frameRateR;this._floats[3]=frameIntArray[valueOffset++]*0.01;if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){valueOffset=this._animationData.frameIntOffset+this._frameValueOffset;}this._floats[1]=frameIntArray[valueOffset++]*frameRateR-this._floats[0];this._floats[4]=frameIntArray[valueOffset++]*0.01-this._floats[3];}else {this._floats[1]=0.0;this._floats[4]=0.0;}};AnimationTimelineState.prototype._onUpdateFrame=function(){_super.prototype._onUpdateFrame.call(this);if(this._tweenState!==2){this._tweenState=0;}if(this._floats[0]>=0.0){this._floats[2]=this._floats[0]+this._floats[1]*this._tweenProgress;}this._floats[5]=this._floats[3]+this._floats[4]*this._tweenProgress;};AnimationTimelineState.prototype.blend=function(state){var animationState=this.animationState;var blendWeight=animationState._blendState.blendWeight;if(state===2){animationState.weight+=this._floats[5]*blendWeight;animationState.currentTime+=this._floats[2]*blendWeight;}else {animationState.weight=this._floats[5]*blendWeight;animationState.currentTime=this._floats[2]*blendWeight;}};return AnimationTimelineState;}(dragonBones.TweenTimelineState);dragonBones.AnimationTimelineState=AnimationTimelineState;})(dragonBones||(dragonBones={}));(function(dragonBones){var EventObject=function(_super){__extends(EventObject,_super);function EventObject(){return _super!==null&&_super.apply(this,arguments)||this;}EventObject.actionDataToInstance=function(data,instance,armature){if(data.type===0){instance.type=EventObject.FRAME_EVENT;}else {instance.type=data.type===10?EventObject.FRAME_EVENT:EventObject.SOUND_EVENT;}instance.name=data.name;instance.armature=armature;instance.actionData=data;instance.data=data.data;if(data.bone!==null){instance.bone=armature.getBone(data.bone.name);}if(data.slot!==null){instance.slot=armature.getSlot(data.slot.name);}};EventObject.toString=function(){return "[class dragonBones.EventObject]";};EventObject.prototype._onClear=function(){this.time=0.0;this.type="";this.name="";this.armature=null;this.bone=null;this.slot=null;this.animationState=null;this.actionData=null;this.data=null;};EventObject.START="start";EventObject.LOOP_COMPLETE="loopComplete";EventObject.COMPLETE="complete";EventObject.FADE_IN="fadeIn";EventObject.FADE_IN_COMPLETE="fadeInComplete";EventObject.FADE_OUT="fadeOut";EventObject.FADE_OUT_COMPLETE="fadeOutComplete";EventObject.FRAME_EVENT="frameEvent";EventObject.SOUND_EVENT="soundEvent";return EventObject;}(dragonBones.BaseObject);dragonBones.EventObject=EventObject;})(dragonBones||(dragonBones={}));(function(dragonBones){var DataParser=function(){function DataParser(){}DataParser._getArmatureType=function(value){switch(value.toLowerCase()){case"stage":return 2;case"armature":return 0;case"movieclip":return 1;default:return 0;}};DataParser._getBoneType=function(value){switch(value.toLowerCase()){case"bone":return 0;case"surface":return 1;default:return 0;}};DataParser._getDisplayType=function(value){switch(value.toLowerCase()){case"image":return 0;case"mesh":return 2;case"armature":return 1;case"boundingbox":return 3;case"path":return 4;default:return 0;}};DataParser._getBoundingBoxType=function(value){switch(value.toLowerCase()){case"rectangle":return 0;case"ellipse":return 1;case"polygon":return 2;default:return 0;}};DataParser._getActionType=function(value){switch(value.toLowerCase()){case"play":return 0;case"frame":return 10;case"sound":return 11;default:return 0;}};DataParser._getBlendMode=function(value){switch(value.toLowerCase()){case"normal":return 0;case"add":return 1;case"alpha":return 2;case"darken":return 3;case"difference":return 4;case"erase":return 5;case"hardlight":return 6;case"invert":return 7;case"layer":return 8;case"lighten":return 9;case"multiply":return 10;case"overlay":return 11;case"screen":return 12;case"subtract":return 13;default:return 0;}};DataParser._getPositionMode=function(value){switch(value.toLocaleLowerCase()){case"percent":return 1;case"fixed":return 0;default:return 1;}};DataParser._getSpacingMode=function(value){switch(value.toLocaleLowerCase()){case"length":return 0;case"percent":return 2;case"fixed":return 1;default:return 0;}};DataParser._getRotateMode=function(value){switch(value.toLocaleLowerCase()){case"tangent":return 0;case"chain":return 1;case"chainscale":return 2;default:return 0;}};DataParser.parseDragonBonesData=function(rawData){console.warn("Deprecated.");if(rawData instanceof ArrayBuffer){return dragonBones.BinaryDataParser.getInstance().parseDragonBonesData(rawData);}else {return dragonBones.ObjectDataParser.getInstance().parseDragonBonesData(rawData);}};DataParser.parseTextureAtlasData=function(rawData,scale){if(scale===void 0){scale=1;}console.warn("已废弃");var textureAtlasData={};var subTextureList=rawData[DataParser.SUB_TEXTURE];for(var i=0,len=subTextureList.length;i<len;i++){var subTextureObject=subTextureList[i];var subTextureName=subTextureObject[DataParser.NAME];var subTextureRegion=new dragonBones.Rectangle();var subTextureFrame=null;subTextureRegion.x=subTextureObject[DataParser.X]/scale;subTextureRegion.y=subTextureObject[DataParser.Y]/scale;subTextureRegion.width=subTextureObject[DataParser.WIDTH]/scale;subTextureRegion.height=subTextureObject[DataParser.HEIGHT]/scale;if(DataParser.FRAME_WIDTH in subTextureObject){subTextureFrame=new dragonBones.Rectangle();subTextureFrame.x=subTextureObject[DataParser.FRAME_X]/scale;subTextureFrame.y=subTextureObject[DataParser.FRAME_Y]/scale;subTextureFrame.width=subTextureObject[DataParser.FRAME_WIDTH]/scale;subTextureFrame.height=subTextureObject[DataParser.FRAME_HEIGHT]/scale;}textureAtlasData[subTextureName]={region:subTextureRegion,frame:subTextureFrame,rotated:false};}return textureAtlasData;};DataParser.DATA_VERSION_2_3="2.3";DataParser.DATA_VERSION_3_0="3.0";DataParser.DATA_VERSION_4_0="4.0";DataParser.DATA_VERSION_4_5="4.5";DataParser.DATA_VERSION_5_0="5.0";DataParser.DATA_VERSION_5_5="5.5";DataParser.DATA_VERSION=DataParser.DATA_VERSION_5_5;DataParser.DATA_VERSIONS=[DataParser.DATA_VERSION_4_0,DataParser.DATA_VERSION_4_5,DataParser.DATA_VERSION_5_0,DataParser.DATA_VERSION_5_5];DataParser.TEXTURE_ATLAS="textureAtlas";DataParser.SUB_TEXTURE="SubTexture";DataParser.FORMAT="format";DataParser.IMAGE_PATH="imagePath";DataParser.WIDTH="width";DataParser.HEIGHT="height";DataParser.ROTATED="rotated";DataParser.FRAME_X="frameX";DataParser.FRAME_Y="frameY";DataParser.FRAME_WIDTH="frameWidth";DataParser.FRAME_HEIGHT="frameHeight";DataParser.DRADON_BONES="dragonBones";DataParser.USER_DATA="userData";DataParser.ARMATURE="armature";DataParser.BONE="bone";DataParser.SURFACE="surface";DataParser.SLOT="slot";DataParser.CONSTRAINT="constraint";DataParser.IK="ik";DataParser.PATH_CONSTRAINT="path";DataParser.SKIN="skin";DataParser.DISPLAY="display";DataParser.ANIMATION="animation";DataParser.Z_ORDER="zOrder";DataParser.FFD="ffd";DataParser.FRAME="frame";DataParser.TRANSLATE_FRAME="translateFrame";DataParser.ROTATE_FRAME="rotateFrame";DataParser.SCALE_FRAME="scaleFrame";DataParser.DISPLAY_FRAME="displayFrame";DataParser.COLOR_FRAME="colorFrame";DataParser.DEFAULT_ACTIONS="defaultActions";DataParser.ACTIONS="actions";DataParser.EVENTS="events";DataParser.INTS="ints";DataParser.FLOATS="floats";DataParser.STRINGS="strings";DataParser.CANVAS="canvas";DataParser.TRANSFORM="transform";DataParser.PIVOT="pivot";DataParser.AABB="aabb";DataParser.COLOR="color";DataParser.VERSION="version";DataParser.COMPATIBLE_VERSION="compatibleVersion";DataParser.FRAME_RATE="frameRate";DataParser.TYPE="type";DataParser.SUB_TYPE="subType";DataParser.NAME="name";DataParser.PARENT="parent";DataParser.TARGET="target";DataParser.STAGE="stage";DataParser.SHARE="share";DataParser.PATH="path";DataParser.LENGTH="length";DataParser.DISPLAY_INDEX="displayIndex";DataParser.BLEND_MODE="blendMode";DataParser.INHERIT_TRANSLATION="inheritTranslation";DataParser.INHERIT_ROTATION="inheritRotation";DataParser.INHERIT_SCALE="inheritScale";DataParser.INHERIT_REFLECTION="inheritReflection";DataParser.INHERIT_ANIMATION="inheritAnimation";DataParser.INHERIT_DEFORM="inheritDeform";DataParser.SEGMENT_X="segmentX";DataParser.SEGMENT_Y="segmentY";DataParser.BEND_POSITIVE="bendPositive";DataParser.CHAIN="chain";DataParser.WEIGHT="weight";DataParser.FADE_IN_TIME="fadeInTime";DataParser.PLAY_TIMES="playTimes";DataParser.SCALE="scale";DataParser.OFFSET="offset";DataParser.POSITION="position";DataParser.DURATION="duration";DataParser.TWEEN_EASING="tweenEasing";DataParser.TWEEN_ROTATE="tweenRotate";DataParser.TWEEN_SCALE="tweenScale";DataParser.CLOCK_WISE="clockwise";DataParser.CURVE="curve";DataParser.SOUND="sound";DataParser.EVENT="event";DataParser.ACTION="action";DataParser.X="x";DataParser.Y="y";DataParser.SKEW_X="skX";DataParser.SKEW_Y="skY";DataParser.SCALE_X="scX";DataParser.SCALE_Y="scY";DataParser.VALUE="value";DataParser.ROTATE="rotate";DataParser.SKEW="skew";DataParser.ALPHA_OFFSET="aO";DataParser.RED_OFFSET="rO";DataParser.GREEN_OFFSET="gO";DataParser.BLUE_OFFSET="bO";DataParser.ALPHA_MULTIPLIER="aM";DataParser.RED_MULTIPLIER="rM";DataParser.GREEN_MULTIPLIER="gM";DataParser.BLUE_MULTIPLIER="bM";DataParser.UVS="uvs";DataParser.VERTICES="vertices";DataParser.TRIANGLES="triangles";DataParser.WEIGHTS="weights";DataParser.SLOT_POSE="slotPose";DataParser.BONE_POSE="bonePose";DataParser.GLUE_WEIGHTS="glueWeights";DataParser.GLUE_MESHES="glueMeshes";DataParser.BONES="bones";DataParser.POSITION_MODE="positionMode";DataParser.SPACING_MODE="spacingMode";DataParser.ROTATE_MODE="rotateMode";DataParser.SPACING="spacing";DataParser.ROTATE_OFFSET="rotateOffset";DataParser.ROTATE_MIX="rotateMix";DataParser.TRANSLATE_MIX="translateMix";DataParser.TARGET_DISPLAY="targetDisplay";DataParser.CLOSED="closed";DataParser.CONSTANT_SPEED="constantSpeed";DataParser.VERTEX_COUNT="vertexCount";DataParser.LENGTHS="lengths";DataParser.GOTO_AND_PLAY="gotoAndPlay";DataParser.DEFAULT_NAME="default";return DataParser;}();dragonBones.DataParser=DataParser;})(dragonBones||(dragonBones={}));(function(dragonBones){var ObjectDataParser=function(_super){__extends(ObjectDataParser,_super);function ObjectDataParser(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this._rawTextureAtlasIndex=0;_this._rawBones=[];_this._data=null;_this._armature=null;_this._bone=null;_this._surface=null;_this._slot=null;_this._skin=null;_this._mesh=null;_this._animation=null;_this._timeline=null;_this._rawTextureAtlases=null;_this._defaultColorOffset=-1;_this._prevClockwise=0;_this._prevRotation=0.0;_this._helpMatrixA=new dragonBones.Matrix();_this._helpMatrixB=new dragonBones.Matrix();_this._helpTransform=new dragonBones.Transform();_this._helpColorTransform=new dragonBones.ColorTransform();_this._helpPoint=new dragonBones.Point();_this._helpArray=[];_this._intArray=[];_this._floatArray=[];_this._frameIntArray=[];_this._frameFloatArray=[];_this._frameArray=[];_this._timelineArray=[];_this._cacheRawMeshes=[];_this._cacheMeshes=[];_this._actionFrames=[];_this._weightSlotPose={};_this._weightBonePoses={};_this._cacheBones={};_this._slotChildActions={};return _this;}ObjectDataParser._getBoolean=function(rawData,key,defaultValue){if(key in rawData){var value=rawData[key];var type=typeof value;if(type==="boolean"){return value;}else if(type==="string"){switch(value){case"0":case"NaN":case"":case"false":case"null":case"undefined":return false;default:return true;}}else {return !!value;}}return defaultValue;};ObjectDataParser._getNumber=function(rawData,key,defaultValue){if(key in rawData){var value=rawData[key];if(value===null||value==="NaN"){return defaultValue;}return +value||0;}return defaultValue;};ObjectDataParser._getString=function(rawData,key,defaultValue){if(key in rawData){var value=rawData[key];var type=typeof value;if(type==="string"){if(dragonBones.DragonBones.webAssembly){for(var i=0,l=value.length;i<l;++i){if(value.charCodeAt(i)>255){return encodeURI(value);}}}return value;}return String(value);}return defaultValue;};ObjectDataParser.prototype._getCurvePoint=function(x1,y1,x2,y2,x3,y3,x4,y4,t,result){var l_t=1.0-t;var powA=l_t*l_t;var powB=t*t;var kA=l_t*powA;var kB=3.0*t*powA;var kC=3.0*l_t*powB;var kD=t*powB;result.x=kA*x1+kB*x2+kC*x3+kD*x4;result.y=kA*y1+kB*y2+kC*y3+kD*y4;};ObjectDataParser.prototype._samplingEasingCurve=function(curve,samples){var curveCount=curve.length;var stepIndex=-2;for(var i=0,l=samples.length;i<l;++i){var t=(i+1)/(l+1);while((stepIndex+6<curveCount?curve[stepIndex+6]:1)<t){stepIndex+=6;}var isInCurve=stepIndex>=0&&stepIndex+6<curveCount;var x1=isInCurve?curve[stepIndex]:0.0;var y1=isInCurve?curve[stepIndex+1]:0.0;var x2=curve[stepIndex+2];var y2=curve[stepIndex+3];var x3=curve[stepIndex+4];var y3=curve[stepIndex+5];var x4=isInCurve?curve[stepIndex+6]:1.0;var y4=isInCurve?curve[stepIndex+7]:1.0;var lower=0.0;var higher=1.0;while(higher-lower>0.0001){var percentage=(higher+lower)*0.5;this._getCurvePoint(x1,y1,x2,y2,x3,y3,x4,y4,percentage,this._helpPoint);if(t-this._helpPoint.x>0.0){lower=percentage;}else {higher=percentage;}}samples[i]=this._helpPoint.y;}};ObjectDataParser.prototype._parseActionDataInFrame=function(rawData,frameStart,bone,slot){if(dragonBones.DataParser.EVENT in rawData){this._mergeActionFrame(rawData[dragonBones.DataParser.EVENT],frameStart,10,bone,slot);}if(dragonBones.DataParser.SOUND in rawData){this._mergeActionFrame(rawData[dragonBones.DataParser.SOUND],frameStart,11,bone,slot);}if(dragonBones.DataParser.ACTION in rawData){this._mergeActionFrame(rawData[dragonBones.DataParser.ACTION],frameStart,0,bone,slot);}if(dragonBones.DataParser.EVENTS in rawData){this._mergeActionFrame(rawData[dragonBones.DataParser.EVENTS],frameStart,10,bone,slot);}if(dragonBones.DataParser.ACTIONS in rawData){this._mergeActionFrame(rawData[dragonBones.DataParser.ACTIONS],frameStart,0,bone,slot);}};ObjectDataParser.prototype._mergeActionFrame=function(rawData,frameStart,type,bone,slot){var actionOffset=dragonBones.DragonBones.webAssembly?this._armature.actions.size():this._armature.actions.length;var actions=this._parseActionData(rawData,type,bone,slot);var frameIndex=0;var frame=null;for(var _i=0,actions_2=actions;_i<actions_2.length;_i++){var action=actions_2[_i];this._armature.addAction(action,false);}if(this._actionFrames.length===0){frame=new ActionFrame();frame.frameStart=0;this._actionFrames.push(frame);frame=null;}for(var _a=0,_b=this._actionFrames;_a<_b.length;_a++){var eachFrame=_b[_a];if(eachFrame.frameStart===frameStart){frame=eachFrame;break;}else if(eachFrame.frameStart>frameStart){break;}frameIndex++;}if(frame===null){frame=new ActionFrame();frame.frameStart=frameStart;this._actionFrames.splice(frameIndex+1,0,frame);}for(var i=0;i<actions.length;++i){frame.actions.push(actionOffset+i);}};ObjectDataParser.prototype._parseArmature=function(rawData,scale){var armature=dragonBones.BaseObject.borrowObject(dragonBones.ArmatureData);armature.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");armature.frameRate=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.FRAME_RATE,this._data.frameRate);armature.scale=scale;if(dragonBones.DataParser.TYPE in rawData&&typeof rawData[dragonBones.DataParser.TYPE]==="string"){armature.type=dragonBones.DataParser._getArmatureType(rawData[dragonBones.DataParser.TYPE]);}else {armature.type=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TYPE,0);}if(armature.frameRate===0){armature.frameRate=24;}this._armature=armature;if(dragonBones.DataParser.CANVAS in rawData){var rawCanvas=rawData[dragonBones.DataParser.CANVAS];var canvas=dragonBones.BaseObject.borrowObject(dragonBones.CanvasData);if(dragonBones.DataParser.COLOR in rawCanvas){canvas.hasBackground=true;}else {canvas.hasBackground=false;}canvas.color=ObjectDataParser._getNumber(rawCanvas,dragonBones.DataParser.COLOR,0);canvas.x=ObjectDataParser._getNumber(rawCanvas,dragonBones.DataParser.X,0)*armature.scale;canvas.y=ObjectDataParser._getNumber(rawCanvas,dragonBones.DataParser.Y,0)*armature.scale;canvas.width=ObjectDataParser._getNumber(rawCanvas,dragonBones.DataParser.WIDTH,0)*armature.scale;canvas.height=ObjectDataParser._getNumber(rawCanvas,dragonBones.DataParser.HEIGHT,0)*armature.scale;armature.canvas=canvas;}if(dragonBones.DataParser.AABB in rawData){var rawAABB=rawData[dragonBones.DataParser.AABB];armature.aabb.x=ObjectDataParser._getNumber(rawAABB,dragonBones.DataParser.X,0.0)*armature.scale;armature.aabb.y=ObjectDataParser._getNumber(rawAABB,dragonBones.DataParser.Y,0.0)*armature.scale;armature.aabb.width=ObjectDataParser._getNumber(rawAABB,dragonBones.DataParser.WIDTH,0.0)*armature.scale;armature.aabb.height=ObjectDataParser._getNumber(rawAABB,dragonBones.DataParser.HEIGHT,0.0)*armature.scale;}if(dragonBones.DataParser.BONE in rawData){var rawBones=rawData[dragonBones.DataParser.BONE];for(var _i=0,rawBones_1=rawBones;_i<rawBones_1.length;_i++){var rawBone=rawBones_1[_i];var parentName=ObjectDataParser._getString(rawBone,dragonBones.DataParser.PARENT,"");var bone=this._parseBone(rawBone);if(parentName.length>0){var parent_1=armature.getBone(parentName);if(parent_1!==null){bone.parent=parent_1;}else {if(!(parentName in this._cacheBones)){this._cacheBones[parentName]=[];}this._cacheBones[parentName].push(bone);}}if(bone.name in this._cacheBones){for(var _a=0,_b=this._cacheBones[bone.name];_a<_b.length;_a++){var child=_b[_a];child.parent=bone;}delete this._cacheBones[bone.name];}armature.addBone(bone);this._rawBones.push(bone);}}if(dragonBones.DataParser.IK in rawData){var rawIKS=rawData[dragonBones.DataParser.IK];for(var _c=0,rawIKS_1=rawIKS;_c<rawIKS_1.length;_c++){var rawIK=rawIKS_1[_c];var constraint=this._parseIKConstraint(rawIK);if(constraint){armature.addConstraint(constraint);}}}armature.sortBones();if(dragonBones.DataParser.SLOT in rawData){var zOrder=0;var rawSlots=rawData[dragonBones.DataParser.SLOT];for(var _d=0,rawSlots_1=rawSlots;_d<rawSlots_1.length;_d++){var rawSlot=rawSlots_1[_d];armature.addSlot(this._parseSlot(rawSlot,zOrder++));}}if(dragonBones.DataParser.SKIN in rawData){var rawSkins=rawData[dragonBones.DataParser.SKIN];for(var _e=0,rawSkins_1=rawSkins;_e<rawSkins_1.length;_e++){var rawSkin=rawSkins_1[_e];armature.addSkin(this._parseSkin(rawSkin));}}if(dragonBones.DataParser.PATH_CONSTRAINT in rawData){var rawPaths=rawData[dragonBones.DataParser.PATH_CONSTRAINT];for(var _f=0,rawPaths_1=rawPaths;_f<rawPaths_1.length;_f++){var rawPath=rawPaths_1[_f];var constraint=this._parsePathConstraint(rawPath);if(constraint){armature.addConstraint(constraint);}}}for(var i=0,l=this._cacheRawMeshes.length;i<l;++i){var rawMeshData=this._cacheRawMeshes[i];if(!(dragonBones.DataParser.GLUE_WEIGHTS in rawMeshData)||!(dragonBones.DataParser.GLUE_MESHES in rawMeshData)){continue;}this._parseMeshGlue(rawMeshData,this._cacheMeshes[i]);}for(var i=0,l=this._cacheRawMeshes.length;i<l;++i){var rawData_1=this._cacheRawMeshes[i];var shareName=ObjectDataParser._getString(rawData_1,dragonBones.DataParser.SHARE,"");if(shareName.length===0){continue;}var skinName=ObjectDataParser._getString(rawData_1,dragonBones.DataParser.SKIN,dragonBones.DataParser.DEFAULT_NAME);if(skinName.length===0){skinName=dragonBones.DataParser.DEFAULT_NAME;}var shareMesh=armature.getMesh(skinName,"",shareName);if(shareMesh===null){continue;}var mesh=this._cacheMeshes[i];mesh.vertices.shareFrom(shareMesh.vertices);}if(dragonBones.DataParser.ANIMATION in rawData){var rawAnimations=rawData[dragonBones.DataParser.ANIMATION];for(var _g=0,rawAnimations_1=rawAnimations;_g<rawAnimations_1.length;_g++){var rawAnimation=rawAnimations_1[_g];var animation=this._parseAnimation(rawAnimation);armature.addAnimation(animation);}}if(dragonBones.DataParser.DEFAULT_ACTIONS in rawData){var actions=this._parseActionData(rawData[dragonBones.DataParser.DEFAULT_ACTIONS],0,null,null);for(var _h=0,actions_3=actions;_h<actions_3.length;_h++){var action=actions_3[_h];armature.addAction(action,true);if(action.type===0){var animation=armature.getAnimation(action.name);if(animation!==null){armature.defaultAnimation=animation;}}}}if(dragonBones.DataParser.ACTIONS in rawData){var actions=this._parseActionData(rawData[dragonBones.DataParser.ACTIONS],0,null,null);for(var _j=0,actions_4=actions;_j<actions_4.length;_j++){var action=actions_4[_j];armature.addAction(action,false);}}this._rawBones.length=0;this._cacheRawMeshes.length=0;this._cacheMeshes.length=0;this._armature=null;for(var k in this._weightSlotPose){delete this._weightSlotPose[k];}for(var k in this._weightBonePoses){delete this._weightBonePoses[k];}for(var k in this._cacheBones){delete this._cacheBones[k];}for(var k in this._slotChildActions){delete this._slotChildActions[k];}return armature;};ObjectDataParser.prototype._parseBone=function(rawData){var type=0;var scale=this._armature.scale;if(dragonBones.DataParser.TYPE in rawData&&typeof rawData[dragonBones.DataParser.TYPE]==="string"){type=dragonBones.DataParser._getBoneType(rawData[dragonBones.DataParser.TYPE]);}else {type=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TYPE,0);}if(type===0){var bone=dragonBones.BaseObject.borrowObject(dragonBones.BoneData);bone.inheritTranslation=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.INHERIT_TRANSLATION,true);bone.inheritRotation=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.INHERIT_ROTATION,true);bone.inheritScale=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.INHERIT_SCALE,true);bone.inheritReflection=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.INHERIT_REFLECTION,true);bone.length=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.LENGTH,0)*scale;bone.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");if(dragonBones.DataParser.TRANSFORM in rawData){this._parseTransform(rawData[dragonBones.DataParser.TRANSFORM],bone.transform,scale);}return bone;}var surface=dragonBones.BaseObject.borrowObject(dragonBones.SurfaceData);surface.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");surface.segmentX=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SEGMENT_X,0);surface.segmentY=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SEGMENT_Y,0);surface.vertices.length=(surface.segmentX+1)*(surface.segmentY+1)*2;if(dragonBones.DataParser.VERTICES in rawData){var rawVertices=rawData[dragonBones.DataParser.VERTICES];for(var i=0,l=surface.vertices.length;i<l;++i){if(i<rawVertices.length){surface.vertices[i]=rawVertices[i]*scale;}else {surface.vertices[i]=0.0;}}}return surface;};ObjectDataParser.prototype._parseIKConstraint=function(rawData){var bone=this._armature.getBone(ObjectDataParser._getString(rawData,dragonBones.DataParser.BONE,""));if(bone===null){return null;}var target=this._armature.getBone(ObjectDataParser._getString(rawData,dragonBones.DataParser.TARGET,""));if(target===null){return null;}var constraint=dragonBones.BaseObject.borrowObject(dragonBones.IKConstraintData);constraint.scaleEnabled=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.SCALE,false);constraint.bendPositive=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.BEND_POSITIVE,true);constraint.weight=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.WEIGHT,1.0);constraint.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");constraint.type=0;constraint.target=target;var chain=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.CHAIN,0);if(chain>0&&bone.parent!==null){constraint.root=bone.parent;constraint.bone=bone;}else {constraint.root=bone;constraint.bone=null;}return constraint;};ObjectDataParser.prototype._parsePathConstraint=function(rawData){var target=this._armature.getSlot(ObjectDataParser._getString(rawData,dragonBones.DataParser.TARGET,""));if(target===null){return null;}var defaultSkin=this._armature.defaultSkin;if(defaultSkin===null){return null;}var targetDisplay=defaultSkin.getDisplay(target.name,ObjectDataParser._getString(rawData,dragonBones.DataParser.TARGET_DISPLAY,target.name));if(targetDisplay===null||!(targetDisplay instanceof dragonBones.PathDisplayData)){return null;}var bones=rawData[dragonBones.DataParser.BONES];if(bones===null||bones.length===0){return null;}var constraint=dragonBones.BaseObject.borrowObject(dragonBones.PathConstraintData);constraint.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");constraint.type=1;constraint.pathSlot=target;constraint.pathDisplayData=targetDisplay;constraint.target=target.parent;constraint.positionMode=dragonBones.DataParser._getPositionMode(ObjectDataParser._getString(rawData,dragonBones.DataParser.POSITION_MODE,""));constraint.spacingMode=dragonBones.DataParser._getSpacingMode(ObjectDataParser._getString(rawData,dragonBones.DataParser.SPACING_MODE,""));constraint.rotateMode=dragonBones.DataParser._getRotateMode(ObjectDataParser._getString(rawData,dragonBones.DataParser.ROTATE_MODE,""));constraint.position=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.POSITION,0);constraint.spacing=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SPACING,0);constraint.rotateOffset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ROTATE_OFFSET,0);constraint.rotateMix=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ROTATE_MIX,1);constraint.translateMix=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TRANSLATE_MIX,1);for(var _i=0,bones_3=bones;_i<bones_3.length;_i++){var boneName=bones_3[_i];var bone=this._armature.getBone(boneName);if(bone!==null){constraint.AddBone(bone);if(constraint.root===null){constraint.root=bone;}}}return constraint;};ObjectDataParser.prototype._parseSlot=function(rawData,zOrder){var slot=dragonBones.BaseObject.borrowObject(dragonBones.SlotData);slot.displayIndex=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.DISPLAY_INDEX,0);slot.zOrder=zOrder;slot.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");slot.parent=this._armature.getBone(ObjectDataParser._getString(rawData,dragonBones.DataParser.PARENT,""));if(dragonBones.DataParser.BLEND_MODE in rawData&&typeof rawData[dragonBones.DataParser.BLEND_MODE]==="string"){slot.blendMode=dragonBones.DataParser._getBlendMode(rawData[dragonBones.DataParser.BLEND_MODE]);}else {slot.blendMode=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.BLEND_MODE,0);}if(dragonBones.DataParser.COLOR in rawData){slot.color=dragonBones.SlotData.createColor();this._parseColorTransform(rawData[dragonBones.DataParser.COLOR],slot.color);}else {slot.color=dragonBones.SlotData.DEFAULT_COLOR;}if(dragonBones.DataParser.ACTIONS in rawData){this._slotChildActions[slot.name]=this._parseActionData(rawData[dragonBones.DataParser.ACTIONS],0,null,null);}return slot;};ObjectDataParser.prototype._parseSkin=function(rawData){var skin=dragonBones.BaseObject.borrowObject(dragonBones.SkinData);skin.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,dragonBones.DataParser.DEFAULT_NAME);if(skin.name.length===0){skin.name=dragonBones.DataParser.DEFAULT_NAME;}if(dragonBones.DataParser.SLOT in rawData){var rawSlots=rawData[dragonBones.DataParser.SLOT];this._skin=skin;for(var _i=0,rawSlots_2=rawSlots;_i<rawSlots_2.length;_i++){var rawSlot=rawSlots_2[_i];var slotName=ObjectDataParser._getString(rawSlot,dragonBones.DataParser.NAME,"");var slot=this._armature.getSlot(slotName);if(slot!==null){this._slot=slot;if(dragonBones.DataParser.DISPLAY in rawSlot){var rawDisplays=rawSlot[dragonBones.DataParser.DISPLAY];for(var _a=0,rawDisplays_1=rawDisplays;_a<rawDisplays_1.length;_a++){var rawDisplay=rawDisplays_1[_a];if(rawDisplay){skin.addDisplay(slotName,this._parseDisplay(rawDisplay));}else {skin.addDisplay(slotName,null);}}}this._slot=null;}}this._skin=null;}return skin;};ObjectDataParser.prototype._parseDisplay=function(rawData){var name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");var path=ObjectDataParser._getString(rawData,dragonBones.DataParser.PATH,"");var type=0;var display=null;if(dragonBones.DataParser.TYPE in rawData&&typeof rawData[dragonBones.DataParser.TYPE]==="string"){type=dragonBones.DataParser._getDisplayType(rawData[dragonBones.DataParser.TYPE]);}else {type=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TYPE,type);}switch(type){case 0:var imageDisplay=display=dragonBones.BaseObject.borrowObject(dragonBones.ImageDisplayData);imageDisplay.name=name;imageDisplay.path=path.length>0?path:name;this._parsePivot(rawData,imageDisplay);break;case 1:var armatureDisplay=display=dragonBones.BaseObject.borrowObject(dragonBones.ArmatureDisplayData);armatureDisplay.name=name;armatureDisplay.path=path.length>0?path:name;armatureDisplay.inheritAnimation=true;if(dragonBones.DataParser.ACTIONS in rawData){var actions=this._parseActionData(rawData[dragonBones.DataParser.ACTIONS],0,null,null);for(var _i=0,actions_5=actions;_i<actions_5.length;_i++){var action=actions_5[_i];armatureDisplay.addAction(action);}}else if(this._slot.name in this._slotChildActions){var displays=this._skin.getDisplays(this._slot.name);if(displays===null?this._slot.displayIndex===0:this._slot.displayIndex===displays.length){for(var _a=0,_b=this._slotChildActions[this._slot.name];_a<_b.length;_a++){var action=_b[_a];armatureDisplay.addAction(action);}delete this._slotChildActions[this._slot.name];}}break;case 2:var meshDisplay=display=dragonBones.BaseObject.borrowObject(dragonBones.MeshDisplayData);meshDisplay.vertices.inheritDeform=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.INHERIT_DEFORM,true);meshDisplay.name=name;meshDisplay.path=path.length>0?path:name;meshDisplay.vertices.data=this._data;if(dragonBones.DataParser.SHARE in rawData){this._cacheRawMeshes.push(rawData);this._cacheMeshes.push(meshDisplay);}else {this._parseMesh(rawData,meshDisplay);}if(dragonBones.DataParser.GLUE_WEIGHTS in rawData&&dragonBones.DataParser.GLUE_MESHES in rawData){this._cacheRawMeshes.push(rawData);this._cacheMeshes.push(meshDisplay);}break;case 3:var boundingBox=this._parseBoundingBox(rawData);if(boundingBox!==null){var boundingBoxDisplay=display=dragonBones.BaseObject.borrowObject(dragonBones.BoundingBoxDisplayData);boundingBoxDisplay.name=name;boundingBoxDisplay.path=path.length>0?path:name;boundingBoxDisplay.boundingBox=boundingBox;}break;case 4:var rawCurveLengths=rawData[dragonBones.DataParser.LENGTHS];var pathDisplay=display=dragonBones.BaseObject.borrowObject(dragonBones.PathDisplayData);pathDisplay.closed=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.CLOSED,false);pathDisplay.constantSpeed=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.CONSTANT_SPEED,false);pathDisplay.name=name;pathDisplay.path=path.length>0?path:name;pathDisplay.vertices.data=this._data;pathDisplay.curveLengths.length=rawCurveLengths.length;for(var i=0,l=rawCurveLengths.length;i<l;++i){pathDisplay.curveLengths[i]=rawCurveLengths[i];}this._parsePath(rawData,pathDisplay);break;}if(display!==null&&dragonBones.DataParser.TRANSFORM in rawData){this._parseTransform(rawData[dragonBones.DataParser.TRANSFORM],display.transform,this._armature.scale);}return display;};ObjectDataParser.prototype._parsePath=function(rawData,display){var rawVertices=rawData[dragonBones.DataParser.VERTICES];var vertexCount=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.VERTEX_COUNT,0);var vertexOffset=this._floatArray.length;var pathOffset=this._intArray.length;display.vertices.offset=pathOffset;this._intArray.length+=1+1;this._intArray[pathOffset+0]=vertexCount;this._intArray[pathOffset+2]=vertexOffset;if(!(dragonBones.DataParser.WEIGHTS in rawData)){this._floatArray.length+=rawVertices.length;for(var i=0,l=rawVertices.length;i<l;++i){this._floatArray[vertexOffset+i]=rawVertices[i];}}else {var rawWeights=rawData[dragonBones.DataParser.WEIGHTS];var rawBones=rawData[dragonBones.DataParser.BONES];var weightBoneCount=rawBones.length;var weightCount=Math.floor(rawWeights.length-vertexCount)/2;var weightOffset=this._intArray.length;var floatOffset=this._floatArray.length;var sortedBones=this._armature.sortedBones;var weight=dragonBones.BaseObject.borrowObject(dragonBones.WeightData);weight.count=weightCount;weight.offset=weightOffset;this._intArray.length+=1+1+weightBoneCount+vertexCount+weightCount;this._intArray[weightOffset+0]=weightBoneCount;this._intArray[weightOffset+1]=floatOffset;for(var i=0;i<weightBoneCount;i++){var rawBoneIndex=rawBones[i];var bone=this._rawBones[rawBoneIndex];weight.addBone(bone);this._intArray[weightOffset+2+i]=sortedBones.indexOf(bone);}this._floatArray.length+=weightCount*3;for(var i=0,iW=0,iV=0,iB=weightOffset+2+weightBoneCount,iF=floatOffset;i<weightCount;i++){var boneCount=rawWeights[iW++];this._intArray[iB++]=boneCount;for(var j=0;j<boneCount;j++){var boneIndex=rawWeights[iW++];var boneWeight=rawWeights[iW++];var x=rawVertices[iV++];var y=rawVertices[iV++];this._intArray[iB++]=rawBones.indexOf(boneIndex);this._floatArray[iF++]=boneWeight;this._floatArray[iF++]=x;this._floatArray[iF++]=y;}}display.vertices.weight=weight;}};ObjectDataParser.prototype._parsePivot=function(rawData,display){if(dragonBones.DataParser.PIVOT in rawData){var rawPivot=rawData[dragonBones.DataParser.PIVOT];display.pivot.x=ObjectDataParser._getNumber(rawPivot,dragonBones.DataParser.X,0.0);display.pivot.y=ObjectDataParser._getNumber(rawPivot,dragonBones.DataParser.Y,0.0);}else {display.pivot.x=0.5;display.pivot.y=0.5;}};ObjectDataParser.prototype._parseMesh=function(rawData,mesh){var rawVertices=rawData[dragonBones.DataParser.VERTICES];var rawUVs=rawData[dragonBones.DataParser.UVS];var rawTriangles=rawData[dragonBones.DataParser.TRIANGLES];var vertexCount=Math.floor(rawVertices.length/2);var triangleCount=Math.floor(rawTriangles.length/3);var vertexOffset=this._floatArray.length;var uvOffset=vertexOffset+vertexCount*2;var meshOffset=this._intArray.length;var meshName=this._skin.name+"_"+this._slot.name+"_"+mesh.name;mesh.vertices.offset=meshOffset;this._intArray.length+=1+1+1+1+triangleCount*3;this._intArray[meshOffset+0]=vertexCount;this._intArray[meshOffset+1]=triangleCount;this._intArray[meshOffset+2]=vertexOffset;for(var i=0,l=triangleCount*3;i<l;++i){this._intArray[meshOffset+4+i]=rawTriangles[i];}this._floatArray.length+=vertexCount*2+vertexCount*2;for(var i=0,l=vertexCount*2;i<l;++i){this._floatArray[vertexOffset+i]=rawVertices[i];this._floatArray[uvOffset+i]=rawUVs[i];}if(dragonBones.DataParser.WEIGHTS in rawData){var rawWeights=rawData[dragonBones.DataParser.WEIGHTS];var rawSlotPose=rawData[dragonBones.DataParser.SLOT_POSE];var rawBonePoses=rawData[dragonBones.DataParser.BONE_POSE];var sortedBones=this._armature.sortedBones;var weightBoneIndices=new Array();var weightBoneCount=Math.floor(rawBonePoses.length/7);var floatOffset=this._floatArray.length;var weightCount=Math.floor(rawWeights.length-vertexCount)/2;var weightOffset=this._intArray.length;var weight=dragonBones.BaseObject.borrowObject(dragonBones.WeightData);weight.count=weightCount;weight.offset=weightOffset;weightBoneIndices.length=weightBoneCount;this._intArray.length+=1+1+weightBoneCount+vertexCount+weightCount;this._intArray[weightOffset+1]=floatOffset;for(var i=0;i<weightBoneCount;++i){var rawBoneIndex=rawBonePoses[i*7];var bone=this._rawBones[rawBoneIndex];weight.addBone(bone);weightBoneIndices[i]=rawBoneIndex;this._intArray[weightOffset+2+i]=sortedBones.indexOf(bone);}this._floatArray.length+=weightCount*3;this._helpMatrixA.copyFromArray(rawSlotPose,0);for(var i=0,iW=0,iB=weightOffset+2+weightBoneCount,iV=floatOffset;i<vertexCount;++i){var iD=i*2;var vertexBoneCount=this._intArray[iB++]=rawWeights[iW++];var x=this._floatArray[vertexOffset+iD];var y=this._floatArray[vertexOffset+iD+1];this._helpMatrixA.transformPoint(x,y,this._helpPoint);x=this._helpPoint.x;y=this._helpPoint.y;for(var j=0;j<vertexBoneCount;++j){var rawBoneIndex=rawWeights[iW++];var boneIndex=weightBoneIndices.indexOf(rawBoneIndex);this._helpMatrixB.copyFromArray(rawBonePoses,boneIndex*7+1);this._helpMatrixB.invert();this._helpMatrixB.transformPoint(x,y,this._helpPoint);this._intArray[iB++]=boneIndex;this._floatArray[iV++]=rawWeights[iW++];this._floatArray[iV++]=this._helpPoint.x;this._floatArray[iV++]=this._helpPoint.y;}}mesh.vertices.weight=weight;this._weightSlotPose[meshName]=rawSlotPose;this._weightBonePoses[meshName]=rawBonePoses;}};ObjectDataParser.prototype._parseMeshGlue=function(rawData,mesh){};ObjectDataParser.prototype._parseBoundingBox=function(rawData){var boundingBox=null;var type=0;if(dragonBones.DataParser.SUB_TYPE in rawData&&typeof rawData[dragonBones.DataParser.SUB_TYPE]==="string"){type=dragonBones.DataParser._getBoundingBoxType(rawData[dragonBones.DataParser.SUB_TYPE]);}else {type=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SUB_TYPE,type);}switch(type){case 0:boundingBox=dragonBones.BaseObject.borrowObject(dragonBones.RectangleBoundingBoxData);break;case 1:boundingBox=dragonBones.BaseObject.borrowObject(dragonBones.EllipseBoundingBoxData);break;case 2:boundingBox=this._parsePolygonBoundingBox(rawData);break;}if(boundingBox!==null){boundingBox.color=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.COLOR,0x000000);if(boundingBox.type===0||boundingBox.type===1){boundingBox.width=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.WIDTH,0.0);boundingBox.height=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.HEIGHT,0.0);}}return boundingBox;};ObjectDataParser.prototype._parsePolygonBoundingBox=function(rawData){var polygonBoundingBox=dragonBones.BaseObject.borrowObject(dragonBones.PolygonBoundingBoxData);if(dragonBones.DataParser.VERTICES in rawData){var scale=this._armature.scale;var rawVertices=rawData[dragonBones.DataParser.VERTICES];var vertices=polygonBoundingBox.vertices;if(dragonBones.DragonBones.webAssembly){vertices.resize(rawVertices.length,0.0);}else {vertices.length=rawVertices.length;}for(var i=0,l=rawVertices.length;i<l;i+=2){var x=rawVertices[i]*scale;var y=rawVertices[i+1]*scale;if(dragonBones.DragonBones.webAssembly){vertices.set(i,x);vertices.set(i+1,y);}else {vertices[i]=x;vertices[i+1]=y;}if(i===0){polygonBoundingBox.x=x;polygonBoundingBox.y=y;polygonBoundingBox.width=x;polygonBoundingBox.height=y;}else {if(x<polygonBoundingBox.x){polygonBoundingBox.x=x;}else if(x>polygonBoundingBox.width){polygonBoundingBox.width=x;}if(y<polygonBoundingBox.y){polygonBoundingBox.y=y;}else if(y>polygonBoundingBox.height){polygonBoundingBox.height=y;}}}polygonBoundingBox.width-=polygonBoundingBox.x;polygonBoundingBox.height-=polygonBoundingBox.y;}else {console.warn("Data error.\n Please reexport DragonBones Data to fixed the bug.");}return polygonBoundingBox;};ObjectDataParser.prototype._parseAnimation=function(rawData){var animation=dragonBones.BaseObject.borrowObject(dragonBones.AnimationData);animation.frameCount=Math.max(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.DURATION,1),1);animation.playTimes=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.PLAY_TIMES,1);animation.duration=animation.frameCount/this._armature.frameRate;animation.fadeInTime=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.FADE_IN_TIME,0.0);animation.scale=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE,1.0);animation.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,dragonBones.DataParser.DEFAULT_NAME);if(animation.name.length===0){animation.name=dragonBones.DataParser.DEFAULT_NAME;}animation.frameIntOffset=this._frameIntArray.length;animation.frameFloatOffset=this._frameFloatArray.length;animation.frameOffset=this._frameArray.length;this._animation=animation;if(dragonBones.DataParser.FRAME in rawData){var rawFrames=rawData[dragonBones.DataParser.FRAME];var keyFrameCount=rawFrames.length;if(keyFrameCount>0){for(var i=0,frameStart=0;i<keyFrameCount;++i){var rawFrame=rawFrames[i];this._parseActionDataInFrame(rawFrame,frameStart,null,null);frameStart+=ObjectDataParser._getNumber(rawFrame,dragonBones.DataParser.DURATION,1);}}}if(dragonBones.DataParser.Z_ORDER in rawData){this._animation.zOrderTimeline=this._parseTimeline(rawData[dragonBones.DataParser.Z_ORDER],null,dragonBones.DataParser.FRAME,1,false,false,0,this._parseZOrderFrame);}if(dragonBones.DataParser.BONE in rawData){var rawTimelines=rawData[dragonBones.DataParser.BONE];for(var _i=0,rawTimelines_1=rawTimelines;_i<rawTimelines_1.length;_i++){var rawTimeline=rawTimelines_1[_i];this._parseBoneTimeline(rawTimeline);}}if(dragonBones.DataParser.SURFACE in rawData){var rawTimelines=rawData[dragonBones.DataParser.SURFACE];for(var _a=0,rawTimelines_2=rawTimelines;_a<rawTimelines_2.length;_a++){var rawTimeline=rawTimelines_2[_a];var surfaceName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.NAME,"");this._surface=this._armature.getBone(surfaceName);if(this._surface===null){continue;}var timeline=this._parseTimeline(rawTimeline,null,dragonBones.DataParser.FRAME,50,false,true,0,this._parseSurfaceFrame);if(timeline!==null){this._animation.addSurfaceTimeline(this._surface,timeline);}this._surface=null;}}if(dragonBones.DataParser.SLOT in rawData){var rawTimelines=rawData[dragonBones.DataParser.SLOT];for(var _b=0,rawTimelines_3=rawTimelines;_b<rawTimelines_3.length;_b++){var rawTimeline=rawTimelines_3[_b];this._parseSlotTimeline(rawTimeline);}}if(dragonBones.DataParser.FFD in rawData){var rawTimelines=rawData[dragonBones.DataParser.FFD];for(var _c=0,rawTimelines_4=rawTimelines;_c<rawTimelines_4.length;_c++){var rawTimeline=rawTimelines_4[_c];var skinName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.SKIN,dragonBones.DataParser.DEFAULT_NAME);var slotName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.SLOT,"");var displayName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.NAME,"");if(skinName.length===0){skinName=dragonBones.DataParser.DEFAULT_NAME;}this._slot=this._armature.getSlot(slotName);this._mesh=this._armature.getMesh(skinName,slotName,displayName);if(this._slot===null||this._mesh===null){continue;}var timeline=this._parseTimeline(rawTimeline,null,dragonBones.DataParser.FRAME,22,false,true,0,this._parseSlotFFDFrame);if(timeline!==null){this._animation.addSlotTimeline(this._slot,timeline);}this._slot=null;this._mesh=null;}}if(dragonBones.DataParser.IK in rawData){var rawTimelines=rawData[dragonBones.DataParser.IK];for(var _d=0,rawTimelines_5=rawTimelines;_d<rawTimelines_5.length;_d++){var rawTimeline=rawTimelines_5[_d];var constraintName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.NAME,"");var constraint=this._armature.getConstraint(constraintName);if(constraint===null){continue;}var timeline=this._parseTimeline(rawTimeline,null,dragonBones.DataParser.FRAME,30,true,false,2,this._parseIKConstraintFrame);if(timeline!==null){this._animation.addConstraintTimeline(constraint,timeline);}}}if(dragonBones.DataParser.ANIMATION in rawData){var rawTimelines=rawData[dragonBones.DataParser.ANIMATION];for(var _e=0,rawTimelines_6=rawTimelines;_e<rawTimelines_6.length;_e++){var rawTimeline=rawTimelines_6[_e];var animationName=ObjectDataParser._getString(rawTimeline,dragonBones.DataParser.NAME,"");var timeline=this._parseTimeline(rawTimeline,null,dragonBones.DataParser.FRAME,40,true,false,2,this._parseAnimationFrame);if(timeline!==null){this._animation.addAnimationTimeline(animationName,timeline);}}}if(this._actionFrames.length>0){this._animation.actionTimeline=this._parseTimeline(null,this._actionFrames,"",0,false,false,0,this._parseActionFrame);this._actionFrames.length=0;}this._animation=null;return animation;};ObjectDataParser.prototype._parseTimeline=function(rawData,rawFrames,framesKey,type,addIntOffset,addFloatOffset,frameValueCount,frameParser){if(rawData!==null&&framesKey.length>0&&framesKey in rawData){rawFrames=rawData[framesKey];}if(rawFrames===null){return null;}var keyFrameCount=rawFrames.length;if(keyFrameCount===0){return null;}var frameIntArrayLength=this._frameIntArray.length;var frameFloatArrayLength=this._frameFloatArray.length;var timeline=dragonBones.BaseObject.borrowObject(dragonBones.TimelineData);var timelineOffset=this._timelineArray.length;this._timelineArray.length+=1+1+1+1+1+keyFrameCount;if(rawData!==null){this._timelineArray[timelineOffset+0]=Math.round(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE,1.0)*100);this._timelineArray[timelineOffset+1]=Math.round(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.OFFSET,0.0)*100);}else {this._timelineArray[timelineOffset+0]=100;this._timelineArray[timelineOffset+1]=0;}this._timelineArray[timelineOffset+2]=keyFrameCount;this._timelineArray[timelineOffset+3]=frameValueCount;if(addIntOffset){this._timelineArray[timelineOffset+4]=frameIntArrayLength-this._animation.frameIntOffset;}else if(addFloatOffset){this._timelineArray[timelineOffset+4]=frameFloatArrayLength-this._animation.frameFloatOffset;}else {this._timelineArray[timelineOffset+4]=0;}this._timeline=timeline;timeline.type=type;timeline.offset=timelineOffset;if(keyFrameCount===1){timeline.frameIndicesOffset=-1;this._timelineArray[timelineOffset+5+0]=frameParser.call(this,rawFrames[0],0,0)-this._animation.frameOffset;}else {var totalFrameCount=this._animation.frameCount+1;var frameIndices=this._data.frameIndices;var frameIndicesOffset=0;if(dragonBones.DragonBones.webAssembly){frameIndicesOffset=frameIndices.size();frameIndices.resize(frameIndicesOffset+totalFrameCount,0);}else {frameIndicesOffset=frameIndices.length;frameIndices.length+=totalFrameCount;}timeline.frameIndicesOffset=frameIndicesOffset;for(var i=0,iK=0,frameStart=0,frameCount=0;i<totalFrameCount;++i){if(frameStart+frameCount<=i&&iK<keyFrameCount){var rawFrame=rawFrames[iK];frameStart=i;if(iK===keyFrameCount-1){frameCount=this._animation.frameCount-frameStart;}else {if(rawFrame instanceof ActionFrame){frameCount=this._actionFrames[iK+1].frameStart-frameStart;}else {frameCount=ObjectDataParser._getNumber(rawFrame,dragonBones.DataParser.DURATION,1);}}this._timelineArray[timelineOffset+5+iK]=frameParser.call(this,rawFrame,frameStart,frameCount)-this._animation.frameOffset;iK++;}if(dragonBones.DragonBones.webAssembly){frameIndices.set(frameIndicesOffset+i,iK-1);}else {frameIndices[frameIndicesOffset+i]=iK-1;}}}this._timeline=null;return timeline;};ObjectDataParser.prototype._parseBoneTimeline=function(rawData){var bone=this._armature.getBone(ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,""));if(bone===null){return;}this._bone=bone;this._slot=this._armature.getSlot(this._bone.name);if(dragonBones.DataParser.TRANSLATE_FRAME in rawData){var timeline=this._parseTimeline(rawData,null,dragonBones.DataParser.TRANSLATE_FRAME,11,false,true,2,this._parseBoneTranslateFrame);if(timeline!==null){this._animation.addBoneTimeline(bone,timeline);}}if(dragonBones.DataParser.ROTATE_FRAME in rawData){var timeline=this._parseTimeline(rawData,null,dragonBones.DataParser.ROTATE_FRAME,12,false,true,2,this._parseBoneRotateFrame);if(timeline!==null){this._animation.addBoneTimeline(bone,timeline);}}if(dragonBones.DataParser.SCALE_FRAME in rawData){var timeline=this._parseTimeline(rawData,null,dragonBones.DataParser.SCALE_FRAME,13,false,true,2,this._parseBoneScaleFrame);if(timeline!==null){this._animation.addBoneTimeline(bone,timeline);}}if(dragonBones.DataParser.FRAME in rawData){var timeline=this._parseTimeline(rawData,null,dragonBones.DataParser.FRAME,10,false,true,6,this._parseBoneAllFrame);if(timeline!==null){this._animation.addBoneTimeline(bone,timeline);}}this._bone=null;this._slot=null;};ObjectDataParser.prototype._parseSlotTimeline=function(rawData){var slot=this._armature.getSlot(ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,""));if(slot===null){return;}this._slot=slot;var displayTimeline=null;if(dragonBones.DataParser.DISPLAY_FRAME in rawData){displayTimeline=this._parseTimeline(rawData,null,dragonBones.DataParser.DISPLAY_FRAME,20,false,false,0,this._parseSlotDisplayFrame);}else {displayTimeline=this._parseTimeline(rawData,null,dragonBones.DataParser.FRAME,20,false,false,0,this._parseSlotDisplayFrame);}if(displayTimeline!==null){this._animation.addSlotTimeline(slot,displayTimeline);}var colorTimeline=null;if(dragonBones.DataParser.COLOR_FRAME in rawData){colorTimeline=this._parseTimeline(rawData,null,dragonBones.DataParser.COLOR_FRAME,21,true,false,1,this._parseSlotColorFrame);}else {colorTimeline=this._parseTimeline(rawData,null,dragonBones.DataParser.FRAME,21,true,false,1,this._parseSlotColorFrame);}if(colorTimeline!==null){this._animation.addSlotTimeline(slot,colorTimeline);}this._slot=null;};ObjectDataParser.prototype._parseFrame=function(rawData,frameStart,frameCount){var frameOffset=this._frameArray.length;this._frameArray.length+=1;this._frameArray[frameOffset+0]=frameStart;return frameOffset;};ObjectDataParser.prototype._parseTweenFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseFrame(rawData,frameStart,frameCount);if(frameCount>0){if(dragonBones.DataParser.CURVE in rawData){var sampleCount=frameCount+1;this._helpArray.length=sampleCount;this._samplingEasingCurve(rawData[dragonBones.DataParser.CURVE],this._helpArray);this._frameArray.length+=1+1+this._helpArray.length;this._frameArray[frameOffset+1]=2;this._frameArray[frameOffset+2]=sampleCount;for(var i=0;i<sampleCount;++i){this._frameArray[frameOffset+3+i]=Math.round(this._helpArray[i]*10000.0);}}else {var noTween=-2.0;var tweenEasing=noTween;if(dragonBones.DataParser.TWEEN_EASING in rawData){tweenEasing=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TWEEN_EASING,noTween);}if(tweenEasing===noTween){this._frameArray.length+=1;this._frameArray[frameOffset+1]=0;}else if(tweenEasing===0.0){this._frameArray.length+=1;this._frameArray[frameOffset+1]=1;}else if(tweenEasing<0.0){this._frameArray.length+=1+1;this._frameArray[frameOffset+1]=3;this._frameArray[frameOffset+2]=Math.round(-tweenEasing*100.0);}else if(tweenEasing<=1.0){this._frameArray.length+=1+1;this._frameArray[frameOffset+1]=4;this._frameArray[frameOffset+2]=Math.round(tweenEasing*100.0);}else {this._frameArray.length+=1+1;this._frameArray[frameOffset+1]=5;this._frameArray[frameOffset+2]=Math.round(tweenEasing*100.0-100.0);}}}else {this._frameArray.length+=1;this._frameArray[frameOffset+1]=0;}return frameOffset;};ObjectDataParser.prototype._parseActionFrame=function(frame,frameStart,frameCount){var frameOffset=this._frameArray.length;var actionCount=frame.actions.length;this._frameArray.length+=1+1+actionCount;this._frameArray[frameOffset+0]=frameStart;this._frameArray[frameOffset+0+1]=actionCount;for(var i=0;i<actionCount;++i){this._frameArray[frameOffset+0+2+i]=frame.actions[i];}return frameOffset;};ObjectDataParser.prototype._parseZOrderFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseFrame(rawData,frameStart,frameCount);if(dragonBones.DataParser.Z_ORDER in rawData){var rawZOrder=rawData[dragonBones.DataParser.Z_ORDER];if(rawZOrder.length>0){var slotCount=this._armature.sortedSlots.length;var unchanged=new Array(slotCount-rawZOrder.length/2);var zOrders=new Array(slotCount);for(var i_1=0;i_1<unchanged.length;++i_1){unchanged[i_1]=0;}for(var i_2=0;i_2<slotCount;++i_2){zOrders[i_2]=-1;}var originalIndex=0;var unchangedIndex=0;for(var i_3=0,l=rawZOrder.length;i_3<l;i_3+=2){var slotIndex=rawZOrder[i_3];var zOrderOffset=rawZOrder[i_3+1];while(originalIndex!==slotIndex){unchanged[unchangedIndex++]=originalIndex++;}var index=originalIndex+zOrderOffset;zOrders[index]=originalIndex++;}while(originalIndex<slotCount){unchanged[unchangedIndex++]=originalIndex++;}this._frameArray.length+=1+slotCount;this._frameArray[frameOffset+1]=slotCount;var i=slotCount;while(i--){if(zOrders[i]===-1){this._frameArray[frameOffset+2+i]=unchanged[--unchangedIndex]||0;}else {this._frameArray[frameOffset+2+i]=zOrders[i]||0;}}return frameOffset;}}this._frameArray.length+=1;this._frameArray[frameOffset+1]=0;return frameOffset;};ObjectDataParser.prototype._parseBoneAllFrame=function(rawData,frameStart,frameCount){this._helpTransform.identity();if(dragonBones.DataParser.TRANSFORM in rawData){this._parseTransform(rawData[dragonBones.DataParser.TRANSFORM],this._helpTransform,1.0);}var rotation=this._helpTransform.rotation;if(frameStart!==0){if(this._prevClockwise===0){rotation=this._prevRotation+dragonBones.Transform.normalizeRadian(rotation-this._prevRotation);}else {if(this._prevClockwise>0?rotation>=this._prevRotation:rotation<=this._prevRotation){this._prevClockwise=this._prevClockwise>0?this._prevClockwise-1:this._prevClockwise+1;}rotation=this._prevRotation+rotation-this._prevRotation+dragonBones.Transform.PI_D*this._prevClockwise;}}this._prevClockwise=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.TWEEN_ROTATE,0.0);this._prevRotation=rotation;var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameFloatOffset=this._frameFloatArray.length;this._frameFloatArray.length+=6;this._frameFloatArray[frameFloatOffset++]=this._helpTransform.x;this._frameFloatArray[frameFloatOffset++]=this._helpTransform.y;this._frameFloatArray[frameFloatOffset++]=rotation;this._frameFloatArray[frameFloatOffset++]=this._helpTransform.skew;this._frameFloatArray[frameFloatOffset++]=this._helpTransform.scaleX;this._frameFloatArray[frameFloatOffset++]=this._helpTransform.scaleY;this._parseActionDataInFrame(rawData,frameStart,this._bone,this._slot);return frameOffset;};ObjectDataParser.prototype._parseBoneTranslateFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameFloatOffset=this._frameFloatArray.length;this._frameFloatArray.length+=2;this._frameFloatArray[frameFloatOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.X,0.0);this._frameFloatArray[frameFloatOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.Y,0.0);return frameOffset;};ObjectDataParser.prototype._parseBoneRotateFrame=function(rawData,frameStart,frameCount){var rotation=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ROTATE,0.0)*dragonBones.Transform.DEG_RAD;if(frameStart!==0){if(this._prevClockwise===0){rotation=this._prevRotation+dragonBones.Transform.normalizeRadian(rotation-this._prevRotation);}else {if(this._prevClockwise>0?rotation>=this._prevRotation:rotation<=this._prevRotation){this._prevClockwise=this._prevClockwise>0?this._prevClockwise-1:this._prevClockwise+1;}rotation=this._prevRotation+rotation-this._prevRotation+dragonBones.Transform.PI_D*this._prevClockwise;}}this._prevClockwise=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.CLOCK_WISE,0);this._prevRotation=rotation;var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameFloatOffset=this._frameFloatArray.length;this._frameFloatArray.length+=2;this._frameFloatArray[frameFloatOffset++]=rotation;this._frameFloatArray[frameFloatOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SKEW,0.0)*dragonBones.Transform.DEG_RAD;return frameOffset;};ObjectDataParser.prototype._parseBoneScaleFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameFloatOffset=this._frameFloatArray.length;this._frameFloatArray.length+=2;this._frameFloatArray[frameFloatOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.X,1.0);this._frameFloatArray[frameFloatOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.Y,1.0);return frameOffset;};ObjectDataParser.prototype._parseSurfaceFrame=function(rawData,frameStart,frameCount){var frameFloatOffset=this._frameFloatArray.length;var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var rawVertices=rawData[dragonBones.DataParser.VERTICES];var offset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.OFFSET,0);var vertexCount=this._surface.vertices.length/2;var x=0.0;var y=0.0;this._frameFloatArray.length+=vertexCount*2;for(var i=0;i<vertexCount*2;i+=2){if(i<offset||i-offset>=rawVertices.length){x=0.0;}else {x=rawVertices[i-offset];}if(i+1<offset||i+1-offset>=rawVertices.length){y=0.0;}else {y=rawVertices[i+1-offset];}this._frameFloatArray[frameFloatOffset+i]=x;this._frameFloatArray[frameFloatOffset+i+1]=y;}if(frameStart===0){var frameIntOffset=this._frameIntArray.length;this._frameIntArray.length+=1+1+1+1+1;this._frameIntArray[frameIntOffset+0]=0;this._frameIntArray[frameIntOffset+1]=this._frameFloatArray.length-frameFloatOffset;this._frameIntArray[frameIntOffset+2]=this._frameFloatArray.length-frameFloatOffset;this._frameIntArray[frameIntOffset+3]=0;this._frameIntArray[frameIntOffset+4]=frameFloatOffset-this._animation.frameFloatOffset;this._timelineArray[this._timeline.offset+3]=frameIntOffset-this._animation.frameIntOffset;}return frameOffset;};ObjectDataParser.prototype._parseSlotDisplayFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseFrame(rawData,frameStart,frameCount);this._frameArray.length+=1;if(dragonBones.DataParser.VALUE in rawData){this._frameArray[frameOffset+1]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.VALUE,0);}else {this._frameArray[frameOffset+1]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.DISPLAY_INDEX,0);}this._parseActionDataInFrame(rawData,frameStart,this._slot.parent,this._slot);return frameOffset;};ObjectDataParser.prototype._parseSlotColorFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var colorOffset=-1;if(dragonBones.DataParser.VALUE in rawData||dragonBones.DataParser.COLOR in rawData){var rawColor=dragonBones.DataParser.VALUE in rawData?rawData[dragonBones.DataParser.VALUE]:rawData[dragonBones.DataParser.COLOR];for(var k in rawColor){this._parseColorTransform(rawColor,this._helpColorTransform);colorOffset=this._intArray.length;this._intArray.length+=8;this._intArray[colorOffset++]=Math.round(this._helpColorTransform.alphaMultiplier*100);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.redMultiplier*100);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.greenMultiplier*100);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.blueMultiplier*100);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.alphaOffset);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.redOffset);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.greenOffset);this._intArray[colorOffset++]=Math.round(this._helpColorTransform.blueOffset);colorOffset-=8;break;}}if(colorOffset<0){if(this._defaultColorOffset<0){this._defaultColorOffset=colorOffset=this._intArray.length;this._intArray.length+=8;this._intArray[colorOffset++]=100;this._intArray[colorOffset++]=100;this._intArray[colorOffset++]=100;this._intArray[colorOffset++]=100;this._intArray[colorOffset++]=0;this._intArray[colorOffset++]=0;this._intArray[colorOffset++]=0;this._intArray[colorOffset++]=0;}colorOffset=this._defaultColorOffset;}var frameIntOffset=this._frameIntArray.length;this._frameIntArray.length+=1;this._frameIntArray[frameIntOffset]=colorOffset;return frameOffset;};ObjectDataParser.prototype._parseSlotFFDFrame=function(rawData,frameStart,frameCount){var frameFloatOffset=this._frameFloatArray.length;var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var rawVertices=dragonBones.DataParser.VERTICES in rawData?rawData[dragonBones.DataParser.VERTICES]:null;var offset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.OFFSET,0);var vertexCount=this._intArray[this._mesh.vertices.offset+0];var meshName=this._mesh.parent.name+"_"+this._slot.name+"_"+this._mesh.name;var weight=this._mesh.vertices.weight;var x=0.0;var y=0.0;var iB=0;var iV=0;if(weight!==null){var rawSlotPose=this._weightSlotPose[meshName];this._helpMatrixA.copyFromArray(rawSlotPose,0);this._frameFloatArray.length+=weight.count*2;iB=weight.offset+2+weight.bones.length;}else {this._frameFloatArray.length+=vertexCount*2;}for(var i=0;i<vertexCount*2;i+=2){if(rawVertices===null){x=0.0;y=0.0;}else {if(i<offset||i-offset>=rawVertices.length){x=0.0;}else {x=rawVertices[i-offset];}if(i+1<offset||i+1-offset>=rawVertices.length){y=0.0;}else {y=rawVertices[i+1-offset];}}if(weight!==null){var rawBonePoses=this._weightBonePoses[meshName];var vertexBoneCount=this._intArray[iB++];this._helpMatrixA.transformPoint(x,y,this._helpPoint,true);x=this._helpPoint.x;y=this._helpPoint.y;for(var j=0;j<vertexBoneCount;++j){var boneIndex=this._intArray[iB++];this._helpMatrixB.copyFromArray(rawBonePoses,boneIndex*7+1);this._helpMatrixB.invert();this._helpMatrixB.transformPoint(x,y,this._helpPoint,true);this._frameFloatArray[frameFloatOffset+iV++]=this._helpPoint.x;this._frameFloatArray[frameFloatOffset+iV++]=this._helpPoint.y;}}else {this._frameFloatArray[frameFloatOffset+i]=x;this._frameFloatArray[frameFloatOffset+i+1]=y;}}if(frameStart===0){var frameIntOffset=this._frameIntArray.length;this._frameIntArray.length+=1+1+1+1+1;this._frameIntArray[frameIntOffset+0]=this._mesh.vertices.offset;this._frameIntArray[frameIntOffset+1]=this._frameFloatArray.length-frameFloatOffset;this._frameIntArray[frameIntOffset+2]=this._frameFloatArray.length-frameFloatOffset;this._frameIntArray[frameIntOffset+3]=0;this._frameIntArray[frameIntOffset+4]=frameFloatOffset-this._animation.frameFloatOffset;this._timelineArray[this._timeline.offset+3]=frameIntOffset-this._animation.frameIntOffset;}return frameOffset;};ObjectDataParser.prototype._parseIKConstraintFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameIntOffset=this._frameIntArray.length;this._frameIntArray.length+=2;this._frameIntArray[frameIntOffset++]=ObjectDataParser._getBoolean(rawData,dragonBones.DataParser.BEND_POSITIVE,true)?1:0;this._frameIntArray[frameIntOffset++]=Math.round(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.WEIGHT,1.0)*100.0);return frameOffset;};ObjectDataParser.prototype._parseAnimationFrame=function(rawData,frameStart,frameCount){var frameOffset=this._parseTweenFrame(rawData,frameStart,frameCount);var frameIntOffset=this._frameIntArray.length;this._frameIntArray.length+=2;this._frameIntArray[frameIntOffset++]=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.VALUE,0);this._frameIntArray[frameIntOffset++]=Math.round(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.WEIGHT,1.0)*100.0);return frameOffset;};ObjectDataParser.prototype._parseActionData=function(rawData,type,bone,slot){var actions=new Array();if(typeof rawData==="string"){var action=dragonBones.BaseObject.borrowObject(dragonBones.ActionData);action.type=type;action.name=rawData;action.bone=bone;action.slot=slot;actions.push(action);}else if(rawData instanceof Array){for(var _i=0,rawData_2=rawData;_i<rawData_2.length;_i++){var rawAction=rawData_2[_i];var action=dragonBones.BaseObject.borrowObject(dragonBones.ActionData);if(dragonBones.DataParser.GOTO_AND_PLAY in rawAction){action.type=0;action.name=ObjectDataParser._getString(rawAction,dragonBones.DataParser.GOTO_AND_PLAY,"");}else {if(dragonBones.DataParser.TYPE in rawAction&&typeof rawAction[dragonBones.DataParser.TYPE]==="string"){action.type=dragonBones.DataParser._getActionType(rawAction[dragonBones.DataParser.TYPE]);}else {action.type=ObjectDataParser._getNumber(rawAction,dragonBones.DataParser.TYPE,type);}action.name=ObjectDataParser._getString(rawAction,dragonBones.DataParser.NAME,"");}if(dragonBones.DataParser.BONE in rawAction){var boneName=ObjectDataParser._getString(rawAction,dragonBones.DataParser.BONE,"");action.bone=this._armature.getBone(boneName);}else {action.bone=bone;}if(dragonBones.DataParser.SLOT in rawAction){var slotName=ObjectDataParser._getString(rawAction,dragonBones.DataParser.SLOT,"");action.slot=this._armature.getSlot(slotName);}else {action.slot=slot;}var userData=null;if(dragonBones.DataParser.INTS in rawAction){if(userData===null){userData=dragonBones.BaseObject.borrowObject(dragonBones.UserData);}var rawInts=rawAction[dragonBones.DataParser.INTS];for(var _a=0,rawInts_1=rawInts;_a<rawInts_1.length;_a++){var rawValue=rawInts_1[_a];userData.addInt(rawValue);}}if(dragonBones.DataParser.FLOATS in rawAction){if(userData===null){userData=dragonBones.BaseObject.borrowObject(dragonBones.UserData);}var rawFloats=rawAction[dragonBones.DataParser.FLOATS];for(var _b=0,rawFloats_1=rawFloats;_b<rawFloats_1.length;_b++){var rawValue=rawFloats_1[_b];userData.addFloat(rawValue);}}if(dragonBones.DataParser.STRINGS in rawAction){if(userData===null){userData=dragonBones.BaseObject.borrowObject(dragonBones.UserData);}var rawStrings=rawAction[dragonBones.DataParser.STRINGS];for(var _c=0,rawStrings_1=rawStrings;_c<rawStrings_1.length;_c++){var rawValue=rawStrings_1[_c];userData.addString(rawValue);}}action.data=userData;actions.push(action);}}return actions;};ObjectDataParser.prototype._parseTransform=function(rawData,transform,scale){transform.x=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.X,0.0)*scale;transform.y=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.Y,0.0)*scale;if(dragonBones.DataParser.ROTATE in rawData||dragonBones.DataParser.SKEW in rawData){transform.rotation=dragonBones.Transform.normalizeRadian(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ROTATE,0.0)*dragonBones.Transform.DEG_RAD);transform.skew=dragonBones.Transform.normalizeRadian(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SKEW,0.0)*dragonBones.Transform.DEG_RAD);}else if(dragonBones.DataParser.SKEW_X in rawData||dragonBones.DataParser.SKEW_Y in rawData){transform.rotation=dragonBones.Transform.normalizeRadian(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SKEW_Y,0.0)*dragonBones.Transform.DEG_RAD);transform.skew=dragonBones.Transform.normalizeRadian(ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SKEW_X,0.0)*dragonBones.Transform.DEG_RAD)-transform.rotation;}transform.scaleX=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE_X,1.0);transform.scaleY=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE_Y,1.0);};ObjectDataParser.prototype._parseColorTransform=function(rawData,color){color.alphaMultiplier=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ALPHA_MULTIPLIER,100)*0.01;color.redMultiplier=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.RED_MULTIPLIER,100)*0.01;color.greenMultiplier=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.GREEN_MULTIPLIER,100)*0.01;color.blueMultiplier=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.BLUE_MULTIPLIER,100)*0.01;color.alphaOffset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.ALPHA_OFFSET,0);color.redOffset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.RED_OFFSET,0);color.greenOffset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.GREEN_OFFSET,0);color.blueOffset=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.BLUE_OFFSET,0);};ObjectDataParser.prototype._parseArray=function(rawData){this._intArray.length=0;this._floatArray.length=0;this._frameIntArray.length=0;this._frameFloatArray.length=0;this._frameArray.length=0;this._timelineArray.length=0;};ObjectDataParser.prototype._modifyArray=function(){if(this._intArray.length%Int16Array.BYTES_PER_ELEMENT!==0){this._intArray.push(0);}if(this._frameIntArray.length%Int16Array.BYTES_PER_ELEMENT!==0){this._frameIntArray.push(0);}if(this._frameArray.length%Int16Array.BYTES_PER_ELEMENT!==0){this._frameArray.push(0);}if(this._timelineArray.length%Uint16Array.BYTES_PER_ELEMENT!==0){this._timelineArray.push(0);}var l1=this._intArray.length*Int16Array.BYTES_PER_ELEMENT;var l2=this._floatArray.length*Float32Array.BYTES_PER_ELEMENT;var l3=this._frameIntArray.length*Int16Array.BYTES_PER_ELEMENT;var l4=this._frameFloatArray.length*Float32Array.BYTES_PER_ELEMENT;var l5=this._frameArray.length*Int16Array.BYTES_PER_ELEMENT;var l6=this._timelineArray.length*Uint16Array.BYTES_PER_ELEMENT;var lTotal=l1+l2+l3+l4+l5+l6;if(dragonBones.DragonBones.webAssembly){var shareBuffer=dragonBones.webAssemblyModule.HEAP16.buffer;var bufferPointer=dragonBones.webAssemblyModule._malloc(lTotal);var intArray=new Int16Array(shareBuffer,bufferPointer,this._intArray.length);var floatArray=new Float32Array(shareBuffer,bufferPointer+l1,this._floatArray.length);var frameIntArray=new Int16Array(shareBuffer,bufferPointer+l1+l2,this._frameIntArray.length);var frameFloatArray=new Float32Array(shareBuffer,bufferPointer+l1+l2+l3,this._frameFloatArray.length);var frameArray=new Int16Array(shareBuffer,bufferPointer+l1+l2+l3+l4,this._frameArray.length);var timelineArray=new Uint16Array(shareBuffer,bufferPointer+l1+l2+l3+l4+l5,this._timelineArray.length);for(var i=0,l=this._intArray.length;i<l;++i){intArray[i]=this._intArray[i];}for(var i=0,l=this._floatArray.length;i<l;++i){floatArray[i]=this._floatArray[i];}for(var i=0,l=this._frameIntArray.length;i<l;++i){frameIntArray[i]=this._frameIntArray[i];}for(var i=0,l=this._frameFloatArray.length;i<l;++i){frameFloatArray[i]=this._frameFloatArray[i];}for(var i=0,l=this._frameArray.length;i<l;++i){frameArray[i]=this._frameArray[i];}for(var i=0,l=this._timelineArray.length;i<l;++i){timelineArray[i]=this._timelineArray[i];}dragonBones.webAssemblyModule.setDataBinary(this._data,bufferPointer,l1,l2,l3,l4,l5,l6);}else {var binary=new ArrayBuffer(lTotal);var intArray=new Int16Array(binary,0,this._intArray.length);var floatArray=new Float32Array(binary,l1,this._floatArray.length);var frameIntArray=new Int16Array(binary,l1+l2,this._frameIntArray.length);var frameFloatArray=new Float32Array(binary,l1+l2+l3,this._frameFloatArray.length);var frameArray=new Int16Array(binary,l1+l2+l3+l4,this._frameArray.length);var timelineArray=new Uint16Array(binary,l1+l2+l3+l4+l5,this._timelineArray.length);for(var i=0,l=this._intArray.length;i<l;++i){intArray[i]=this._intArray[i];}for(var i=0,l=this._floatArray.length;i<l;++i){floatArray[i]=this._floatArray[i];}for(var i=0,l=this._frameIntArray.length;i<l;++i){frameIntArray[i]=this._frameIntArray[i];}for(var i=0,l=this._frameFloatArray.length;i<l;++i){frameFloatArray[i]=this._frameFloatArray[i];}for(var i=0,l=this._frameArray.length;i<l;++i){frameArray[i]=this._frameArray[i];}for(var i=0,l=this._timelineArray.length;i<l;++i){timelineArray[i]=this._timelineArray[i];}this._data.binary=binary;this._data.intArray=intArray;this._data.floatArray=floatArray;this._data.frameIntArray=frameIntArray;this._data.frameFloatArray=frameFloatArray;this._data.frameArray=frameArray;this._data.timelineArray=timelineArray;}this._defaultColorOffset=-1;};ObjectDataParser.prototype.parseDragonBonesData=function(rawData,scale){if(scale===void 0){scale=1;}console.assert(rawData!==null&&rawData!==undefined,"Data error.");var version=ObjectDataParser._getString(rawData,dragonBones.DataParser.VERSION,"");var compatibleVersion=ObjectDataParser._getString(rawData,dragonBones.DataParser.COMPATIBLE_VERSION,"");if(dragonBones.DataParser.DATA_VERSIONS.indexOf(version)>=0||dragonBones.DataParser.DATA_VERSIONS.indexOf(compatibleVersion)>=0){var data=dragonBones.BaseObject.borrowObject(dragonBones.DragonBonesData);data.version=version;data.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");data.frameRate=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.FRAME_RATE,24);if(data.frameRate===0){data.frameRate=24;}if(dragonBones.DataParser.ARMATURE in rawData){this._data=data;this._parseArray(rawData);var rawArmatures=rawData[dragonBones.DataParser.ARMATURE];for(var _i=0,rawArmatures_1=rawArmatures;_i<rawArmatures_1.length;_i++){var rawArmature=rawArmatures_1[_i];data.addArmature(this._parseArmature(rawArmature,scale));}if(!this._data.binary){this._modifyArray();}if(dragonBones.DataParser.STAGE in rawData){data.stage=data.getArmature(ObjectDataParser._getString(rawData,dragonBones.DataParser.STAGE,""));}else if(data.armatureNames.length>0){data.stage=data.getArmature(data.armatureNames[0]);}this._data=null;}if(dragonBones.DataParser.TEXTURE_ATLAS in rawData){this._rawTextureAtlases=rawData[dragonBones.DataParser.TEXTURE_ATLAS];}return data;}else {console.assert(false,"Nonsupport data version: "+version+"\n"+"Please convert DragonBones data to support version.\n"+"Read more: https://github.com/DragonBones/Tools/");}return null;};ObjectDataParser.prototype.parseTextureAtlasData=function(rawData,textureAtlasData,scale){if(scale===void 0){scale=1.0;}console.assert(rawData!==undefined);if(rawData===null){if(this._rawTextureAtlases===null||this._rawTextureAtlases.length===0){return false;}var rawTextureAtlas=this._rawTextureAtlases[this._rawTextureAtlasIndex++];this.parseTextureAtlasData(rawTextureAtlas,textureAtlasData,scale);if(this._rawTextureAtlasIndex>=this._rawTextureAtlases.length){this._rawTextureAtlasIndex=0;this._rawTextureAtlases=null;}return true;}textureAtlasData.width=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.WIDTH,0);textureAtlasData.height=ObjectDataParser._getNumber(rawData,dragonBones.DataParser.HEIGHT,0);textureAtlasData.scale=scale===1.0?1.0/ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE,1.0):scale;textureAtlasData.name=ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,"");textureAtlasData.imagePath=ObjectDataParser._getString(rawData,dragonBones.DataParser.IMAGE_PATH,"");if(dragonBones.DataParser.SUB_TEXTURE in rawData){var rawTextures=rawData[dragonBones.DataParser.SUB_TEXTURE];for(var i=0,l=rawTextures.length;i<l;++i){var rawTexture=rawTextures[i];var textureData=textureAtlasData.createTexture();textureData.rotated=ObjectDataParser._getBoolean(rawTexture,dragonBones.DataParser.ROTATED,false);textureData.name=ObjectDataParser._getString(rawTexture,dragonBones.DataParser.NAME,"");textureData.region.x=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.X,0.0);textureData.region.y=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.Y,0.0);textureData.region.width=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.WIDTH,0.0);textureData.region.height=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.HEIGHT,0.0);var frameWidth=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.FRAME_WIDTH,-1.0);var frameHeight=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.FRAME_HEIGHT,-1.0);if(frameWidth>0.0&&frameHeight>0.0){textureData.frame=dragonBones.TextureData.createRectangle();textureData.frame.x=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.FRAME_X,0.0);textureData.frame.y=ObjectDataParser._getNumber(rawTexture,dragonBones.DataParser.FRAME_Y,0.0);textureData.frame.width=frameWidth;textureData.frame.height=frameHeight;}textureAtlasData.addTexture(textureData);}}return true;};ObjectDataParser.getInstance=function(){if(ObjectDataParser._objectDataParserInstance===null){ObjectDataParser._objectDataParserInstance=new ObjectDataParser();}return ObjectDataParser._objectDataParserInstance;};ObjectDataParser._objectDataParserInstance=null;return ObjectDataParser;}(dragonBones.DataParser);dragonBones.ObjectDataParser=ObjectDataParser;var ActionFrame=function(){function ActionFrame(){this.frameStart=0;this.actions=[];}return ActionFrame;}();dragonBones.ActionFrame=ActionFrame;})(dragonBones||(dragonBones={}));(function(dragonBones){var BinaryDataParser=function(_super){__extends(BinaryDataParser,_super);function BinaryDataParser(){return _super!==null&&_super.apply(this,arguments)||this;}BinaryDataParser.prototype._inRange=function(a,min,max){return min<=a&&a<=max;};BinaryDataParser.prototype._decodeUTF8=function(data){var EOF_byte=-1;var EOF_code_point=-1;var FATAL_POINT=0xFFFD;var pos=0;var result="";var code_point;var utf8_code_point=0;var utf8_bytes_needed=0;var utf8_bytes_seen=0;var utf8_lower_boundary=0;while(data.length>pos){var _byte=data[pos++];if(_byte===EOF_byte){if(utf8_bytes_needed!==0){code_point=FATAL_POINT;}else {code_point=EOF_code_point;}}else {if(utf8_bytes_needed===0){if(this._inRange(_byte,0x00,0x7F)){code_point=_byte;}else {if(this._inRange(_byte,0xC2,0xDF)){utf8_bytes_needed=1;utf8_lower_boundary=0x80;utf8_code_point=_byte-0xC0;}else if(this._inRange(_byte,0xE0,0xEF)){utf8_bytes_needed=2;utf8_lower_boundary=0x800;utf8_code_point=_byte-0xE0;}else if(this._inRange(_byte,0xF0,0xF4)){utf8_bytes_needed=3;utf8_lower_boundary=0x10000;utf8_code_point=_byte-0xF0;}else;utf8_code_point=utf8_code_point*Math.pow(64,utf8_bytes_needed);code_point=null;}}else if(!this._inRange(_byte,0x80,0xBF)){utf8_code_point=0;utf8_bytes_needed=0;utf8_bytes_seen=0;utf8_lower_boundary=0;pos--;code_point=_byte;}else {utf8_bytes_seen+=1;utf8_code_point=utf8_code_point+(_byte-0x80)*Math.pow(64,utf8_bytes_needed-utf8_bytes_seen);if(utf8_bytes_seen!==utf8_bytes_needed){code_point=null;}else {var cp=utf8_code_point;var lower_boundary=utf8_lower_boundary;utf8_code_point=0;utf8_bytes_needed=0;utf8_bytes_seen=0;utf8_lower_boundary=0;if(this._inRange(cp,lower_boundary,0x10FFFF)&&!this._inRange(cp,0xD800,0xDFFF)){code_point=cp;}else {code_point=_byte;}}}}if(code_point!==null&&code_point!==EOF_code_point){if(code_point<=0xFFFF){if(code_point>0)result+=String.fromCharCode(code_point);}else {code_point-=0x10000;result+=String.fromCharCode(0xD800+(code_point>>10&0x3ff));result+=String.fromCharCode(0xDC00+(code_point&0x3ff));}}}return result;};BinaryDataParser.prototype._getUTF16Key=function(value){for(var i=0,l=value.length;i<l;++i){if(value.charCodeAt(i)>255){return encodeURI(value);}}return value;};BinaryDataParser.prototype._parseBinaryTimeline=function(type,offset,timelineData){if(timelineData===void 0){timelineData=null;}var timeline=timelineData!==null?timelineData:dragonBones.BaseObject.borrowObject(dragonBones.TimelineData);timeline.type=type;timeline.offset=offset;this._timeline=timeline;var keyFrameCount=this._timelineArrayBuffer[timeline.offset+2];if(keyFrameCount===1){timeline.frameIndicesOffset=-1;}else {var frameIndicesOffset=0;var totalFrameCount=this._animation.frameCount+1;var frameIndices=this._data.frameIndices;if(dragonBones.DragonBones.webAssembly){frameIndicesOffset=frameIndices.size();frameIndices.resize(frameIndicesOffset+totalFrameCount,0);}else {frameIndicesOffset=frameIndices.length;frameIndices.length+=totalFrameCount;}timeline.frameIndicesOffset=frameIndicesOffset;for(var i=0,iK=0,frameStart=0,frameCount=0;i<totalFrameCount;++i){if(frameStart+frameCount<=i&&iK<keyFrameCount){frameStart=this._frameArrayBuffer[this._animation.frameOffset+this._timelineArrayBuffer[timeline.offset+5+iK]];if(iK===keyFrameCount-1){frameCount=this._animation.frameCount-frameStart;}else {frameCount=this._frameArrayBuffer[this._animation.frameOffset+this._timelineArrayBuffer[timeline.offset+5+iK+1]]-frameStart;}iK++;}if(dragonBones.DragonBones.webAssembly){frameIndices.set(frameIndicesOffset+i,iK-1);}else {frameIndices[frameIndicesOffset+i]=iK-1;}}}this._timeline=null;return timeline;};BinaryDataParser.prototype._parseVertices=function(rawData,vertices){vertices.offset=rawData[dragonBones.DataParser.OFFSET];var weightOffset=this._intArrayBuffer[vertices.offset+3];if(weightOffset>=0){var weight=dragonBones.BaseObject.borrowObject(dragonBones.WeightData);var vertexCount=this._intArrayBuffer[vertices.offset+0];var boneCount=this._intArrayBuffer[weightOffset+0];weight.offset=weightOffset;for(var i=0;i<boneCount;++i){var boneIndex=this._intArrayBuffer[weightOffset+2+i];weight.addBone(this._rawBones[boneIndex]);}var boneIndicesOffset=weightOffset+2+boneCount;var weightCount=0;for(var i=0,l=vertexCount;i<l;++i){var vertexBoneCount=this._intArrayBuffer[boneIndicesOffset++];weightCount+=vertexBoneCount;boneIndicesOffset+=vertexBoneCount;}weight.count=weightCount;vertices.weight=weight;}};BinaryDataParser.prototype._parseMesh=function(rawData,mesh){this._parseVertices(rawData,mesh.vertices);};BinaryDataParser.prototype._parsePath=function(rawData,path){this._parseVertices(rawData,path.vertices);};BinaryDataParser.prototype._parseAnimation=function(rawData){var animation=dragonBones.BaseObject.borrowObject(dragonBones.AnimationData);animation.frameCount=Math.max(dragonBones.ObjectDataParser._getNumber(rawData,dragonBones.DataParser.DURATION,1),1);animation.playTimes=dragonBones.ObjectDataParser._getNumber(rawData,dragonBones.DataParser.PLAY_TIMES,1);animation.duration=animation.frameCount/this._armature.frameRate;animation.fadeInTime=dragonBones.ObjectDataParser._getNumber(rawData,dragonBones.DataParser.FADE_IN_TIME,0.0);animation.scale=dragonBones.ObjectDataParser._getNumber(rawData,dragonBones.DataParser.SCALE,1.0);animation.name=dragonBones.ObjectDataParser._getString(rawData,dragonBones.DataParser.NAME,dragonBones.DataParser.DEFAULT_NAME);if(animation.name.length===0){animation.name=dragonBones.DataParser.DEFAULT_NAME;}var offsets=rawData[dragonBones.DataParser.OFFSET];animation.frameIntOffset=offsets[0];animation.frameFloatOffset=offsets[1];animation.frameOffset=offsets[2];this._animation=animation;if(dragonBones.DataParser.ACTION in rawData){animation.actionTimeline=this._parseBinaryTimeline(0,rawData[dragonBones.DataParser.ACTION]);}if(dragonBones.DataParser.Z_ORDER in rawData){animation.zOrderTimeline=this._parseBinaryTimeline(1,rawData[dragonBones.DataParser.Z_ORDER]);}if(dragonBones.DataParser.BONE in rawData){var rawTimeliness=rawData[dragonBones.DataParser.BONE];for(var k in rawTimeliness){var rawTimelines=rawTimeliness[k];if(dragonBones.DragonBones.webAssembly){k=this._getUTF16Key(k);}var bone=this._armature.getBone(k);if(bone===null){continue;}for(var i=0,l=rawTimelines.length;i<l;i+=2){var timelineType=rawTimelines[i];var timelineOffset=rawTimelines[i+1];var timeline=this._parseBinaryTimeline(timelineType,timelineOffset);this._animation.addBoneTimeline(bone,timeline);}}}if(dragonBones.DataParser.SURFACE in rawData){var rawTimeliness=rawData[dragonBones.DataParser.SURFACE];for(var k in rawTimeliness){var rawTimelines=rawTimeliness[k];if(dragonBones.DragonBones.webAssembly){k=this._getUTF16Key(k);}var surface=this._armature.getBone(k);if(surface===null){continue;}for(var i=0,l=rawTimelines.length;i<l;i+=2){var timelineType=rawTimelines[i];var timelineOffset=rawTimelines[i+1];var timeline=this._parseBinaryTimeline(timelineType,timelineOffset);this._animation.addSurfaceTimeline(surface,timeline);}}}if(dragonBones.DataParser.SLOT in rawData){var rawTimeliness=rawData[dragonBones.DataParser.SLOT];for(var k in rawTimeliness){var rawTimelines=rawTimeliness[k];if(dragonBones.DragonBones.webAssembly){k=this._getUTF16Key(k);}var slot=this._armature.getSlot(k);if(slot===null){continue;}for(var i=0,l=rawTimelines.length;i<l;i+=2){var timelineType=rawTimelines[i];var timelineOffset=rawTimelines[i+1];var timeline=this._parseBinaryTimeline(timelineType,timelineOffset);this._animation.addSlotTimeline(slot,timeline);}}}if(dragonBones.DataParser.CONSTRAINT in rawData){var rawTimeliness=rawData[dragonBones.DataParser.CONSTRAINT];for(var k in rawTimeliness){var rawTimelines=rawTimeliness[k];if(dragonBones.DragonBones.webAssembly){k=this._getUTF16Key(k);}var constraint=this._armature.getConstraint(k);if(constraint===null){continue;}for(var i=0,l=rawTimelines.length;i<l;i+=2){var timelineType=rawTimelines[i];var timelineOffset=rawTimelines[i+1];var timeline=this._parseBinaryTimeline(timelineType,timelineOffset);this._animation.addConstraintTimeline(constraint,timeline);}}}if(dragonBones.DataParser.ANIMATION in rawData){var rawTimeliness=rawData[dragonBones.DataParser.ANIMATION];for(var k in rawTimeliness){var rawTimelines=rawTimeliness[k];if(dragonBones.DragonBones.webAssembly){k=this._getUTF16Key(k);}for(var i=0,l=rawTimelines.length;i<l;i+=2){var timelineType=rawTimelines[i];var timelineOffset=rawTimelines[i+1];var timeline=this._parseBinaryTimeline(timelineType,timelineOffset);this._animation.addAnimationTimeline(k,timeline);}}}this._animation=null;return animation;};BinaryDataParser.prototype._parseArray=function(rawData){var offsets=rawData[dragonBones.DataParser.OFFSET];var l1=offsets[1];var l2=offsets[3];var l3=offsets[5];var l4=offsets[7];var l5=offsets[9];var l6=offsets[11];var intArray=new Int16Array(this._binary,this._binaryOffset+offsets[0],l1/Int16Array.BYTES_PER_ELEMENT);var floatArray=new Float32Array(this._binary,this._binaryOffset+offsets[2],l2/Float32Array.BYTES_PER_ELEMENT);var frameIntArray=new Int16Array(this._binary,this._binaryOffset+offsets[4],l3/Int16Array.BYTES_PER_ELEMENT);var frameFloatArray=new Float32Array(this._binary,this._binaryOffset+offsets[6],l4/Float32Array.BYTES_PER_ELEMENT);var frameArray=new Int16Array(this._binary,this._binaryOffset+offsets[8],l5/Int16Array.BYTES_PER_ELEMENT);var timelineArray=new Uint16Array(this._binary,this._binaryOffset+offsets[10],l6/Uint16Array.BYTES_PER_ELEMENT);if(dragonBones.DragonBones.webAssembly){var lTotal=l1+l2+l3+l4+l5+l6;var bufferPointer=dragonBones.webAssemblyModule._malloc(lTotal);var rawArray=new Uint8Array(this._binary,this._binaryOffset,lTotal/Uint8Array.BYTES_PER_ELEMENT);var copyArray=new Uint8Array(dragonBones.webAssemblyModule.HEAP16.buffer,bufferPointer,rawArray.length);for(var i=0,l=rawArray.length;i<l;++i){copyArray[i]=rawArray[i];}dragonBones.webAssemblyModule.setDataBinary(this._data,bufferPointer,l1,l2,l3,l4,l5,l6);this._intArrayBuffer=intArray;this._floatArrayBuffer=floatArray;this._frameIntArrayBuffer=frameIntArray;this._frameFloatArrayBuffer=frameFloatArray;this._frameArrayBuffer=frameArray;this._timelineArrayBuffer=timelineArray;}else {this._data.binary=this._binary;this._data.intArray=this._intArrayBuffer=intArray;this._data.floatArray=this._floatArrayBuffer=floatArray;this._data.frameIntArray=this._frameIntArrayBuffer=frameIntArray;this._data.frameFloatArray=this._frameFloatArrayBuffer=frameFloatArray;this._data.frameArray=this._frameArrayBuffer=frameArray;this._data.timelineArray=this._timelineArrayBuffer=timelineArray;}};BinaryDataParser.prototype.parseDragonBonesData=function(rawData,scale){if(scale===void 0){scale=1;}console.assert(rawData!==null&&rawData!==undefined&&rawData instanceof ArrayBuffer,"Data error.");var tag=new Uint8Array(rawData,0,8);if(tag[0]!=="D".charCodeAt(0)||tag[1]!=="B".charCodeAt(0)||tag[2]!=="D".charCodeAt(0)||tag[3]!=="T".charCodeAt(0)){console.assert(false,"Nonsupport data.");return null;}var headerLength=new Uint32Array(rawData,8,1)[0];var headerBytes=new Uint8Array(rawData,8+4,headerLength);var headerString=this._decodeUTF8(headerBytes);var header=JSON.parse(headerString);this._binaryOffset=8+4+headerLength;this._binary=rawData;return _super.prototype.parseDragonBonesData.call(this,header,scale);};BinaryDataParser.getInstance=function(){if(BinaryDataParser._binaryDataParserInstance===null){BinaryDataParser._binaryDataParserInstance=new BinaryDataParser();}return BinaryDataParser._binaryDataParserInstance;};BinaryDataParser._binaryDataParserInstance=null;return BinaryDataParser;}(dragonBones.ObjectDataParser);dragonBones.BinaryDataParser=BinaryDataParser;})(dragonBones||(dragonBones={}));(function(dragonBones){var BaseFactory=function(){function BaseFactory(dataParser){if(dataParser===void 0){dataParser=null;}this.autoSearch=false;this._dragonBonesDataMap={};this._textureAtlasDataMap={};this._dragonBones=null;this._dataParser=null;if(BaseFactory._objectParser===null){BaseFactory._objectParser=new dragonBones.ObjectDataParser();}if(BaseFactory._binaryParser===null){BaseFactory._binaryParser=new dragonBones.BinaryDataParser();}this._dataParser=dataParser!==null?dataParser:BaseFactory._objectParser;}BaseFactory.prototype._isSupportMesh=function(){return true;};BaseFactory.prototype._getTextureData=function(textureAtlasName,textureName){if(textureAtlasName in this._textureAtlasDataMap){for(var _i=0,_a=this._textureAtlasDataMap[textureAtlasName];_i<_a.length;_i++){var textureAtlasData=_a[_i];var textureData=textureAtlasData.getTexture(textureName);if(textureData!==null){return textureData;}}}if(this.autoSearch){for(var k in this._textureAtlasDataMap){for(var _b=0,_c=this._textureAtlasDataMap[k];_b<_c.length;_b++){var textureAtlasData=_c[_b];if(textureAtlasData.autoSearch){var textureData=textureAtlasData.getTexture(textureName);if(textureData!==null){return textureData;}}}}}return null;};BaseFactory.prototype._fillBuildArmaturePackage=function(dataPackage,dragonBonesName,armatureName,skinName,textureAtlasName){var dragonBonesData=null;var armatureData=null;if(dragonBonesName.length>0){if(dragonBonesName in this._dragonBonesDataMap){dragonBonesData=this._dragonBonesDataMap[dragonBonesName];armatureData=dragonBonesData.getArmature(armatureName);}}if(armatureData===null&&(dragonBonesName.length===0||this.autoSearch)){for(var k in this._dragonBonesDataMap){dragonBonesData=this._dragonBonesDataMap[k];if(dragonBonesName.length===0||dragonBonesData.autoSearch){armatureData=dragonBonesData.getArmature(armatureName);if(armatureData!==null){dragonBonesName=k;break;}}}}if(armatureData!==null){dataPackage.dataName=dragonBonesName;dataPackage.textureAtlasName=textureAtlasName;dataPackage.data=dragonBonesData;dataPackage.armature=armatureData;dataPackage.skin=null;if(skinName.length>0){dataPackage.skin=armatureData.getSkin(skinName);if(dataPackage.skin===null&&this.autoSearch){for(var k in this._dragonBonesDataMap){var skinDragonBonesData=this._dragonBonesDataMap[k];var skinArmatureData=skinDragonBonesData.getArmature(skinName);if(skinArmatureData!==null){dataPackage.skin=skinArmatureData.defaultSkin;break;}}}}if(dataPackage.skin===null){dataPackage.skin=armatureData.defaultSkin;}return true;}return false;};BaseFactory.prototype._buildBones=function(dataPackage,armature){for(var _i=0,_a=dataPackage.armature.sortedBones;_i<_a.length;_i++){var boneData=_a[_i];var bone=dragonBones.BaseObject.borrowObject(boneData.type===0?dragonBones.Bone:dragonBones.Surface);bone.init(boneData,armature);}};BaseFactory.prototype._buildSlots=function(dataPackage,armature){var currentSkin=dataPackage.skin;var defaultSkin=dataPackage.armature.defaultSkin;if(currentSkin===null||defaultSkin===null){return;}var skinSlots={};for(var k in defaultSkin.displays){var displays=defaultSkin.getDisplays(k);skinSlots[k]=displays;}if(currentSkin!==defaultSkin){for(var k in currentSkin.displays){var displays=currentSkin.getDisplays(k);skinSlots[k]=displays;}}for(var _i=0,_a=dataPackage.armature.sortedSlots;_i<_a.length;_i++){var slotData=_a[_i];var displayDatas=slotData.name in skinSlots?skinSlots[slotData.name]:null;var slot=this._buildSlot(dataPackage,slotData,armature);slot.rawDisplayDatas=displayDatas;if(displayDatas!==null){var displayList=new Array();for(var i=0,l=dragonBones.DragonBones.webAssembly?displayDatas.size():displayDatas.length;i<l;++i){var displayData=dragonBones.DragonBones.webAssembly?displayDatas.get(i):displayDatas[i];if(displayData!==null){displayList.push(this._getSlotDisplay(dataPackage,displayData,null,slot));}else {displayList.push(null);}}slot._setDisplayList(displayList);}slot._setDisplayIndex(slotData.displayIndex,true);}};BaseFactory.prototype._buildConstraints=function(dataPackage,armature){var constraints=dataPackage.armature.constraints;for(var k in constraints){var constraintData=constraints[k];switch(constraintData.type){case 0:var ikConstraint=dragonBones.BaseObject.borrowObject(dragonBones.IKConstraint);ikConstraint.init(constraintData,armature);armature._addConstraint(ikConstraint);break;case 1:var pathConstraint=dragonBones.BaseObject.borrowObject(dragonBones.PathConstraint);pathConstraint.init(constraintData,armature);armature._addConstraint(pathConstraint);break;default:var constraint=dragonBones.BaseObject.borrowObject(dragonBones.IKConstraint);constraint.init(constraintData,armature);armature._addConstraint(constraint);break;}}};BaseFactory.prototype._buildChildArmature=function(dataPackage,slot,displayData){return this.buildArmature(displayData.path,dataPackage!==null?dataPackage.dataName:"","",dataPackage!==null?dataPackage.textureAtlasName:"");};BaseFactory.prototype._getSlotDisplay=function(dataPackage,displayData,rawDisplayData,slot){var dataName=dataPackage!==null?dataPackage.dataName:displayData.parent.parent.parent.name;var display=null;switch(displayData.type){case 0:{var imageDisplayData=displayData;if(dataPackage!==null&&dataPackage.textureAtlasName.length>0){imageDisplayData.texture=this._getTextureData(dataPackage.textureAtlasName,displayData.path);}if(imageDisplayData.texture===null){imageDisplayData.texture=this._getTextureData(dataName,displayData.path);}if(rawDisplayData!==null&&rawDisplayData.type===2&&this._isSupportMesh()){display=slot.meshDisplay;}else {display=slot.rawDisplay;}break;}case 2:{var meshDisplayData=displayData;if(dataPackage!==null&&dataPackage.textureAtlasName.length>0){meshDisplayData.texture=this._getTextureData(dataPackage.textureAtlasName,meshDisplayData.path);}if(meshDisplayData.texture===null){meshDisplayData.texture=this._getTextureData(dataName,meshDisplayData.path);}if(this._isSupportMesh()){display=slot.meshDisplay;}else {display=slot.rawDisplay;}break;}case 1:{var armatureDisplayData=displayData;var childArmature=this._buildChildArmature(dataPackage,slot,displayData);if(childArmature!==null){childArmature.inheritAnimation=armatureDisplayData.inheritAnimation;if(!childArmature.inheritAnimation){var actions=armatureDisplayData.actions.length>0?armatureDisplayData.actions:childArmature.armatureData.defaultActions;if(actions.length>0){for(var _i=0,actions_6=actions;_i<actions_6.length;_i++){var action=actions_6[_i];var eventObject=dragonBones.BaseObject.borrowObject(dragonBones.EventObject);dragonBones.EventObject.actionDataToInstance(action,eventObject,slot.armature);eventObject.slot=slot;slot.armature._bufferAction(eventObject,false);}}else {childArmature.animation.play();}}armatureDisplayData.armature=childArmature.armatureData;}display=childArmature;break;}}return display;};BaseFactory.prototype.parseDragonBonesData=function(rawData,name,scale){if(name===void 0){name=null;}if(scale===void 0){scale=1.0;}var dataParser=rawData instanceof ArrayBuffer?BaseFactory._binaryParser:this._dataParser;var dragonBonesData=dataParser.parseDragonBonesData(rawData,scale);while(true){var textureAtlasData=this._buildTextureAtlasData(null,null);if(dataParser.parseTextureAtlasData(null,textureAtlasData,scale)){this.addTextureAtlasData(textureAtlasData,name);}else {textureAtlasData.returnToPool();break;}}if(dragonBonesData!==null){this.addDragonBonesData(dragonBonesData,name);}return dragonBonesData;};BaseFactory.prototype.parseTextureAtlasData=function(rawData,textureAtlas,name,scale){if(name===void 0){name=null;}if(scale===void 0){scale=1.0;}var textureAtlasData=this._buildTextureAtlasData(null,null);this._dataParser.parseTextureAtlasData(rawData,textureAtlasData,scale);this._buildTextureAtlasData(textureAtlasData,textureAtlas||null);this.addTextureAtlasData(textureAtlasData,name);return textureAtlasData;};BaseFactory.prototype.updateTextureAtlasData=function(name,textureAtlases){var textureAtlasDatas=this.getTextureAtlasData(name);if(textureAtlasDatas!==null){for(var i=0,l=textureAtlasDatas.length;i<l;++i){if(i<textureAtlases.length){this._buildTextureAtlasData(textureAtlasDatas[i],textureAtlases[i]);}}}};BaseFactory.prototype.getDragonBonesData=function(name){return name in this._dragonBonesDataMap?this._dragonBonesDataMap[name]:null;};BaseFactory.prototype.addDragonBonesData=function(data,name){if(name===void 0){name=null;}name=name!==null?name:data.name;if(name in this._dragonBonesDataMap){if(this._dragonBonesDataMap[name]===data){return;}console.warn("Can not add same name data: "+name);return;}this._dragonBonesDataMap[name]=data;};BaseFactory.prototype.removeDragonBonesData=function(name,disposeData){if(disposeData===void 0){disposeData=true;}if(name in this._dragonBonesDataMap){if(disposeData){this._dragonBones.bufferObject(this._dragonBonesDataMap[name]);}delete this._dragonBonesDataMap[name];}};BaseFactory.prototype.getTextureAtlasData=function(name){return name in this._textureAtlasDataMap?this._textureAtlasDataMap[name]:null;};BaseFactory.prototype.addTextureAtlasData=function(data,name){if(name===void 0){name=null;}name=name!==null?name:data.name;var textureAtlasList=name in this._textureAtlasDataMap?this._textureAtlasDataMap[name]:this._textureAtlasDataMap[name]=[];if(textureAtlasList.indexOf(data)<0){textureAtlasList.push(data);}};BaseFactory.prototype.removeTextureAtlasData=function(name,disposeData){if(disposeData===void 0){disposeData=true;}if(name in this._textureAtlasDataMap){var textureAtlasDataList=this._textureAtlasDataMap[name];if(disposeData){for(var _i=0,textureAtlasDataList_1=textureAtlasDataList;_i<textureAtlasDataList_1.length;_i++){var textureAtlasData=textureAtlasDataList_1[_i];this._dragonBones.bufferObject(textureAtlasData);}}delete this._textureAtlasDataMap[name];}};BaseFactory.prototype.getArmatureData=function(name,dragonBonesName){if(dragonBonesName===void 0){dragonBonesName="";}var dataPackage=new BuildArmaturePackage();if(!this._fillBuildArmaturePackage(dataPackage,dragonBonesName,name,"","")){return null;}return dataPackage.armature;};BaseFactory.prototype.clear=function(disposeData){if(disposeData===void 0){disposeData=true;}for(var k in this._dragonBonesDataMap){if(disposeData){this._dragonBones.bufferObject(this._dragonBonesDataMap[k]);}delete this._dragonBonesDataMap[k];}for(var k in this._textureAtlasDataMap){if(disposeData){var textureAtlasDataList=this._textureAtlasDataMap[k];for(var _i=0,textureAtlasDataList_2=textureAtlasDataList;_i<textureAtlasDataList_2.length;_i++){var textureAtlasData=textureAtlasDataList_2[_i];this._dragonBones.bufferObject(textureAtlasData);}}delete this._textureAtlasDataMap[k];}};BaseFactory.prototype.buildArmature=function(armatureName,dragonBonesName,skinName,textureAtlasName){if(dragonBonesName===void 0){dragonBonesName="";}if(skinName===void 0){skinName="";}if(textureAtlasName===void 0){textureAtlasName="";}var dataPackage=new BuildArmaturePackage();if(!this._fillBuildArmaturePackage(dataPackage,dragonBonesName||"",armatureName,skinName||"",textureAtlasName||"")){console.warn("No armature data: "+armatureName+", "+(dragonBonesName!==null?dragonBonesName:""));return null;}var armature=this._buildArmature(dataPackage);this._buildBones(dataPackage,armature);this._buildSlots(dataPackage,armature);this._buildConstraints(dataPackage,armature);armature.invalidUpdate(null,true);armature.advanceTime(0.0);return armature;};BaseFactory.prototype.replaceDisplay=function(slot,displayData,displayIndex){if(displayIndex===void 0){displayIndex=-1;}if(displayIndex<0){displayIndex=slot.displayIndex;}if(displayIndex<0){displayIndex=0;}slot.replaceDisplayData(displayData,displayIndex);var displayList=slot.displayList;if(displayList.length<=displayIndex){displayList.length=displayIndex+1;for(var i=0,l=displayList.length;i<l;++i){if(!displayList[i]){displayList[i]=null;}}}if(displayData!==null){var rawDisplayDatas=slot.rawDisplayDatas;var rawDisplayData=null;if(rawDisplayDatas){if(dragonBones.DragonBones.webAssembly){if(displayIndex<rawDisplayDatas.size()){rawDisplayData=rawDisplayDatas.get(displayIndex);}}else {if(displayIndex<rawDisplayDatas.length){rawDisplayData=rawDisplayDatas[displayIndex];}}}displayList[displayIndex]=this._getSlotDisplay(null,displayData,rawDisplayData,slot);}else {displayList[displayIndex]=null;}slot.displayList=displayList;};BaseFactory.prototype.replaceSlotDisplay=function(dragonBonesName,armatureName,slotName,displayName,slot,displayIndex){if(displayIndex===void 0){displayIndex=-1;}var armatureData=this.getArmatureData(armatureName,dragonBonesName||"");if(!armatureData||!armatureData.defaultSkin){return false;}var displayData=armatureData.defaultSkin.getDisplay(slotName,displayName);if(!displayData){return false;}this.replaceDisplay(slot,displayData,displayIndex);return true;};BaseFactory.prototype.replaceSlotDisplayList=function(dragonBonesName,armatureName,slotName,slot){var armatureData=this.getArmatureData(armatureName,dragonBonesName||"");if(!armatureData||!armatureData.defaultSkin){return false;}var displays=armatureData.defaultSkin.getDisplays(slotName);if(!displays){return false;}var displayIndex=0;for(var i=0,l=dragonBones.DragonBones.webAssembly?displays.size():displays.length;i<l;++i){var displayData=dragonBones.DragonBones.webAssembly?displays.get(i):displays[i];this.replaceDisplay(slot,displayData,displayIndex++);}return true;};BaseFactory.prototype.replaceSkin=function(armature,skin,isOverride,exclude){if(isOverride===void 0){isOverride=false;}if(exclude===void 0){exclude=null;}var success=false;var defaultSkin=skin.parent.defaultSkin;for(var _i=0,_a=armature.getSlots();_i<_a.length;_i++){var slot=_a[_i];if(exclude!==null&&exclude.indexOf(slot.name)>=0){continue;}var displays=skin.getDisplays(slot.name);if(!displays){if(defaultSkin!==null&&skin!==defaultSkin){displays=defaultSkin.getDisplays(slot.name);}if(!displays){if(isOverride){slot.rawDisplayDatas=null;slot.displayList=[];}continue;}}var displayCount=dragonBones.DragonBones.webAssembly?displays.size():displays.length;var displayList=slot.displayList;displayList.length=displayCount;for(var i=0,l=displayCount;i<l;++i){var displayData=dragonBones.DragonBones.webAssembly?displays.get(i):displays[i];if(displayData!==null){displayList[i]=this._getSlotDisplay(null,displayData,null,slot);}else {displayList[i]=null;}}success=true;slot.rawDisplayDatas=displays;slot.displayList=displayList;}return success;};BaseFactory.prototype.replaceAnimation=function(armature,armatureData,isOverride){if(isOverride===void 0){isOverride=true;}var skinData=armatureData.defaultSkin;if(skinData===null){return false;}if(isOverride){armature.animation.animations=armatureData.animations;}else {var rawAnimations=armature.animation.animations;var animations={};for(var k in rawAnimations){animations[k]=rawAnimations[k];}for(var k in armatureData.animations){animations[k]=armatureData.animations[k];}armature.animation.animations=animations;}for(var _i=0,_a=armature.getSlots();_i<_a.length;_i++){var slot=_a[_i];var index=0;for(var _b=0,_c=slot.displayList;_b<_c.length;_b++){var display=_c[_b];if(display instanceof dragonBones.Armature){var displayDatas=skinData.getDisplays(slot.name);if(displayDatas!==null&&index<(dragonBones.DragonBones.webAssembly?displayDatas.size():displayDatas.length)){var displayData=dragonBones.DragonBones.webAssembly?displayDatas.get(index):displayDatas[index];if(displayData!==null&&displayData.type===1){var childArmatureData=this.getArmatureData(displayData.path,displayData.parent.parent.parent.name);if(childArmatureData){this.replaceAnimation(display,childArmatureData,isOverride);}}}}index++;}}return true;};BaseFactory.prototype.getAllDragonBonesData=function(){return this._dragonBonesDataMap;};BaseFactory.prototype.getAllTextureAtlasData=function(){return this._textureAtlasDataMap;};Object.defineProperty(BaseFactory.prototype,"clock",{get:function get(){return this._dragonBones.clock;},enumerable:true,configurable:true});Object.defineProperty(BaseFactory.prototype,"dragonBones",{get:function get(){return this._dragonBones;},enumerable:true,configurable:true});BaseFactory.prototype.changeSkin=function(armature,skin,exclude){if(exclude===void 0){exclude=null;}return this.replaceSkin(armature,skin,false,exclude);};BaseFactory.prototype.copyAnimationsToArmature=function(toArmature,fromArmatreName,fromSkinName,fromDragonBonesDataName,replaceOriginalAnimation){if(fromDragonBonesDataName===void 0){fromDragonBonesDataName="";}if(replaceOriginalAnimation===void 0){replaceOriginalAnimation=true;}var armatureData=this.getArmatureData(fromArmatreName,fromDragonBonesDataName);if(!armatureData){return false;}return this.replaceAnimation(toArmature,armatureData,replaceOriginalAnimation);};BaseFactory._objectParser=null;BaseFactory._binaryParser=null;return BaseFactory;}();dragonBones.BaseFactory=BaseFactory;var BuildArmaturePackage=function(){function BuildArmaturePackage(){this.dataName="";this.textureAtlasName="";this.skin=null;}return BuildArmaturePackage;}();dragonBones.BuildArmaturePackage=BuildArmaturePackage;})(dragonBones||(dragonBones={}));(function(dragonBones){dragonBones.BinaryOffset={WeigthBoneCount:0,WeigthFloatOffset:1,WeigthBoneIndices:2,MeshVertexCount:0,MeshTriangleCount:1,MeshFloatOffset:2,MeshWeightOffset:3,MeshVertexIndices:4,TimelineScale:0,TimelineOffset:1,TimelineKeyFrameCount:2,TimelineFrameValueCount:3,TimelineFrameValueOffset:4,TimelineFrameOffset:5,FramePosition:0,FrameTweenType:1,FrameTweenEasingOrCurveSampleCount:2,FrameCurveSamples:3,DeformMeshOffset:0,DeformCount:1,DeformValueCount:2,DeformValueOffset:3,DeformFloatOffset:4};dragonBones.ArmatureType={Armature:0,MovieClip:1,Stage:2};dragonBones.BoneType={Bone:0,Surface:1};dragonBones.DisplayType={Image:0,Armature:1,Mesh:2,BoundingBox:3};dragonBones.BoundingBoxType={Rectangle:0,Ellipse:1,Polygon:2};dragonBones.ActionType={Play:0,Stop:1,GotoAndPlay:2,GotoAndStop:3,FadeIn:4,FadeOut:5,Frame:10,Sound:11};dragonBones.BlendMode={Normal:0,Add:1,Alpha:2,Darken:3,Difference:4,Erase:5,HardLight:6,Invert:7,Layer:8,Lighten:9,Multiply:10,Overlay:11,Screen:12,Subtract:13};dragonBones.TweenType={None:0,Line:1,Curve:2,QuadIn:3,QuadOut:4,QuadInOut:5};dragonBones.TimelineType={Action:0,ZOrder:1,BoneAll:10,BoneTranslate:11,BoneRotate:12,BoneScale:13,Surface:50,SlotDisplay:20,SlotColor:21,SlotFFD:22,IKConstraint:30,AnimationTime:40,AnimationWeight:41};})(dragonBones||(dragonBones={}));var DragonBones=dragonBones.DragonBones;var BaseObject=dragonBones.BaseObject;var Matrix=dragonBones.Matrix;var Transform=dragonBones.Transform;var ColorTransform=dragonBones.ColorTransform;var Point$1=dragonBones.Point;var Rectangle=dragonBones.Rectangle;var UserData=dragonBones.UserData;var ActionData=dragonBones.ActionData;var DragonBonesData=dragonBones.DragonBonesData;var ArmatureData=dragonBones.ArmatureData;var BoneData=dragonBones.BoneData;var SurfaceData=dragonBones.SurfaceData;var SlotData=dragonBones.SlotData;var ConstraintData=dragonBones.ConstraintData;var IKConstraintData=dragonBones.IKConstraintData;var PathConstraintData=dragonBones.PathConstraintData;var CanvasData=dragonBones.CanvasData;var SkinData=dragonBones.SkinData;var VerticesData=dragonBones.VerticesData;var DisplayData=dragonBones.DisplayData;var ImageDisplayData=dragonBones.ImageDisplayData;var ArmatureDisplayData=dragonBones.ArmatureDisplayData;var MeshDisplayData=dragonBones.MeshDisplayData;var BoundingBoxDisplayData=dragonBones.BoundingBoxDisplayData;var PathDisplayData=dragonBones.PathDisplayData;var WeightData=dragonBones.WeightData;var BoundingBoxData=dragonBones.BoundingBoxData;var RectangleBoundingBoxData=dragonBones.RectangleBoundingBoxData;var EllipseBoundingBoxData=dragonBones.EllipseBoundingBoxData;var PolygonBoundingBoxData=dragonBones.PolygonBoundingBoxData;var AnimationData=dragonBones.AnimationData;var TimelineData=dragonBones.TimelineData;var AnimationConfig=dragonBones.AnimationConfig;var TextureAtlasData=dragonBones.TextureAtlasData;var TextureData=dragonBones.TextureData;var DeformVertices=dragonBones.DeformVertices;var Armature=dragonBones.Armature;var TransformObject=dragonBones.TransformObject;var Bone=dragonBones.Bone;var Surface=dragonBones.Surface;var Slot=dragonBones.Slot;var Constraint$2=dragonBones.Constraint;var IKConstraint=dragonBones.IKConstraint;var PathConstraint=dragonBones.PathConstraint;var WorldClock=dragonBones.WorldClock;var Animation$1=dragonBones.Animation;var AnimationState=dragonBones.AnimationState;var BonePose=dragonBones.BonePose;var BlendState=dragonBones.BlendState;var TimelineState=dragonBones.TimelineState;var TweenTimelineState=dragonBones.TweenTimelineState;var BoneTimelineState=dragonBones.BoneTimelineState;var SlotTimelineState=dragonBones.SlotTimelineState;var ConstraintTimelineState=dragonBones.ConstraintTimelineState;var ActionTimelineState=dragonBones.ActionTimelineState;var ZOrderTimelineState=dragonBones.ZOrderTimelineState;var BoneAllTimelineState=dragonBones.BoneAllTimelineState;var BoneTranslateTimelineState=dragonBones.BoneTranslateTimelineState;var BoneRotateTimelineState=dragonBones.BoneRotateTimelineState;var BoneScaleTimelineState=dragonBones.BoneScaleTimelineState;var SurfaceTimelineState=dragonBones.SurfaceTimelineState;var SlotDislayTimelineState=dragonBones.SlotDislayTimelineState;var SlotColorTimelineState=dragonBones.SlotColorTimelineState;var DeformTimelineState=dragonBones.DeformTimelineState;var IKConstraintTimelineState=dragonBones.IKConstraintTimelineState;var AnimationTimelineState=dragonBones.AnimationTimelineState;var EventObject=dragonBones.EventObject;var DataParser=dragonBones.DataParser;var ObjectDataParser=dragonBones.ObjectDataParser;var ActionFrame=dragonBones.ActionFrame;var BinaryDataParser=dragonBones.BinaryDataParser;var BaseFactory=dragonBones.BaseFactory;var BuildArmaturePackage=dragonBones.BuildArmaturePackage;var BinaryOffset=dragonBones.BinaryOffset;var ArmatureType=dragonBones.ArmatureType;var BoneType=dragonBones.BoneType;var DisplayType=dragonBones.DisplayType;var BoundingBoxType=dragonBones.BoundingBoxType;var ActionType=dragonBones.ActionType;var BlendMode=dragonBones.BlendMode;var TweenType=dragonBones.TweenType;var TimelineType=dragonBones.TimelineType;

      var _dec$1y, _class$1v, _dec2$1m, _class3$s;
      var ccclass$o = ccclass$M;
      var CCTextureAtlasData = (_dec$1y = ccclass$o('dragonBones.CCTextureAtlasData'), _dec$1y(_class$1v = function (_TextureAtlasData) {
        _inheritsLoose(CCTextureAtlasData, _TextureAtlasData);
        function CCTextureAtlasData() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _TextureAtlasData.call.apply(_TextureAtlasData, [this].concat(args)) || this;
          _this._renderTexture = null;
          return _this;
        }
        CCTextureAtlasData.toString = function toString() {
          return '[class dragonBones.CCTextureAtlasData]';
        };
        var _proto = CCTextureAtlasData.prototype;
        _proto.createTexture = function createTexture() {
          return BaseObject.borrowObject(CCTextureData);
        };
        _proto._onClear = function _onClear() {
          _TextureAtlasData.prototype._onClear.call(this);
          this.renderTexture = null;
        };
        _createClass(CCTextureAtlasData, [{
          key: "renderTexture",
          get: function get() {
            return this._renderTexture;
          },
          set: function set(value) {
            this._renderTexture = value;
            if (value) {
              for (var k in this.textures) {
                var textureData = this.textures[k];
                if (!textureData.spriteFrame) {
                  var rect = null;
                  if (textureData.rotated) {
                    rect = new Rect$1(textureData.region.x, textureData.region.y, textureData.region.height, textureData.region.width);
                  } else {
                    rect = new Rect$1(textureData.region.x, textureData.region.y, textureData.region.width, textureData.region.height);
                    textureData.spriteFrame = new SpriteFrame();
                    textureData.spriteFrame.texture = value;
                    textureData.spriteFrame.rect = rect;
                  }
                }
              }
            } else {
              for (var _k in this.textures) {
                var _textureData = this.textures[_k];
                _textureData.spriteFrame = null;
              }
            }
          }
        }]);
        return CCTextureAtlasData;
      }(TextureAtlasData)) || _class$1v);
      var CCTextureData = (_dec2$1m = ccclass$o('dragonBones.CCTextureData'), _dec2$1m(_class3$s = function (_TextureData) {
        _inheritsLoose(CCTextureData, _TextureData);
        function CCTextureData() {
          var _this2;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this2 = _TextureData.call.apply(_TextureData, [this].concat(args)) || this;
          _this2.spriteFrame = null;
          return _this2;
        }
        CCTextureData.toString = function toString() {
          return '[class dragonBones.CCTextureData]';
        };
        var _proto2 = CCTextureData.prototype;
        _proto2._onClear = function _onClear() {
          _TextureData.prototype._onClear.call(this);
          this.spriteFrame = null;
        };
        return CCTextureData;
      }(TextureData)) || _class3$s);

      var _dec$1x, _class$1u;
      var ccclass$n = ccclass$M;
      var CCSlot = (_dec$1x = ccclass$n('dragonBones.CCSlot'), _dec$1x(_class$1u = function (_Slot) {
        _inheritsLoose(CCSlot, _Slot);
        CCSlot.toString = function toString() {
          return '[class dragonBones.CCSlot]';
        };
        function CCSlot() {
          var _this;
          _this = _Slot.call(this) || this;
          _this._localVertices = void 0;
          _this._indices = void 0;
          _this._matrix = void 0;
          _this._worldMatrix = void 0;
          _this._worldMatrixDirty = void 0;
          _this._color = void 0;
          _this._localVertices = [];
          _this._indices = [];
          _this._matrix = new Mat4();
          _this._worldMatrix = new Mat4();
          _this._worldMatrixDirty = true;
          _this._visible = false;
          _this._color = new Color$1();
          return _this;
        }
        var _proto = CCSlot.prototype;
        _proto.getTexture = function getTexture() {
          if (this._textureData) {
            var sp = this._textureData.spriteFrame;
            var tex = sp.texture;
            return tex;
          }
          return null;
        };
        _proto.calculWorldMatrix = function calculWorldMatrix() {
          var parent = this._armature._parent;
          if (parent) {
            this._mulMat(this._worldMatrix, parent._worldMatrix, this._matrix);
          } else {
            Mat4.copy(this._worldMatrix, this._matrix);
          }
          this._worldMatrixDirty = false;
        };
        _proto._onClear = function _onClear() {
          _Slot.prototype._onClear.call(this);
          this._localVertices.length = 0;
          this._indices.length = 0;
          Mat4.identity(this._matrix);
          Mat4.identity(this._worldMatrix);
          this._worldMatrixDirty = true;
          this._color = new Color$1();
          this._visible = false;
        };
        _proto._onUpdateDisplay = function _onUpdateDisplay() {};
        _proto._initDisplay = function _initDisplay(value) {};
        _proto._addDisplay = function _addDisplay() {
          this._visible = true;
        };
        _proto._replaceDisplay = function _replaceDisplay(value) {};
        _proto._removeDisplay = function _removeDisplay() {
          this._visible = false;
        };
        _proto._disposeDisplay = function _disposeDisplay(object) {};
        _proto._updateVisible = function _updateVisible() {
          this._visible = this.parent.visible;
        };
        _proto._updateGlueMesh = function _updateGlueMesh() {};
        _proto._updateZOrder = function _updateZOrder() {};
        _proto._updateBlendMode = function _updateBlendMode() {
          if (this._childArmature) {
            var childSlots = this._childArmature.getSlots();
            for (var i = 0, l = childSlots.length; i < l; i++) {
              var slot = childSlots[i];
              slot._blendMode = this._blendMode;
              slot._updateBlendMode();
            }
          }
        };
        _proto._updateColor = function _updateColor() {
          var c = this._color;
          c.r = this._colorTransform.redMultiplier * 255;
          c.g = this._colorTransform.greenMultiplier * 255;
          c.b = this._colorTransform.blueMultiplier * 255;
          c.a = this._colorTransform.alphaMultiplier * 255;
        };
        _proto._updateFrame = function _updateFrame() {
          this._indices.length = 0;
          var indices = this._indices;
          var localVertices = this._localVertices;
          var indexOffset = 0;
          var vfOffset = 0;
          var currentTextureData = this._textureData;
          if (!this._display || this._displayIndex < 0 || !currentTextureData || !currentTextureData.spriteFrame) return;
          var texture = currentTextureData.spriteFrame.texture;
          var textureAtlasWidth = texture.width;
          var textureAtlasHeight = texture.height;
          var region = currentTextureData.region;
          if (textureAtlasWidth === 0 || textureAtlasHeight === 0) {
            console.error("SpriteFrame " + currentTextureData.spriteFrame.name + " incorrect size " + textureAtlasWidth + " x " + textureAtlasHeight);
            return;
          }
          var currentVerticesData = this._deformVertices !== null && this._display === this._meshDisplay ? this._deformVertices.verticesData : null;
          if (currentVerticesData) {
            var data = currentVerticesData.data;
            var intArray = data.intArray;
            var floatArray = data.floatArray;
            var vertexCount = intArray[currentVerticesData.offset + BinaryOffset.MeshVertexCount];
            var triangleCount = intArray[currentVerticesData.offset + BinaryOffset.MeshTriangleCount];
            var vertexOffset = intArray[currentVerticesData.offset + BinaryOffset.MeshFloatOffset];
            if (vertexOffset < 0) {
              vertexOffset += 65536;
            }
            var uvOffset = vertexOffset + vertexCount * 2;
            var scale = this._armature._armatureData.scale;
            for (var i = 0, l = vertexCount * 2; i < l; i += 2) {
              localVertices[vfOffset++] = floatArray[vertexOffset + i] * scale;
              localVertices[vfOffset++] = -floatArray[vertexOffset + i + 1] * scale;
              if (currentVerticesData.rotated) {
                localVertices[vfOffset++] = (region.x + (1.0 - floatArray[uvOffset + i]) * region.width) / textureAtlasWidth;
                localVertices[vfOffset++] = (region.y + floatArray[uvOffset + i + 1] * region.height) / textureAtlasHeight;
              } else {
                localVertices[vfOffset++] = (region.x + floatArray[uvOffset + i] * region.width) / textureAtlasWidth;
                localVertices[vfOffset++] = (region.y + floatArray[uvOffset + i + 1] * region.height) / textureAtlasHeight;
              }
            }
            for (var _i = 0; _i < triangleCount * 3; ++_i) {
              indices[indexOffset++] = intArray[currentVerticesData.offset + BinaryOffset.MeshVertexIndices + _i];
            }
            localVertices.length = vfOffset;
            indices.length = indexOffset;
            var isSkinned = !!currentVerticesData.weight;
            if (isSkinned) {
              this._identityTransform();
            }
          } else {
            var _l = region.x / textureAtlasWidth;
            var b = (region.y + region.height) / textureAtlasHeight;
            var r = (region.x + region.width) / textureAtlasWidth;
            var t = region.y / textureAtlasHeight;
            localVertices[vfOffset++] = 0;
            localVertices[vfOffset++] = 0;
            localVertices[vfOffset++] = _l;
            localVertices[vfOffset++] = b;
            localVertices[vfOffset++] = region.width;
            localVertices[vfOffset++] = 0;
            localVertices[vfOffset++] = r;
            localVertices[vfOffset++] = b;
            localVertices[vfOffset++] = 0;
            localVertices[vfOffset++] = region.height;
            localVertices[vfOffset++] = _l;
            localVertices[vfOffset++] = t;
            localVertices[vfOffset++] = region.width;
            localVertices[vfOffset++] = region.height;
            localVertices[vfOffset++] = r;
            localVertices[vfOffset++] = t;
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;
            indices[3] = 1;
            indices[4] = 3;
            indices[5] = 2;
            localVertices.length = vfOffset;
            indices.length = 6;
          }
          this._visibleDirty = true;
          this._blendModeDirty = true;
          this._colorDirty = true;
        };
        _proto._updateMesh = function _updateMesh() {
          var scale = this._armature._armatureData.scale;
          var deformVertices = this._deformVertices.vertices;
          var bones = this._deformVertices.bones;
          var verticesData = this._deformVertices.verticesData;
          var weightData = verticesData.weight;
          var hasDeform = deformVertices.length > 0 && verticesData.inheritDeform;
          var localVertices = this._localVertices;
          if (weightData) {
            var data = verticesData.data;
            var intArray = data.intArray;
            var floatArray = data.floatArray;
            var vertexCount = intArray[verticesData.offset + BinaryOffset.MeshVertexCount];
            var weightFloatOffset = intArray[weightData.offset + BinaryOffset.WeigthFloatOffset];
            if (weightFloatOffset < 0) {
              weightFloatOffset += 65536;
            }
            for (var i = 0, iB = weightData.offset + BinaryOffset.WeigthBoneIndices + bones.length, iV = weightFloatOffset, iF = 0, lvi = 0; i < vertexCount; i++, lvi += 4) {
              var boneCount = intArray[iB++];
              var xG = 0.0;
              var yG = 0.0;
              for (var j = 0; j < boneCount; ++j) {
                var boneIndex = intArray[iB++];
                var bone = bones[boneIndex];
                if (bone !== null) {
                  var matrix = bone.globalTransformMatrix;
                  var weight = floatArray[iV++];
                  var xL = floatArray[iV++] * scale;
                  var yL = floatArray[iV++] * scale;
                  if (hasDeform) {
                    xL += deformVertices[iF++];
                    yL += deformVertices[iF++];
                  }
                  xG += (matrix.a * xL + matrix.c * yL + matrix.tx) * weight;
                  yG += (matrix.b * xL + matrix.d * yL + matrix.ty) * weight;
                }
              }
              localVertices[lvi] = xG;
              localVertices[lvi + 1] = -yG;
            }
          } else if (hasDeform) {
            var isSurface = this._parent._boneData.type !== BoneType.Bone;
            var _data = verticesData.data;
            var _intArray = _data.intArray;
            var _floatArray = _data.floatArray;
            var _vertexCount = _intArray[verticesData.offset + BinaryOffset.MeshVertexCount];
            var vertexOffset = _intArray[verticesData.offset + BinaryOffset.MeshFloatOffset];
            if (vertexOffset < 0) {
              vertexOffset += 65536;
            }
            for (var _i2 = 0, l = _vertexCount, _lvi = 0; _i2 < l; _i2++, _lvi += 4) {
              var x = _floatArray[vertexOffset + _i2 * 2] * scale + deformVertices[_i2 * 2];
              var y = _floatArray[vertexOffset + _i2 * 2 + 1] * scale + deformVertices[_i2 * 2 + 1];
              if (isSurface) {
                var _matrix = this._parent._getGlobalTransformMatrix(x, y);
                localVertices[_lvi] = _matrix.a * x + _matrix.c * y + _matrix.tx;
                localVertices[_lvi + 1] = -_matrix.b * x + _matrix.d * y + _matrix.ty;
              } else {
                localVertices[_lvi] = x;
                localVertices[_lvi + 1] = -y;
              }
            }
          }
          if (weightData) {
            this._identityTransform();
          }
        };
        _proto._identityTransform = function _identityTransform() {
          var m = this._matrix;
          m.m00 = 1.0;
          m.m01 = 0.0;
          m.m04 = -0.0;
          m.m05 = -1.0;
          m.m12 = 0.0;
          m.m13 = 0.0;
          this._worldMatrixDirty = true;
        };
        _proto._updateTransform = function _updateTransform() {
          var m = this._matrix;
          m.m00 = this.globalTransformMatrix.a;
          m.m01 = this.globalTransformMatrix.b;
          m.m04 = -this.globalTransformMatrix.c;
          m.m05 = -this.globalTransformMatrix.d;
          if (this._childArmature) {
            m.m12 = this.globalTransformMatrix.tx;
            m.m13 = this.globalTransformMatrix.ty;
          } else {
            m.m12 = this.globalTransformMatrix.tx - (this.globalTransformMatrix.a * this._pivotX - this.globalTransformMatrix.c * this._pivotY);
            m.m13 = this.globalTransformMatrix.ty - (this.globalTransformMatrix.b * this._pivotX - this.globalTransformMatrix.d * this._pivotY);
          }
          this._worldMatrixDirty = true;
        };
        _proto.updateWorldMatrix = function updateWorldMatrix() {
          if (!this._armature) return;
          var parentSlot = this._armature._parent;
          if (parentSlot) {
            parentSlot.updateWorldMatrix();
          }
          if (this._worldMatrixDirty) {
            this.calculWorldMatrix();
            var childArmature = this.childArmature;
            if (!childArmature) return;
            var slots = childArmature.getSlots();
            for (var i = 0, n = slots.length; i < n; i++) {
              var slot = slots[i];
              if (slot) {
                slot._worldMatrixDirty = true;
              }
            }
          }
        };
        _proto._mulMat = function _mulMat(out, a, b) {
          var aa = a.m00;
          var ab = a.m01;
          var ac = a.m04;
          var ad = a.m05;
          var atx = a.m12;
          var aty = a.m13;
          var ba = b.m00;
          var bb = b.m01;
          var bc = b.m04;
          var bd = b.m05;
          var btx = b.m12;
          var bty = b.m13;
          if (ab !== 0 || ac !== 0) {
            out.m00 = ba * aa + bb * ac;
            out.m01 = ba * ab + bb * ad;
            out.m04 = bc * aa + bd * ac;
            out.m05 = bc * ab + bd * ad;
            out.m12 = aa * btx + ac * bty + atx;
            out.m13 = ab * btx + ad * bty + aty;
          } else {
            out.m00 = ba * aa;
            out.m01 = bb * ad;
            out.m04 = bc * aa;
            out.m05 = bd * ad;
            out.m12 = aa * btx + atx;
            out.m13 = ad * bty + aty;
          }
        };
        return CCSlot;
      }(Slot)) || _class$1u);

      var _dec$1w, _class$1t;
      var ccclass$m = ccclass$M;
      var CCArmatureDisplay = (_dec$1w = ccclass$m('dragonBones.CCArmatureDisplay'), _dec$1w(_class$1t = function (_DisplayData) {
        _inheritsLoose(CCArmatureDisplay, _DisplayData);
        function CCArmatureDisplay() {
          var _this;
          _this = _DisplayData.call(this) || this;
          _this.shouldAdvanced = false;
          _this._ccNode = null;
          _this._ccComponent = null;
          _this._eventTarget = void 0;
          _this._armature = null;
          _this._eventTarget = new EventTarget();
          return _this;
        }
        var _proto = CCArmatureDisplay.prototype;
        _proto.hasEvent = function hasEvent(type) {
          console.warn('Method not implemented.');
          return false;
        };
        _proto.addEvent = function addEvent(type, listener, thisObject) {
          console.warn('Method not implemented.');
        };
        _proto.removeEvent = function removeEvent(type, listener, thisObject) {
          console.warn('Method not implemented.');
        };
        _proto.setEventTarget = function setEventTarget(eventTarget) {
          this._eventTarget = eventTarget;
        };
        _proto.getRootDisplay = function getRootDisplay() {
          var parentSlot = this._armature._parent;
          if (!parentSlot) {
            return this;
          }
          var slot;
          while (parentSlot) {
            slot = parentSlot;
            parentSlot = parentSlot._armature._parent;
          }
          return slot._armature.display;
        };
        _proto.convertToRootSpace = function convertToRootSpace(pos) {
          var slot = this._armature._parent;
          if (!slot) {
            return pos;
          }
          slot.updateWorldMatrix();
          var worldMatrix = slot._worldMatrix;
          var newPos = new Vec3(0, 0);
          newPos.x = pos.x * worldMatrix.m00 + pos.y * worldMatrix.m04 + worldMatrix.m12;
          newPos.y = pos.x * worldMatrix.m01 + pos.y * worldMatrix.m05 + worldMatrix.m13;
          return newPos;
        };
        _proto.convertToWorldSpace = function convertToWorldSpace(point) {
          var _ccNode$_uiProps$uiTr;
          var newPos = this.convertToRootSpace(point);
          var ccNode = this.getRootNode();
          return ccNode === null || ccNode === void 0 ? void 0 : (_ccNode$_uiProps$uiTr = ccNode._uiProps.uiTransformComp) === null || _ccNode$_uiProps$uiTr === void 0 ? void 0 : _ccNode$_uiProps$uiTr.convertToWorldSpaceAR(newPos);
        };
        _proto.getRootNode = function getRootNode() {
          var rootDisplay = this.getRootDisplay();
          return rootDisplay && rootDisplay._ccNode;
        };
        _proto.dbInit = function dbInit(armature) {
          this._armature = armature;
        };
        _proto.dbClear = function dbClear() {
          this._armature = null;
        };
        _proto.dbUpdate = function dbUpdate() {
          if (this._ccComponent) {
            this._ccComponent.markForUpdateRenderData();
          }
        };
        _proto.advanceTimeBySelf = function advanceTimeBySelf(on) {
          this.shouldAdvanced = !!on;
        };
        _proto.hasDBEventListener = function hasDBEventListener(type) {
          return this._eventTarget.hasEventListener(type);
        };
        _proto.addDBEventListener = function addDBEventListener(type, listener, target) {
          this._eventTarget.on(type, listener, target);
        };
        _proto.removeDBEventListener = function removeDBEventListener(type, listener, target) {
          this._eventTarget.off(type, listener, target);
        };
        _proto.dispatchDBEvent = function dispatchDBEvent(type, eventObject) {
          this._eventTarget.emit(type, eventObject);
        };
        _createClass(CCArmatureDisplay, [{
          key: "node",
          get: function get() {
            return this;
          }
        }]);
        return CCArmatureDisplay;
      }(DisplayData)) || _class$1t);

      var _dec$1v, _class$1s, _class2$1q;
      var ccclass$l = ccclass$M;
      var CCFactory = (_dec$1v = ccclass$l('CCFactory'), _dec$1v(_class$1s = (_class2$1q = function (_BaseFactory) {
        _inheritsLoose(CCFactory, _BaseFactory);
        CCFactory.getInstance = function getInstance() {
          if (!CCFactory._factory) {
            CCFactory._factory = new CCFactory();
          }
          return CCFactory._factory;
        };
        function CCFactory() {
          var _this;
          _this = _BaseFactory.call(this) || this;
          _this.id = void 0;
          _this.uuid = void 0;
          _this._slots = void 0;
          var eventManager = new CCArmatureDisplay();
          _this._dragonBones = new DragonBones(eventManager);
          if (director.getScheduler()) {
            game.on(Game.EVENT_RESTART, _this.onRestart, _assertThisInitialized(_this));
            _this.initUpdate();
          }
          _this.id = _this.uuid = 'CCFactory';
          return _this;
        }
        var _proto = CCFactory.prototype;
        _proto.onRestart = function onRestart() {
          CCFactory._factory = null;
        };
        _proto.initUpdate = function initUpdate(dt) {
          Scheduler.enableForTarget(this);
          director.getScheduler().scheduleUpdate(this, System.Priority.HIGH, false);
        };
        _proto.update = function update(dt) {
          this._dragonBones.advanceTime(dt);
        };
        _proto.getDragonBonesDataByRawData = function getDragonBonesDataByRawData(rawData) {
          var dataParser = rawData instanceof ArrayBuffer ? BaseFactory._binaryParser : this._dataParser;
          return dataParser.parseDragonBonesData(rawData, 1.0);
        };
        _proto.buildArmatureDisplay = function buildArmatureDisplay(armatureName, dragonBonesName, skinName, textureAtlasName) {
          var armature = this.buildArmature(armatureName, dragonBonesName, skinName, textureAtlasName);
          return armature ? armature._display : null;
        };
        _proto.createArmatureNode = function createArmatureNode(comp, armatureName, node) {
          node = node || new Node$1();
          var display = node.getComponent('dragonBones.ArmatureDisplay');
          if (!display) {
            display = node.addComponent('dragonBones.ArmatureDisplay');
          }
          node.name = armatureName;
          display._armatureName = armatureName;
          display._dragonAsset = comp.dragonAsset;
          display._dragonAtlasAsset = comp.dragonAtlasAsset;
          display._init();
          return display;
        };
        _proto._buildTextureAtlasData = function _buildTextureAtlasData(textureAtlasData, textureAtlas) {
          if (textureAtlasData) {
            textureAtlasData.renderTexture = textureAtlas;
          } else {
            textureAtlasData = BaseObject.borrowObject(CCTextureAtlasData);
          }
          return textureAtlasData;
        };
        _proto._sortSlots = function _sortSlots() {
          var slots = this._slots;
          var sortedSlots = [];
          for (var i = 0, l = slots.length; i < l; i++) {
            var slot = slots[i];
            var zOrder = slot._zOrder;
            var inserted = false;
            for (var j = sortedSlots.length - 1; j >= 0; j--) {
              if (zOrder >= sortedSlots[j]._zOrder) {
                sortedSlots.splice(j + 1, 0, slot);
                inserted = true;
                break;
              }
            }
            if (!inserted) {
              sortedSlots.unshift(slot);
            }
          }
          this._slots = sortedSlots;
        };
        _proto._buildArmature = function _buildArmature(dataPackage) {
          var armature = BaseObject.borrowObject(Armature);
          armature._skinData = dataPackage.skin;
          armature._animation = BaseObject.borrowObject(Animation$1);
          armature._animation._armature = armature;
          armature._animation.animations = dataPackage.armature.animations;
          armature._isChildArmature = false;
          var display = new CCArmatureDisplay();
          armature.init(dataPackage.armature, display, display, this._dragonBones);
          return armature;
        };
        _proto._buildSlot = function _buildSlot(dataPackage, slotData, displays) {
          var slot = BaseObject.borrowObject(CCSlot);
          var display = slot;
          slot.init(slotData, displays, display, display);
          return slot;
        };
        _proto.getDragonBonesDataByUUID = function getDragonBonesDataByUUID(uuid) {
          for (var name in this._dragonBonesDataMap) {
            if (name.indexOf(uuid) !== -1) {
              return this._dragonBonesDataMap[name];
            }
          }
          return null;
        };
        _proto.removeDragonBonesDataByUUID = function removeDragonBonesDataByUUID(uuid, disposeData) {
          if (disposeData === undefined) {
            disposeData = true;
          }
          for (var name in this._dragonBonesDataMap) {
            if (name.indexOf(uuid) === -1) continue;
            if (disposeData) {
              this._dragonBones.bufferObject(this._dragonBonesDataMap[name]);
            }
            delete this._dragonBonesDataMap[name];
          }
        };
        return CCFactory;
      }(BaseFactory), _class2$1q._factory = null, _class2$1q)) || _class$1s);

      var _class2$1p;
      var MaxCacheTime$1 = 30;
      var FrameTime$1 = 1 / 60;
      var _vertices = [];
      var _indices = [];
      var _boneInfoOffset = 0;
      var _indexOffset$1 = 0;
      var _vfOffset$1 = 0;
      var _preTexUrl = null;
      var _preBlendMode = null;
      var _segVCount = 0;
      var _segICount = 0;
      var _segOffset = 0;
      var _colorOffset = 0;
      var _preColor = 0;
      var _x;
      var _y;
      var PER_VERTEX_SIZE$1 = 5;
      var EXPORT_VERTEX_SIZE = 9;
      var AnimationCache$1 = function () {
        function AnimationCache() {
          this.maxVertexCount = 0;
          this.maxIndexCount = 0;
          this._privateMode = false;
          this._inited = false;
          this._invalid = true;
          this._enableCacheAttachedInfo = false;
          this.frames = [];
          this.totalTime = 0;
          this.isCompleted = false;
          this._frameIdx = -1;
          this._armatureInfo = null;
          this._animationName = null;
          this._tempSegments = null;
          this._tempColors = null;
          this._tempBoneInfos = null;
        }
        var _proto = AnimationCache.prototype;
        _proto.init = function init(armatureInfo, animationName) {
          this._inited = true;
          this._armatureInfo = armatureInfo;
          this._animationName = animationName;
        };
        _proto.clear = function clear() {
          this._inited = false;
          for (var i = 0, n = this.frames.length; i < n; i++) {
            var frame = this.frames[i];
            frame.segments.length = 0;
          }
          this.invalidAllFrame();
        };
        _proto.begin = function begin() {
          if (!this._invalid) return;
          var armatureInfo = this._armatureInfo;
          var curAnimationCache = armatureInfo.curAnimationCache;
          if (curAnimationCache && curAnimationCache !== this) {
            if (this._privateMode) {
              curAnimationCache.invalidAllFrame();
            } else {
              curAnimationCache.updateToFrame();
            }
          }
          var armature = armatureInfo.armature;
          var animation = armature.animation;
          animation.play(this._animationName, 1);
          armatureInfo.curAnimationCache = this;
          this._invalid = false;
          this._frameIdx = -1;
          this.totalTime = 0;
          this.isCompleted = false;
        };
        _proto.end = function end() {
          if (!this._needToUpdate()) {
            this._armatureInfo.curAnimationCache = null;
            this.frames.length = this._frameIdx + 1;
            this.isCompleted = true;
          }
        };
        _proto._needToUpdate = function _needToUpdate(toFrameIdx) {
          var armatureInfo = this._armatureInfo;
          var armature = armatureInfo.armature;
          var animation = armature.animation;
          return !animation.isCompleted && this.totalTime < MaxCacheTime$1 && (toFrameIdx === undefined || this._frameIdx < toFrameIdx);
        };
        _proto.updateToFrame = function updateToFrame(toFrameIdx) {
          if (!this._inited) return;
          this.begin();
          if (!this._needToUpdate(toFrameIdx)) return;
          var armatureInfo = this._armatureInfo;
          var armature = armatureInfo.armature;
          do {
            armature.advanceTime(FrameTime$1);
            this._frameIdx++;
            this.updateFrame(armature, this._frameIdx);
            this.totalTime += FrameTime$1;
          } while (this._needToUpdate(toFrameIdx));
          this.end();
        };
        _proto.isInited = function isInited() {
          return this._inited;
        };
        _proto.isInvalid = function isInvalid() {
          return this._invalid;
        };
        _proto.invalidAllFrame = function invalidAllFrame() {
          this.isCompleted = false;
          this._invalid = true;
        };
        _proto.updateAllFrame = function updateAllFrame() {
          this.invalidAllFrame();
          this.updateToFrame();
        };
        _proto.enableCacheAttachedInfo = function enableCacheAttachedInfo() {
          if (!this._enableCacheAttachedInfo) {
            this._enableCacheAttachedInfo = true;
            this.invalidAllFrame();
          }
        };
        _proto.updateFrame = function updateFrame(armature, index) {
          _vfOffset$1 = 0;
          _boneInfoOffset = 0;
          _indexOffset$1 = 0;
          _preTexUrl = null;
          _preBlendMode = null;
          _segVCount = 0;
          _segICount = 0;
          _segOffset = 0;
          _colorOffset = 0;
          _preColor = 0;
          this.frames[index] = this.frames[index] || {
            segments: [],
            colors: [],
            boneInfos: [],
            vertices: new Float32Array(),
            uintVert: new Uint32Array(),
            indices: new Uint16Array()
          };
          var frame = this.frames[index];
          var segments = this._tempSegments = frame.segments;
          var colors = this._tempColors = frame.colors;
          var boneInfos = this._tempBoneInfos = frame.boneInfos;
          this._traverseArmature(armature, 1.0);
          if (_colorOffset > 0) {
            colors[_colorOffset - 1].vfOffset = _vfOffset$1;
          }
          colors.length = _colorOffset;
          boneInfos.length = _boneInfoOffset;
          var preSegOffset = _segOffset - 1;
          if (preSegOffset >= 0) {
            if (_segICount > 0) {
              var preSegInfo = segments[preSegOffset];
              preSegInfo.indexCount = _segICount;
              preSegInfo.vfCount = _segVCount * EXPORT_VERTEX_SIZE;
              preSegInfo.vertexCount = _segVCount;
              segments.length = _segOffset;
            } else {
              segments.length = _segOffset - 1;
            }
          }
          if (segments.length === 0) return;
          var vertices = frame.vertices;
          var vertexCount = _vfOffset$1 / PER_VERTEX_SIZE$1;
          var copyOutVerticeSize = vertexCount * EXPORT_VERTEX_SIZE;
          if (!vertices || vertices.length < _vfOffset$1) {
            vertices = frame.vertices = new Float32Array(copyOutVerticeSize);
          }
          var colorI32;
          for (var i = 0, j = 0; i < copyOutVerticeSize;) {
            vertices[i] = _vertices[j++];
            vertices[i + 1] = _vertices[j++];
            vertices[i + 3] = _vertices[j++];
            vertices[i + 4] = _vertices[j++];
            colorI32 = _vertices[j++];
            vertices[i + 5] = (colorI32 & 0xff) / 255.0;
            vertices[i + 6] = (colorI32 >> 8 & 0xff) / 255.0;
            vertices[i + 7] = (colorI32 >> 16 & 0xff) / 255.0;
            vertices[i + 8] = (colorI32 >> 24 & 0xff) / 255.0;
            i += EXPORT_VERTEX_SIZE;
          }
          var indices = frame.indices;
          if (!indices || indices.length < _indexOffset$1) {
            indices = frame.indices = new Uint16Array(_indexOffset$1);
          }
          for (var _i = 0; _i < _indexOffset$1; _i++) {
            indices[_i] = _indices[_i];
          }
          frame.vertices = vertices;
          frame.indices = indices;
          this.maxVertexCount = vertexCount > this.maxVertexCount ? vertexCount : this.maxVertexCount;
          this.maxIndexCount = indices.length > this.maxIndexCount ? indices.length : this.maxIndexCount;
        };
        _proto._traverseArmature = function _traverseArmature(armature, parentOpacity) {
          var colors = this._tempColors;
          var segments = this._tempSegments;
          var boneInfos = this._tempBoneInfos;
          var slots = armature._slots;
          var slotVertices;
          var slotIndices;
          var slot;
          var slotMatrix;
          var slotColor;
          var colorVal;
          var texture;
          var preSegOffset;
          var preSegInfo;
          var bones = armature._bones;
          if (this._enableCacheAttachedInfo) {
            for (var i = 0, l = bones.length; i < l; i++, _boneInfoOffset++) {
              var bone = bones[i];
              var boneInfo = boneInfos[_boneInfoOffset];
              if (!boneInfo) {
                boneInfo = boneInfos[_boneInfoOffset] = {
                  globalTransformMatrix: new Matrix()
                };
              }
              var boneMat = bone.globalTransformMatrix;
              var cacheBoneMat = boneInfo.globalTransformMatrix;
              cacheBoneMat.copyFrom(boneMat);
            }
          }
          for (var _i2 = 0, _l = slots.length; _i2 < _l; _i2++) {
            slot = slots[_i2];
            if (!slot._visible || !slot._displayData) continue;
            slot.updateWorldMatrix();
            slotColor = slot._color;
            if (slot.childArmature) {
              this._traverseArmature(slot.childArmature, parentOpacity * slotColor.a / 255);
              continue;
            }
            texture = slot.getTexture();
            if (!texture) continue;
            if (_preTexUrl !== texture.nativeUrl || _preBlendMode !== slot._blendMode) {
              _preTexUrl = texture.nativeUrl;
              _preBlendMode = slot._blendMode;
              preSegOffset = _segOffset - 1;
              if (preSegOffset >= 0) {
                if (_segICount > 0) {
                  preSegInfo = segments[preSegOffset];
                  preSegInfo.indexCount = _segICount;
                  preSegInfo.vertexCount = _segVCount;
                  preSegInfo.vfCount = _segVCount * EXPORT_VERTEX_SIZE;
                } else {
                  _segOffset--;
                }
              }
              segments[_segOffset] = {
                tex: texture,
                blendMode: slot._blendMode,
                indexCount: 0,
                vertexCount: 0,
                vfCount: 0
              };
              _segOffset++;
              _segICount = 0;
              _segVCount = 0;
            }
            colorVal = (slotColor.a * parentOpacity << 24 >>> 0) + (slotColor.b << 16) + (slotColor.g << 8) + slotColor.r;
            if (_preColor !== colorVal) {
              _preColor = colorVal;
              if (_colorOffset > 0) {
                colors[_colorOffset - 1].vfOffset = _vfOffset$1;
              }
              colors[_colorOffset++] = {
                r: slotColor.r,
                g: slotColor.g,
                b: slotColor.b,
                a: slotColor.a * parentOpacity,
                vfOffset: 0
              };
            }
            slotVertices = slot._localVertices;
            slotIndices = slot._indices;
            slotMatrix = slot._worldMatrix;
            for (var j = 0, vl = slotVertices.length; j < vl;) {
              _x = slotVertices[j++];
              _y = slotVertices[j++];
              _vertices[_vfOffset$1++] = _x * slotMatrix.m00 + _y * slotMatrix.m04 + slotMatrix.m12;
              _vertices[_vfOffset$1++] = _x * slotMatrix.m01 + _y * slotMatrix.m05 + slotMatrix.m13;
              _vertices[_vfOffset$1++] = slotVertices[j++];
              _vertices[_vfOffset$1++] = slotVertices[j++];
              _vertices[_vfOffset$1++] = colorVal;
            }
            for (var ii = 0, il = slotIndices.length; ii < il; ii++) {
              _indices[_indexOffset$1++] = _segVCount + slotIndices[ii];
            }
            _segICount += slotIndices.length;
            _segVCount += slotVertices.length / 4;
          }
        };
        return AnimationCache;
      }();
      var ArmatureCache = function () {
        function ArmatureCache() {
          this._privateMode = false;
          this._animationPool = {};
          this._armatureCache = {};
        }
        var _proto2 = ArmatureCache.prototype;
        _proto2.enablePrivateMode = function enablePrivateMode() {
          this._privateMode = true;
        };
        _proto2.dispose = function dispose() {
          for (var _key in this._armatureCache) {
            var armatureInfo = this._armatureCache[_key];
            if (armatureInfo) {
              var armature = armatureInfo.armature;
              if (armature) armature.dispose();
            }
          }
          this._armatureCache = {};
          this._animationPool = {};
        };
        _proto2._removeArmature = function _removeArmature(armatureKey) {
          var armatureInfo = this._armatureCache[armatureKey];
          var animationsCache = armatureInfo.animationsCache;
          for (var aniKey in animationsCache) {
            var animationCache = animationsCache[aniKey];
            if (!animationCache) continue;
            this._animationPool[armatureKey + "#" + aniKey] = animationCache;
            animationCache.clear();
          }
          var armature = armatureInfo.armature;
          if (armature) armature.dispose();
          delete this._armatureCache[armatureKey];
        };
        _proto2.resetArmature = function resetArmature(uuid) {
          for (var armatureKey in this._armatureCache) {
            if (armatureKey.indexOf(uuid) === -1) continue;
            this._removeArmature(armatureKey);
          }
        };
        _proto2.getArmatureCache = function getArmatureCache(armatureName, armatureKey, atlasUUID) {
          var armatureInfo = this._armatureCache[armatureKey];
          var armature;
          if (!armatureInfo) {
            var factory = CCFactory.getInstance();
            var proxy = factory.buildArmatureDisplay(armatureName, armatureKey, '', atlasUUID);
            if (!proxy || !proxy._armature) return null;
            armature = proxy._armature;
            if (!ArmatureCache.canCache(armature)) {
              armature.dispose();
              return null;
            }
            this._armatureCache[armatureKey] = {
              armature: armature,
              animationsCache: {},
              curAnimationCache: null
            };
          } else {
            armature = armatureInfo.armature;
          }
          return armature;
        };
        _proto2.getAnimationCache = function getAnimationCache(armatureKey, animationName) {
          var armatureInfo = this._armatureCache[armatureKey];
          if (!armatureInfo) return null;
          var animationsCache = armatureInfo.animationsCache;
          return animationsCache[animationName];
        };
        _proto2.initAnimationCache = function initAnimationCache(armatureKey, animationName) {
          if (!animationName) return null;
          var armatureInfo = this._armatureCache[armatureKey];
          var armature = armatureInfo && armatureInfo.armature;
          if (!armature) return null;
          var animation = armature.animation;
          var hasAni = animation.hasAnimation(animationName);
          if (!hasAni) return null;
          var animationsCache = armatureInfo.animationsCache;
          var animationCache = animationsCache[animationName];
          if (!animationCache) {
            var poolKey = armatureKey + "#" + animationName;
            animationCache = this._animationPool[poolKey];
            if (animationCache) {
              delete this._animationPool[poolKey];
            } else {
              animationCache = new AnimationCache$1();
              animationCache._privateMode = this._privateMode;
            }
            animationCache.init(armatureInfo, animationName);
            animationsCache[animationName] = animationCache;
          }
          return animationCache;
        };
        _proto2.invalidAnimationCache = function invalidAnimationCache(armatureKey) {
          var armatureInfo = this._armatureCache[armatureKey];
          var armature = armatureInfo && armatureInfo.armature;
          if (!armature) return;
          var animationsCache = armatureInfo.animationsCache;
          for (var aniKey in animationsCache) {
            var animationCache = animationsCache[aniKey];
            animationCache.invalidAllFrame();
          }
        };
        _proto2.updateAnimationCache = function updateAnimationCache(armatureKey, animationName) {
          if (animationName) {
            var animationCache = this.initAnimationCache(armatureKey, animationName);
            if (!animationCache) return;
            animationCache.updateAllFrame();
          } else {
            var armatureInfo = this._armatureCache[armatureKey];
            var armature = armatureInfo && armatureInfo.armature;
            if (!armature) return;
            var animationsCache = armatureInfo.animationsCache;
            for (var aniKey in animationsCache) {
              var _animationCache = animationsCache[aniKey];
              _animationCache.updateAllFrame();
            }
          }
        };
        ArmatureCache.canCache = function canCache(armature) {
          var slots = armature._slots;
          for (var i = 0, l = slots.length; i < l; i++) {
            var slot = slots[i];
            if (slot.childArmature) {
              return false;
            }
          }
          return true;
        };
        return ArmatureCache;
      }();
      _class2$1p = ArmatureCache;
      ArmatureCache.FrameTime = FrameTime$1;
      ArmatureCache.sharedCache = new _class2$1p();

      var _dec$1u, _class$1r, _class2$1o, _initializer$1l;
      var ccclass$k = ccclass$M,
        serializable$5 = serializable$p;
      var DragonBonesAsset = (_dec$1u = ccclass$k('dragonBones.DragonBonesAsset'), _dec$1u(_class$1r = (_class2$1o = function (_Asset) {
        _inheritsLoose(DragonBonesAsset, _Asset);
        function DragonBonesAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this._dragonBonesJson = _initializer$1l && _initializer$1l();
          _this._factory = null;
          _this._dragonBonesJsonData = void 0;
          _this._armaturesEnum = null;
          return _this;
        }
        var _proto = DragonBonesAsset.prototype;
        _proto.constructctor = function constructctor() {
          this.reset();
        };
        _proto.createNode = function createNode(callback) {
          var node = new Node$1(this.name);
          var armatureDisplay = node.addComponent('dragonBones.ArmatureDisplay');
          armatureDisplay.dragonAsset = this;
          return callback(null, node);
        };
        _proto.reset = function reset() {
          this._clear();
        };
        _proto.init = function init(factory, atlasUUID) {
          this._factory = factory || CCFactory.getInstance();
          if (!this._dragonBonesJsonData && this.dragonBonesJson) {
            this._dragonBonesJsonData = JSON.parse(this.dragonBonesJson);
          }
          var rawData = null;
          if (this._dragonBonesJsonData) {
            rawData = this._dragonBonesJsonData;
          } else {
            rawData = this._nativeAsset;
          }
          if (!this._uuid) {
            var dbData = this._factory.getDragonBonesDataByRawData(rawData);
            if (dbData) {
              this._uuid = dbData.name;
            } else {
              console.warn('dragonbones name is empty');
            }
          }
          var armatureKey = this._uuid + "#" + atlasUUID;
          var dragonBonesData = this._factory.getDragonBonesData(armatureKey);
          if (dragonBonesData) return armatureKey;
          this._factory.parseDragonBonesData(rawData instanceof ArrayBuffer ? rawData : rawData.buffer instanceof ArrayBuffer ? rawData.buffer : rawData, armatureKey);
          return armatureKey;
        };
        _proto.getArmatureEnum = function getArmatureEnum() {
          if (this._armaturesEnum) {
            return this._armaturesEnum;
          }
          this.init();
          var dragonBonesData = this._factory.getDragonBonesDataByUUID(this._uuid);
          if (dragonBonesData) {
            var armatureNames = dragonBonesData.armatureNames;
            var enumDef = {};
            for (var i = 0; i < armatureNames.length; i++) {
              var name = armatureNames[i];
              enumDef[name] = i;
            }
            return this._armaturesEnum = Enum(enumDef);
          }
          return null;
        };
        _proto.getAnimsEnum = function getAnimsEnum(armatureName) {
          this.init();
          var dragonBonesData = this._factory.getDragonBonesDataByUUID(this._uuid);
          if (dragonBonesData) {
            var armature = dragonBonesData.getArmature(armatureName);
            if (!armature) {
              return null;
            }
            var enumDef = {
              '<None>': 0
            };
            var anims = armature.animations;
            var i = 0;
            for (var animName in anims) {
              if (anims.hasOwnProperty(animName)) {
                enumDef[animName] = i + 1;
                i++;
              }
            }
            return Enum(enumDef);
          }
          return null;
        };
        _proto.destroy = function destroy() {
          this._clear();
          return _Asset.prototype.destroy.call(this);
        };
        _proto._clear = function _clear() {
          if (this._factory) {
            ArmatureCache.sharedCache.resetArmature(this._uuid);
            this._factory.removeDragonBonesDataByUUID(this._uuid, true);
          }
        };
        _createClass(DragonBonesAsset, [{
          key: "dragonBonesJson",
          get: function get() {
            return this._dragonBonesJson;
          },
          set: function set(value) {
            this._dragonBonesJson = value;
            this._dragonBonesJsonData = JSON.parse(value);
            this.reset();
          }
        }]);
        return DragonBonesAsset;
      }(Asset), (_initializer$1l = applyDecoratedInitializer(_class2$1o.prototype, "_dragonBonesJson", [serializable$5], function () {
        return '';
      })), _class2$1o)) || _class$1r);
      legacyCC.internal.DragonBonesAsset = DragonBonesAsset;

      var _dec$1t, _dec2$1l, _class$1q, _class2$1n, _initializer$1k, _initializer2$1d, _initializer3$Y, _initializer4$Q;
      var ccclass$j = ccclass$M,
        serializable$4 = serializable$p,
        type$5 = type$d;
      var DragonBonesAtlasAsset = (_dec$1t = ccclass$j('dragonBones.DragonBonesAtlasAsset'), _dec2$1l = type$5(Texture2D), _dec$1t(_class$1q = (_class2$1n = function (_Asset) {
        _inheritsLoose(DragonBonesAtlasAsset, _Asset);
        function DragonBonesAtlasAsset() {
          var _this;
          _this = _Asset.call(this) || this;
          _this._atlasJson = _initializer$1k && _initializer$1k();
          _this._texture = _initializer2$1d && _initializer2$1d();
          _this._atlasJsonData = _initializer3$Y && _initializer3$Y();
          _this._factory = null;
          _this._textureAtlasData = _initializer4$Q && _initializer4$Q();
          _this._clear();
          return _this;
        }
        var _proto = DragonBonesAtlasAsset.prototype;
        _proto.createNode = function createNode(callback) {
          var node = new Node$1(this.name);
          var armatureDisplay = node.addComponent('dragonBones.ArmatureDisplay');
          armatureDisplay.dragonAtlasAsset = this;
          return callback(null, node);
        };
        _proto.init = function init(factory) {
          this._factory = factory;
          if (!this._atlasJsonData) {
            this._atlasJsonData = JSON.parse(this.atlasJson);
          }
          var atlasJsonObj = this._atlasJsonData;
          this._uuid = this._uuid || atlasJsonObj.name;
          if (this._textureAtlasData) {
            factory.addTextureAtlasData(this._textureAtlasData, this._uuid);
          } else {
            this._textureAtlasData = factory.parseTextureAtlasData(atlasJsonObj, this.texture, this._uuid);
          }
        };
        _proto.destroy = function destroy() {
          this._clear();
          return _Asset.prototype.destroy.call(this);
        };
        _proto._clear = function _clear() {
          if (this._factory) {
            ArmatureCache.sharedCache.resetArmature(this._uuid);
            this._factory.removeTextureAtlasData(this._uuid, true);
            this._factory.removeDragonBonesDataByUUID(this._uuid, true);
          }
          this._textureAtlasData = null;
        };
        _createClass(DragonBonesAtlasAsset, [{
          key: "atlasJson",
          get: function get() {
            return this._atlasJson;
          },
          set: function set(value) {
            this._atlasJson = value;
            this._atlasJsonData = JSON.parse(this.atlasJson);
            this._clear();
          }
        }, {
          key: "texture",
          get: function get() {
            return this._texture;
          },
          set: function set(value) {
            this._texture = value;
            this._clear();
          }
        }]);
        return DragonBonesAtlasAsset;
      }(Asset), (_initializer$1k = applyDecoratedInitializer(_class2$1n.prototype, "_atlasJson", [serializable$4], function () {
        return '';
      }), _initializer2$1d = applyDecoratedInitializer(_class2$1n.prototype, "_texture", [serializable$4, _dec2$1l], function () {
        return null;
      }), _initializer3$Y = applyDecoratedInitializer(_class2$1n.prototype, "_atlasJsonData", [serializable$4], function () {
        return {};
      }), _initializer4$Q = applyDecoratedInitializer(_class2$1n.prototype, "_textureAtlasData", [serializable$4], function () {
        return null;
      })), _class2$1n)) || _class$1q);
      legacyCC.internal.DragonBonesAtlasAsset = DragonBonesAtlasAsset;

      var _dec$1s, _class$1p;
      var _tempMat4 = new Mat4();
      var ccclass$i = ccclass$M;
      var AttachUtil$1 = (_dec$1s = ccclass$i('dragonBones.AttachUtil'), _dec$1s(_class$1p = function () {
        function AttachUtil() {
          this._inited = false;
          this._armature = null;
          this._armatureNode = null;
          this._armatureDisplay = null;
        }
        var _proto = AttachUtil.prototype;
        _proto.init = function init(armatureDisplay) {
          this._inited = true;
          this._armature = armatureDisplay._armature;
          this._armatureNode = armatureDisplay.node;
          this._armatureDisplay = armatureDisplay;
        };
        _proto.reset = function reset() {
          this._inited = false;
          this._armature = null;
          this._armatureNode = null;
          this._armatureDisplay = null;
        };
        _proto._syncAttachedNode = function _syncAttachedNode() {
          if (!this._inited) return;
          this._armatureNode.worldMatrix;
          var boneInfos = null;
          var isCached = this._armatureDisplay.isAnimationCached();
          if (isCached && this._armatureDisplay) {
            boneInfos = this._armatureDisplay._curFrame && this._armatureDisplay._curFrame.boneInfos;
            if (!boneInfos) return;
          }
          var sockets = this._armatureDisplay.sockets;
          var socketNodes = this._armatureDisplay.socketNodes;
          var matrixHandle = function matrixHandle(node, boneMat) {
            var tm = _tempMat4;
            tm.m00 = boneMat.a;
            tm.m01 = boneMat.b;
            tm.m04 = -boneMat.c;
            tm.m05 = -boneMat.d;
            tm.m12 = boneMat.tx;
            tm.m13 = boneMat.ty;
            node.matrix = _tempMat4;
          };
          var bones = this._armature.getBones();
          for (var l = sockets.length - 1; l >= 0; l--) {
            var sock = sockets[l];
            var boneNode = sock.target;
            if (!boneNode) continue;
            if (!boneNode.isValid) {
              socketNodes["delete"](sock.path);
              sockets.splice(l, 1);
              continue;
            }
            var bone = isCached ? boneInfos[sock.boneIndex] : bones[sock.boneIndex];
            if (!bone) continue;
            matrixHandle(boneNode, bone.globalTransformMatrix);
          }
        };
        return AttachUtil;
      }()) || _class$1p);

      var ArmatureSystem = function (_System) {
        _inheritsLoose(ArmatureSystem, _System);
        function ArmatureSystem() {
          var _this;
          _this = _System.call(this) || this;
          _this._armatures = new Set();
          return _this;
        }
        ArmatureSystem.getInstance = function getInstance() {
          if (!ArmatureSystem._instance) {
            ArmatureSystem._instance = new ArmatureSystem();
            director.registerSystem(ArmatureSystem.ID, ArmatureSystem._instance, System.Priority.HIGH);
          }
          return ArmatureSystem._instance;
        };
        var _proto = ArmatureSystem.prototype;
        _proto.add = function add(armature) {
          if (!armature) return;
          if (!this._armatures.has(armature)) {
            this._armatures.add(armature);
          }
        };
        _proto.remove = function remove(armature) {
          if (!armature) return;
          if (this._armatures.has(armature)) {
            this._armatures["delete"](armature);
          }
        };
        _proto.postUpdate = function postUpdate(dt) {
          if (!this._armatures) {
            return;
          }
          this._armatures.forEach(function (armature) {
            armature.updateAnimation(dt);
            armature.syncAttachedNode();
          });
        };
        _proto.prepareRenderData = function prepareRenderData() {
          if (!this._armatures) {
            return;
          }
          this._armatures.forEach(function (armature) {
            armature.markForUpdateRenderData();
          });
        };
        return ArmatureSystem;
      }(System);
      ArmatureSystem.ID = 'ARMATURE';
      ArmatureSystem._instance = void 0;
      legacyCC.internal.ArmatureSystem = ArmatureSystem;

      var _dec$1r, _dec2$1k, _class$1o, _class2$1m, _initializer$1j, _initializer2$1c, _dec3$12, _dec4$P, _dec5$L, _dec6$x, _dec7$p, _dec8$i, _dec9$f, _class4$7, _class5$8, _initializer3$X, _initializer4$P, _initializer5$H, _initializer6$A, _initializer7$t, _initializer8$p, _initializer9$l, _initializer10$j, _initializer11$j, _initializer12$h, _initializer13$e, _initializer14$b, _initializer15$9, _initializer16$9, _class6$3;
      var DefaultArmaturesEnum;
      (function (DefaultArmaturesEnum) {
        DefaultArmaturesEnum[DefaultArmaturesEnum["default"] = -1] = "default";
      })(DefaultArmaturesEnum || (DefaultArmaturesEnum = {}));
      ccenum(DefaultArmaturesEnum);
      var DefaultAnimsEnum$1;
      (function (DefaultAnimsEnum) {
        DefaultAnimsEnum[DefaultAnimsEnum["<None>"] = 0] = "<None>";
      })(DefaultAnimsEnum$1 || (DefaultAnimsEnum$1 = {}));
      ccenum(DefaultAnimsEnum$1);
      var DefaultCacheMode;
      (function (DefaultCacheMode) {
        DefaultCacheMode[DefaultCacheMode["REALTIME"] = 0] = "REALTIME";
      })(DefaultCacheMode || (DefaultCacheMode = {}));
      ccenum(DefaultAnimsEnum$1);
      var timeScale$1 = 1;
      var AnimationCacheMode$1;
      (function (AnimationCacheMode) {
        AnimationCacheMode[AnimationCacheMode["REALTIME"] = 0] = "REALTIME";
        AnimationCacheMode[AnimationCacheMode["SHARED_CACHE"] = 1] = "SHARED_CACHE";
        AnimationCacheMode[AnimationCacheMode["PRIVATE_CACHE"] = 2] = "PRIVATE_CACHE";
      })(AnimationCacheMode$1 || (AnimationCacheMode$1 = {}));
      ccenum(AnimationCacheMode$1);
      var ccclass$h = ccclass$M,
        serializable$3 = serializable$p,
        type$4 = type$d,
        override = override$1;
      var DragonBoneSocket = (_dec$1r = ccclass$h('dragonBones.ArmatureDisplay.DragonBoneSocket'), _dec2$1k = type$4(Node$1), _dec$1r(_class$1o = (_class2$1m = function DragonBoneSocket(path, target) {
        if (path === void 0) {
          path = '';
        }
        if (target === void 0) {
          target = null;
        }
        this.path = _initializer$1j && _initializer$1j();
        this.target = _initializer2$1c && _initializer2$1c();
        this.boneIndex = null;
        this.path = path;
        this.target = target;
      }, (_initializer$1j = applyDecoratedInitializer(_class2$1m.prototype, "path", [serializable$3], function () {
        return '';
      }), _initializer2$1c = applyDecoratedInitializer(_class2$1m.prototype, "target", [_dec2$1k, serializable$3], function () {
        return null;
      })), _class2$1m)) || _class$1o);
      setClassAlias(DragonBoneSocket, 'dragonBones.ArmatureDisplay.DragonBoneSocket');
      var ArmatureDisplay = (_dec3$12 = ccclass$h('dragonBones.ArmatureDisplay'), _dec4$P = type$4(DragonBonesAsset), _dec5$L = type$4(DragonBonesAtlasAsset), _dec6$x = type$4(DefaultArmaturesEnum), _dec7$p = type$4(DefaultAnimsEnum$1), _dec8$i = type$4([DragonBoneSocket]), _dec9$f = type$4(Material), _dec3$12(_class4$7 = (_class5$8 = (_class6$3 = function (_UIRenderer) {
        _inheritsLoose(ArmatureDisplay, _UIRenderer);
        var _proto = ArmatureDisplay.prototype;
        _proto.requestDrawInfo = function requestDrawInfo(idx) {
          if (!this._drawInfoList[idx]) {
            this._drawInfoList[idx] = new RenderDrawInfo();
          }
          return this._drawInfoList[idx];
        };
        function ArmatureDisplay() {
          var _this;
          _this = _UIRenderer.call(this) || this;
          _this.playTimes = _initializer3$X && _initializer3$X();
          _this.premultipliedAlpha = _initializer4$P && _initializer4$P();
          _this._armature = null;
          _this.attachUtil = void 0;
          _this._defaultArmatureIndexValue = _initializer5$H && _initializer5$H();
          _this._dragonAsset = _initializer6$A && _initializer6$A();
          _this._dragonAtlasAsset = _initializer7$t && _initializer7$t();
          _this._armatureName = _initializer8$p && _initializer8$p();
          _this._animationName = _initializer9$l && _initializer9$l();
          _this._animationIndexValue = _initializer10$j && _initializer10$j();
          _this._preCacheMode = -1;
          _this._cacheMode = AnimationCacheMode$1.REALTIME;
          _this._defaultCacheModeValue = _initializer11$j && _initializer11$j();
          _this._timeScale = _initializer12$h && _initializer12$h();
          _this._playTimes = _initializer13$e && _initializer13$e();
          _this._debugBones = _initializer14$b && _initializer14$b();
          _this._enableBatch = _initializer15$9 && _initializer15$9();
          _this._debugDraw = null;
          _this._armatureKey = '';
          _this._accTime = 0;
          _this._playCount = 0;
          _this._frameCache = null;
          _this._curFrame = null;
          _this._playing = false;
          _this._armatureCache = null;
          _this._eventTarget = void 0;
          _this._factory = null;
          _this._displayProxy = null;
          _this._drawIdx = 0;
          _this._drawList = new RecyclePool(function () {
            return {
              material: null,
              texture: null,
              indexOffset: 0,
              indexCount: 0
            };
          }, 1);
          _this.maxVertexCount = 0;
          _this.maxIndexCount = 0;
          _this._materialCache = {};
          _this._enumArmatures = Enum({});
          _this._enumAnimations = Enum({});
          _this._socketNodes = new Map();
          _this._cachedSockets = new Map();
          _this._sockets = _initializer16$9 && _initializer16$9();
          _this._inited = void 0;
          _this._drawInfoList = [];
          _this._cacheModeEnum = void 0;
          _this._eventTarget = new EventTarget();
          _this._inited = false;
          _this.attachUtil = new AttachUtil$1();
          _this.initFactory();
          setPropertyEnumType(_assertThisInitialized(_this), '_animationIndex', _this._enumAnimations);
          setPropertyEnumType(_assertThisInitialized(_this), '_defaultArmatureIndex', _this._enumArmatures);
          _this._useVertexOpacity = true;
          return _this;
        }
        _proto.initFactory = function initFactory() {
          this._factory = CCFactory.getInstance();
        };
        _proto.onLoad = function onLoad() {
          _UIRenderer.prototype.onLoad.call(this);
        };
        _proto._requestDrawData = function _requestDrawData(material, texture, indexOffset, indexCount) {
          var draw = this._drawList.add();
          draw.material = material;
          draw.texture = texture;
          draw.indexOffset = indexOffset;
          draw.indexCount = indexCount;
          return draw;
        };
        _proto.destroyRenderData = function destroyRenderData() {
          this._drawList.reset();
          _UIRenderer.prototype.destroyRenderData.call(this);
        };
        _proto.getMaterialTemplate = function getMaterialTemplate() {
          if (this.customMaterial !== null) return this.customMaterial;
          if (this.material) return this.material;
          this.updateMaterial();
          return this.material;
        };
        _proto.getMaterialForBlend = function getMaterialForBlend(src, dst) {
          var key = src + "/" + dst;
          var inst = this._materialCache[key];
          if (inst) {
            return inst;
          }
          var material = this.getMaterialTemplate();
          var matInfo = {
            parent: material,
            subModelIdx: 0,
            owner: this
          };
          inst = new MaterialInstance(matInfo);
          inst.recompileShaders({
            TWO_COLORED: false,
            USE_LOCAL: false
          });
          this._materialCache[key] = inst;
          inst.overridePipelineStates({
            blendState: {
              targets: [{
                blendSrc: src,
                blendDst: dst
              }]
            }
          });
          return inst;
        };
        _proto._updateBuiltinMaterial = function _updateBuiltinMaterial() {
          var material = builtinResMgr.get('default-spine-material');
          return material;
        };
        _proto.updateMaterial = function updateMaterial() {
          var mat;
          if (this._customMaterial) mat = this._customMaterial;else mat = this._updateBuiltinMaterial();
          this.setSharedMaterial(mat, 0);
          this._cleanMaterialCache();
        };
        _proto._render = function _render(batcher) {
          var indicesCount = 0;
          if (this.renderData && this._drawList) {
            var rd = this.renderData;
            var chunk = rd.chunk;
            var accessor = chunk.vertexAccessor;
            var meshBuffer = rd.getMeshBuffer();
            var origin = meshBuffer.indexOffset;
            for (var i = 0; i < this._drawList.length; i++) {
              this._drawIdx = i;
              var dc = this._drawList.data[i];
              if (dc.texture) {
                batcher.commitMiddleware(this, meshBuffer, origin + dc.indexOffset, dc.indexCount, dc.texture, dc.material, this._enableBatch);
              }
              indicesCount += dc.indexCount;
            }
            var subIndices = rd.indices.subarray(0, indicesCount);
            accessor.appendIndices(chunk.bufferId, subIndices);
          }
        };
        _proto.__preload = function __preload() {
          _UIRenderer.prototype.__preload.call(this);
          this._init();
        };
        _proto._init = function _init() {
          this._cacheMode = this._defaultCacheMode;
          if (this._inited) return;
          this._inited = true;
          this._parseDragonAtlasAsset();
          this._refresh();
          var children = this.node.children;
          for (var i = 0, n = children.length; i < n; i++) {
            var child = children[i];
            if (child && child.name === 'DEBUG_DRAW_NODE') {
              child.destroy();
            }
          }
          this._updateDebugDraw();
          this._indexBoneSockets();
          this._updateSocketBindings();
        };
        _proto.getArmatureKey = function getArmatureKey() {
          return this._armatureKey;
        };
        _proto.setAnimationCacheMode = function setAnimationCacheMode(cacheMode) {
          if (this._preCacheMode !== cacheMode) {
            this._cacheMode = cacheMode;
            this._buildArmature();
            if (this._armature && !this.isAnimationCached()) {
              this._factory._dragonBones.clock.add(this._armature);
            }
            this._updateSocketBindings();
            this.markForUpdateRenderData();
          }
        };
        _proto.isAnimationCached = function isAnimationCached() {
          return this._cacheMode !== AnimationCacheMode$1.REALTIME;
        };
        _proto.onEnable = function onEnable() {
          _UIRenderer.prototype.onEnable.call(this);
          if (this._armature && !this.isAnimationCached()) {
            this._factory._dragonBones.clock.add(this._armature);
          }
          this._flushAssembler();
          ArmatureSystem.getInstance().add(this);
        };
        _proto.onDisable = function onDisable() {
          _UIRenderer.prototype.onDisable.call(this);
          if (this._armature && !this.isAnimationCached()) {
            this._factory._dragonBones.clock.remove(this._armature);
          }
          ArmatureSystem.getInstance().remove(this);
        };
        _proto._emitCacheCompleteEvent = function _emitCacheCompleteEvent() {
          this._eventTarget.emit(EventObject.LOOP_COMPLETE);
          this._eventTarget.emit(EventObject.COMPLETE);
        };
        _proto.updateAnimation = function updateAnimation(dt) {
          this.markForUpdateRenderData();
          if (!this.isAnimationCached()) return;
          if (!this._frameCache) return;
          var frameCache = this._frameCache;
          if (!frameCache.isInited()) {
            return;
          }
          var frames = frameCache.frames;
          if (!this._playing) {
            if (frameCache.isInvalid()) {
              frameCache.updateToFrame();
              this._curFrame = frames[frames.length - 1];
              if (this.renderData && (this.renderData.vertexCount < frameCache.maxVertexCount || this.renderData.indexCount < frameCache.maxIndexCount)) {
                this.maxVertexCount = frameCache.maxVertexCount > this.maxVertexCount ? frameCache.maxVertexCount : this.maxVertexCount;
                this.maxIndexCount = frameCache.maxIndexCount > this.maxIndexCount ? frameCache.maxIndexCount : this.maxIndexCount;
                this.renderData.resize(this.maxVertexCount, this.maxIndexCount);
                if (!this.renderData.indices || this.maxIndexCount > this.renderData.indices.length) {
                  this.renderData.indices = new Uint16Array(this.maxIndexCount);
                }
              }
            }
            return;
          }
          var frameTime = ArmatureCache.FrameTime;
          if (this._accTime === 0 && this._playCount === 0) {
            this._eventTarget.emit(EventObject.START);
          }
          var globalTimeScale = timeScale$1;
          this._accTime += dt * this.timeScale * globalTimeScale;
          var frameIdx = Math.floor(this._accTime / frameTime);
          if (!frameCache.isCompleted) {
            frameCache.updateToFrame(frameIdx);
            if (this.renderData && (this.renderData.vertexCount < frameCache.maxVertexCount || this.renderData.indexCount < frameCache.maxIndexCount)) {
              this.maxVertexCount = frameCache.maxVertexCount > this.maxVertexCount ? frameCache.maxVertexCount : this.maxVertexCount;
              this.maxIndexCount = frameCache.maxIndexCount > this.maxIndexCount ? frameCache.maxIndexCount : this.maxIndexCount;
              this.renderData.resize(this.maxVertexCount, this.maxIndexCount);
              if (!this.renderData.indices || this.maxIndexCount > this.renderData.indices.length) {
                this.renderData.indices = new Uint16Array(this.maxIndexCount);
              }
            }
          }
          if (frameCache.isCompleted && frameIdx >= frames.length) {
            this._playCount++;
            if (this.playTimes > 0 && this._playCount >= this.playTimes) {
              this._curFrame = frames[frames.length - 1];
              this._accTime = 0;
              this._playing = false;
              this._playCount = 0;
              this._emitCacheCompleteEvent();
              this.attachUtil._syncAttachedNode();
              return;
            }
            this._accTime = 0;
            frameIdx = 0;
            this._emitCacheCompleteEvent();
          }
          this._curFrame = frames[frameIdx];
          this.attachUtil._syncAttachedNode();
        };
        _proto.onDestroy = function onDestroy() {
          this._materialInstances = this._materialInstances.filter(function (instance) {
            return !!instance;
          });
          this._inited = false;
          {
            if (this._cacheMode === AnimationCacheMode$1.PRIVATE_CACHE) {
              this._armatureCache.dispose();
              this._armatureCache = null;
              this._armature = null;
            } else if (this._cacheMode === AnimationCacheMode$1.SHARED_CACHE) {
              this._armatureCache = null;
              this._armature = null;
            } else if (this._armature) {
              this._armature.dispose();
              this._armature = null;
            }
          }
          this._drawList.destroy();
          _UIRenderer.prototype.onDestroy.call(this);
        };
        _proto._updateDebugDraw = function _updateDebugDraw() {
          if (this.debugBones) {
            if (!this._debugDraw) {
              var debugDrawNode = new Node$1('DEBUG_DRAW_NODE');
              debugDrawNode.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
              var debugDraw = debugDrawNode.addComponent(Graphics);
              debugDraw.lineWidth = 1;
              debugDraw.strokeColor = new Color$1(255, 0, 0, 255);
              this._debugDraw = debugDraw;
            }
            this._debugDraw.node.parent = this.node;
          } else if (this._debugDraw) {
            this._debugDraw.node.parent = null;
          }
          this.markForUpdateRenderData();
        };
        _proto._updateBatch = function _updateBatch() {
          this._cleanMaterialCache();
          this.markForUpdateRenderData();
        };
        _proto._buildArmature = function _buildArmature() {
          if (!this.dragonAsset || !this.dragonAtlasAsset || !this.armatureName) return;
          if (this._armature) {
            {
              if (this._preCacheMode === AnimationCacheMode$1.PRIVATE_CACHE) {
                this._armatureCache.dispose();
              } else if (this._preCacheMode === AnimationCacheMode$1.REALTIME) {
                this._armature.dispose();
              }
            }
            this._armatureCache = null;
            this._armature = null;
            this._displayProxy = null;
            this._frameCache = null;
            this._curFrame = null;
            this._playing = false;
            this._preCacheMode = -1;
          }
          {
            if (this._cacheMode === AnimationCacheMode$1.SHARED_CACHE) {
              this._armatureCache = ArmatureCache.sharedCache;
            } else if (this._cacheMode === AnimationCacheMode$1.PRIVATE_CACHE) {
              this._armatureCache = new ArmatureCache();
              this._armatureCache.enablePrivateMode();
            }
          }
          var atlasUUID = this.dragonAtlasAsset._uuid;
          this._armatureKey = this.dragonAsset.init(this._factory, atlasUUID);
          if (this.isAnimationCached()) {
            this._armature = this._armatureCache.getArmatureCache(this.armatureName, this._armatureKey, atlasUUID);
            if (!this._armature) {
              this._cacheMode = AnimationCacheMode$1.REALTIME;
            }
          }
          this._preCacheMode = this._cacheMode;
          if (this._cacheMode === AnimationCacheMode$1.REALTIME) {
            this._displayProxy = this._factory.buildArmatureDisplay(this.armatureName, this._armatureKey, '', atlasUUID);
            if (!this._displayProxy) return;
            this._displayProxy._ccNode = this.node;
            this._displayProxy._ccComponent = this;
            this._displayProxy.setEventTarget(this._eventTarget);
            this._armature = this._displayProxy._armature;
            this._armature.animation.timeScale = this.timeScale;
          }
          if (this._cacheMode !== AnimationCacheMode$1.REALTIME && this.debugBones) {
            console.warn('Debug bones is invalid in cached mode');
          }
          if (this._armature) {
            var armatureData = this._armature.armatureData;
            var aabb = armatureData.aabb;
            this.node._uiProps.uiTransformComp.setContentSize(aabb.width, aabb.height);
          }
          this.attachUtil.init(this);
          if (this.animationName) {
            this.playAnimation(this.animationName, this.playTimes);
          }
          this._flushAssembler();
        };
        _proto.querySockets = function querySockets() {
          if (!this._armature) {
            return [];
          }
          if (this._cachedSockets.size === 0) {
            this._indexBoneSockets();
          }
          return Array.from(this._cachedSockets.keys()).sort();
        };
        _proto.querySocketPathByName = function querySocketPathByName(name) {
          var ret = [];
          for (var _iterator = _createForOfIteratorHelperLoose(this._cachedSockets.keys()), _step; !(_step = _iterator()).done;) {
            var _key = _step.value;
            if (_key.endsWith(name)) {
              ret.push(_key);
            }
          }
          return ret;
        };
        _proto._parseDragonAtlasAsset = function _parseDragonAtlasAsset() {
          if (this.dragonAtlasAsset) {
            this.dragonAtlasAsset.init(this._factory);
          }
        };
        _proto._refresh = function _refresh() {
          this._buildArmature();
          this._indexBoneSockets();
          this.markForUpdateRenderData();
        };
        _proto._updateCacheModeEnum = function _updateCacheModeEnum() {
          this._cacheModeEnum = Enum({});
          if (this._armature) {
            Object.assign(this._cacheModeEnum, AnimationCacheMode$1);
          } else {
            Object.assign(this._cacheModeEnum, DefaultCacheMode);
          }
          setPropertyEnumType(this, '_defaultCacheMode', this._cacheModeEnum);
        };
        _proto._updateAnimEnum = function _updateAnimEnum() {
          var animEnum;
          if (this.dragonAsset) {
            animEnum = this.dragonAsset.getAnimsEnum(this.armatureName);
          } else {
            animEnum = DefaultAnimsEnum$1;
          }
          this._enumAnimations = Enum({});
          Object.assign(this._enumAnimations, animEnum || DefaultAnimsEnum$1);
          Enum.update(this._enumAnimations);
          setPropertyEnumType(this, '_animationIndex', this._enumAnimations);
        };
        _proto._updateArmatureEnum = function _updateArmatureEnum() {
          var armatureEnum;
          if (this.dragonAsset) {
            armatureEnum = this.dragonAsset.getArmatureEnum();
          } else {
            armatureEnum = DefaultArmaturesEnum;
          }
          this._enumArmatures = Enum({});
          Object.assign(this._enumArmatures, armatureEnum || DefaultArmaturesEnum);
          Enum.update(this._enumArmatures);
          setPropertyEnumType(this, '_defaultArmatureIndex', this._enumArmatures);
        };
        _proto._indexBoneSockets = function _indexBoneSockets() {
          if (!this._armature) {
            return;
          }
          this._cachedSockets.clear();
          var nameToBone = this._cachedSockets;
          var cacheBoneName = function cacheBoneName(bi, bones, cache) {
            if (cache.has(bi)) {
              return cache.get(bi);
            }
            var bone = bones[bi];
            if (!bone.parent) {
              cache.set(bi, bone.name);
              bone.path = bone.name;
              return bone.name;
            }
            var name = cacheBoneName(bone.parent._boneIndex, bones, cache) + "/" + bone.name;
            cache.set(bi, name);
            bone.path = name;
            return name;
          };
          var walkArmature = function walkArmature(prefix, armature) {
            var bones = armature.getBones();
            var boneToName = new Map();
            for (var i = 0; i < bones.length; i++) {
              bones[i]._boneIndex = i;
            }
            for (var _i = 0; _i < bones.length; _i++) {
              cacheBoneName(_i, bones, boneToName);
            }
            for (var _iterator2 = _createForOfIteratorHelperLoose(boneToName.keys()), _step2; !(_step2 = _iterator2()).done;) {
              var bone = _step2.value;
              nameToBone.set("" + prefix + boneToName.get(bone), bone);
            }
            var slots = armature.getSlots();
            for (var _i2 = 0; _i2 < slots.length; _i2++) {
              if (slots[_i2].childArmature) {
                walkArmature(slots[_i2].name, slots[_i2].childArmature);
              }
            }
          };
          walkArmature('', this._armature);
        };
        _proto.playAnimation = function playAnimation(animName, playTimes) {
          this.playTimes = playTimes === undefined ? -1 : playTimes;
          this.animationName = animName;
          if (this.isAnimationCached()) {
            var cache = this._armatureCache.getAnimationCache(this._armatureKey, animName);
            if (!cache) {
              cache = this._armatureCache.initAnimationCache(this._armatureKey, animName);
            }
            if (cache) {
              this._accTime = 0;
              this._playCount = 0;
              this._frameCache = cache;
              if (this._sockets.length > 0) {
                this._frameCache.enableCacheAttachedInfo();
              }
              this._frameCache.updateToFrame(0);
              this._playing = true;
              this._curFrame = this._frameCache.frames[0];
            }
          } else if (this._armature) {
            return this._armature.animation.play(animName, this.playTimes);
          }
          this.markForUpdateRenderData();
          return null;
        };
        _proto.updateAnimationCache = function updateAnimationCache(animName) {
          if (!this.isAnimationCached()) return;
          this._armatureCache.updateAnimationCache(this._armatureKey, animName);
        };
        _proto.invalidAnimationCache = function invalidAnimationCache() {
          if (!this.isAnimationCached()) return;
          this._armatureCache.invalidAnimationCache(this._armatureKey);
        };
        _proto.getArmatureNames = function getArmatureNames() {
          var dragonBonesData = this._factory.getDragonBonesData(this._armatureKey);
          return dragonBonesData && dragonBonesData.armatureNames || [];
        };
        _proto.getAnimationNames = function getAnimationNames(armatureName) {
          var ret = [];
          var dragonBonesData = this._factory.getDragonBonesData(this._armatureKey);
          if (dragonBonesData) {
            var armatureData = dragonBonesData.getArmature(armatureName);
            if (armatureData) {
              for (var animName in armatureData.animations) {
                if (armatureData.animations.hasOwnProperty(animName)) {
                  ret.push(animName);
                }
              }
            }
          }
          return ret;
        };
        _proto.on = function on(eventType, listener, target) {
          this.addEventListener(eventType, listener, target);
        };
        _proto.off = function off(eventType, listener, target) {
          this.removeEventListener(eventType, listener, target);
        };
        _proto.once = function once(eventType, listener, target) {
          this._eventTarget.once(eventType, listener, target);
        };
        _proto.addEventListener = function addEventListener(eventType, listener, target) {
          this._eventTarget.on(eventType, listener, target);
        };
        _proto.removeEventListener = function removeEventListener(eventType, listener, target) {
          this._eventTarget.off(eventType, listener, target);
        };
        _proto.buildArmature = function buildArmature(armatureName, node) {
          return this._factory.createArmatureNode(this, armatureName, node);
        };
        _proto.armature = function armature() {
          return this._armature;
        };
        _proto._flushAssembler = function _flushAssembler() {
          var assembler = ArmatureDisplay.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
          }
          if (this._armature && this._assembler) {
            this._renderData = this._assembler.createData(this);
            if (this._renderData) {
              this.maxVertexCount = this._renderData.vertexCount;
              this.maxIndexCount = this._renderData.indexCount;
            }
            this.markForUpdateRenderData();
            this._updateColor();
          }
        };
        _proto._updateSocketBindings = function _updateSocketBindings() {
          if (!this._armature) return;
          this._socketNodes.clear();
          for (var i = 0, l = this._sockets.length; i < l; i++) {
            var socket = this._sockets[i];
            if (socket.path && socket.target) {
              var bone = this._cachedSockets.get(socket.path);
              if (!bone) {
                console.error("Skeleton data does not contain path " + socket.path);
                continue;
              }
              socket.boneIndex = bone;
              this._socketNodes.set(socket.path, socket.target);
            }
          }
        };
        _proto._verifySockets = function _verifySockets(sockets) {
          for (var i = 0, l = sockets.length; i < l; i++) {
            var target = sockets[i].target;
            if (target) {
              if (!target.parent || target.parent !== this.node) {
                console.error("Target node " + target.name + " is expected to be a direct child of " + this.node.name);
                continue;
              }
            }
          }
        };
        _proto._cleanMaterialCache = function _cleanMaterialCache() {
          for (var val in this._materialCache) {
            this._materialCache[val].destroy();
          }
          this._materialCache = {};
        };
        _proto.createRenderEntity = function createRenderEntity() {
          var renderEntity = new RenderEntity(RenderEntityType.DYNAMIC);
          renderEntity.setUseLocal(false);
          return renderEntity;
        };
        _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
          if (enable === void 0) {
            enable = true;
          }
          _UIRenderer.prototype.markForUpdateRenderData.call(this, enable);
          if (this._debugDraw) {
            this._debugDraw.markForUpdateRenderData(enable);
          }
        };
        _proto.syncAttachedNode = function syncAttachedNode() {
          this.attachUtil._syncAttachedNode();
        };
        _createClass(ArmatureDisplay, [{
          key: "dragonAsset",
          get: function get() {
            return this._dragonAsset;
          },
          set: function set(value) {
            this._dragonAsset = value;
            this.destroyRenderData();
            this._refresh();
          }
        }, {
          key: "dragonAtlasAsset",
          get: function get() {
            return this._dragonAtlasAsset;
          },
          set: function set(value) {
            this._dragonAtlasAsset = value;
            this._parseDragonAtlasAsset();
            this._refresh();
          }
        }, {
          key: "armatureName",
          get: function get() {
            return this._armatureName;
          },
          set: function set(name) {
            this._armatureName = name;
            var animNames = this.getAnimationNames(this._armatureName);
            if (!this.animationName || animNames.indexOf(this.animationName) < 0) {
              {
                this.animationName = '';
              }
            }
            if (this._armature && !this.isAnimationCached()) {
              this._factory._dragonBones.clock.remove(this._armature);
            }
            this._refresh();
            if (this._armature && !this.isAnimationCached()) {
              this._factory._dragonBones.clock.add(this._armature);
            }
          }
        }, {
          key: "animationName",
          get: function get() {
            return this._animationName;
          },
          set: function set(value) {
            this._animationName = value;
          }
        }, {
          key: "_defaultArmatureIndex",
          get: function get() {
            return this._defaultArmatureIndexValue;
          },
          set: function set(value) {
            this._defaultArmatureIndexValue = value;
            var armatureName = '';
            if (this.dragonAsset) {
              var armaturesEnum;
              if (this.dragonAsset) {
                armaturesEnum = this.dragonAsset.getArmatureEnum();
              }
              if (!armaturesEnum) {
                errorID(7400, this.name);
                return;
              }
              armatureName = armaturesEnum[this._defaultArmatureIndex];
            }
            if (armatureName !== undefined) {
              this.armatureName = armatureName;
            } else {
              errorID(7401, this.name);
            }
            this.markForUpdateRenderData();
          }
        }, {
          key: "_animationIndex",
          get: function get() {
            return this._animationIndexValue;
          },
          set: function set(value) {
            this._animationIndexValue = value;
            if (this._animationIndex === 0) {
              this.animationName = '';
              return;
            }
            var animsEnum;
            if (this.dragonAsset) {
              animsEnum = this.dragonAsset.getAnimsEnum(this.armatureName);
            }
            if (!animsEnum) {
              return;
            }
            var animName = animsEnum[this._animationIndex];
            if (animName !== undefined) {
              this.playAnimation(animName, this.playTimes);
            } else {
              errorID(7402, this.name);
            }
          }
        }, {
          key: "_defaultCacheMode",
          get: function get() {
            return this._defaultCacheModeValue;
          },
          set: function set(value) {
            this._defaultCacheModeValue = value;
            if (this._defaultCacheMode !== AnimationCacheMode$1.REALTIME) {
              if (this._armature && !ArmatureCache.canCache(this._armature)) {
                this._defaultCacheMode = AnimationCacheMode$1.REALTIME;
                console.warn('Animation cache mode doesn\'t support skeletal nesting');
                return;
              }
            }
            this.setAnimationCacheMode(this._defaultCacheMode);
          }
        }, {
          key: "timeScale",
          get: function get() {
            return this._timeScale;
          },
          set: function set(value) {
            this._timeScale = value;
            if (this._armature && !this.isAnimationCached()) {
              this._armature.animation.timeScale = this.timeScale;
            }
          }
        }, {
          key: "debugBones",
          get: function get() {
            return this._debugBones;
          },
          set: function set(value) {
            this._debugBones = value;
            this._updateDebugDraw();
          }
        }, {
          key: "enableBatch",
          get: function get() {
            return this._enableBatch;
          },
          set: function set(value) {
            if (value !== this._enableBatch) {
              this._enableBatch = value;
              this._updateBatch();
            }
          }
        }, {
          key: "sockets",
          get: function get() {
            return this._sockets;
          },
          set: function set(val) {
            this._verifySockets(val);
            this._sockets = val;
            this._updateSocketBindings();
            if (val.length > 0 && this._frameCache) {
              this._frameCache.enableCacheAttachedInfo();
            }
          }
        }, {
          key: "socketNodes",
          get: function get() {
            return this._socketNodes;
          }
        }, {
          key: "drawList",
          get: function get() {
            return this._drawList;
          }
        }, {
          key: "customMaterial",
          get: function get() {
            return this._customMaterial;
          },
          set: function set(val) {
            this._customMaterial = val;
            this.updateMaterial();
            this.markForUpdateRenderData();
          }
        }]);
        return ArmatureDisplay;
      }(UIRenderer), _class6$3.AnimationCacheMode = AnimationCacheMode$1, _class6$3), (_applyDecoratedDescriptor(_class5$8.prototype, "dragonAsset", [_dec4$P], Object.getOwnPropertyDescriptor(_class5$8.prototype, "dragonAsset"), _class5$8.prototype), _applyDecoratedDescriptor(_class5$8.prototype, "dragonAtlasAsset", [_dec5$L], Object.getOwnPropertyDescriptor(_class5$8.prototype, "dragonAtlasAsset"), _class5$8.prototype), _applyDecoratedDescriptor(_class5$8.prototype, "_defaultArmatureIndex", [_dec6$x], Object.getOwnPropertyDescriptor(_class5$8.prototype, "_defaultArmatureIndex"), _class5$8.prototype), _applyDecoratedDescriptor(_class5$8.prototype, "_animationIndex", [_dec7$p], Object.getOwnPropertyDescriptor(_class5$8.prototype, "_animationIndex"), _class5$8.prototype), _applyDecoratedDescriptor(_class5$8.prototype, "timeScale", [serializable$3], Object.getOwnPropertyDescriptor(_class5$8.prototype, "timeScale"), _class5$8.prototype), _initializer3$X = applyDecoratedInitializer(_class5$8.prototype, "playTimes", [serializable$3], function () {
        return -1;
      }), _initializer4$P = applyDecoratedInitializer(_class5$8.prototype, "premultipliedAlpha", [serializable$3], function () {
        return false;
      }), _applyDecoratedDescriptor(_class5$8.prototype, "sockets", [_dec8$i], Object.getOwnPropertyDescriptor(_class5$8.prototype, "sockets"), _class5$8.prototype), _initializer5$H = applyDecoratedInitializer(_class5$8.prototype, "_defaultArmatureIndexValue", [serializable$3], function () {
        return DefaultArmaturesEnum["default"];
      }), _initializer6$A = applyDecoratedInitializer(_class5$8.prototype, "_dragonAsset", [serializable$3], function () {
        return null;
      }), _initializer7$t = applyDecoratedInitializer(_class5$8.prototype, "_dragonAtlasAsset", [serializable$3], function () {
        return null;
      }), _initializer8$p = applyDecoratedInitializer(_class5$8.prototype, "_armatureName", [serializable$3], function () {
        return '';
      }), _initializer9$l = applyDecoratedInitializer(_class5$8.prototype, "_animationName", [serializable$3], function () {
        return '';
      }), _initializer10$j = applyDecoratedInitializer(_class5$8.prototype, "_animationIndexValue", [serializable$3], function () {
        return 0;
      }), _initializer11$j = applyDecoratedInitializer(_class5$8.prototype, "_defaultCacheModeValue", [serializable$3], function () {
        return AnimationCacheMode$1.REALTIME;
      }), _initializer12$h = applyDecoratedInitializer(_class5$8.prototype, "_timeScale", [serializable$3], function () {
        return 1;
      }), _initializer13$e = applyDecoratedInitializer(_class5$8.prototype, "_playTimes", [serializable$3], function () {
        return -1;
      }), _initializer14$b = applyDecoratedInitializer(_class5$8.prototype, "_debugBones", [serializable$3], function () {
        return false;
      }), _initializer15$9 = applyDecoratedInitializer(_class5$8.prototype, "_enableBatch", [serializable$3], function () {
        return false;
      }), _initializer16$9 = applyDecoratedInitializer(_class5$8.prototype, "_sockets", [serializable$3], function () {
        return [];
      }), _applyDecoratedDescriptor(_class5$8.prototype, "customMaterial", [override, _dec9$f], Object.getOwnPropertyDescriptor(_class5$8.prototype, "customMaterial"), _class5$8.prototype)), _class5$8)) || _class4$7);
      legacyCC.internal.ArmatureDisplay = ArmatureDisplay;

      var NEED_COLOR = 0x01;
      var _boneColor$1 = new Color$1(255, 0, 0, 255);
      var _slotColor$1 = new Color$1(0, 0, 255, 255);
      var _originColor$1 = new Color$1(0, 255, 0, 255);
      var _nodeR$1;
      var _nodeG$1;
      var _nodeB$1;
      var _nodeA$1;
      var _premultipliedAlpha$1;
      var _mustFlush;
      var _renderData;
      var _ibuf;
      var _vbuf;
      var _comp;
      var _vertexFloatCount = 0;
      var _vertexCount = 0;
      var _vertexOffset = 0;
      var _vertexFloatOffset = 0;
      var _indexCount = 0;
      var _indexOffset = 0;
      var _actualVCount = 0;
      var _actualICount = 0;
      var _prevDrawIndexOffset = 0;
      var LOCAL_FLOAT_PER_VERTEX = 4;
      var PER_VERTEX_SIZE = 3 + 2 + 4;
      var _c = new Float32Array(4);
      var _handleVal;
      var _tempVecPos = new Vec3(0, 0, 0);
      var _slotMat = new Mat4();
      var _currentMaterial = null;
      var _currentTexture = null;
      function _getSlotMaterial$1(tex, blendMode) {
        if (!tex) return null;
        var src;
        var dst;
        switch (blendMode) {
          case 1:
            src = _premultipliedAlpha$1 ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
            dst = BlendFactor.ONE;
            break;
          case 10:
            src = BlendFactor.DST_COLOR;
            dst = BlendFactor.ONE_MINUS_SRC_ALPHA;
            break;
          case 12:
            src = BlendFactor.ONE;
            dst = BlendFactor.ONE_MINUS_SRC_COLOR;
            break;
          case 0:
          default:
            src = _premultipliedAlpha$1 ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
            dst = BlendFactor.ONE_MINUS_SRC_ALPHA;
            break;
        }
        return _comp.getMaterialForBlend(src, dst);
      }
      function _handleColor(color, parentOpacity) {
        var _a = color.a * parentOpacity * _nodeA$1;
        var _multiply = _premultipliedAlpha$1 ? _a / 255.0 : 1.0;
        var _r = color.r * _nodeR$1 * _multiply / 255.0;
        var _g = color.g * _nodeG$1 * _multiply / 255.0;
        var _b = color.b * _nodeB$1 * _multiply / 255.0;
        _c[0] = _r;
        _c[1] = _g;
        _c[2] = _b;
        _c[3] = _premultipliedAlpha$1 ? 1.0 : _a / 255.0;
      }
      var _accessor$2 = null;
      var simple$2 = {
        accessor: _accessor$2,
        vCount: 32767,
        ensureAccessor: function ensureAccessor() {
          if (!_accessor$2) {
            var device = director.root.device;
            var batcher = director.root.batcher2D;
            var attributes = vfmtPosUvColor;
            this.accessor = _accessor$2 = new StaticVBAccessor(device, attributes, this.vCount);
            batcher.registerBufferAccessor(Number.parseInt('DRAGONBONES', 36), _accessor$2);
          }
          return this.accessor;
        },
        createData: function createData(comp) {
          var rd = comp.renderData;
          if (!rd) {
            this.ensureAccessor();
            var slots = comp._armature._slots;
            var vCount = 0;
            var iCount = 0;
            for (var i = 0; i < slots.length; ++i) {
              var slot = slots[i];
              var remainder = slot._localVertices.length % 4;
              if (remainder === 0) {
                vCount += slot._localVertices.length / LOCAL_FLOAT_PER_VERTEX;
              } else {
                vCount += (slot._localVertices.length - remainder) / LOCAL_FLOAT_PER_VERTEX + 1;
              }
              iCount += slot._indices.length;
            }
            rd = RenderData.add(vfmtPosUvColor, this.accessor);
            rd.resize(vCount, iCount);
            if (!rd.indices || iCount !== rd.indices.length) {
              rd.indices = new Uint16Array(iCount);
            }
          }
          return rd;
        },
        updateRenderData: function updateRenderData(comp, batcher) {
          _comp = comp;
          var armature = comp._armature;
          if (armature) {
            updateComponentRenderData$1(comp);
          }
        },
        updateColor: function updateColor(comp) {
          if (!comp) return;
          _comp = comp;
          _comp.markForUpdateRenderData();
        }
      };
      function realTimeTraverse$1(armature, parentOpacity, worldMat) {
        var rd = _renderData;
        _vbuf = rd.chunk.vb;
        _ibuf = rd.indices;
        var slots = armature._slots;
        var material;
        var vertices;
        var indices;
        var slotColor;
        var slot;
        var cumulatedCount = 0;
        for (var i = 0, l = slots.length; i < l; i++) {
          slot = slots[i];
          slotColor = slot._color;
          if (!slot._visible || !slot._displayData) continue;
          if (worldMat) {
            Mat4.multiply(slot._worldMatrix, worldMat, slot._matrix);
          } else {
            Mat4.copy(slot._worldMatrix, slot._matrix);
          }
          if (slot.childArmature) {
            realTimeTraverse$1(slot.childArmature, slotColor.a / 255, slot._worldMatrix);
            continue;
          }
          material = _getSlotMaterial$1(slot.getTexture(), slot._blendMode);
          if (!material) {
            continue;
          }
          if (!_currentMaterial) _currentMaterial = material;
          var texture = slot.getTexture();
          if (_mustFlush || material.hash !== _currentMaterial.hash || texture && _currentTexture !== texture) {
            _mustFlush = false;
            var _cumulatedCount = _indexOffset - _prevDrawIndexOffset;
            if (_cumulatedCount > 0) {
              _comp._requestDrawData(_currentMaterial, _currentTexture, _prevDrawIndexOffset, _cumulatedCount);
              _prevDrawIndexOffset = _indexOffset;
            }
            _currentTexture = texture;
            _currentMaterial = material;
          }
          _handleColor(slotColor, parentOpacity);
          _slotMat.set(slot._worldMatrix);
          vertices = slot._localVertices;
          _vertexCount = vertices.length / LOCAL_FLOAT_PER_VERTEX;
          _vertexFloatCount = _vertexCount * PER_VERTEX_SIZE;
          indices = slot._indices;
          _indexCount = indices.length;
          var isResize = false;
          if (_vertexOffset + _vertexCount > _actualVCount) {
            _actualVCount = _vertexOffset + _vertexCount;
            isResize = true;
          }
          if (_indexOffset + _indexCount > _actualICount) {
            _actualICount = _indexOffset + _indexCount;
            isResize = true;
          }
          if (isResize) {
            var oldIndices = _ibuf;
            var oldChunkOffset = rd.chunk.vertexOffset;
            rd.resizeAndCopy(_actualVCount, _actualICount > rd.indexCount ? _actualICount : rd.indexCount);
            _vbuf = rd.chunk.vb;
            if (_actualICount > _ibuf.length) {
              _ibuf = rd.indices = new Uint16Array(_actualICount);
            }
            var correction = rd.chunk.vertexOffset - oldChunkOffset;
            for (var _i = 0; _i < _indexOffset; ++_i) {
              _ibuf[_i] = oldIndices[_i] + correction;
            }
          }
          for (var vi = 0, vl = vertices.length, v = _vertexFloatOffset; vi < vl; v += PER_VERTEX_SIZE) {
            _tempVecPos.x = vertices[vi++];
            _tempVecPos.y = vertices[vi++];
            _tempVecPos.z = 0;
            _tempVecPos.transformMat4(_slotMat);
            _vbuf[v] = _tempVecPos.x;
            _vbuf[v + 1] = _tempVecPos.y;
            _vbuf[v + 2] = _tempVecPos.z;
            _vbuf[v + 3] = vertices[vi++];
            _vbuf[v + 4] = vertices[vi++];
            _vbuf.set(_c, v + 5);
          }
          var chunkOffset = rd.chunk.vertexOffset;
          for (var _i2 = 0, il = indices.length, ii = _indexOffset; _i2 < il; _i2++, ii++) {
            _ibuf[ii] = _vertexOffset + indices[_i2] + chunkOffset;
          }
          _vertexFloatOffset += _vertexFloatCount;
          _vertexOffset += _vertexCount;
          _indexOffset += _indexCount;
          _vertexCount = 0;
          _indexCount = 0;
        }
        cumulatedCount = _indexOffset - _prevDrawIndexOffset;
        if (_currentTexture && cumulatedCount > 0) {
          _comp._requestDrawData(_currentMaterial, _currentTexture, _prevDrawIndexOffset, cumulatedCount);
          _prevDrawIndexOffset = _indexOffset;
        }
        if (_comp.maxIndexCount < _actualICount) {
          _comp.maxIndexCount = _actualICount;
        }
        if (_comp.maxVertexCount < _actualVCount) {
          _comp.maxVertexCount = _actualVCount;
        }
      }
      function cacheTraverse$1(frame, parentMat) {
        if (!frame) return;
        var segments = frame.segments;
        if (segments.length === 0) return;
        var material = null;
        var vertices = frame.vertices;
        var indices = frame.indices;
        var chunkOffset = 0;
        var frameVFOffset = 0;
        var frameIndexOffset = 0;
        var segVFCount = 0;
        var colorOffset = 0;
        var colors = frame.colors;
        var nowColor = colors[colorOffset++];
        var maxVFOffset = nowColor.vfOffset;
        _handleColor(nowColor, 1.0);
        var rd = _renderData;
        var vbuf = rd.chunk.vb;
        var ibuf = rd.indices;
        for (var i = 0, n = segments.length; i < n; i++) {
          var segInfo = segments[i];
          material = _getSlotMaterial$1(segInfo.tex, segInfo.blendMode);
          if (!material) continue;
          if (!_currentMaterial) _currentMaterial = material;
          if (_mustFlush || material.hash !== _currentMaterial.hash || segInfo.tex && segInfo.tex !== _currentTexture) {
            _mustFlush = false;
            var _cumulatedCount2 = _indexOffset - _prevDrawIndexOffset;
            if (_cumulatedCount2 > 0) {
              _comp._requestDrawData(_currentMaterial, _currentTexture, _prevDrawIndexOffset, _cumulatedCount2);
              _prevDrawIndexOffset = _indexOffset;
            }
            _currentMaterial = material;
            _currentTexture = segInfo.tex;
          }
          _vertexCount = segInfo.vertexCount;
          _indexCount = segInfo.indexCount;
          chunkOffset = rd.chunk.vertexOffset;
          for (var ii = _indexOffset, il = _indexOffset + _indexCount; ii < il; ii++) {
            ibuf[ii] = chunkOffset + _vertexOffset + indices[frameIndexOffset++];
          }
          segVFCount = segInfo.vfCount;
          var subArray = vertices.subarray(frameVFOffset, segVFCount);
          vbuf.set(subArray, frameVFOffset);
          var offset = 0;
          if (parentMat) {
            for (var _ii = 0, _il = _vertexCount; _ii < _il; _ii++) {
              _tempVecPos.x = vbuf[offset];
              _tempVecPos.y = vbuf[offset + 1];
              _tempVecPos.z = 0;
              _tempVecPos.transformMat4(parentMat);
              vbuf[offset] = _tempVecPos.x;
              vbuf[offset + 1] = _tempVecPos.y;
              vbuf[offset + 2] = _tempVecPos.z;
              offset += PER_VERTEX_SIZE;
            }
          }
          if (_handleVal & NEED_COLOR) {
            var frameColorOffset = frameVFOffset / 9 * 5;
            for (var _ii2 = frameVFOffset, iEnd = frameVFOffset + segVFCount; _ii2 < iEnd; _ii2 += PER_VERTEX_SIZE, frameColorOffset += 5) {
              if (frameColorOffset >= maxVFOffset) {
                nowColor = colors[colorOffset++];
                _handleColor(nowColor, 1.0);
                maxVFOffset = nowColor.vfOffset;
              }
              vbuf.set(_c, _ii2 + 5);
            }
          }
          frameVFOffset += segVFCount;
          _vertexOffset += _vertexCount;
          _indexOffset += _indexCount;
          _vertexCount = 0;
          _indexCount = 0;
        }
        var cumulatedCount = _indexOffset - _prevDrawIndexOffset;
        if (_currentTexture && cumulatedCount > 0) {
          _comp._requestDrawData(_currentMaterial, _currentTexture, _prevDrawIndexOffset, cumulatedCount);
        }
      }
      function updateComponentRenderData$1(comp, batcher) {
        var armature = comp._armature;
        if (!armature || comp.renderData === null) return;
        _mustFlush = true;
        _premultipliedAlpha$1 = comp.premultipliedAlpha;
        comp.drawList.reset();
        _comp = comp;
        comp.node;
        _renderData = comp.renderData;
        _comp = comp;
        _handleVal = 0;
        _currentMaterial = null;
        var nodeColor = comp.color;
        _nodeR$1 = nodeColor.r / 255;
        _nodeG$1 = nodeColor.g / 255;
        _nodeB$1 = nodeColor.b / 255;
        _nodeA$1 = comp.node._uiProps.opacity;
        if (nodeColor._val !== 0xffffffff) {
          _handleVal |= NEED_COLOR;
        }
        var worldMat = comp.node.getWorldMatrix();
        _vertexFloatCount = 0;
        _vertexOffset = 0;
        _vertexFloatOffset = 0;
        _indexCount = 0;
        _indexOffset = 0;
        _prevDrawIndexOffset = 0;
        _actualVCount = _comp.maxVertexCount;
        _actualICount = _comp.maxIndexCount;
        if (comp.isAnimationCached()) {
          cacheTraverse$1(comp._curFrame, worldMat);
        } else {
          realTimeTraverse$1(armature, 1.0, worldMat);
          var graphics = comp._debugDraw;
          if (comp.debugBones && graphics) {
            graphics.clear();
            graphics.lineWidth = 5;
            graphics.strokeColor = _boneColor$1;
            graphics.fillColor = _slotColor$1;
            var bones = armature.getBones();
            for (var i = 0, l = bones.length; i < l; i++) {
              var bone = bones[i];
              var boneLength = Math.max(bone.boneData.length, 5);
              var startX = bone.globalTransformMatrix.tx;
              var startY = bone.globalTransformMatrix.ty;
              var endX = startX + bone.globalTransformMatrix.a * boneLength;
              var endY = startY + bone.globalTransformMatrix.b * boneLength;
              graphics.moveTo(startX, startY);
              graphics.lineTo(endX, endY);
              graphics.stroke();
              graphics.circle(startX, startY, Math.PI * 2);
              graphics.fill();
              if (i === 0) {
                graphics.fillColor = _originColor$1;
              }
            }
          }
        }
        _accessor$2.getMeshBuffer(_renderData.chunk.bufferId).setDirty();
        _comp = undefined;
      }
      legacyCC.internal.DragonBonesAssembler = simple$2;

      var simpleDragonBoneAssembler = {
        getAssembler: function getAssembler() {
          return simple$2;
        }
      };
      ArmatureDisplay.Assembler = simpleDragonBoneAssembler;

      var ExtensionType;
      (function (ExtensionType) {
        ExtensionType[ExtensionType["FFD"] = 0] = "FFD";
        ExtensionType[ExtensionType["AdjustColor"] = 10] = "AdjustColor";
        ExtensionType[ExtensionType["BevelFilter"] = 11] = "BevelFilter";
        ExtensionType[ExtensionType["BlurFilter"] = 12] = "BlurFilter";
        ExtensionType[ExtensionType["DropShadowFilter"] = 13] = "DropShadowFilter";
        ExtensionType[ExtensionType["GlowFilter"] = 14] = "GlowFilter";
        ExtensionType[ExtensionType["GradientBevelFilter"] = 15] = "GradientBevelFilter";
        ExtensionType[ExtensionType["GradientGlowFilter"] = 16] = "GradientGlowFilter";
      })(ExtensionType || (ExtensionType = {}));
      var EventType$7;
      (function (EventType) {
        EventType[EventType["Frame"] = 0] = "Frame";
        EventType[EventType["Sound"] = 1] = "Sound";
      })(EventType$7 || (EventType$7 = {}));
      var AnimationFadeOutMode;
      (function (AnimationFadeOutMode) {
        AnimationFadeOutMode[AnimationFadeOutMode["None"] = 0] = "None";
        AnimationFadeOutMode[AnimationFadeOutMode["SameLayer"] = 1] = "SameLayer";
        AnimationFadeOutMode[AnimationFadeOutMode["SameGroup"] = 2] = "SameGroup";
        AnimationFadeOutMode[AnimationFadeOutMode["SameLayerAndGroup"] = 3] = "SameLayerAndGroup";
        AnimationFadeOutMode[AnimationFadeOutMode["All"] = 4] = "All";
      })(AnimationFadeOutMode || (AnimationFadeOutMode = {}));

      var index$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get ExtensionType () { return ExtensionType; },
        get EventType () { return EventType$7; },
        get AnimationFadeOutMode () { return AnimationFadeOutMode; },
        CCFactory: CCFactory,
        CCSlot: CCSlot,
        CCTextureAtlasData: CCTextureAtlasData,
        CCTextureData: CCTextureData,
        CCArmatureDisplay: CCArmatureDisplay,
        AnimationCache: AnimationCache$1,
        ArmatureCache: ArmatureCache,
        DragonBonesAsset: DragonBonesAsset,
        DragonBonesAtlasAsset: DragonBonesAtlasAsset,
        timeScale: timeScale$1,
        get AnimationCacheMode () { return AnimationCacheMode$1; },
        DragonBoneSocket: DragonBoneSocket,
        ArmatureDisplay: ArmatureDisplay,
        AttachUtil: AttachUtil$1,
        simpleDragonBoneAssembler: simpleDragonBoneAssembler,
        DragonBones: DragonBones,
        BaseObject: BaseObject,
        Matrix: Matrix,
        Transform: Transform,
        ColorTransform: ColorTransform,
        Point: Point$1,
        Rectangle: Rectangle,
        UserData: UserData,
        ActionData: ActionData,
        DragonBonesData: DragonBonesData,
        ArmatureData: ArmatureData,
        BoneData: BoneData,
        SurfaceData: SurfaceData,
        SlotData: SlotData,
        ConstraintData: ConstraintData,
        IKConstraintData: IKConstraintData,
        PathConstraintData: PathConstraintData,
        CanvasData: CanvasData,
        SkinData: SkinData,
        VerticesData: VerticesData,
        DisplayData: DisplayData,
        ImageDisplayData: ImageDisplayData,
        ArmatureDisplayData: ArmatureDisplayData,
        MeshDisplayData: MeshDisplayData,
        BoundingBoxDisplayData: BoundingBoxDisplayData,
        PathDisplayData: PathDisplayData,
        WeightData: WeightData,
        BoundingBoxData: BoundingBoxData,
        RectangleBoundingBoxData: RectangleBoundingBoxData,
        EllipseBoundingBoxData: EllipseBoundingBoxData,
        PolygonBoundingBoxData: PolygonBoundingBoxData,
        AnimationData: AnimationData,
        TimelineData: TimelineData,
        AnimationConfig: AnimationConfig,
        TextureAtlasData: TextureAtlasData,
        TextureData: TextureData,
        DeformVertices: DeformVertices,
        Armature: Armature,
        TransformObject: TransformObject,
        Bone: Bone,
        Surface: Surface,
        Slot: Slot,
        Constraint: Constraint$2,
        IKConstraint: IKConstraint,
        PathConstraint: PathConstraint,
        WorldClock: WorldClock,
        Animation: Animation$1,
        AnimationState: AnimationState,
        BonePose: BonePose,
        BlendState: BlendState,
        TimelineState: TimelineState,
        TweenTimelineState: TweenTimelineState,
        BoneTimelineState: BoneTimelineState,
        SlotTimelineState: SlotTimelineState,
        ConstraintTimelineState: ConstraintTimelineState,
        ActionTimelineState: ActionTimelineState,
        ZOrderTimelineState: ZOrderTimelineState,
        BoneAllTimelineState: BoneAllTimelineState,
        BoneTranslateTimelineState: BoneTranslateTimelineState,
        BoneRotateTimelineState: BoneRotateTimelineState,
        BoneScaleTimelineState: BoneScaleTimelineState,
        SurfaceTimelineState: SurfaceTimelineState,
        SlotDislayTimelineState: SlotDislayTimelineState,
        SlotColorTimelineState: SlotColorTimelineState,
        DeformTimelineState: DeformTimelineState,
        IKConstraintTimelineState: IKConstraintTimelineState,
        AnimationTimelineState: AnimationTimelineState,
        EventObject: EventObject,
        DataParser: DataParser,
        ObjectDataParser: ObjectDataParser,
        ActionFrame: ActionFrame,
        BinaryDataParser: BinaryDataParser,
        BaseFactory: BaseFactory,
        BuildArmaturePackage: BuildArmaturePackage,
        BinaryOffset: BinaryOffset,
        ArmatureType: ArmatureType,
        BoneType: BoneType,
        DisplayType: DisplayType,
        BoundingBoxType: BoundingBoxType,
        ActionType: ActionType,
        BlendMode: BlendMode,
        TweenType: TweenType,
        TimelineType: TimelineType
      });
      exports('eS', index$1);

      var WebGLDescriptorSet = function (_DescriptorSet) {
        _inheritsLoose(WebGLDescriptorSet, _DescriptorSet);
        function WebGLDescriptorSet() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _DescriptorSet.call.apply(_DescriptorSet, [this].concat(args)) || this;
          _this._gpuDescriptorSet = null;
          return _this;
        }
        var _proto = WebGLDescriptorSet.prototype;
        _proto.initialize = function initialize(info) {
          this._layout = info.layout;
          var _gpuDescriptorSetLayo = info.layout.gpuDescriptorSetLayout,
            bindings = _gpuDescriptorSetLayo.bindings,
            descriptorIndices = _gpuDescriptorSetLayo.descriptorIndices,
            descriptorCount = _gpuDescriptorSetLayo.descriptorCount;
          this._buffers = Array(descriptorCount).fill(null);
          this._textures = Array(descriptorCount).fill(null);
          this._samplers = Array(descriptorCount).fill(null);
          var gpuDescriptors = [];
          this._gpuDescriptorSet = {
            gpuDescriptors: gpuDescriptors,
            descriptorIndices: descriptorIndices
          };
          for (var i = 0; i < bindings.length; ++i) {
            var binding = bindings[i];
            for (var j = 0; j < binding.count; j++) {
              gpuDescriptors.push({
                type: binding.descriptorType,
                gpuBuffer: null,
                gpuTexture: null,
                gpuSampler: null
              });
            }
          }
        };
        _proto.destroy = function destroy() {
          this._layout = null;
          this._gpuDescriptorSet = null;
        };
        _proto.update = function update() {
          if (this._isDirty && this._gpuDescriptorSet) {
            var descriptors = this._gpuDescriptorSet.gpuDescriptors;
            for (var i = 0; i < descriptors.length; ++i) {
              if (descriptors[i].type & DESCRIPTOR_BUFFER_TYPE) {
                var buffer = this._buffers[i];
                if (buffer) {
                  descriptors[i].gpuBuffer = buffer.gpuBuffer || buffer.gpuBufferView;
                }
              } else if (descriptors[i].type & DESCRIPTOR_SAMPLER_TYPE) {
                if (this._textures[i]) {
                  descriptors[i].gpuTexture = this._textures[i].gpuTexture;
                }
                if (this._samplers[i]) {
                  descriptors[i].gpuSampler = this._samplers[i].gpuSampler;
                }
              }
            }
            this._isDirty = false;
          }
        };
        _createClass(WebGLDescriptorSet, [{
          key: "gpuDescriptorSet",
          get: function get() {
            return this._gpuDescriptorSet;
          }
        }]);
        return WebGLDescriptorSet;
      }(DescriptorSet);

      var WebGLEXT;
      (function (WebGLEXT) {
        WebGLEXT[WebGLEXT["RGBA16F_EXT"] = 34842] = "RGBA16F_EXT";
        WebGLEXT[WebGLEXT["RGB16F_EXT"] = 34843] = "RGB16F_EXT";
        WebGLEXT[WebGLEXT["RGBA32F_EXT"] = 34836] = "RGBA32F_EXT";
        WebGLEXT[WebGLEXT["FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT"] = 33297] = "FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT";
        WebGLEXT[WebGLEXT["UNSIGNED_NORMALIZED_EXT"] = 35863] = "UNSIGNED_NORMALIZED_EXT";
        WebGLEXT[WebGLEXT["UNSIGNED_INT_24_8_WEBGL"] = 34042] = "UNSIGNED_INT_24_8_WEBGL";
        WebGLEXT[WebGLEXT["HALF_FLOAT_OES"] = 36193] = "HALF_FLOAT_OES";
        WebGLEXT[WebGLEXT["SRGB_EXT"] = 35904] = "SRGB_EXT";
        WebGLEXT[WebGLEXT["SRGB_ALPHA_EXT"] = 35906] = "SRGB_ALPHA_EXT";
        WebGLEXT[WebGLEXT["SRGB8_ALPHA8_EXT"] = 35907] = "SRGB8_ALPHA8_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL";
        WebGLEXT[WebGLEXT["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_4x4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4x4_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_5x4_KHR"] = 37809] = "COMPRESSED_RGBA_ASTC_5x4_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_5x5_KHR"] = 37810] = "COMPRESSED_RGBA_ASTC_5x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_6x5_KHR"] = 37811] = "COMPRESSED_RGBA_ASTC_6x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_6x6_KHR"] = 37812] = "COMPRESSED_RGBA_ASTC_6x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_8x5_KHR"] = 37813] = "COMPRESSED_RGBA_ASTC_8x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_8x6_KHR"] = 37814] = "COMPRESSED_RGBA_ASTC_8x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_8x8_KHR"] = 37815] = "COMPRESSED_RGBA_ASTC_8x8_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_10x5_KHR"] = 37816] = "COMPRESSED_RGBA_ASTC_10x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_10x6_KHR"] = 37817] = "COMPRESSED_RGBA_ASTC_10x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_10x8_KHR"] = 37818] = "COMPRESSED_RGBA_ASTC_10x8_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_10x10_KHR"] = 37819] = "COMPRESSED_RGBA_ASTC_10x10_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_12x10_KHR"] = 37820] = "COMPRESSED_RGBA_ASTC_12x10_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_12x12_KHR"] = 37821] = "COMPRESSED_RGBA_ASTC_12x12_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR"] = 37840] = "COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR"] = 37841] = "COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR"] = 37842] = "COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR"] = 37843] = "COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR"] = 37844] = "COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR"] = 37845] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR"] = 37846] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR"] = 37847] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR"] = 37848] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR"] = 37849] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR"] = 37850] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR"] = 37851] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR"] = 37852] = "COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR"] = 37853] = "COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR";
      })(WebGLEXT || (WebGLEXT = {}));
      var WebGLDeviceManager = function () {
        function WebGLDeviceManager() {}
        WebGLDeviceManager.setInstance = function setInstance(instance) {
          WebGLDeviceManager._instance = instance;
        };
        _createClass(WebGLDeviceManager, null, [{
          key: "instance",
          get: function get() {
            return WebGLDeviceManager._instance;
          }
        }]);
        return WebGLDeviceManager;
      }();
      WebGLDeviceManager._instance = null;

      function GFXFormatToWebGLType$1(format, gl) {
        switch (format) {
          case Format.R8:
            return gl.UNSIGNED_BYTE;
          case Format.R8SN:
            return gl.BYTE;
          case Format.R8UI:
            return gl.UNSIGNED_BYTE;
          case Format.R8I:
            return gl.BYTE;
          case Format.R16F:
            return WebGLEXT.HALF_FLOAT_OES;
          case Format.R16UI:
            return gl.UNSIGNED_SHORT;
          case Format.R16I:
            return gl.SHORT;
          case Format.R32F:
            return gl.FLOAT;
          case Format.R32UI:
            return gl.UNSIGNED_INT;
          case Format.R32I:
            return gl.INT;
          case Format.RG8:
            return gl.UNSIGNED_BYTE;
          case Format.RG8SN:
            return gl.BYTE;
          case Format.RG8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RG8I:
            return gl.BYTE;
          case Format.RG16F:
            return WebGLEXT.HALF_FLOAT_OES;
          case Format.RG16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RG16I:
            return gl.SHORT;
          case Format.RG32F:
            return gl.FLOAT;
          case Format.RG32UI:
            return gl.UNSIGNED_INT;
          case Format.RG32I:
            return gl.INT;
          case Format.RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.SRGB8:
            return gl.UNSIGNED_BYTE;
          case Format.RGB8SN:
            return gl.BYTE;
          case Format.RGB8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RGB8I:
            return gl.BYTE;
          case Format.RGB16F:
            return WebGLEXT.HALF_FLOAT_OES;
          case Format.RGB16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RGB16I:
            return gl.SHORT;
          case Format.RGB32F:
            return gl.FLOAT;
          case Format.RGB32UI:
            return gl.UNSIGNED_INT;
          case Format.RGB32I:
            return gl.INT;
          case Format.BGRA8:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8:
            return gl.UNSIGNED_BYTE;
          case Format.SRGB8_A8:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8SN:
            return gl.BYTE;
          case Format.RGBA8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8I:
            return gl.BYTE;
          case Format.RGBA16F:
            return WebGLEXT.HALF_FLOAT_OES;
          case Format.RGBA16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RGBA16I:
            return gl.SHORT;
          case Format.RGBA32F:
            return gl.FLOAT;
          case Format.RGBA32UI:
            return gl.UNSIGNED_INT;
          case Format.RGBA32I:
            return gl.INT;
          case Format.R5G6B5:
            return gl.UNSIGNED_SHORT_5_6_5;
          case Format.R11G11B10F:
            return gl.FLOAT;
          case Format.RGB5A1:
            return gl.UNSIGNED_SHORT_5_5_5_1;
          case Format.RGBA4:
            return gl.UNSIGNED_SHORT_4_4_4_4;
          case Format.RGB10A2:
            return gl.UNSIGNED_BYTE;
          case Format.RGB10A2UI:
            return gl.UNSIGNED_INT;
          case Format.RGB9E5:
            return gl.UNSIGNED_BYTE;
          case Format.DEPTH:
            return gl.UNSIGNED_INT;
          case Format.DEPTH_STENCIL:
            return WebGLEXT.UNSIGNED_INT_24_8_WEBGL;
          case Format.BC1:
            return gl.UNSIGNED_BYTE;
          case Format.BC1_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC2:
            return gl.UNSIGNED_BYTE;
          case Format.BC2_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC3:
            return gl.UNSIGNED_BYTE;
          case Format.BC3_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC4:
            return gl.UNSIGNED_BYTE;
          case Format.BC4_SNORM:
            return gl.BYTE;
          case Format.BC5:
            return gl.UNSIGNED_BYTE;
          case Format.BC5_SNORM:
            return gl.BYTE;
          case Format.BC6H_SF16:
            return gl.FLOAT;
          case Format.BC6H_UF16:
            return gl.FLOAT;
          case Format.BC7:
            return gl.UNSIGNED_BYTE;
          case Format.BC7_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.ETC_RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_SRGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_RGB8_A1:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_SRGB8_A1:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_R11:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_R11SN:
            return gl.BYTE;
          case Format.EAC_RG11:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_RG11SN:
            return gl.BYTE;
          case Format.PVRTC_RGB2:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGBA2:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGB4:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGBA4:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC2_2BPP:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC2_4BPP:
            return gl.UNSIGNED_BYTE;
          case Format.ASTC_RGBA_4X4:
          case Format.ASTC_RGBA_5X4:
          case Format.ASTC_RGBA_5X5:
          case Format.ASTC_RGBA_6X5:
          case Format.ASTC_RGBA_6X6:
          case Format.ASTC_RGBA_8X5:
          case Format.ASTC_RGBA_8X6:
          case Format.ASTC_RGBA_8X8:
          case Format.ASTC_RGBA_10X5:
          case Format.ASTC_RGBA_10X6:
          case Format.ASTC_RGBA_10X8:
          case Format.ASTC_RGBA_10X10:
          case Format.ASTC_RGBA_12X10:
          case Format.ASTC_RGBA_12X12:
          case Format.ASTC_SRGBA_4X4:
          case Format.ASTC_SRGBA_5X4:
          case Format.ASTC_SRGBA_5X5:
          case Format.ASTC_SRGBA_6X5:
          case Format.ASTC_SRGBA_6X6:
          case Format.ASTC_SRGBA_8X5:
          case Format.ASTC_SRGBA_8X6:
          case Format.ASTC_SRGBA_8X8:
          case Format.ASTC_SRGBA_10X5:
          case Format.ASTC_SRGBA_10X6:
          case Format.ASTC_SRGBA_10X8:
          case Format.ASTC_SRGBA_10X10:
          case Format.ASTC_SRGBA_12X10:
          case Format.ASTC_SRGBA_12X12:
            return gl.UNSIGNED_BYTE;
          default:
            {
              return gl.UNSIGNED_BYTE;
            }
        }
      }
      function GFXFormatToWebGLInternalFormat$1(format, gl) {
        switch (format) {
          case Format.R5G6B5:
            return gl.RGB565;
          case Format.RGB5A1:
            return gl.RGB5_A1;
          case Format.RGBA4:
            return gl.RGBA4;
          case Format.RGBA16F:
            return WebGLEXT.RGBA16F_EXT;
          case Format.RGBA32F:
            return WebGLEXT.RGBA32F_EXT;
          case Format.SRGB8_A8:
            return WebGLEXT.SRGB8_ALPHA8_EXT;
          case Format.DEPTH:
            return gl.DEPTH_COMPONENT16;
          case Format.DEPTH_STENCIL:
            return gl.DEPTH_STENCIL;
          default:
            {
              error('Unsupported Format, convert to WebGL internal format failed.');
              return gl.RGBA;
            }
        }
      }
      function GFXFormatToWebGLFormat$1(format, gl) {
        switch (format) {
          case Format.A8:
            return gl.ALPHA;
          case Format.L8:
            return gl.LUMINANCE;
          case Format.LA8:
            return gl.LUMINANCE_ALPHA;
          case Format.RGB8:
            return gl.RGB;
          case Format.RGB16F:
            return gl.RGB;
          case Format.RGB32F:
            return gl.RGB;
          case Format.BGRA8:
            return gl.RGBA;
          case Format.RGBA8:
            return gl.RGBA;
          case Format.SRGB8_A8:
            return gl.RGBA;
          case Format.RGBA16F:
            return gl.RGBA;
          case Format.RGBA32F:
            return gl.RGBA;
          case Format.R5G6B5:
            return gl.RGB;
          case Format.RGB5A1:
            return gl.RGBA;
          case Format.RGBA4:
            return gl.RGBA;
          case Format.DEPTH:
            return gl.DEPTH_COMPONENT;
          case Format.DEPTH_STENCIL:
            return gl.DEPTH_STENCIL;
          case Format.BC1:
            return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT;
          case Format.BC1_ALPHA:
            return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT;
          case Format.BC1_SRGB:
            return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT;
          case Format.BC1_SRGB_ALPHA:
            return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
          case Format.BC2:
            return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT;
          case Format.BC2_SRGB:
            return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
          case Format.BC3:
            return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
          case Format.BC3_SRGB:
            return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
          case Format.ETC_RGB8:
            return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL;
          case Format.ETC2_RGB8:
            return WebGLEXT.COMPRESSED_RGB8_ETC2;
          case Format.ETC2_SRGB8:
            return WebGLEXT.COMPRESSED_SRGB8_ETC2;
          case Format.ETC2_RGB8_A1:
            return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_SRGB8_A1:
            return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_RGBA8:
            return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC;
          case Format.ETC2_SRGB8_A8:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
          case Format.EAC_R11:
            return WebGLEXT.COMPRESSED_R11_EAC;
          case Format.EAC_R11SN:
            return WebGLEXT.COMPRESSED_SIGNED_R11_EAC;
          case Format.EAC_RG11:
            return WebGLEXT.COMPRESSED_RG11_EAC;
          case Format.EAC_RG11SN:
            return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC;
          case Format.PVRTC_RGB2:
            return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGBA2:
            return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGB4:
            return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
          case Format.PVRTC_RGBA4:
            return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
          case Format.ASTC_RGBA_4X4:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR;
          case Format.ASTC_RGBA_5X4:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR;
          case Format.ASTC_RGBA_5X5:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR;
          case Format.ASTC_RGBA_6X5:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR;
          case Format.ASTC_RGBA_6X6:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR;
          case Format.ASTC_RGBA_8X5:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR;
          case Format.ASTC_RGBA_8X6:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR;
          case Format.ASTC_RGBA_8X8:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR;
          case Format.ASTC_RGBA_10X5:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR;
          case Format.ASTC_RGBA_10X6:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR;
          case Format.ASTC_RGBA_10X8:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR;
          case Format.ASTC_RGBA_10X10:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR;
          case Format.ASTC_RGBA_12X10:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR;
          case Format.ASTC_RGBA_12X12:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR;
          case Format.ASTC_SRGBA_4X4:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
          case Format.ASTC_SRGBA_5X4:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;
          case Format.ASTC_SRGBA_5X5:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;
          case Format.ASTC_SRGBA_6X5:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;
          case Format.ASTC_SRGBA_6X6:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;
          case Format.ASTC_SRGBA_8X5:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;
          case Format.ASTC_SRGBA_8X6:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;
          case Format.ASTC_SRGBA_8X8:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;
          case Format.ASTC_SRGBA_10X5:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;
          case Format.ASTC_SRGBA_10X6:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;
          case Format.ASTC_SRGBA_10X8:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;
          case Format.ASTC_SRGBA_10X10:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;
          case Format.ASTC_SRGBA_12X10:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;
          case Format.ASTC_SRGBA_12X12:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;
          default:
            {
              error('Unsupported Format, convert to WebGL format failed.');
              return gl.RGBA;
            }
        }
      }
      function GFXTypeToWebGLType$1(type, gl) {
        switch (type) {
          case Type$1.BOOL:
            return gl.BOOL;
          case Type$1.BOOL2:
            return gl.BOOL_VEC2;
          case Type$1.BOOL3:
            return gl.BOOL_VEC3;
          case Type$1.BOOL4:
            return gl.BOOL_VEC4;
          case Type$1.INT:
            return gl.INT;
          case Type$1.INT2:
            return gl.INT_VEC2;
          case Type$1.INT3:
            return gl.INT_VEC3;
          case Type$1.INT4:
            return gl.INT_VEC4;
          case Type$1.UINT:
            return gl.UNSIGNED_INT;
          case Type$1.FLOAT:
            return gl.FLOAT;
          case Type$1.FLOAT2:
            return gl.FLOAT_VEC2;
          case Type$1.FLOAT3:
            return gl.FLOAT_VEC3;
          case Type$1.FLOAT4:
            return gl.FLOAT_VEC4;
          case Type$1.MAT2:
            return gl.FLOAT_MAT2;
          case Type$1.MAT3:
            return gl.FLOAT_MAT3;
          case Type$1.MAT4:
            return gl.FLOAT_MAT4;
          case Type$1.SAMPLER2D:
            return gl.SAMPLER_2D;
          case Type$1.SAMPLER_CUBE:
            return gl.SAMPLER_CUBE;
          default:
            {
              error('Unsupported GLType, convert to GL type failed.');
              return Type$1.UNKNOWN;
            }
        }
      }
      function GFXTypeToTypedArrayCtor(type) {
        switch (type) {
          case Type$1.BOOL:
          case Type$1.BOOL2:
          case Type$1.BOOL3:
          case Type$1.BOOL4:
          case Type$1.INT:
          case Type$1.INT2:
          case Type$1.INT3:
          case Type$1.INT4:
          case Type$1.UINT:
            return Int32Array;
          case Type$1.FLOAT:
          case Type$1.FLOAT2:
          case Type$1.FLOAT3:
          case Type$1.FLOAT4:
          case Type$1.MAT2:
          case Type$1.MAT3:
          case Type$1.MAT4:
            return Float32Array;
          default:
            {
              error('Unsupported GLType, convert to TypedArrayConstructor failed.');
              return Float32Array;
            }
        }
      }
      function WebGLTypeToGFXType$1(glType, gl) {
        switch (glType) {
          case gl.BOOL:
            return Type$1.BOOL;
          case gl.BOOL_VEC2:
            return Type$1.BOOL2;
          case gl.BOOL_VEC3:
            return Type$1.BOOL3;
          case gl.BOOL_VEC4:
            return Type$1.BOOL4;
          case gl.INT:
            return Type$1.INT;
          case gl.INT_VEC2:
            return Type$1.INT2;
          case gl.INT_VEC3:
            return Type$1.INT3;
          case gl.INT_VEC4:
            return Type$1.INT4;
          case gl.UNSIGNED_INT:
            return Type$1.UINT;
          case gl.FLOAT:
            return Type$1.FLOAT;
          case gl.FLOAT_VEC2:
            return Type$1.FLOAT2;
          case gl.FLOAT_VEC3:
            return Type$1.FLOAT3;
          case gl.FLOAT_VEC4:
            return Type$1.FLOAT4;
          case gl.FLOAT_MAT2:
            return Type$1.MAT2;
          case gl.FLOAT_MAT3:
            return Type$1.MAT3;
          case gl.FLOAT_MAT4:
            return Type$1.MAT4;
          case gl.SAMPLER_2D:
            return Type$1.SAMPLER2D;
          case gl.SAMPLER_CUBE:
            return Type$1.SAMPLER_CUBE;
          default:
            {
              error('Unsupported GLType, convert to Type failed.');
              return Type$1.UNKNOWN;
            }
        }
      }
      function WebGLGetTypeSize$1(glType, gl) {
        switch (glType) {
          case gl.BOOL:
            return 4;
          case gl.BOOL_VEC2:
            return 8;
          case gl.BOOL_VEC3:
            return 12;
          case gl.BOOL_VEC4:
            return 16;
          case gl.INT:
            return 4;
          case gl.INT_VEC2:
            return 8;
          case gl.INT_VEC3:
            return 12;
          case gl.INT_VEC4:
            return 16;
          case gl.UNSIGNED_INT:
            return 4;
          case gl.FLOAT:
            return 4;
          case gl.FLOAT_VEC2:
            return 8;
          case gl.FLOAT_VEC3:
            return 12;
          case gl.FLOAT_VEC4:
            return 16;
          case gl.FLOAT_MAT2:
            return 16;
          case gl.FLOAT_MAT3:
            return 36;
          case gl.FLOAT_MAT4:
            return 64;
          case gl.SAMPLER_2D:
            return 4;
          case gl.SAMPLER_CUBE:
            return 4;
          default:
            {
              error('Unsupported GLType, get type failed.');
              return 0;
            }
        }
      }
      function WebGLGetComponentCount$1(glType, gl) {
        switch (glType) {
          case gl.FLOAT_MAT2:
            return 2;
          case gl.FLOAT_MAT3:
            return 3;
          case gl.FLOAT_MAT4:
            return 4;
          default:
            {
              return 1;
            }
        }
      }
      var WebGLCmpFuncs$1 = [0x0200, 0x0201, 0x0202, 0x0203, 0x0204, 0x0205, 0x0206, 0x0207];
      var WebGLStencilOps$1 = [0x0000, 0x1E00, 0x1E01, 0x1E02, 0x1E03, 0x150A, 0x8507, 0x8508];
      var WebGLBlendOps$1 = [0x8006, 0x800A, 0x800B, 0x8007, 0x8008];
      var WebGLBlendFactors$1 = [0x0000, 0x0001, 0x0302, 0x0304, 0x0303, 0x0305, 0x0300, 0x0306, 0x0301, 0x0307, 0x0308, 0x8001, 0x8002, 0x8003, 0x8004];
      var WebGLCmd;
      (function (WebGLCmd) {
        WebGLCmd[WebGLCmd["BEGIN_RENDER_PASS"] = 0] = "BEGIN_RENDER_PASS";
        WebGLCmd[WebGLCmd["END_RENDER_PASS"] = 1] = "END_RENDER_PASS";
        WebGLCmd[WebGLCmd["BIND_STATES"] = 2] = "BIND_STATES";
        WebGLCmd[WebGLCmd["DRAW"] = 3] = "DRAW";
        WebGLCmd[WebGLCmd["UPDATE_BUFFER"] = 4] = "UPDATE_BUFFER";
        WebGLCmd[WebGLCmd["COPY_BUFFER_TO_TEXTURE"] = 5] = "COPY_BUFFER_TO_TEXTURE";
        WebGLCmd[WebGLCmd["BLIT_TEXTURE"] = 6] = "BLIT_TEXTURE";
        WebGLCmd[WebGLCmd["COUNT"] = 7] = "COUNT";
      })(WebGLCmd || (WebGLCmd = {}));
      var WebGLCmdObject = function WebGLCmdObject(type) {
        this.cmdType = void 0;
        this.refCount = 0;
        this.cmdType = type;
      };
      var WebGLCmdBeginRenderPass = function (_WebGLCmdObject) {
        _inheritsLoose(WebGLCmdBeginRenderPass, _WebGLCmdObject);
        function WebGLCmdBeginRenderPass() {
          var _this;
          _this = _WebGLCmdObject.call(this, WebGLCmd.BEGIN_RENDER_PASS) || this;
          _this.gpuRenderPass = null;
          _this.gpuFramebuffer = null;
          _this.renderArea = new Rect();
          _this.clearFlag = ClearFlagBit.NONE;
          _this.clearColors = [];
          _this.clearDepth = 1.0;
          _this.clearStencil = 0;
          return _this;
        }
        var _proto = WebGLCmdBeginRenderPass.prototype;
        _proto.clear = function clear() {
          this.gpuFramebuffer = null;
          this.clearColors.length = 0;
        };
        return WebGLCmdBeginRenderPass;
      }(WebGLCmdObject);
      var WebGLCmdBindStates = function (_WebGLCmdObject2) {
        _inheritsLoose(WebGLCmdBindStates, _WebGLCmdObject2);
        function WebGLCmdBindStates() {
          var _this2;
          _this2 = _WebGLCmdObject2.call(this, WebGLCmd.BIND_STATES) || this;
          _this2.gpuPipelineState = null;
          _this2.gpuInputAssembler = null;
          _this2.gpuDescriptorSets = [];
          _this2.dynamicOffsets = [];
          _this2.dynamicStates = new DynamicStates();
          return _this2;
        }
        var _proto2 = WebGLCmdBindStates.prototype;
        _proto2.clear = function clear() {
          this.gpuPipelineState = null;
          this.gpuDescriptorSets.length = 0;
          this.gpuInputAssembler = null;
          this.dynamicOffsets.length = 0;
        };
        return WebGLCmdBindStates;
      }(WebGLCmdObject);
      var WebGLCmdDraw = function (_WebGLCmdObject3) {
        _inheritsLoose(WebGLCmdDraw, _WebGLCmdObject3);
        function WebGLCmdDraw() {
          var _this3;
          _this3 = _WebGLCmdObject3.call(this, WebGLCmd.DRAW) || this;
          _this3.drawInfo = new DrawInfo();
          return _this3;
        }
        var _proto3 = WebGLCmdDraw.prototype;
        _proto3.clear = function clear() {};
        return WebGLCmdDraw;
      }(WebGLCmdObject);
      var WebGLCmdUpdateBuffer = function (_WebGLCmdObject4) {
        _inheritsLoose(WebGLCmdUpdateBuffer, _WebGLCmdObject4);
        function WebGLCmdUpdateBuffer() {
          var _this4;
          _this4 = _WebGLCmdObject4.call(this, WebGLCmd.UPDATE_BUFFER) || this;
          _this4.gpuBuffer = null;
          _this4.buffer = null;
          _this4.offset = 0;
          _this4.size = 0;
          return _this4;
        }
        var _proto4 = WebGLCmdUpdateBuffer.prototype;
        _proto4.clear = function clear() {
          this.gpuBuffer = null;
          this.buffer = null;
        };
        return WebGLCmdUpdateBuffer;
      }(WebGLCmdObject);
      var WebGLCmdCopyBufferToTexture = function (_WebGLCmdObject5) {
        _inheritsLoose(WebGLCmdCopyBufferToTexture, _WebGLCmdObject5);
        function WebGLCmdCopyBufferToTexture() {
          var _this5;
          _this5 = _WebGLCmdObject5.call(this, WebGLCmd.COPY_BUFFER_TO_TEXTURE) || this;
          _this5.gpuTexture = null;
          _this5.buffers = [];
          _this5.regions = [];
          return _this5;
        }
        var _proto5 = WebGLCmdCopyBufferToTexture.prototype;
        _proto5.clear = function clear() {
          this.gpuTexture = null;
          this.buffers.length = 0;
          this.regions.length = 0;
        };
        return WebGLCmdCopyBufferToTexture;
      }(WebGLCmdObject);
      var WebGLCmdBlitTexture = function (_WebGLCmdObject6) {
        _inheritsLoose(WebGLCmdBlitTexture, _WebGLCmdObject6);
        function WebGLCmdBlitTexture() {
          var _this6;
          _this6 = _WebGLCmdObject6.call(this, WebGLCmd.BLIT_TEXTURE) || this;
          _this6.srcTexture = null;
          _this6.dstTexture = null;
          _this6.regions = [];
          _this6.filter = Filter$1.LINEAR;
          return _this6;
        }
        var _proto6 = WebGLCmdBlitTexture.prototype;
        _proto6.clear = function clear() {
          this.srcTexture = null;
          this.dstTexture = null;
          this.regions.length = 0;
        };
        return WebGLCmdBlitTexture;
      }(WebGLCmdObject);
      var WebGLCmdPackage = function () {
        function WebGLCmdPackage() {
          this.cmds = new CachedArray(1);
          this.beginRenderPassCmds = new CachedArray(1);
          this.bindStatesCmds = new CachedArray(1);
          this.drawCmds = new CachedArray(1);
          this.updateBufferCmds = new CachedArray(1);
          this.copyBufferToTextureCmds = new CachedArray(1);
          this.blitTextureCmds = new CachedArray(1);
        }
        var _proto7 = WebGLCmdPackage.prototype;
        _proto7.clearCmds = function clearCmds(allocator) {
          if (this.beginRenderPassCmds.length) {
            allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds);
            this.beginRenderPassCmds.clear();
          }
          if (this.bindStatesCmds.length) {
            allocator.bindStatesCmdPool.freeCmds(this.bindStatesCmds);
            this.bindStatesCmds.clear();
          }
          if (this.drawCmds.length) {
            allocator.drawCmdPool.freeCmds(this.drawCmds);
            this.drawCmds.clear();
          }
          if (this.updateBufferCmds.length) {
            allocator.updateBufferCmdPool.freeCmds(this.updateBufferCmds);
            this.updateBufferCmds.clear();
          }
          if (this.copyBufferToTextureCmds.length) {
            allocator.copyBufferToTextureCmdPool.freeCmds(this.copyBufferToTextureCmds);
            this.copyBufferToTextureCmds.clear();
          }
          if (this.blitTextureCmds.length) {
            allocator.blitTextureCmdPool.freeCmds(this.blitTextureCmds);
            this.blitTextureCmds.clear();
          }
          this.cmds.clear();
        };
        return WebGLCmdPackage;
      }();
      function WebGLCmdFuncCreateBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        var glUsage = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
        if (gpuBuffer.usage & BufferUsageBit.VERTEX) {
          gpuBuffer.glTarget = gl.ARRAY_BUFFER;
          var glBuffer = gl.createBuffer();
          if (glBuffer) {
            gpuBuffer.glBuffer = glBuffer;
            if (gpuBuffer.size > 0) {
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                  cache.glVAO = null;
                }
              }
              gfxStateCache$1.gpuInputAssembler = null;
              if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) {
                gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
                device.stateCache.glArrayBuffer = gpuBuffer.glBuffer;
              }
              gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.size, glUsage);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              device.stateCache.glArrayBuffer = null;
            }
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
          gpuBuffer.glTarget = gl.ELEMENT_ARRAY_BUFFER;
          var _glBuffer = gl.createBuffer();
          if (_glBuffer) {
            gpuBuffer.glBuffer = _glBuffer;
            if (gpuBuffer.size > 0) {
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                  cache.glVAO = null;
                }
              }
              gfxStateCache$1.gpuInputAssembler = null;
              if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
                device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer;
              }
              gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              device.stateCache.glElementArrayBuffer = null;
            }
          }
        } else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
          gpuBuffer.glTarget = gl.NONE;
          if (gpuBuffer.buffer) {
            gpuBuffer.vf32 = new Float32Array(gpuBuffer.buffer.buffer);
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT) {
          gpuBuffer.glTarget = gl.NONE;
        } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_DST) {
          gpuBuffer.glTarget = gl.NONE;
        } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) {
          gpuBuffer.glTarget = gl.NONE;
        } else {
          error('Unsupported BufferType, create buffer failed.');
          gpuBuffer.glTarget = gl.NONE;
        }
      }
      function WebGLCmdFuncDestroyBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        if (gpuBuffer.glBuffer) {
          switch (gpuBuffer.glTarget) {
            case gl.ARRAY_BUFFER:
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                  device.stateCache.glVAO = null;
                }
              }
              gfxStateCache$1.gpuInputAssembler = null;
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              device.stateCache.glArrayBuffer = null;
              break;
            case gl.ELEMENT_ARRAY_BUFFER:
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                  device.stateCache.glVAO = null;
                }
              }
              gfxStateCache$1.gpuInputAssembler = null;
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              device.stateCache.glElementArrayBuffer = null;
              break;
          }
          gl.deleteBuffer(gpuBuffer.glBuffer);
          gpuBuffer.glBuffer = null;
        }
      }
      function WebGLCmdFuncResizeBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        var glUsage = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
        if (gpuBuffer.usage & BufferUsageBit.VERTEX) {
          if (device.extensions.useVAO) {
            if (cache.glVAO) {
              device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
              cache.glVAO = null;
            }
          }
          gfxStateCache$1.gpuInputAssembler = null;
          if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) {
            gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
          }
          if (gpuBuffer.buffer) {
            gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.buffer, glUsage);
          } else {
            gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.size, glUsage);
          }
          gl.bindBuffer(gl.ARRAY_BUFFER, null);
          device.stateCache.glArrayBuffer = null;
        } else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
          if (device.extensions.useVAO) {
            if (cache.glVAO) {
              device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
              cache.glVAO = null;
            }
          }
          gfxStateCache$1.gpuInputAssembler = null;
          if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
          }
          if (gpuBuffer.buffer) {
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.buffer, glUsage);
          } else {
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
          }
          gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
          device.stateCache.glElementArrayBuffer = null;
        } else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
          if (gpuBuffer.buffer) {
            gpuBuffer.vf32 = new Float32Array(gpuBuffer.buffer.buffer);
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT || gpuBuffer.usage & BufferUsageBit.TRANSFER_DST || gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) {
          gpuBuffer.glTarget = gl.NONE;
        } else {
          error('Unsupported BufferType, create buffer failed.');
          gpuBuffer.glTarget = gl.NONE;
        }
      }
      function WebGLCmdFuncUpdateBuffer(device, gpuBuffer, buffer, offset, size) {
        if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
          if (ArrayBuffer.isView(buffer)) {
            gpuBuffer.vf32.set(buffer, offset / Float32Array.BYTES_PER_ELEMENT);
          } else {
            gpuBuffer.vf32.set(new Float32Array(buffer), offset / Float32Array.BYTES_PER_ELEMENT);
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT) {
          gpuBuffer.indirects.clearDraws();
          var drawInfos = buffer.drawInfos;
          for (var i = 0; i < drawInfos.length; ++i) {
            gpuBuffer.indirects.setDrawInfo(offset + i, drawInfos[i]);
          }
        } else {
          var buff = buffer;
          var gl = device.gl;
          var cache = device.stateCache;
          switch (gpuBuffer.glTarget) {
            case gl.ARRAY_BUFFER:
              {
                if (device.extensions.useVAO) {
                  if (cache.glVAO) {
                    device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                    cache.glVAO = null;
                  }
                }
                gfxStateCache$1.gpuInputAssembler = null;
                if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
                  device.stateCache.glArrayBuffer = gpuBuffer.glBuffer;
                }
                break;
              }
            case gl.ELEMENT_ARRAY_BUFFER:
              {
                if (device.extensions.useVAO) {
                  if (cache.glVAO) {
                    device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                    cache.glVAO = null;
                  }
                }
                gfxStateCache$1.gpuInputAssembler = null;
                if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
                  device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer;
                }
                break;
              }
            default:
              {
                error('Unsupported BufferType, update buffer failed.');
                return;
              }
          }
          if (size === buff.byteLength) {
            gl.bufferSubData(gpuBuffer.glTarget, offset, buff);
          } else {
            gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size));
          }
        }
      }
      function WebGLCmdFuncCreateTexture(device, gpuTexture) {
        var gl = device.gl;
        gpuTexture.glFormat = gpuTexture.glInternalFmt = GFXFormatToWebGLFormat$1(gpuTexture.format, gl);
        gpuTexture.glType = GFXFormatToWebGLType$1(gpuTexture.format, gl);
        var w = gpuTexture.width;
        var h = gpuTexture.height;
        switch (gpuTexture.type) {
          case TextureType.TEX2D:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D;
              var maxSize = Math.max(w, h);
              if (maxSize > device.capabilities.maxTextureSize) {
                errorID(9100, maxSize, device.capabilities.maxTextureSize);
              }
              if (!device.textureExclusive[gpuTexture.format] && !device.extensions.WEBGL_depth_texture && FormatInfos[gpuTexture.format].hasDepth) {
                gpuTexture.glInternalFmt = GFXFormatToWebGLInternalFormat$1(gpuTexture.format, gl);
                gpuTexture.glRenderbuffer = gl.createRenderbuffer();
                if (gpuTexture.size > 0) {
                  if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) {
                    gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
                    device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer;
                  }
                  gl.renderbufferStorage(gl.RENDERBUFFER, gpuTexture.glInternalFmt, w, h);
                }
              } else {
                gpuTexture.glTexture = gl.createTexture();
                if (gpuTexture.size > 0) {
                  var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                  if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                    gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture);
                    glTexUnit.glTexture = gpuTexture.glTexture;
                  }
                  if (FormatInfos[gpuTexture.format].isCompressed) {
                    for (var i = 0; i < gpuTexture.mipLevel; ++i) {
                      var imgSize = FormatSize(gpuTexture.format, w, h, 1);
                      var view = new Uint8Array(imgSize);
                      gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view);
                      w = Math.max(1, w >> 1);
                      h = Math.max(1, h >> 1);
                    }
                  } else {
                    for (var _i = 0; _i < gpuTexture.mipLevel; ++_i) {
                      gl.texImage2D(gl.TEXTURE_2D, _i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                      w = Math.max(1, w >> 1);
                      h = Math.max(1, h >> 1);
                    }
                  }
                  if (gpuTexture.isPowerOf2) {
                    gpuTexture.glWrapS = gl.REPEAT;
                    gpuTexture.glWrapT = gl.REPEAT;
                  } else {
                    gpuTexture.glWrapS = gl.CLAMP_TO_EDGE;
                    gpuTexture.glWrapT = gl.CLAMP_TO_EDGE;
                  }
                  gpuTexture.glMinFilter = gl.LINEAR;
                  gpuTexture.glMagFilter = gl.LINEAR;
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_S, gpuTexture.glWrapS);
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, gpuTexture.glWrapT);
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter);
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter);
                }
              }
              break;
            }
          case TextureType.CUBE:
            {
              gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP;
              var _maxSize = Math.max(w, h);
              if (_maxSize > device.capabilities.maxCubeMapTextureSize) {
                errorID(9100, _maxSize, device.capabilities.maxTextureSize);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture);
                  _glTexUnit.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var f = 0; f < 6; ++f) {
                    w = gpuTexture.width;
                    h = gpuTexture.height;
                    for (var _i2 = 0; _i2 < gpuTexture.mipLevel; ++_i2) {
                      var _imgSize = FormatSize(gpuTexture.format, w, h, 1);
                      var _view = new Uint8Array(_imgSize);
                      gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _i2, gpuTexture.glInternalFmt, w, h, 0, _view);
                      w = Math.max(1, w >> 1);
                      h = Math.max(1, h >> 1);
                    }
                  }
                } else {
                  for (var _f = 0; _f < 6; ++_f) {
                    w = gpuTexture.width;
                    h = gpuTexture.height;
                    for (var _i3 = 0; _i3 < gpuTexture.mipLevel; ++_i3) {
                      gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + _f, _i3, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                      w = Math.max(1, w >> 1);
                      h = Math.max(1, h >> 1);
                    }
                  }
                }
                if (gpuTexture.isPowerOf2) {
                  gpuTexture.glWrapS = gl.REPEAT;
                  gpuTexture.glWrapT = gl.REPEAT;
                } else {
                  gpuTexture.glWrapS = gl.CLAMP_TO_EDGE;
                  gpuTexture.glWrapT = gl.CLAMP_TO_EDGE;
                }
                gpuTexture.glMinFilter = gl.LINEAR;
                gpuTexture.glMagFilter = gl.LINEAR;
                gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_S, gpuTexture.glWrapS);
                gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, gpuTexture.glWrapT);
                gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter);
                gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter);
              }
              break;
            }
          default:
            {
              error('Unsupported TextureType, create texture failed.');
              gpuTexture.type = TextureType.TEX2D;
              gpuTexture.glTarget = gl.TEXTURE_2D;
            }
        }
      }
      function WebGLCmdFuncDestroyTexture(device, gpuTexture) {
        var gl = device.gl;
        if (gpuTexture.glTexture) {
          var glTexUnits = device.stateCache.glTexUnits;
          var texUnit = device.stateCache.texUnit;
          gl.deleteTexture(gpuTexture.glTexture);
          for (var i = 0; i < glTexUnits.length; i++) {
            if (glTexUnits[i].glTexture === gpuTexture.glTexture) {
              gl.activeTexture(gl.TEXTURE0 + i);
              texUnit = i;
              gl.bindTexture(gpuTexture.glTarget, null);
              glTexUnits[i].glTexture = null;
            }
          }
          device.stateCache.texUnit = texUnit;
          gpuTexture.glTexture = null;
        }
        if (gpuTexture.glRenderbuffer) {
          var glRenderbuffer = device.stateCache.glRenderbuffer;
          gl.deleteRenderbuffer(gpuTexture.glRenderbuffer);
          if (glRenderbuffer === gpuTexture.glRenderbuffer) {
            gl.bindRenderbuffer(gl.RENDERBUFFER, null);
            glRenderbuffer = null;
          }
          gpuTexture.glRenderbuffer = null;
        }
      }
      function WebGLCmdFuncResizeTexture(device, gpuTexture) {
        if (!gpuTexture.size) return;
        var gl = device.gl;
        var w = gpuTexture.width;
        var h = gpuTexture.height;
        switch (gpuTexture.type) {
          case TextureType.TEX2D:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D;
              var maxSize = Math.max(w, h);
              if (maxSize > device.capabilities.maxTextureSize) {
                errorID(9100, maxSize, device.capabilities.maxTextureSize);
              }
              if (gpuTexture.glRenderbuffer) {
                if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) {
                  gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
                  device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer;
                }
                gl.renderbufferStorage(gl.RENDERBUFFER, gpuTexture.glInternalFmt, w, h);
              } else if (gpuTexture.glTexture) {
                var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture);
                  glTexUnit.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var i = 0; i < gpuTexture.mipLevel; ++i) {
                    var imgSize = FormatSize(gpuTexture.format, w, h, 1);
                    var view = new Uint8Array(imgSize);
                    gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  for (var _i4 = 0; _i4 < gpuTexture.mipLevel; ++_i4) {
                    gl.texImage2D(gl.TEXTURE_2D, _i4, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                }
              }
              break;
            }
          case TextureType.CUBE:
            {
              gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP;
              var _maxSize2 = Math.max(w, h);
              if (_maxSize2 > device.capabilities.maxCubeMapTextureSize) {
                errorID(9100, _maxSize2, device.capabilities.maxTextureSize);
              }
              var _glTexUnit2 = device.stateCache.glTexUnits[device.stateCache.texUnit];
              if (_glTexUnit2.glTexture !== gpuTexture.glTexture) {
                gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture);
                _glTexUnit2.glTexture = gpuTexture.glTexture;
              }
              if (FormatInfos[gpuTexture.format].isCompressed) {
                for (var f = 0; f < 6; ++f) {
                  w = gpuTexture.width;
                  h = gpuTexture.height;
                  for (var _i5 = 0; _i5 < gpuTexture.mipLevel; ++_i5) {
                    var _imgSize2 = FormatSize(gpuTexture.format, w, h, 1);
                    var _view2 = new Uint8Array(_imgSize2);
                    gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _i5, gpuTexture.glInternalFmt, w, h, 0, _view2);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                }
              } else {
                for (var _f2 = 0; _f2 < 6; ++_f2) {
                  w = gpuTexture.width;
                  h = gpuTexture.height;
                  for (var _i6 = 0; _i6 < gpuTexture.mipLevel; ++_i6) {
                    gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + _f2, _i6, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                }
              }
              break;
            }
          default:
            {
              error('Unsupported TextureType, create texture failed.');
              gpuTexture.type = TextureType.TEX2D;
              gpuTexture.glTarget = gl.TEXTURE_2D;
            }
        }
      }
      function WebGLCmdFuncCreateFramebuffer(device, gpuFramebuffer) {
        for (var i = 0; i < gpuFramebuffer.gpuColorTextures.length; ++i) {
          var tex = gpuFramebuffer.gpuColorTextures[i];
          if (tex.isSwapchainTexture) {
            gpuFramebuffer.isOffscreen = false;
            return;
          }
        }
        var gl = device.gl;
        var attachments = [];
        var glFramebuffer = gl.createFramebuffer();
        if (glFramebuffer) {
          gpuFramebuffer.glFramebuffer = glFramebuffer;
          if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer);
          }
          for (var _i7 = 0; _i7 < gpuFramebuffer.gpuColorTextures.length; ++_i7) {
            var gpuTexture = gpuFramebuffer.gpuColorTextures[_i7];
            if (gpuTexture) {
              if (gpuTexture.glTexture) {
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + _i7, gpuTexture.glTarget, gpuTexture.glTexture, 0);
              } else {
                gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + _i7, gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
              }
              attachments.push(gl.COLOR_ATTACHMENT0 + _i7);
              gpuFramebuffer.width = Math.min(gpuFramebuffer.width, gpuTexture.width);
              gpuFramebuffer.height = Math.min(gpuFramebuffer.height, gpuTexture.height);
            }
          }
          var dst = gpuFramebuffer.gpuDepthStencilTexture;
          if (dst) {
            var glAttachment = FormatInfos[dst.format].hasStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
            if (dst.glTexture) {
              gl.framebufferTexture2D(gl.FRAMEBUFFER, glAttachment, dst.glTarget, dst.glTexture, 0);
            } else {
              gl.framebufferRenderbuffer(gl.FRAMEBUFFER, glAttachment, gl.RENDERBUFFER, dst.glRenderbuffer);
            }
            gpuFramebuffer.width = Math.min(gpuFramebuffer.width, dst.width);
            gpuFramebuffer.height = Math.min(gpuFramebuffer.height, dst.height);
          }
          if (device.extensions.WEBGL_draw_buffers) {
            device.extensions.WEBGL_draw_buffers.drawBuffersWEBGL(attachments);
          }
          var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
          if (status !== gl.FRAMEBUFFER_COMPLETE) {
            switch (status) {
              case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT');
                  break;
                }
              case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT');
                  break;
                }
              case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS');
                  break;
                }
              case gl.FRAMEBUFFER_UNSUPPORTED:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED');
                  break;
                }
            }
          }
          if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, device.stateCache.glFramebuffer);
          }
        }
      }
      function WebGLCmdFuncDestroyFramebuffer(device, gpuFramebuffer) {
        if (gpuFramebuffer.glFramebuffer) {
          device.gl.deleteFramebuffer(gpuFramebuffer.glFramebuffer);
          if (device.stateCache.glFramebuffer === gpuFramebuffer.glFramebuffer) {
            device.gl.bindFramebuffer(device.gl.FRAMEBUFFER, null);
            device.stateCache.glFramebuffer = null;
          }
          gpuFramebuffer.glFramebuffer = null;
        }
      }
      function WebGLCmdFuncCreateShader(device, gpuShader) {
        var gl = device.gl;
        var _loop = function _loop() {
            var gpuStage = gpuShader.gpuStages[k];
            var glShaderType = 0;
            var shaderTypeStr = '';
            var lineNumber = 1;
            switch (gpuStage.type) {
              case ShaderStageFlagBit.VERTEX:
                {
                  shaderTypeStr = 'VertexShader';
                  glShaderType = gl.VERTEX_SHADER;
                  break;
                }
              case ShaderStageFlagBit.FRAGMENT:
                {
                  shaderTypeStr = 'FragmentShader';
                  glShaderType = gl.FRAGMENT_SHADER;
                  break;
                }
              default:
                {
                  error('Unsupported ShaderType.');
                  return {
                    v: void 0
                  };
                }
            }
            var glShader = gl.createShader(glShaderType);
            if (glShader) {
              gpuStage.glShader = glShader;
              gl.shaderSource(gpuStage.glShader, gpuStage.source);
              gl.compileShader(gpuStage.glShader);
              if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) {
                error(shaderTypeStr + " in '" + gpuShader.name + "' compilation failed.");
                error('Shader source dump:', gpuStage.source.replace(/^|\n/g, function () {
                  return "\n" + lineNumber++ + " ";
                }));
                error(gl.getShaderInfoLog(gpuStage.glShader));
                for (var l = 0; l < gpuShader.gpuStages.length; l++) {
                  var stage = gpuShader.gpuStages[k];
                  if (stage.glShader) {
                    gl.deleteShader(stage.glShader);
                    stage.glShader = null;
                  }
                }
                return {
                  v: void 0
                };
              }
            }
          },
          _ret;
        for (var k = 0; k < gpuShader.gpuStages.length; k++) {
          _ret = _loop();
          if (_ret) return _ret.v;
        }
        var glProgram = gl.createProgram();
        if (!glProgram) {
          return;
        }
        gpuShader.glProgram = glProgram;
        for (var _k = 0; _k < gpuShader.gpuStages.length; _k++) {
          var gpuStage = gpuShader.gpuStages[_k];
          gl.attachShader(gpuShader.glProgram, gpuStage.glShader);
        }
        gl.linkProgram(gpuShader.glProgram);
        if (device.extensions.destroyShadersImmediately) {
          for (var _k2 = 0; _k2 < gpuShader.gpuStages.length; _k2++) {
            var _gpuStage = gpuShader.gpuStages[_k2];
            if (_gpuStage.glShader) {
              gl.detachShader(gpuShader.glProgram, _gpuStage.glShader);
              gl.deleteShader(_gpuStage.glShader);
              _gpuStage.glShader = null;
            }
          }
        }
        if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) {
          debug("Shader '" + gpuShader.name + "' compilation succeeded.");
        } else {
          error("Failed to link shader '" + gpuShader.name + "'.");
          error(gl.getProgramInfoLog(gpuShader.glProgram));
          return;
        }
        var activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES);
        gpuShader.glInputs = new Array(activeAttribCount);
        for (var i = 0; i < activeAttribCount; ++i) {
          var attribInfo = gl.getActiveAttrib(gpuShader.glProgram, i);
          if (attribInfo) {
            var varName = void 0;
            var nameOffset = attribInfo.name.indexOf('[');
            if (nameOffset !== -1) {
              varName = attribInfo.name.substr(0, nameOffset);
            } else {
              varName = attribInfo.name;
            }
            var glLoc = gl.getAttribLocation(gpuShader.glProgram, varName);
            var type = WebGLTypeToGFXType$1(attribInfo.type, gl);
            var stride = WebGLGetTypeSize$1(attribInfo.type, gl);
            gpuShader.glInputs[i] = {
              binding: glLoc,
              name: varName,
              type: type,
              stride: stride,
              count: attribInfo.size,
              size: stride * attribInfo.size,
              glType: attribInfo.type,
              glLoc: glLoc
            };
          }
        }
        if (gpuShader.blocks.length > 0) {
          gpuShader.glBlocks = new Array(gpuShader.blocks.length);
          for (var _i8 = 0; _i8 < gpuShader.blocks.length; ++_i8) {
            var block = gpuShader.blocks[_i8];
            var glBlock = {
              set: block.set,
              binding: block.binding,
              name: block.name,
              size: 0,
              glUniforms: new Array(block.members.length),
              glActiveUniforms: []
            };
            gpuShader.glBlocks[_i8] = glBlock;
            for (var u = 0; u < block.members.length; ++u) {
              var uniform = block.members[u];
              var glType = GFXTypeToWebGLType$1(uniform.type, gl);
              var _stride = WebGLGetTypeSize$1(glType, gl);
              var size = _stride * uniform.count;
              glBlock.glUniforms[u] = {
                binding: -1,
                name: uniform.name,
                type: uniform.type,
                stride: _stride,
                count: uniform.count,
                size: size,
                offset: 0,
                glType: glType,
                glLoc: null,
                array: null
              };
            }
          }
        }
        for (var _i9 = 0; _i9 < gpuShader.subpassInputs.length; ++_i9) {
          var subpassInput = gpuShader.subpassInputs[_i9];
          gpuShader.samplerTextures.push(new UniformSamplerTexture(subpassInput.set, subpassInput.binding, subpassInput.name, Type$1.SAMPLER2D, subpassInput.count));
        }
        if (gpuShader.samplerTextures.length > 0) {
          gpuShader.glSamplerTextures = new Array(gpuShader.samplerTextures.length);
          for (var _i10 = 0; _i10 < gpuShader.samplerTextures.length; ++_i10) {
            var sampler = gpuShader.samplerTextures[_i10];
            gpuShader.glSamplerTextures[_i10] = {
              set: sampler.set,
              binding: sampler.binding,
              name: sampler.name,
              type: sampler.type,
              count: sampler.count,
              units: [],
              glUnits: null,
              glType: GFXTypeToWebGLType$1(sampler.type, gl),
              glLoc: null
            };
          }
        }
        var activeUniformCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORMS);
        for (var _i11 = 0; _i11 < activeUniformCount; ++_i11) {
          var uniformInfo = gl.getActiveUniform(gpuShader.glProgram, _i11);
          if (uniformInfo) {
            var isSampler = uniformInfo.type === gl.SAMPLER_2D || uniformInfo.type === gl.SAMPLER_CUBE;
            if (!isSampler) {
              var _glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name);
              if (device.extensions.isLocationActive(_glLoc)) {
                var _varName = void 0;
                var _nameOffset = uniformInfo.name.indexOf('[');
                if (_nameOffset !== -1) {
                  _varName = uniformInfo.name.substr(0, _nameOffset);
                } else {
                  _varName = uniformInfo.name;
                }
                for (var j = 0; j < gpuShader.glBlocks.length; j++) {
                  var _glBlock = gpuShader.glBlocks[j];
                  for (var _k3 = 0; _k3 < _glBlock.glUniforms.length; _k3++) {
                    var glUniform = _glBlock.glUniforms[_k3];
                    if (glUniform.name === _varName) {
                      glUniform.glLoc = _glLoc;
                      glUniform.count = uniformInfo.size;
                      glUniform.size = glUniform.stride * glUniform.count;
                      glUniform.array = new (GFXTypeToTypedArrayCtor(glUniform.type))(glUniform.size / 4);
                      _glBlock.glActiveUniforms.push(glUniform);
                      break;
                    }
                  }
                }
              }
            }
          }
        }
        for (var _j = 0; _j < gpuShader.glBlocks.length; _j++) {
          var _glBlock2 = gpuShader.glBlocks[_j];
          for (var _k4 = 0; _k4 < _glBlock2.glUniforms.length; _k4++) {
            var _glUniform = _glBlock2.glUniforms[_k4];
            _glUniform.offset = _glBlock2.size / 4;
            _glBlock2.size += _glUniform.size;
          }
        }
        var glActiveSamplers = [];
        var glActiveSamplerLocations = [];
        var bindingMappings = device.bindingMappings;
        var texUnitCacheMap = device.stateCache.texUnitCacheMap;
        if (!(legacyCC.rendering && legacyCC.rendering.enableEffectImport)) {
          var flexibleSetBaseOffset = 0;
          for (var _i12 = 0; _i12 < gpuShader.blocks.length; ++_i12) {
            if (gpuShader.blocks[_i12].set === bindingMappings.flexibleSet) {
              flexibleSetBaseOffset++;
            }
          }
          var arrayOffset = 0;
          for (var _i13 = 0; _i13 < gpuShader.samplerTextures.length; ++_i13) {
            var _sampler = gpuShader.samplerTextures[_i13];
            var _glLoc2 = gl.getUniformLocation(gpuShader.glProgram, _sampler.name);
            if (device.extensions.isLocationActive(_glLoc2)) {
              glActiveSamplers.push(gpuShader.glSamplerTextures[_i13]);
              glActiveSamplerLocations.push(_glLoc2);
            }
            if (texUnitCacheMap[_sampler.name] === undefined) {
              var binding = _sampler.binding + bindingMappings.samplerTextureOffsets[_sampler.set] + arrayOffset;
              if (_sampler.set === bindingMappings.flexibleSet) {
                binding -= flexibleSetBaseOffset;
              }
              texUnitCacheMap[_sampler.name] = binding % device.capabilities.maxTextureUnits;
              arrayOffset += _sampler.count - 1;
            }
          }
        } else {
          for (var _i14 = 0; _i14 < gpuShader.samplerTextures.length; ++_i14) {
            var _sampler2 = gpuShader.samplerTextures[_i14];
            var _glLoc3 = gl.getUniformLocation(gpuShader.glProgram, _sampler2.name);
            if (device.extensions.isLocationActive(_glLoc3)) {
              glActiveSamplers.push(gpuShader.glSamplerTextures[_i14]);
              glActiveSamplerLocations.push(_glLoc3);
            }
            if (texUnitCacheMap[_sampler2.name] === undefined) {
              texUnitCacheMap[_sampler2.name] = _sampler2.flattened % device.capabilities.maxTextureUnits;
            }
          }
        }
        if (glActiveSamplers.length) {
          var usedTexUnits = [];
          for (var _i15 = 0; _i15 < glActiveSamplers.length; ++_i15) {
            var glSampler = glActiveSamplers[_i15];
            var cachedUnit = texUnitCacheMap[glSampler.name];
            if (cachedUnit !== undefined) {
              glSampler.glLoc = glActiveSamplerLocations[_i15];
              for (var t = 0; t < glSampler.count; ++t) {
                while (usedTexUnits[cachedUnit]) {
                  cachedUnit = (cachedUnit + 1) % device.capabilities.maxTextureUnits;
                }
                glSampler.units.push(cachedUnit);
                usedTexUnits[cachedUnit] = true;
              }
            }
          }
          var unitIdx = 0;
          for (var _i16 = 0; _i16 < glActiveSamplers.length; ++_i16) {
            var _glSampler = glActiveSamplers[_i16];
            if (!device.extensions.isLocationActive(_glSampler.glLoc)) {
              _glSampler.glLoc = glActiveSamplerLocations[_i16];
              for (var _t = 0; _t < _glSampler.count; ++_t) {
                while (usedTexUnits[unitIdx]) {
                  unitIdx = (unitIdx + 1) % device.capabilities.maxTextureUnits;
                }
                if (texUnitCacheMap[_glSampler.name] === undefined) {
                  texUnitCacheMap[_glSampler.name] = unitIdx;
                }
                _glSampler.units.push(unitIdx);
                usedTexUnits[unitIdx] = true;
              }
            }
          }
          if (device.stateCache.glProgram !== gpuShader.glProgram) {
            gl.useProgram(gpuShader.glProgram);
          }
          for (var _i17 = 0; _i17 < glActiveSamplers.length; _i17++) {
            var _glSampler2 = glActiveSamplers[_i17];
            _glSampler2.glUnits = new Int32Array(_glSampler2.units);
            gl.uniform1iv(_glSampler2.glLoc, _glSampler2.glUnits);
          }
          if (device.stateCache.glProgram !== gpuShader.glProgram) {
            gl.useProgram(device.stateCache.glProgram);
          }
        }
        for (var _i18 = 0; _i18 < gpuShader.glBlocks.length;) {
          if (gpuShader.glBlocks[_i18].glActiveUniforms.length) {
            _i18++;
          } else {
            gpuShader.glBlocks[_i18] = gpuShader.glBlocks[gpuShader.glBlocks.length - 1];
            gpuShader.glBlocks.length--;
          }
        }
        gpuShader.glSamplerTextures = glActiveSamplers;
      }
      function WebGLCmdFuncDestroyShader(device, gpuShader) {
        if (gpuShader.glProgram) {
          var gl = device.gl;
          if (!device.extensions.destroyShadersImmediately) {
            for (var k = 0; k < gpuShader.gpuStages.length; k++) {
              var gpuStage = gpuShader.gpuStages[k];
              if (gpuStage.glShader) {
                gl.detachShader(gpuShader.glProgram, gpuStage.glShader);
                gl.deleteShader(gpuStage.glShader);
                gpuStage.glShader = null;
              }
            }
          }
          gl.deleteProgram(gpuShader.glProgram);
          if (device.stateCache.glProgram === gpuShader.glProgram) {
            device.gl.useProgram(null);
            device.stateCache.glProgram = null;
          }
          gpuShader.glProgram = null;
        }
      }
      function WebGLCmdFuncCreateInputAssember(device, gpuInputAssembler) {
        var gl = device.gl;
        gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length);
        var offsets = [0, 0, 0, 0, 0, 0, 0, 0];
        for (var i = 0; i < gpuInputAssembler.attributes.length; ++i) {
          var attrib = gpuInputAssembler.attributes[i];
          var stream = attrib.stream !== undefined ? attrib.stream : 0;
          var gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream];
          var glType = GFXFormatToWebGLType$1(attrib.format, gl);
          var size = FormatInfos[attrib.format].size;
          gpuInputAssembler.glAttribs[i] = {
            name: attrib.name,
            glBuffer: gpuBuffer.glBuffer,
            glType: glType,
            size: size,
            count: FormatInfos[attrib.format].count,
            stride: gpuBuffer.stride,
            componentCount: WebGLGetComponentCount$1(glType, gl),
            isNormalized: attrib.isNormalized !== undefined ? attrib.isNormalized : false,
            isInstanced: attrib.isInstanced !== undefined ? attrib.isInstanced : false,
            offset: offsets[stream]
          };
          offsets[stream] += size;
        }
      }
      function WebGLCmdFuncDestroyInputAssembler(device, gpuInputAssembler) {
        var it = gpuInputAssembler.glVAOs.values();
        var res = it.next();
        var OES_vertex_array_object = device.extensions.OES_vertex_array_object;
        var glVAO = device.stateCache.glVAO;
        while (!res.done) {
          OES_vertex_array_object.deleteVertexArrayOES(res.value);
          if (glVAO === res.value) {
            OES_vertex_array_object.bindVertexArrayOES(null);
            glVAO = null;
          }
          res = it.next();
        }
        device.stateCache.glVAO = glVAO;
        gpuInputAssembler.glVAOs.clear();
      }
      var gfxStateCache$1 = {
        gpuPipelineState: null,
        gpuInputAssembler: null,
        glPrimitive: 0
      };
      var realRenderArea = new Rect();
      function WebGLCmdFuncBeginRenderPass(device, gpuRenderPass, gpuFramebuffer, renderArea, clearColors, clearDepth, clearStencil) {
        var gl = device.gl;
        var cache = device.stateCache;
        var clears = 0;
        if (gpuFramebuffer) {
          realRenderArea.x = renderArea.x << gpuFramebuffer.lodLevel;
          realRenderArea.y = renderArea.y << gpuFramebuffer.lodLevel;
          realRenderArea.width = renderArea.width << gpuFramebuffer.lodLevel;
          realRenderArea.height = renderArea.height << gpuFramebuffer.lodLevel;
        }
        if (gpuFramebuffer && gpuRenderPass) {
          if (cache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer);
            cache.glFramebuffer = gpuFramebuffer.glFramebuffer;
          }
          if (cache.viewport.left !== realRenderArea.x || cache.viewport.top !== realRenderArea.y || cache.viewport.width !== realRenderArea.width || cache.viewport.height !== realRenderArea.height) {
            gl.viewport(realRenderArea.x, realRenderArea.y, realRenderArea.width, realRenderArea.height);
            cache.viewport.left = realRenderArea.x;
            cache.viewport.top = realRenderArea.y;
            cache.viewport.width = realRenderArea.width;
            cache.viewport.height = realRenderArea.height;
          }
          if (cache.scissorRect.x !== realRenderArea.x || cache.scissorRect.y !== realRenderArea.y || cache.scissorRect.width !== realRenderArea.width || cache.scissorRect.height !== realRenderArea.height) {
            gl.scissor(realRenderArea.x, realRenderArea.y, realRenderArea.width, realRenderArea.height);
            cache.scissorRect.x = realRenderArea.x;
            cache.scissorRect.y = realRenderArea.y;
            cache.scissorRect.width = realRenderArea.width;
            cache.scissorRect.height = realRenderArea.height;
          }
          var clearCount = clearColors.length;
          if (!device.extensions.WEBGL_draw_buffers) {
            clearCount = 1;
          }
          for (var j = 0; j < clearCount; ++j) {
            var colorAttachment = gpuRenderPass.colorAttachments[j];
            if (colorAttachment.format !== Format.UNKNOWN) {
              switch (colorAttachment.loadOp) {
                case LoadOp.LOAD:
                  break;
                case LoadOp.CLEAR:
                  {
                    if (cache.bs.targets[0].blendColorMask !== ColorMask.ALL) {
                      gl.colorMask(true, true, true, true);
                    }
                    var clearColor = clearColors[0];
                    gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
                    clears |= gl.COLOR_BUFFER_BIT;
                    break;
                  }
                case LoadOp.DISCARD:
                  {
                    break;
                  }
              }
            }
          }
          if (gpuRenderPass.depthStencilAttachment) {
            if (gpuRenderPass.depthStencilAttachment.format !== Format.UNKNOWN) {
              switch (gpuRenderPass.depthStencilAttachment.depthLoadOp) {
                case LoadOp.LOAD:
                  break;
                case LoadOp.CLEAR:
                  {
                    if (!cache.dss.depthWrite) {
                      gl.depthMask(true);
                    }
                    gl.clearDepth(clearDepth);
                    clears |= gl.DEPTH_BUFFER_BIT;
                    break;
                  }
                case LoadOp.DISCARD:
                  {
                    break;
                  }
              }
              if (FormatInfos[gpuRenderPass.depthStencilAttachment.format].hasStencil) {
                switch (gpuRenderPass.depthStencilAttachment.stencilLoadOp) {
                  case LoadOp.LOAD:
                    break;
                  case LoadOp.CLEAR:
                    {
                      if (!cache.dss.stencilWriteMaskFront) {
                        gl.stencilMaskSeparate(gl.FRONT, 0xffff);
                      }
                      if (!cache.dss.stencilWriteMaskBack) {
                        gl.stencilMaskSeparate(gl.BACK, 0xffff);
                      }
                      gl.clearStencil(clearStencil);
                      clears |= gl.STENCIL_BUFFER_BIT;
                      break;
                    }
                  case LoadOp.DISCARD:
                    {
                      break;
                    }
                }
              }
            }
          }
          if (clears) {
            gl.clear(clears);
          }
          if (clears & gl.COLOR_BUFFER_BIT) {
            var colorMask = cache.bs.targets[0].blendColorMask;
            if (colorMask !== ColorMask.ALL) {
              var r = (colorMask & ColorMask.R) !== ColorMask.NONE;
              var g = (colorMask & ColorMask.G) !== ColorMask.NONE;
              var b = (colorMask & ColorMask.B) !== ColorMask.NONE;
              var a = (colorMask & ColorMask.A) !== ColorMask.NONE;
              gl.colorMask(r, g, b, a);
            }
          }
          if (clears & gl.DEPTH_BUFFER_BIT && !cache.dss.depthWrite) {
            gl.depthMask(false);
          }
          if (clears & gl.STENCIL_BUFFER_BIT) {
            if (!cache.dss.stencilWriteMaskFront) {
              gl.stencilMaskSeparate(gl.FRONT, 0);
            }
            if (!cache.dss.stencilWriteMaskBack) {
              gl.stencilMaskSeparate(gl.BACK, 0);
            }
          }
        }
      }
      function WebGLCmdFuncBindStates(device, gpuPipelineState, gpuInputAssembler, gpuDescriptorSets, dynamicOffsets, dynamicStates) {
        var gl = device.gl;
        var cache = device.stateCache;
        var gpuShader = gpuPipelineState && gpuPipelineState.gpuShader;
        var isShaderChanged = false;
        var glWrapS;
        var glWrapT;
        var glMinFilter;
        if (gpuPipelineState && gfxStateCache$1.gpuPipelineState !== gpuPipelineState) {
          gfxStateCache$1.gpuPipelineState = gpuPipelineState;
          gfxStateCache$1.glPrimitive = gpuPipelineState.glPrimitive;
          if (gpuPipelineState.gpuShader) {
            var glProgram = gpuPipelineState.gpuShader.glProgram;
            if (cache.glProgram !== glProgram) {
              gl.useProgram(glProgram);
              cache.glProgram = glProgram;
              isShaderChanged = true;
            }
          }
          var rs = gpuPipelineState.rs;
          if (rs) {
            if (cache.rs.cullMode !== rs.cullMode) {
              switch (rs.cullMode) {
                case CullMode.NONE:
                  {
                    gl.disable(gl.CULL_FACE);
                    break;
                  }
                case CullMode.FRONT:
                  {
                    gl.enable(gl.CULL_FACE);
                    gl.cullFace(gl.FRONT);
                    break;
                  }
                case CullMode.BACK:
                  {
                    gl.enable(gl.CULL_FACE);
                    gl.cullFace(gl.BACK);
                    break;
                  }
              }
              cache.rs.cullMode = rs.cullMode;
            }
            var isFrontFaceCCW = rs.isFrontFaceCCW;
            if (cache.rs.isFrontFaceCCW !== isFrontFaceCCW) {
              gl.frontFace(isFrontFaceCCW ? gl.CCW : gl.CW);
              cache.rs.isFrontFaceCCW = isFrontFaceCCW;
            }
            if (cache.rs.depthBias !== rs.depthBias || cache.rs.depthBiasSlop !== rs.depthBiasSlop) {
              gl.polygonOffset(rs.depthBias, rs.depthBiasSlop);
              cache.rs.depthBias = rs.depthBias;
              cache.rs.depthBiasSlop = rs.depthBiasSlop;
            }
            if (cache.rs.lineWidth !== rs.lineWidth) {
              gl.lineWidth(rs.lineWidth);
              cache.rs.lineWidth = rs.lineWidth;
            }
          }
          var dss = gpuPipelineState.dss;
          if (dss) {
            if (cache.dss.depthTest !== dss.depthTest) {
              if (dss.depthTest) {
                gl.enable(gl.DEPTH_TEST);
              } else {
                gl.disable(gl.DEPTH_TEST);
              }
              cache.dss.depthTest = dss.depthTest;
            }
            if (cache.dss.depthWrite !== dss.depthWrite) {
              gl.depthMask(dss.depthWrite);
              cache.dss.depthWrite = dss.depthWrite;
            }
            if (cache.dss.depthFunc !== dss.depthFunc) {
              gl.depthFunc(WebGLCmpFuncs$1[dss.depthFunc]);
              cache.dss.depthFunc = dss.depthFunc;
            }
            if (cache.dss.stencilTestFront !== dss.stencilTestFront || cache.dss.stencilTestBack !== dss.stencilTestBack) {
              if (dss.stencilTestFront || dss.stencilTestBack) {
                gl.enable(gl.STENCIL_TEST);
              } else {
                gl.disable(gl.STENCIL_TEST);
              }
              cache.dss.stencilTestFront = dss.stencilTestFront;
              cache.dss.stencilTestBack = dss.stencilTestBack;
            }
            if (cache.dss.stencilFuncFront !== dss.stencilFuncFront || cache.dss.stencilRefFront !== dss.stencilRefFront || cache.dss.stencilReadMaskFront !== dss.stencilReadMaskFront) {
              gl.stencilFuncSeparate(gl.FRONT, WebGLCmpFuncs$1[dss.stencilFuncFront], dss.stencilRefFront, dss.stencilReadMaskFront);
              cache.dss.stencilFuncFront = dss.stencilFuncFront;
              cache.dss.stencilRefFront = dss.stencilRefFront;
              cache.dss.stencilReadMaskFront = dss.stencilReadMaskFront;
            }
            if (cache.dss.stencilFailOpFront !== dss.stencilFailOpFront || cache.dss.stencilZFailOpFront !== dss.stencilZFailOpFront || cache.dss.stencilPassOpFront !== dss.stencilPassOpFront) {
              gl.stencilOpSeparate(gl.FRONT, WebGLStencilOps$1[dss.stencilFailOpFront], WebGLStencilOps$1[dss.stencilZFailOpFront], WebGLStencilOps$1[dss.stencilPassOpFront]);
              cache.dss.stencilFailOpFront = dss.stencilFailOpFront;
              cache.dss.stencilZFailOpFront = dss.stencilZFailOpFront;
              cache.dss.stencilPassOpFront = dss.stencilPassOpFront;
            }
            if (cache.dss.stencilWriteMaskFront !== dss.stencilWriteMaskFront) {
              gl.stencilMaskSeparate(gl.FRONT, dss.stencilWriteMaskFront);
              cache.dss.stencilWriteMaskFront = dss.stencilWriteMaskFront;
            }
            if (cache.dss.stencilFuncBack !== dss.stencilFuncBack || cache.dss.stencilRefBack !== dss.stencilRefBack || cache.dss.stencilReadMaskBack !== dss.stencilReadMaskBack) {
              gl.stencilFuncSeparate(gl.BACK, WebGLCmpFuncs$1[dss.stencilFuncBack], dss.stencilRefBack, dss.stencilReadMaskBack);
              cache.dss.stencilFuncBack = dss.stencilFuncBack;
              cache.dss.stencilRefBack = dss.stencilRefBack;
              cache.dss.stencilReadMaskBack = dss.stencilReadMaskBack;
            }
            if (cache.dss.stencilFailOpBack !== dss.stencilFailOpBack || cache.dss.stencilZFailOpBack !== dss.stencilZFailOpBack || cache.dss.stencilPassOpBack !== dss.stencilPassOpBack) {
              gl.stencilOpSeparate(gl.BACK, WebGLStencilOps$1[dss.stencilFailOpBack], WebGLStencilOps$1[dss.stencilZFailOpBack], WebGLStencilOps$1[dss.stencilPassOpBack]);
              cache.dss.stencilFailOpBack = dss.stencilFailOpBack;
              cache.dss.stencilZFailOpBack = dss.stencilZFailOpBack;
              cache.dss.stencilPassOpBack = dss.stencilPassOpBack;
            }
            if (cache.dss.stencilWriteMaskBack !== dss.stencilWriteMaskBack) {
              gl.stencilMaskSeparate(gl.BACK, dss.stencilWriteMaskBack);
              cache.dss.stencilWriteMaskBack = dss.stencilWriteMaskBack;
            }
          }
          var bs = gpuPipelineState.bs;
          if (bs) {
            if (cache.bs.isA2C !== bs.isA2C) {
              if (bs.isA2C) {
                gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE);
              } else {
                gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
              }
              cache.bs.isA2C = bs.isA2C;
            }
            if (cache.bs.blendColor.x !== bs.blendColor.x || cache.bs.blendColor.y !== bs.blendColor.y || cache.bs.blendColor.z !== bs.blendColor.z || cache.bs.blendColor.w !== bs.blendColor.w) {
              gl.blendColor(bs.blendColor.x, bs.blendColor.y, bs.blendColor.z, bs.blendColor.w);
              cache.bs.blendColor.x = bs.blendColor.x;
              cache.bs.blendColor.y = bs.blendColor.y;
              cache.bs.blendColor.z = bs.blendColor.z;
              cache.bs.blendColor.w = bs.blendColor.w;
            }
            var target0 = bs.targets[0];
            var target0Cache = cache.bs.targets[0];
            if (target0Cache.blend !== target0.blend) {
              if (target0.blend) {
                gl.enable(gl.BLEND);
              } else {
                gl.disable(gl.BLEND);
              }
              target0Cache.blend = target0.blend;
            }
            if (target0Cache.blendEq !== target0.blendEq || target0Cache.blendAlphaEq !== target0.blendAlphaEq) {
              gl.blendEquationSeparate(WebGLBlendOps$1[target0.blendEq], WebGLBlendOps$1[target0.blendAlphaEq]);
              target0Cache.blendEq = target0.blendEq;
              target0Cache.blendAlphaEq = target0.blendAlphaEq;
            }
            if (target0Cache.blendSrc !== target0.blendSrc || target0Cache.blendDst !== target0.blendDst || target0Cache.blendSrcAlpha !== target0.blendSrcAlpha || target0Cache.blendDstAlpha !== target0.blendDstAlpha) {
              gl.blendFuncSeparate(WebGLBlendFactors$1[target0.blendSrc], WebGLBlendFactors$1[target0.blendDst], WebGLBlendFactors$1[target0.blendSrcAlpha], WebGLBlendFactors$1[target0.blendDstAlpha]);
              target0Cache.blendSrc = target0.blendSrc;
              target0Cache.blendDst = target0.blendDst;
              target0Cache.blendSrcAlpha = target0.blendSrcAlpha;
              target0Cache.blendDstAlpha = target0.blendDstAlpha;
            }
            if (target0Cache.blendColorMask !== target0.blendColorMask) {
              gl.colorMask((target0.blendColorMask & ColorMask.R) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.G) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.B) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.A) !== ColorMask.NONE);
              target0Cache.blendColorMask = target0.blendColorMask;
            }
          }
        }
        if (gpuPipelineState && gpuPipelineState.gpuPipelineLayout && gpuShader) {
          var blockLen = gpuShader.glBlocks.length;
          var dynamicOffsetIndices = gpuPipelineState.gpuPipelineLayout.dynamicOffsetIndices;
          for (var j = 0; j < blockLen; j++) {
            var glBlock = gpuShader.glBlocks[j];
            var gpuDescriptorSet = gpuDescriptorSets[glBlock.set];
            var descriptorIdx = gpuDescriptorSet && gpuDescriptorSet.descriptorIndices[glBlock.binding];
            var gpuDescriptor = descriptorIdx >= 0 && gpuDescriptorSet.gpuDescriptors[descriptorIdx];
            var vf32 = null;
            var offset = 0;
            if (gpuDescriptor && gpuDescriptor.gpuBuffer) {
              var gpuBuffer = gpuDescriptor.gpuBuffer;
              var dynamicOffsetIndexSet = dynamicOffsetIndices[glBlock.set];
              var dynamicOffsetIndex = dynamicOffsetIndexSet && dynamicOffsetIndexSet[glBlock.binding];
              if (dynamicOffsetIndex >= 0) {
                offset = dynamicOffsets[dynamicOffsetIndex];
              }
              if ('vf32' in gpuBuffer) {
                vf32 = gpuBuffer.vf32;
              } else {
                offset += gpuBuffer.offset;
                vf32 = gpuBuffer.gpuBuffer.vf32;
              }
              offset >>= 2;
            }
            if (!vf32) {
              continue;
            }
            var uniformLen = glBlock.glActiveUniforms.length;
            for (var l = 0; l < uniformLen; l++) {
              var glUniform = glBlock.glActiveUniforms[l];
              switch (glUniform.glType) {
                case gl.BOOL:
                case gl.INT:
                  {
                    for (var u = 0; u < glUniform.array.length; ++u) {
                      var idx = glUniform.offset + offset + u;
                      if (vf32[idx] !== glUniform.array[u]) {
                        for (var n = u, m = idx; n < glUniform.array.length; ++n, ++m) {
                          glUniform.array[n] = vf32[m];
                        }
                        gl.uniform1iv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.BOOL_VEC2:
                case gl.INT_VEC2:
                  {
                    for (var _u = 0; _u < glUniform.array.length; ++_u) {
                      var _idx = glUniform.offset + offset + _u;
                      if (vf32[_idx] !== glUniform.array[_u]) {
                        for (var _n = _u, _m = _idx; _n < glUniform.array.length; ++_n, ++_m) {
                          glUniform.array[_n] = vf32[_m];
                        }
                        gl.uniform2iv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.BOOL_VEC3:
                case gl.INT_VEC3:
                  {
                    for (var _u2 = 0; _u2 < glUniform.array.length; ++_u2) {
                      var _idx2 = glUniform.offset + offset + _u2;
                      if (vf32[_idx2] !== glUniform.array[_u2]) {
                        for (var _n2 = _u2, _m2 = _idx2; _n2 < glUniform.array.length; ++_n2, ++_m2) {
                          glUniform.array[_n2] = vf32[_m2];
                        }
                        gl.uniform3iv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.BOOL_VEC4:
                case gl.INT_VEC4:
                  {
                    for (var _u3 = 0; _u3 < glUniform.array.length; ++_u3) {
                      var _idx3 = glUniform.offset + offset + _u3;
                      if (vf32[_idx3] !== glUniform.array[_u3]) {
                        for (var _n3 = _u3, _m3 = _idx3; _n3 < glUniform.array.length; ++_n3, ++_m3) {
                          glUniform.array[_n3] = vf32[_m3];
                        }
                        gl.uniform4iv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT:
                  {
                    for (var _u4 = 0; _u4 < glUniform.array.length; ++_u4) {
                      var _idx4 = glUniform.offset + offset + _u4;
                      if (vf32[_idx4] !== glUniform.array[_u4]) {
                        for (var _n4 = _u4, _m4 = _idx4; _n4 < glUniform.array.length; ++_n4, ++_m4) {
                          glUniform.array[_n4] = vf32[_m4];
                        }
                        gl.uniform1fv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_VEC2:
                  {
                    for (var _u5 = 0; _u5 < glUniform.array.length; ++_u5) {
                      var _idx5 = glUniform.offset + offset + _u5;
                      if (vf32[_idx5] !== glUniform.array[_u5]) {
                        for (var _n5 = _u5, _m5 = _idx5; _n5 < glUniform.array.length; ++_n5, ++_m5) {
                          glUniform.array[_n5] = vf32[_m5];
                        }
                        gl.uniform2fv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_VEC3:
                  {
                    for (var _u6 = 0; _u6 < glUniform.array.length; ++_u6) {
                      var _idx6 = glUniform.offset + offset + _u6;
                      if (vf32[_idx6] !== glUniform.array[_u6]) {
                        for (var _n6 = _u6, _m6 = _idx6; _n6 < glUniform.array.length; ++_n6, ++_m6) {
                          glUniform.array[_n6] = vf32[_m6];
                        }
                        gl.uniform3fv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_VEC4:
                  {
                    for (var _u7 = 0; _u7 < glUniform.array.length; ++_u7) {
                      var _idx7 = glUniform.offset + offset + _u7;
                      if (vf32[_idx7] !== glUniform.array[_u7]) {
                        for (var _n7 = _u7, _m7 = _idx7; _n7 < glUniform.array.length; ++_n7, ++_m7) {
                          glUniform.array[_n7] = vf32[_m7];
                        }
                        gl.uniform4fv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_MAT2:
                  {
                    for (var _u8 = 0; _u8 < glUniform.array.length; ++_u8) {
                      var _idx8 = glUniform.offset + offset + _u8;
                      if (vf32[_idx8] !== glUniform.array[_u8]) {
                        for (var _n8 = _u8, _m8 = _idx8; _n8 < glUniform.array.length; ++_n8, ++_m8) {
                          glUniform.array[_n8] = vf32[_m8];
                        }
                        gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_MAT3:
                  {
                    for (var _u9 = 0; _u9 < glUniform.array.length; ++_u9) {
                      var _idx9 = glUniform.offset + offset + _u9;
                      if (vf32[_idx9] !== glUniform.array[_u9]) {
                        for (var _n9 = _u9, _m9 = _idx9; _n9 < glUniform.array.length; ++_n9, ++_m9) {
                          glUniform.array[_n9] = vf32[_m9];
                        }
                        gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_MAT4:
                  {
                    for (var _u10 = 0; _u10 < glUniform.array.length; ++_u10) {
                      var _idx10 = glUniform.offset + offset + _u10;
                      if (vf32[_idx10] !== glUniform.array[_u10]) {
                        for (var _n10 = _u10, _m10 = _idx10; _n10 < glUniform.array.length; ++_n10, ++_m10) {
                          glUniform.array[_n10] = vf32[_m10];
                        }
                        gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
              }
            }
            continue;
          }
          var samplerLen = gpuShader.glSamplerTextures.length;
          for (var i = 0; i < samplerLen; i++) {
            var glSampler = gpuShader.glSamplerTextures[i];
            var _gpuDescriptorSet = gpuDescriptorSets[glSampler.set];
            var descriptorIndex = _gpuDescriptorSet && _gpuDescriptorSet.descriptorIndices[glSampler.binding];
            var _gpuDescriptor = descriptorIndex >= 0 && _gpuDescriptorSet.gpuDescriptors[descriptorIndex];
            var texUnitLen = glSampler.units.length;
            for (var _l = 0; _l < texUnitLen; _l++) {
              var texUnit = glSampler.units[_l];
              if (!_gpuDescriptor || !_gpuDescriptor.gpuSampler) {
                continue;
              }
              if (_gpuDescriptor.gpuTexture && _gpuDescriptor.gpuTexture.size > 0) {
                var _gpuDescriptor2 = _gpuDescriptor,
                  gpuTexture = _gpuDescriptor2.gpuTexture;
                var glTexUnit = cache.glTexUnits[texUnit];
                if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  if (gpuTexture.glTexture) {
                    gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
                  } else {
                    gl.bindTexture(gpuTexture.glTarget, device.nullTex2D.gpuTexture.glTexture);
                  }
                  glTexUnit.glTexture = gpuTexture.glTexture;
                }
                var _gpuDescriptor3 = _gpuDescriptor,
                  gpuSampler = _gpuDescriptor3.gpuSampler;
                if (gpuTexture.isPowerOf2) {
                  glWrapS = gpuSampler.glWrapS;
                  glWrapT = gpuSampler.glWrapT;
                } else {
                  glWrapS = gl.CLAMP_TO_EDGE;
                  glWrapT = gl.CLAMP_TO_EDGE;
                }
                if (gpuTexture.isPowerOf2) {
                  if (gpuTexture.mipLevel <= 1 && (gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_NEAREST || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_LINEAR)) {
                    glMinFilter = gl.LINEAR;
                  } else {
                    glMinFilter = gpuSampler.glMinFilter;
                  }
                } else if (gpuSampler.glMinFilter === gl.LINEAR || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_NEAREST || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_LINEAR) {
                  glMinFilter = gl.LINEAR;
                } else {
                  glMinFilter = gl.NEAREST;
                }
                if (gpuTexture.glWrapS !== glWrapS) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_S, glWrapS);
                  gpuTexture.glWrapS = glWrapS;
                }
                if (gpuTexture.glWrapT !== glWrapT) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, glWrapT);
                  gpuTexture.glWrapT = glWrapT;
                }
                if (gpuTexture.glMinFilter !== glMinFilter) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, glMinFilter);
                  gpuTexture.glMinFilter = glMinFilter;
                }
                if (gpuTexture.glMagFilter !== gpuSampler.glMagFilter) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuSampler.glMagFilter);
                  gpuTexture.glMagFilter = gpuSampler.glMagFilter;
                }
              }
              _gpuDescriptor = _gpuDescriptorSet.gpuDescriptors[++descriptorIndex];
            }
          }
        }
        if (gpuInputAssembler && gpuShader && (isShaderChanged || gfxStateCache$1.gpuInputAssembler !== gpuInputAssembler)) {
          gfxStateCache$1.gpuInputAssembler = gpuInputAssembler;
          var ia = device.extensions.ANGLE_instanced_arrays;
          if (device.extensions.useVAO) {
            var vao = device.extensions.OES_vertex_array_object;
            var glVAO = gpuInputAssembler.glVAOs.get(gpuShader.glProgram);
            if (!glVAO) {
              glVAO = vao.createVertexArrayOES();
              gpuInputAssembler.glVAOs.set(gpuShader.glProgram, glVAO);
              vao.bindVertexArrayOES(glVAO);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              cache.glArrayBuffer = null;
              cache.glElementArrayBuffer = null;
              var glAttrib;
              var inputLen = gpuShader.glInputs.length;
              for (var _j2 = 0; _j2 < inputLen; _j2++) {
                var glInput = gpuShader.glInputs[_j2];
                glAttrib = null;
                var attribLen = gpuInputAssembler.glAttribs.length;
                for (var k = 0; k < attribLen; k++) {
                  var attrib = gpuInputAssembler.glAttribs[k];
                  if (attrib.name === glInput.name) {
                    glAttrib = attrib;
                    break;
                  }
                }
                if (glAttrib) {
                  if (cache.glArrayBuffer !== glAttrib.glBuffer) {
                    gl.bindBuffer(gl.ARRAY_BUFFER, glAttrib.glBuffer);
                    cache.glArrayBuffer = glAttrib.glBuffer;
                  }
                  for (var c = 0; c < glAttrib.componentCount; ++c) {
                    var glLoc = glInput.glLoc + c;
                    var attribOffset = glAttrib.offset + glAttrib.size * c;
                    gl.enableVertexAttribArray(glLoc);
                    cache.glCurrentAttribLocs[glLoc] = true;
                    gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, glAttrib.isNormalized, glAttrib.stride, attribOffset);
                    if (ia) {
                      ia.vertexAttribDivisorANGLE(glLoc, glAttrib.isInstanced ? 1 : 0);
                    }
                  }
                }
              }
              var _gpuBuffer = gpuInputAssembler.gpuIndexBuffer;
              if (_gpuBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _gpuBuffer.glBuffer);
              }
              vao.bindVertexArrayOES(null);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              cache.glArrayBuffer = null;
              cache.glElementArrayBuffer = null;
            }
            if (cache.glVAO !== glVAO) {
              vao.bindVertexArrayOES(glVAO);
              cache.glVAO = glVAO;
            }
          } else {
            for (var a = 0; a < device.capabilities.maxVertexAttributes; ++a) {
              cache.glCurrentAttribLocs[a] = false;
            }
            var _inputLen = gpuShader.glInputs.length;
            for (var _j3 = 0; _j3 < _inputLen; _j3++) {
              var _glInput = gpuShader.glInputs[_j3];
              var _glAttrib = null;
              var _attribLen = gpuInputAssembler.glAttribs.length;
              for (var _k5 = 0; _k5 < _attribLen; _k5++) {
                var _attrib = gpuInputAssembler.glAttribs[_k5];
                if (_attrib.name === _glInput.name) {
                  _glAttrib = _attrib;
                  break;
                }
              }
              if (_glAttrib) {
                if (cache.glArrayBuffer !== _glAttrib.glBuffer) {
                  gl.bindBuffer(gl.ARRAY_BUFFER, _glAttrib.glBuffer);
                  cache.glArrayBuffer = _glAttrib.glBuffer;
                }
                for (var _c = 0; _c < _glAttrib.componentCount; ++_c) {
                  var _glLoc4 = _glInput.glLoc + _c;
                  var _attribOffset = _glAttrib.offset + _glAttrib.size * _c;
                  if (!cache.glEnabledAttribLocs[_glLoc4] && _glLoc4 >= 0) {
                    gl.enableVertexAttribArray(_glLoc4);
                    cache.glEnabledAttribLocs[_glLoc4] = true;
                  }
                  cache.glCurrentAttribLocs[_glLoc4] = true;
                  gl.vertexAttribPointer(_glLoc4, _glAttrib.count, _glAttrib.glType, _glAttrib.isNormalized, _glAttrib.stride, _attribOffset);
                  if (ia) {
                    ia.vertexAttribDivisorANGLE(_glLoc4, _glAttrib.isInstanced ? 1 : 0);
                  }
                }
              }
            }
            var _gpuBuffer2 = gpuInputAssembler.gpuIndexBuffer;
            if (_gpuBuffer2) {
              if (cache.glElementArrayBuffer !== _gpuBuffer2.glBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _gpuBuffer2.glBuffer);
                cache.glElementArrayBuffer = _gpuBuffer2.glBuffer;
              }
            }
            for (var _a = 0; _a < device.capabilities.maxVertexAttributes; ++_a) {
              if (cache.glEnabledAttribLocs[_a] !== cache.glCurrentAttribLocs[_a]) {
                gl.disableVertexAttribArray(_a);
                cache.glEnabledAttribLocs[_a] = false;
              }
            }
          }
        }
        if (gpuPipelineState && gpuPipelineState.dynamicStates.length) {
          var dsLen = gpuPipelineState.dynamicStates.length;
          for (var _j4 = 0; _j4 < dsLen; _j4++) {
            var dynamicState = gpuPipelineState.dynamicStates[_j4];
            switch (dynamicState) {
              case DynamicStateFlagBit.LINE_WIDTH:
                {
                  if (cache.rs.lineWidth !== dynamicStates.lineWidth) {
                    gl.lineWidth(dynamicStates.lineWidth);
                    cache.rs.lineWidth = dynamicStates.lineWidth;
                  }
                  break;
                }
              case DynamicStateFlagBit.DEPTH_BIAS:
                {
                  if (cache.rs.depthBias !== dynamicStates.depthBiasConstant || cache.rs.depthBiasSlop !== dynamicStates.depthBiasSlope) {
                    gl.polygonOffset(dynamicStates.depthBiasConstant, dynamicStates.depthBiasSlope);
                    cache.rs.depthBias = dynamicStates.depthBiasConstant;
                    cache.rs.depthBiasSlop = dynamicStates.depthBiasSlope;
                  }
                  break;
                }
              case DynamicStateFlagBit.BLEND_CONSTANTS:
                {
                  var blendConstant = dynamicStates.blendConstant;
                  if (cache.bs.blendColor.x !== blendConstant.x || cache.bs.blendColor.y !== blendConstant.y || cache.bs.blendColor.z !== blendConstant.z || cache.bs.blendColor.w !== blendConstant.w) {
                    gl.blendColor(blendConstant.x, blendConstant.y, blendConstant.z, blendConstant.w);
                    cache.bs.blendColor.copy(blendConstant);
                  }
                  break;
                }
              case DynamicStateFlagBit.STENCIL_WRITE_MASK:
                {
                  var front = dynamicStates.stencilStatesFront;
                  var back = dynamicStates.stencilStatesBack;
                  if (cache.dss.stencilWriteMaskFront !== front.writeMask) {
                    gl.stencilMaskSeparate(gl.FRONT, front.writeMask);
                    cache.dss.stencilWriteMaskFront = front.writeMask;
                  }
                  if (cache.dss.stencilWriteMaskBack !== back.writeMask) {
                    gl.stencilMaskSeparate(gl.BACK, back.writeMask);
                    cache.dss.stencilWriteMaskBack = back.writeMask;
                  }
                  break;
                }
              case DynamicStateFlagBit.STENCIL_COMPARE_MASK:
                {
                  var _front = dynamicStates.stencilStatesFront;
                  var _back = dynamicStates.stencilStatesBack;
                  if (cache.dss.stencilRefFront !== _front.reference || cache.dss.stencilReadMaskFront !== _front.compareMask) {
                    gl.stencilFuncSeparate(gl.FRONT, WebGLCmpFuncs$1[cache.dss.stencilFuncFront], _front.reference, _front.compareMask);
                    cache.dss.stencilRefFront = _front.reference;
                    cache.dss.stencilReadMaskFront = _front.compareMask;
                  }
                  if (cache.dss.stencilRefBack !== _back.reference || cache.dss.stencilReadMaskBack !== _back.compareMask) {
                    gl.stencilFuncSeparate(gl.BACK, WebGLCmpFuncs$1[cache.dss.stencilFuncBack], _back.reference, _back.compareMask);
                    cache.dss.stencilRefBack = _back.reference;
                    cache.dss.stencilReadMaskBack = _back.compareMask;
                  }
                  break;
                }
            }
          }
        }
      }
      function WebGLCmdFuncDraw(device, drawInfo) {
        var gl = device.gl;
        var _device$extensions = device.extensions,
          ia = _device$extensions.ANGLE_instanced_arrays,
          md = _device$extensions.WEBGL_multi_draw;
        var gpuInputAssembler = gfxStateCache$1.gpuInputAssembler,
          glPrimitive = gfxStateCache$1.glPrimitive;
        if (gpuInputAssembler) {
          var indexBuffer = gpuInputAssembler.gpuIndexBuffer;
          if (gpuInputAssembler.gpuIndirectBuffer) {
            var indirects = gpuInputAssembler.gpuIndirectBuffer.indirects;
            if (indirects.drawByIndex) {
              for (var j = 0; j < indirects.drawCount; j++) {
                indirects.byteOffsets[j] = indirects.offsets[j] * indexBuffer.stride;
              }
              if (md) {
                if (indirects.instancedDraw) {
                  md.multiDrawElementsInstancedWEBGL(glPrimitive, indirects.counts, 0, gpuInputAssembler.glIndexType, indirects.byteOffsets, 0, indirects.instances, 0, indirects.drawCount);
                } else {
                  md.multiDrawElementsWEBGL(glPrimitive, indirects.counts, 0, gpuInputAssembler.glIndexType, indirects.byteOffsets, 0, indirects.drawCount);
                }
              } else {
                for (var _j5 = 0; _j5 < indirects.drawCount; _j5++) {
                  if (indirects.instances[_j5] && ia) {
                    ia.drawElementsInstancedANGLE(glPrimitive, indirects.counts[_j5], gpuInputAssembler.glIndexType, indirects.byteOffsets[_j5], indirects.instances[_j5]);
                  } else {
                    gl.drawElements(glPrimitive, indirects.counts[_j5], gpuInputAssembler.glIndexType, indirects.byteOffsets[_j5]);
                  }
                }
              }
            } else if (md) {
              if (indirects.instancedDraw) {
                md.multiDrawArraysInstancedWEBGL(glPrimitive, indirects.offsets, 0, indirects.counts, 0, indirects.instances, 0, indirects.drawCount);
              } else {
                md.multiDrawArraysWEBGL(glPrimitive, indirects.offsets, 0, indirects.counts, 0, indirects.drawCount);
              }
            } else {
              for (var _j6 = 0; _j6 < indirects.drawCount; _j6++) {
                if (indirects.instances[_j6] && ia) {
                  ia.drawArraysInstancedANGLE(glPrimitive, indirects.offsets[_j6], indirects.counts[_j6], indirects.instances[_j6]);
                } else {
                  gl.drawArrays(glPrimitive, indirects.offsets[_j6], indirects.counts[_j6]);
                }
              }
            }
          } else if (drawInfo.instanceCount && ia) {
            if (indexBuffer) {
              if (drawInfo.indexCount > 0) {
                var offset = drawInfo.firstIndex * indexBuffer.stride;
                ia.drawElementsInstancedANGLE(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset, drawInfo.instanceCount);
              }
            } else if (drawInfo.vertexCount > 0) {
              ia.drawArraysInstancedANGLE(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount);
            }
          } else if (indexBuffer) {
            if (drawInfo.indexCount > 0) {
              var _offset = drawInfo.firstIndex * indexBuffer.stride;
              gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, _offset);
            }
          } else if (drawInfo.vertexCount > 0) {
            gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount);
          }
        }
      }
      var cmdIds$1 = new Array(WebGLCmd.COUNT);
      function WebGLCmdFuncExecuteCmds(device, cmdPackage) {
        cmdIds$1.fill(0);
        for (var i = 0; i < cmdPackage.cmds.length; ++i) {
          var cmd = cmdPackage.cmds.array[i];
          var cmdId = cmdIds$1[cmd]++;
          switch (cmd) {
            case WebGLCmd.BEGIN_RENDER_PASS:
              {
                var cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId];
                WebGLCmdFuncBeginRenderPass(device, cmd0.gpuRenderPass, cmd0.gpuFramebuffer, cmd0.renderArea, cmd0.clearColors, cmd0.clearDepth, cmd0.clearStencil);
                break;
              }
            case WebGLCmd.BIND_STATES:
              {
                var cmd2 = cmdPackage.bindStatesCmds.array[cmdId];
                WebGLCmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, cmd2.dynamicStates);
                break;
              }
            case WebGLCmd.DRAW:
              {
                var cmd3 = cmdPackage.drawCmds.array[cmdId];
                WebGLCmdFuncDraw(device, cmd3.drawInfo);
                break;
              }
            case WebGLCmd.UPDATE_BUFFER:
              {
                var cmd4 = cmdPackage.updateBufferCmds.array[cmdId];
                WebGLCmdFuncUpdateBuffer(device, cmd4.gpuBuffer, cmd4.buffer, cmd4.offset, cmd4.size);
                break;
              }
            case WebGLCmd.COPY_BUFFER_TO_TEXTURE:
              {
                var cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId];
                WebGLCmdFuncCopyBuffersToTexture(device, cmd5.buffers, cmd5.gpuTexture, cmd5.regions);
                break;
              }
            case WebGLCmd.BLIT_TEXTURE:
              {
                var cmd6 = cmdPackage.blitTextureCmds.array[cmdId];
                WebGLCmdFuncBlitTexture(device, cmd6.srcTexture, cmd6.dstTexture, cmd6.regions, cmd6.filter);
                break;
              }
          }
        }
      }
      function WebGLCmdFuncCopyTexImagesToTexture(device, texImages, gpuTexture, regions) {
        var gl = device.gl;
        var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
        if (glTexUnit.glTexture !== gpuTexture.glTexture) {
          gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
          glTexUnit.glTexture = gpuTexture.glTexture;
        }
        var n = 0;
        var f = 0;
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              for (var i = 0; i < regions.length; i++) {
                var region = regions[i];
                gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, region.texOffset.x, region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]);
              }
              break;
            }
          case gl.TEXTURE_CUBE_MAP:
            {
              for (var _i19 = 0; _i19 < regions.length; _i19++) {
                var _region = regions[_i19];
                var fcount = _region.texSubres.baseArrayLayer + _region.texSubres.layerCount;
                for (f = _region.texSubres.baseArrayLayer; f < fcount; ++f) {
                  gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _region.texSubres.mipLevel, _region.texOffset.x, _region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]);
                }
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy buffer to texture failed.');
            }
        }
        if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP && gpuTexture.isPowerOf2) {
          gl.generateMipmap(gpuTexture.glTarget);
        }
      }
      var stagingBuffer$1 = new Uint8Array(1);
      function pixelBufferPick$1(buffer, format, offset, stride, extent) {
        var blockHeight = formatAlignment(format).height;
        var bufferSize = FormatSize(format, extent.width, extent.height, extent.depth);
        var rowStride = FormatSize(format, stride.width, 1, 1);
        var sliceStride = FormatSize(format, stride.width, stride.height, 1);
        var chunkSize = FormatSize(format, extent.width, 1, 1);
        var ArrayBufferCtor = getTypedArrayConstructor(FormatInfos[format]);
        if (stagingBuffer$1.byteLength < bufferSize) {
          stagingBuffer$1 = new Uint8Array(bufferSize);
        }
        var destOffset = 0;
        var bufferOffset = offset;
        for (var i = 0; i < extent.depth; i++) {
          bufferOffset = offset + sliceStride * i;
          for (var j = 0; j < extent.height; j += blockHeight) {
            stagingBuffer$1.subarray(destOffset, destOffset + chunkSize).set(new Uint8Array(buffer.buffer, buffer.byteOffset + bufferOffset, chunkSize));
            destOffset += chunkSize;
            bufferOffset += rowStride;
          }
        }
        var length = bufferSize / ArrayBufferCtor.BYTES_PER_ELEMENT;
        assertID(Number.isInteger(length), 9101);
        return new ArrayBufferCtor(stagingBuffer$1.buffer, 0, length);
      }
      function WebGLCmdFuncCopyBuffersToTexture(device, buffers, gpuTexture, regions) {
        var gl = device.gl;
        var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
        if (glTexUnit.glTexture !== gpuTexture.glTexture) {
          gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
          glTexUnit.glTexture = gpuTexture.glTexture;
        }
        var n = 0;
        var f = 0;
        var fmtInfo = FormatInfos[gpuTexture.format];
        var ArrayBufferCtor = getTypedArrayConstructor(fmtInfo);
        var isCompressed = fmtInfo.isCompressed;
        var blockSize = formatAlignment(gpuTexture.format);
        var extent = new Extent();
        var offset = new Offset();
        var stride = new Extent();
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              for (var i = 0; i < regions.length; i++) {
                var region = regions[i];
                var mipLevel = region.texSubres.mipLevel;
                offset.x = region.texOffset.x === 0 ? 0 : alignTo(region.texOffset.x, blockSize.width);
                offset.y = region.texOffset.y === 0 ? 0 : alignTo(region.texOffset.y, blockSize.height);
                extent.width = region.texExtent.width < blockSize.width ? region.texExtent.width : alignTo(region.texExtent.width, blockSize.width);
                extent.height = region.texExtent.height < blockSize.height ? region.texExtent.width : alignTo(region.texExtent.height, blockSize.height);
                stride.width = region.buffStride > 0 ? region.buffStride : extent.width;
                stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
                var destWidth = region.texExtent.width + offset.x === gpuTexture.width >> mipLevel ? region.texExtent.width : extent.width;
                var destHeight = region.texExtent.height + offset.y === gpuTexture.height >> mipLevel ? region.texExtent.height : extent.height;
                var pixels = void 0;
                var buffer = buffers[n++];
                if (stride.width === extent.width && stride.height === extent.height) {
                  var length = FormatSize(gpuTexture.format, destWidth, destHeight, 1) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                  assertID(Number.isInteger(length), 9101);
                  pixels = new ArrayBufferCtor(buffer.buffer, buffer.byteOffset + region.buffOffset, length);
                } else {
                  pixels = pixelBufferPick$1(buffer, gpuTexture.format, region.buffOffset, stride, extent);
                }
                if (!isCompressed) {
                  gl.texSubImage2D(gl.TEXTURE_2D, mipLevel, offset.x, offset.y, destWidth, destHeight, gpuTexture.glFormat, gpuTexture.glType, pixels);
                } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !device.extensions.noCompressedTexSubImage2D) {
                  gl.compressedTexSubImage2D(gl.TEXTURE_2D, mipLevel, offset.x, offset.y, destWidth, destHeight, gpuTexture.glFormat, pixels);
                } else {
                  gl.compressedTexImage2D(gl.TEXTURE_2D, mipLevel, gpuTexture.glInternalFmt, destWidth, destHeight, 0, pixels);
                }
              }
              break;
            }
          case gl.TEXTURE_CUBE_MAP:
            {
              for (var _i20 = 0; _i20 < regions.length; _i20++) {
                var _region2 = regions[_i20];
                var _mipLevel = _region2.texSubres.mipLevel;
                offset.x = _region2.texOffset.x === 0 ? 0 : alignTo(_region2.texOffset.x, blockSize.width);
                offset.y = _region2.texOffset.y === 0 ? 0 : alignTo(_region2.texOffset.y, blockSize.height);
                extent.width = _region2.texExtent.width < blockSize.width ? _region2.texExtent.width : alignTo(_region2.texExtent.width, blockSize.width);
                extent.height = _region2.texExtent.height < blockSize.height ? _region2.texExtent.width : alignTo(_region2.texExtent.height, blockSize.height);
                stride.width = _region2.buffStride > 0 ? _region2.buffStride : extent.width;
                stride.height = _region2.buffTexHeight > 0 ? _region2.buffTexHeight : extent.height;
                var _destWidth = _region2.texExtent.width + offset.x === gpuTexture.width >> _mipLevel ? _region2.texExtent.width : extent.width;
                var _destHeight = _region2.texExtent.height + offset.y === gpuTexture.height >> _mipLevel ? _region2.texExtent.height : extent.height;
                var fcount = _region2.texSubres.baseArrayLayer + _region2.texSubres.layerCount;
                for (f = _region2.texSubres.baseArrayLayer; f < fcount; ++f) {
                  var _pixels = void 0;
                  var _buffer = buffers[n++];
                  if (stride.width === extent.width && stride.height === extent.height) {
                    var _length = FormatSize(gpuTexture.format, _destWidth, _destHeight, 1) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                    assertID(Number.isInteger(_length), 9101);
                    _pixels = new ArrayBufferCtor(_buffer.buffer, _buffer.byteOffset + _region2.buffOffset, _length);
                  } else {
                    _pixels = pixelBufferPick$1(_buffer, gpuTexture.format, _region2.buffOffset, stride, extent);
                  }
                  if (!isCompressed) {
                    gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel, offset.x, offset.y, _destWidth, _destHeight, gpuTexture.glFormat, gpuTexture.glType, _pixels);
                  } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !device.extensions.noCompressedTexSubImage2D) {
                    gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel, offset.x, offset.y, _destWidth, _destHeight, gpuTexture.glFormat, _pixels);
                  } else {
                    gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel, gpuTexture.glInternalFmt, _destWidth, _destHeight, 0, _pixels);
                  }
                }
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy buffer to texture failed.');
            }
        }
        if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) {
          gl.generateMipmap(gpuTexture.glTarget);
        }
      }
      function WebGLCmdFuncCopyTextureToBuffers(device, gpuTexture, buffers, regions) {
        var gl = device.gl;
        var cache = device.stateCache;
        var framebuffer = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
        var x = 0;
        var y = 0;
        var w = 1;
        var h = 1;
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              for (var k = 0; k < regions.length; k++) {
                var region = regions[k];
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gpuTexture.glTarget, gpuTexture.glTexture, region.texSubres.mipLevel);
                x = region.texOffset.x;
                y = region.texOffset.y;
                w = region.texExtent.width;
                h = region.texExtent.height;
                gl.readPixels(x, y, w, h, gpuTexture.glFormat, gpuTexture.glType, buffers[k]);
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy texture to buffers failed.');
            }
        }
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        cache.glFramebuffer = null;
        gl.deleteFramebuffer(framebuffer);
      }
      function WebGLCmdFuncBlitTexture(device, srcTexture, dstTexture, regions, filter) {
        device.blitManager.draw(srcTexture, dstTexture, regions, filter);
      }

      var WebGLIndirectDrawInfos = function () {
        function WebGLIndirectDrawInfos() {
          this.counts = void 0;
          this.offsets = void 0;
          this.instances = void 0;
          this.drawCount = 0;
          this.drawByIndex = false;
          this.instancedDraw = false;
          this.byteOffsets = void 0;
          this._capacity = 4;
          this.counts = new Int32Array(this._capacity);
          this.offsets = new Int32Array(this._capacity);
          this.instances = new Int32Array(this._capacity);
          this.byteOffsets = new Int32Array(this._capacity);
        }
        var _proto = WebGLIndirectDrawInfos.prototype;
        _proto.clearDraws = function clearDraws() {
          this.drawCount = 0;
          this.drawByIndex = false;
          this.instancedDraw = false;
        };
        _proto.setDrawInfo = function setDrawInfo(idx, info) {
          this._ensureCapacity(idx);
          this.drawByIndex = info.indexCount > 0;
          this.instancedDraw = !!info.instanceCount;
          this.drawCount = Math.max(idx + 1, this.drawCount);
          if (this.drawByIndex) {
            this.counts[idx] = info.indexCount;
            this.offsets[idx] = info.firstIndex;
          } else {
            this.counts[idx] = info.vertexCount;
            this.offsets[idx] = info.firstVertex;
          }
          this.instances[idx] = Math.max(1, info.instanceCount);
        };
        _proto._ensureCapacity = function _ensureCapacity(target) {
          if (this._capacity > target) return;
          this._capacity = nextPow2(target);
          var counts = new Int32Array(this._capacity);
          var offsets = new Int32Array(this._capacity);
          var instances = new Int32Array(this._capacity);
          this.byteOffsets = new Int32Array(this._capacity);
          counts.set(this.counts);
          offsets.set(this.offsets);
          instances.set(this.instances);
          this.counts = counts;
          this.offsets = offsets;
          this.instances = instances;
        };
        return WebGLIndirectDrawInfos;
      }();
      var IWebGLBlitManager = function () {
        function IWebGLBlitManager() {
          this._gpuShader = null;
          this._gpuDescriptorSetLayout = null;
          this._gpuPipelineLayout = null;
          this._gpuPipelineState = null;
          this._gpuVertexBuffer = null;
          this._gpuInputAssembler = null;
          this._gpuPointSampler = null;
          this._gpuLinearSampler = null;
          this._gpuDescriptorSet = null;
          this._gpuUniformBuffer = null;
          this._drawInfo = null;
          this._glFramebuffer = null;
          this._uniformBuffer = null;
          var gl = WebGLDeviceManager.instance.gl;
          var device = WebGLDeviceManager.instance;
          var samplerOffset = device.bindingMappingInfo.maxBlockCounts[0];
          this._gpuShader = {
            name: 'Blit Pass',
            blocks: [new UniformBlock(0, 0, "BlitParams", [new Uniform("tilingOffsetSrc", Type$1.FLOAT4, 1), new Uniform("tilingOffsetDst", Type$1.FLOAT4, 1)], 1)],
            samplerTextures: [new UniformSamplerTexture(0, samplerOffset, 'textureSrc', Type$1.SAMPLER2D, 1)],
            subpassInputs: [],
            gpuStages: [{
              type: ShaderStageFlagBit.VERTEX,
              source: "\n                    precision mediump float;\n\n                    attribute vec2 a_position;\n                    attribute vec2 a_texCoord;\n            \n                    uniform vec4 tilingOffsetSrc;\n                    uniform vec4 tilingOffsetDst;\n            \n                    varying vec2 v_texCoord;\n            \n                    void main() {\n                        v_texCoord = a_texCoord * tilingOffsetSrc.xy + tilingOffsetSrc.zw;\n                        gl_Position = vec4((a_position + 1.0) * tilingOffsetDst.xy - 1.0 + tilingOffsetDst.zw * 2.0, 0, 1);\n                    }",
              glShader: null
            }, {
              type: ShaderStageFlagBit.FRAGMENT,
              source: "\n                    precision mediump float;\n                    uniform sampler2D textureSrc;\n\n                    varying vec2 v_texCoord;\n                    \n                    void main() {\n                        gl_FragColor = texture2D(textureSrc, v_texCoord);\n                    }",
              glShader: null
            }],
            glProgram: null,
            glInputs: [],
            glUniforms: [],
            glBlocks: [],
            glSamplerTextures: []
          };
          WebGLCmdFuncCreateShader(WebGLDeviceManager.instance, this._gpuShader);
          this._gpuDescriptorSetLayout = {
            bindings: [new DescriptorSetLayoutBinding(0, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX), new DescriptorSetLayoutBinding(samplerOffset, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT)],
            dynamicBindings: [],
            descriptorIndices: [],
            descriptorCount: samplerOffset + 1
          };
          for (var i = 0; i < samplerOffset; i++) {
            this._gpuDescriptorSetLayout.descriptorIndices[i] = 0;
          }
          this._gpuDescriptorSetLayout.descriptorIndices.push(1);
          this._gpuPipelineLayout = {
            gpuSetLayouts: [this._gpuDescriptorSetLayout],
            dynamicOffsetCount: 0,
            dynamicOffsetOffsets: [0],
            dynamicOffsetIndices: [[]]
          };
          this._gpuPipelineState = {
            glPrimitive: gl.TRIANGLE_STRIP,
            gpuShader: this._gpuShader,
            gpuPipelineLayout: this._gpuPipelineLayout,
            rs: null,
            dss: new DepthStencilState(false, false),
            bs: null,
            dynamicStates: [],
            gpuRenderPass: null
          };
          this._gpuVertexBuffer = {
            usage: BufferUsageBit.VERTEX,
            memUsage: MemoryUsageBit.DEVICE,
            size: 16 * Float32Array.BYTES_PER_ELEMENT,
            stride: 4 * Float32Array.BYTES_PER_ELEMENT,
            buffer: null,
            vf32: null,
            indirects: new WebGLIndirectDrawInfos(),
            glTarget: 0,
            glBuffer: null
          };
          WebGLCmdFuncCreateBuffer(WebGLDeviceManager.instance, this._gpuVertexBuffer);
          WebGLDeviceManager.instance.memoryStatus.bufferSize += this._gpuVertexBuffer.size;
          var data = new Float32Array([-1.0, -1.0, 0.0, 0.0, 1.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0]);
          WebGLCmdFuncUpdateBuffer(WebGLDeviceManager.instance, this._gpuVertexBuffer, data, 0, data.length);
          this._gpuInputAssembler = {
            attributes: [new Attribute("a_position", Format.RG32F), new Attribute("a_texCoord", Format.RG32F)],
            gpuVertexBuffers: [this._gpuVertexBuffer],
            gpuIndexBuffer: null,
            gpuIndirectBuffer: null,
            glAttribs: [],
            glIndexType: 0,
            glVAOs: new Map()
          };
          WebGLCmdFuncCreateInputAssember(WebGLDeviceManager.instance, this._gpuInputAssembler);
          this._gpuPointSampler = {
            glMinFilter: 0x2600,
            glMagFilter: 0x2600,
            glWrapS: 0x2901,
            glWrapT: 0x2901,
            glWrapR: 0x2901
          };
          this._gpuLinearSampler = {
            glMinFilter: 0x2601,
            glMagFilter: 0x2601,
            glWrapS: 0x2901,
            glWrapT: 0x2901,
            glWrapR: 0x2901
          };
          this._uniformBuffer = new Float32Array(8);
          this._gpuUniformBuffer = {
            usage: BufferUsageBit.UNIFORM,
            memUsage: MemoryUsageBit.DEVICE,
            size: 8 * Float32Array.BYTES_PER_ELEMENT,
            stride: 8 * Float32Array.BYTES_PER_ELEMENT,
            buffer: this._uniformBuffer,
            vf32: null,
            indirects: new WebGLIndirectDrawInfos(),
            glTarget: 0,
            glBuffer: null
          };
          WebGLCmdFuncCreateBuffer(WebGLDeviceManager.instance, this._gpuUniformBuffer);
          WebGLDeviceManager.instance.memoryStatus.bufferSize += this._gpuUniformBuffer.size;
          this._gpuDescriptorSet = {
            gpuDescriptors: [{
              type: DescriptorType.UNIFORM_BUFFER,
              gpuBuffer: this._gpuUniformBuffer,
              gpuTexture: null,
              gpuSampler: null
            }, {
              type: DescriptorType.SAMPLER_TEXTURE,
              gpuBuffer: null,
              gpuTexture: null,
              gpuSampler: null
            }],
            descriptorIndices: this._gpuDescriptorSetLayout.descriptorIndices
          };
          this._drawInfo = new DrawInfo(4, 0, 0, 0, 0, 0, 0);
          this._glFramebuffer = WebGLDeviceManager.instance.gl.createFramebuffer();
        }
        var _proto2 = IWebGLBlitManager.prototype;
        _proto2.destroy = function destroy() {
          if (this._glFramebuffer) {
            WebGLDeviceManager.instance.gl.deleteFramebuffer(this._glFramebuffer);
            this._glFramebuffer = null;
          }
          if (this._gpuVertexBuffer) {
            WebGLDeviceManager.instance.memoryStatus.bufferSize -= this._gpuVertexBuffer.size;
            WebGLCmdFuncDestroyBuffer(WebGLDeviceManager.instance, this._gpuVertexBuffer);
          }
          if (this._gpuUniformBuffer) {
            WebGLDeviceManager.instance.memoryStatus.bufferSize -= this._gpuUniformBuffer.size;
            WebGLCmdFuncDestroyBuffer(WebGLDeviceManager.instance, this._gpuUniformBuffer);
          }
          if (this._gpuShader) {
            WebGLCmdFuncDestroyShader(WebGLDeviceManager.instance, this._gpuShader);
          }
          if (this._gpuInputAssembler) {
            WebGLCmdFuncDestroyInputAssembler(WebGLDeviceManager.instance, this._gpuInputAssembler);
          }
        };
        _proto2.draw = function draw(gpuTextureSrc, gpuTextureDst, regions, filter) {
          var device = WebGLDeviceManager.instance;
          var gl = device.gl;
          var stateCache = device.stateCache;
          var origFramebuffer = stateCache.glFramebuffer;
          gl.viewport(0, 0, gpuTextureDst.width, gpuTextureDst.height);
          gl.scissor(0, 0, gpuTextureDst.width, gpuTextureDst.height);
          if (!this._uniformBuffer || !this._gpuUniformBuffer || !this._gpuPipelineState || !this._gpuInputAssembler || !this._gpuDescriptorSet || !this._drawInfo) {
            return;
          }
          var descriptor = this._gpuDescriptorSet.gpuDescriptors[1];
          descriptor.gpuTexture = gpuTextureSrc;
          descriptor.gpuSampler = filter === Filter$1.POINT ? this._gpuPointSampler : this._gpuLinearSampler;
          var formatInfo = FormatInfos[gpuTextureDst.format];
          var attachment = gl.COLOR_ATTACHMENT0;
          if (formatInfo.hasStencil) {
            attachment = gl.DEPTH_STENCIL_ATTACHMENT;
          } else if (formatInfo.hasDepth) {
            attachment = gl.DEPTH_ATTACHMENT;
          }
          var regionIndices = regions.map(function (_, i) {
            return i;
          });
          regionIndices.sort(function (a, b) {
            return regions[a].srcSubres.mipLevel - regions[b].srcSubres.mipLevel;
          });
          if (stateCache.glFramebuffer !== this._glFramebuffer) {
            device.gl.bindFramebuffer(device.gl.FRAMEBUFFER, this._glFramebuffer);
            stateCache.glFramebuffer = this._glFramebuffer;
          }
          var mipLevel = regions[0].dstSubres.mipLevel;
          if (gpuTextureDst.glTexture) {
            gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gpuTextureDst.glTarget, gpuTextureDst.glTexture, mipLevel);
          } else {
            gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, gpuTextureDst.glRenderbuffer);
          }
          for (var i = 0; i < regionIndices.length; ++i) {
            var region = regions[regionIndices[i]];
            if (gpuTextureSrc.glTexture && mipLevel !== region.srcSubres.mipLevel) {
              mipLevel = region.srcSubres.mipLevel;
              gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gpuTextureDst.glTarget, gpuTextureDst.glTexture, mipLevel);
            }
            var srcWidth = gpuTextureSrc.width;
            var srcHeight = gpuTextureSrc.height;
            var dstWidth = gpuTextureDst.width;
            var dstHeight = gpuTextureDst.height;
            this._uniformBuffer[0] = region.srcExtent.width / srcWidth;
            this._uniformBuffer[1] = region.srcExtent.height / srcHeight;
            this._uniformBuffer[2] = region.srcOffset.x / srcWidth;
            this._uniformBuffer[3] = region.srcOffset.y / srcHeight;
            this._uniformBuffer[4] = region.dstExtent.width / dstWidth;
            this._uniformBuffer[5] = region.dstExtent.height / dstHeight;
            this._uniformBuffer[6] = region.dstOffset.x / dstWidth;
            this._uniformBuffer[7] = region.dstOffset.y / dstHeight;
            WebGLCmdFuncUpdateBuffer(device, this._gpuUniformBuffer, this._uniformBuffer, 0, this._uniformBuffer.length * Float32Array.BYTES_PER_ELEMENT);
            WebGLCmdFuncBindStates(device, this._gpuPipelineState, this._gpuInputAssembler, [this._gpuDescriptorSet], [], null);
            WebGLCmdFuncDraw(device, this._drawInfo);
          }
          if (stateCache.glFramebuffer !== origFramebuffer) {
            device.gl.bindFramebuffer(device.gl.FRAMEBUFFER, origFramebuffer);
            stateCache.glFramebuffer = origFramebuffer;
          }
          var origViewport = stateCache.viewport;
          gl.viewport(origViewport.left, origViewport.top, origViewport.width, origViewport.height);
          var origScissor = stateCache.scissorRect;
          gl.scissor(origScissor.x, origScissor.y, origScissor.width, origScissor.height);
        };
        return IWebGLBlitManager;
      }();

      var WebGLBuffer = function (_Buffer) {
        _inheritsLoose(WebGLBuffer, _Buffer);
        function WebGLBuffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Buffer.call.apply(_Buffer, [this].concat(args)) || this;
          _this._gpuBuffer = null;
          _this._gpuBufferView = null;
          _this._uniformBuffer = null;
          return _this;
        }
        var _proto = WebGLBuffer.prototype;
        _proto.initialize = function initialize(info) {
          if ('buffer' in info) {
            this._isBufferView = true;
            var buffer = info.buffer;
            this._usage = buffer.usage;
            this._memUsage = buffer.memUsage;
            this._size = this._stride = info.range;
            this._count = 1;
            this._flags = buffer.flags;
            this._gpuBufferView = {
              gpuBuffer: buffer.gpuBuffer,
              offset: info.offset,
              range: info.range
            };
          } else {
            this._usage = info.usage;
            this._memUsage = info.memUsage;
            this._size = info.size;
            this._stride = Math.max(info.stride || this._size, 1);
            this._count = this._size / this._stride;
            this._flags = info.flags;
            if (this._usage & BufferUsageBit.UNIFORM && this._size > 0) {
              this._uniformBuffer = new Uint8Array(this._size);
            }
            this._gpuBuffer = {
              usage: this._usage,
              memUsage: this._memUsage,
              size: this._size,
              stride: this._stride,
              buffer: null,
              vf32: null,
              indirects: new WebGLIndirectDrawInfos(),
              glTarget: 0,
              glBuffer: null
            };
            if (this._usage & BufferUsageBit.UNIFORM) {
              this._gpuBuffer.buffer = this._uniformBuffer;
            }
            WebGLCmdFuncCreateBuffer(WebGLDeviceManager.instance, this._gpuBuffer);
            WebGLDeviceManager.instance.memoryStatus.bufferSize += this._size;
          }
        };
        _proto.destroy = function destroy() {
          if (this._gpuBuffer) {
            WebGLCmdFuncDestroyBuffer(WebGLDeviceManager.instance, this._gpuBuffer);
            WebGLDeviceManager.instance.memoryStatus.bufferSize -= this._size;
            this._gpuBuffer = null;
          }
          if (this._gpuBufferView) {
            this._gpuBufferView = null;
          }
        };
        _proto.resize = function resize(size) {
          if (this._isBufferView) {
            console.warn('cannot resize buffer views!');
            return;
          }
          var oldSize = this._size;
          if (oldSize === size) {
            return;
          }
          this._size = size;
          this._count = this._size / this._stride;
          if (this._uniformBuffer) {
            this._uniformBuffer = new Uint8Array(size);
          }
          if (this._gpuBuffer) {
            if (this._uniformBuffer) {
              this._gpuBuffer.buffer = this._uniformBuffer;
            }
            this._gpuBuffer.size = size;
            if (size > 0) {
              WebGLCmdFuncResizeBuffer(WebGLDeviceManager.instance, this._gpuBuffer);
              WebGLDeviceManager.instance.memoryStatus.bufferSize -= oldSize;
              WebGLDeviceManager.instance.memoryStatus.bufferSize += size;
            }
          }
        };
        _proto.update = function update(buffer, size) {
          if (this._isBufferView) {
            console.warn('cannot update through buffer views!');
            return;
          }
          var buffSize;
          if (size !== undefined) {
            buffSize = size;
          } else if (this._usage & BufferUsageBit.INDIRECT) {
            buffSize = 0;
          } else {
            buffSize = buffer.byteLength;
          }
          WebGLCmdFuncUpdateBuffer(WebGLDeviceManager.instance, this._gpuBuffer, buffer, 0, buffSize);
        };
        _createClass(WebGLBuffer, [{
          key: "gpuBuffer",
          get: function get() {
            return this._gpuBuffer;
          }
        }, {
          key: "gpuBufferView",
          get: function get() {
            return this._gpuBufferView;
          }
        }]);
        return WebGLBuffer;
      }(Buffer);

      var WebGLCommandPool = function () {
        function WebGLCommandPool(Clazz, count) {
          this._frees = void 0;
          this._freeIdx = 0;
          this._freeCmds = void 0;
          this._frees = new Array(count);
          this._freeCmds = new CachedArray(count);
          for (var i = 0; i < count; ++i) {
            this._frees[i] = new Clazz();
          }
          this._freeIdx = count - 1;
        }
        var _proto = WebGLCommandPool.prototype;
        _proto.alloc = function alloc(Clazz) {
          if (this._freeIdx < 0) {
            var size = this._frees.length * 2;
            var temp = this._frees;
            this._frees = new Array(size);
            var increase = size - temp.length;
            for (var i = 0; i < increase; ++i) {
              this._frees[i] = new Clazz();
            }
            for (var _i = increase, j = 0; _i < size; ++_i, ++j) {
              this._frees[_i] = temp[j];
            }
            this._freeIdx += increase;
          }
          var cmd = this._frees[this._freeIdx];
          this._frees[this._freeIdx--] = null;
          ++cmd.refCount;
          return cmd;
        };
        _proto.free = function free(cmd) {
          if (--cmd.refCount === 0) {
            this._freeCmds.push(cmd);
          }
        };
        _proto.freeCmds = function freeCmds(cmds) {
          for (var i = 0; i < cmds.length; ++i) {
            if (--cmds.array[i].refCount === 0) {
              this._freeCmds.push(cmds.array[i]);
            }
          }
        };
        _proto.release = function release() {
          for (var i = 0; i < this._freeCmds.length; ++i) {
            var cmd = this._freeCmds.array[i];
            cmd.clear();
            this._frees[++this._freeIdx] = cmd;
          }
          this._freeCmds.clear();
        };
        return WebGLCommandPool;
      }();
      var WebGLCommandAllocator = function () {
        function WebGLCommandAllocator() {
          this.beginRenderPassCmdPool = void 0;
          this.bindStatesCmdPool = void 0;
          this.drawCmdPool = void 0;
          this.updateBufferCmdPool = void 0;
          this.copyBufferToTextureCmdPool = void 0;
          this.blitTextureCmdPool = void 0;
          this.beginRenderPassCmdPool = new WebGLCommandPool(WebGLCmdBeginRenderPass, 1);
          this.bindStatesCmdPool = new WebGLCommandPool(WebGLCmdBindStates, 1);
          this.drawCmdPool = new WebGLCommandPool(WebGLCmdDraw, 1);
          this.updateBufferCmdPool = new WebGLCommandPool(WebGLCmdUpdateBuffer, 1);
          this.copyBufferToTextureCmdPool = new WebGLCommandPool(WebGLCmdCopyBufferToTexture, 1);
          this.blitTextureCmdPool = new WebGLCommandPool(WebGLCmdBlitTexture, 1);
        }
        var _proto2 = WebGLCommandAllocator.prototype;
        _proto2.clearCmds = function clearCmds(cmdPackage) {
          if (cmdPackage.beginRenderPassCmds.length) {
            this.beginRenderPassCmdPool.freeCmds(cmdPackage.beginRenderPassCmds);
            cmdPackage.beginRenderPassCmds.clear();
          }
          if (cmdPackage.bindStatesCmds.length) {
            this.bindStatesCmdPool.freeCmds(cmdPackage.bindStatesCmds);
            cmdPackage.bindStatesCmds.clear();
          }
          if (cmdPackage.drawCmds.length) {
            this.drawCmdPool.freeCmds(cmdPackage.drawCmds);
            cmdPackage.drawCmds.clear();
          }
          if (cmdPackage.updateBufferCmds.length) {
            this.updateBufferCmdPool.freeCmds(cmdPackage.updateBufferCmds);
            cmdPackage.updateBufferCmds.clear();
          }
          if (cmdPackage.copyBufferToTextureCmds.length) {
            this.copyBufferToTextureCmdPool.freeCmds(cmdPackage.copyBufferToTextureCmds);
            cmdPackage.copyBufferToTextureCmds.clear();
          }
          if (cmdPackage.blitTextureCmds.length) {
            this.blitTextureCmdPool.freeCmds(cmdPackage.blitTextureCmds);
            cmdPackage.blitTextureCmds.clear();
          }
          cmdPackage.cmds.clear();
        };
        _proto2.releaseCmds = function releaseCmds() {
          this.beginRenderPassCmdPool.release();
          this.bindStatesCmdPool.release();
          this.drawCmdPool.release();
          this.updateBufferCmdPool.release();
          this.copyBufferToTextureCmdPool.release();
          this.blitTextureCmdPool.release();
        };
        return WebGLCommandAllocator;
      }();

      var WebGLCommandBuffer = function (_CommandBuffer) {
        _inheritsLoose(WebGLCommandBuffer, _CommandBuffer);
        function WebGLCommandBuffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _CommandBuffer.call.apply(_CommandBuffer, [this].concat(args)) || this;
          _this.cmdPackage = new WebGLCmdPackage();
          _this._cmdAllocator = new WebGLCommandAllocator();
          _this._isInRenderPass = false;
          _this._curGPUPipelineState = null;
          _this._curGPUInputAssembler = null;
          _this._curGPUDescriptorSets = [];
          _this._curDynamicOffsets = Array(8).fill(0);
          _this._curDynamicStates = new DynamicStates();
          _this._isStateInvalied = false;
          return _this;
        }
        var _proto = WebGLCommandBuffer.prototype;
        _proto.initialize = function initialize(info) {
          this._type = info.type;
          this._queue = info.queue;
          var setCount = WebGLDeviceManager.instance.bindingMappings.blockOffsets.length;
          for (var i = 0; i < setCount; i++) {
            this._curGPUDescriptorSets.push(null);
          }
        };
        _proto.destroy = function destroy() {
          this._cmdAllocator.clearCmds(this.cmdPackage);
        };
        _proto.begin = function begin(renderPass, subpass, frameBuffer) {
          this._cmdAllocator.clearCmds(this.cmdPackage);
          this._curGPUPipelineState = null;
          this._curGPUInputAssembler = null;
          this._curGPUDescriptorSets.length = 0;
          this._numDrawCalls = 0;
          this._numInstances = 0;
          this._numTris = 0;
        };
        _proto.end = function end() {
          if (this._isStateInvalied) {
            this.bindStates();
          }
          this._isInRenderPass = false;
        };
        _proto.beginRenderPass = function beginRenderPass(renderPass, framebuffer, renderArea, clearColors, clearDepth, clearStencil) {
          var cmd = this._cmdAllocator.beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass);
          cmd.gpuRenderPass = renderPass.gpuRenderPass;
          cmd.gpuFramebuffer = framebuffer.gpuFramebuffer;
          cmd.renderArea.copy(renderArea);
          cmd.clearColors.length = clearColors.length;
          for (var i = 0; i < clearColors.length; ++i) {
            cmd.clearColors[i] = clearColors[i];
          }
          cmd.clearDepth = clearDepth;
          cmd.clearStencil = clearStencil;
          this.cmdPackage.beginRenderPassCmds.push(cmd);
          this.cmdPackage.cmds.push(WebGLCmd.BEGIN_RENDER_PASS);
          this._isInRenderPass = true;
        };
        _proto.endRenderPass = function endRenderPass() {
          this._isInRenderPass = false;
        };
        _proto.bindPipelineState = function bindPipelineState(pipelineState) {
          var gpuPipelineState = pipelineState.gpuPipelineState;
          if (gpuPipelineState !== this._curGPUPipelineState) {
            this._curGPUPipelineState = gpuPipelineState;
            this._isStateInvalied = true;
          }
        };
        _proto.bindDescriptorSet = function bindDescriptorSet(set, descriptorSet, dynamicOffsets) {
          var gpuDescriptorSet = descriptorSet.gpuDescriptorSet;
          if (gpuDescriptorSet !== this._curGPUDescriptorSets[set]) {
            this._curGPUDescriptorSets[set] = gpuDescriptorSet;
            this._isStateInvalied = true;
          }
          if (dynamicOffsets) {
            var _this$_curGPUPipeline;
            var gpuPipelineLayout = (_this$_curGPUPipeline = this._curGPUPipelineState) === null || _this$_curGPUPipeline === void 0 ? void 0 : _this$_curGPUPipeline.gpuPipelineLayout;
            if (gpuPipelineLayout) {
              var offsets = this._curDynamicOffsets;
              var idx = gpuPipelineLayout.dynamicOffsetOffsets[set];
              for (var i = 0; i < dynamicOffsets.length; i++) offsets[idx + i] = dynamicOffsets[i];
              this._isStateInvalied = true;
            }
          }
        };
        _proto.bindInputAssembler = function bindInputAssembler(inputAssembler) {
          var gpuInputAssembler = inputAssembler.gpuInputAssembler;
          this._curGPUInputAssembler = gpuInputAssembler;
          this._isStateInvalied = true;
        };
        _proto.setViewport = function setViewport(viewport) {
          var cache = this._curDynamicStates.viewport;
          if (cache.left !== viewport.left || cache.top !== viewport.top || cache.width !== viewport.width || cache.height !== viewport.height || cache.minDepth !== viewport.minDepth || cache.maxDepth !== viewport.maxDepth) {
            cache.left = viewport.left;
            cache.top = viewport.top;
            cache.width = viewport.width;
            cache.height = viewport.height;
            cache.minDepth = viewport.minDepth;
            cache.maxDepth = viewport.maxDepth;
            this._isStateInvalied = true;
          }
        };
        _proto.setScissor = function setScissor(scissor) {
          var cache = this._curDynamicStates.scissor;
          if (cache.x !== scissor.x || cache.y !== scissor.y || cache.width !== scissor.width || cache.height !== scissor.height) {
            cache.x = scissor.x;
            cache.y = scissor.y;
            cache.width = scissor.width;
            cache.height = scissor.height;
            this._isStateInvalied = true;
          }
        };
        _proto.setLineWidth = function setLineWidth(lineWidth) {
          if (this._curDynamicStates.lineWidth !== lineWidth) {
            this._curDynamicStates.lineWidth = lineWidth;
            this._isStateInvalied = true;
          }
        };
        _proto.setDepthBias = function setDepthBias(depthBiasConstantFactor, depthBiasClamp, depthBiasSlopeFactor) {
          var cache = this._curDynamicStates;
          if (cache.depthBiasConstant !== depthBiasConstantFactor || cache.depthBiasClamp !== depthBiasClamp || cache.depthBiasSlope !== depthBiasSlopeFactor) {
            cache.depthBiasConstant = depthBiasConstantFactor;
            cache.depthBiasClamp = depthBiasClamp;
            cache.depthBiasSlope = depthBiasSlopeFactor;
            this._isStateInvalied = true;
          }
        };
        _proto.setBlendConstants = function setBlendConstants(blendConstants) {
          var cache = this._curDynamicStates.blendConstant;
          if (cache.x !== blendConstants.x || cache.y !== blendConstants.y || cache.z !== blendConstants.z || cache.w !== blendConstants.w) {
            cache.copy(blendConstants);
            this._isStateInvalied = true;
          }
        };
        _proto.setDepthBound = function setDepthBound(minDepthBounds, maxDepthBounds) {
          var cache = this._curDynamicStates;
          if (cache.depthMinBounds !== minDepthBounds || cache.depthMaxBounds !== maxDepthBounds) {
            cache.depthMinBounds = minDepthBounds;
            cache.depthMaxBounds = maxDepthBounds;
            this._isStateInvalied = true;
          }
        };
        _proto.setStencilWriteMask = function setStencilWriteMask(face, writeMask) {
          var front = this._curDynamicStates.stencilStatesFront;
          var back = this._curDynamicStates.stencilStatesBack;
          if (face & StencilFace.FRONT) {
            if (front.writeMask !== writeMask) {
              front.writeMask = writeMask;
              this._isStateInvalied = true;
            }
          }
          if (face & StencilFace.BACK) {
            if (back.writeMask !== writeMask) {
              back.writeMask = writeMask;
              this._isStateInvalied = true;
            }
          }
        };
        _proto.setStencilCompareMask = function setStencilCompareMask(face, reference, compareMask) {
          var front = this._curDynamicStates.stencilStatesFront;
          var back = this._curDynamicStates.stencilStatesBack;
          if (face & StencilFace.FRONT) {
            if (front.compareMask !== compareMask || front.reference !== reference) {
              front.reference = reference;
              front.compareMask = compareMask;
              this._isStateInvalied = true;
            }
          }
          if (face & StencilFace.BACK) {
            if (back.compareMask !== compareMask || back.reference !== reference) {
              back.reference = reference;
              back.compareMask = compareMask;
              this._isStateInvalied = true;
            }
          }
        };
        _proto.draw = function draw(infoOrAssembler) {
          if (this._type === CommandBufferType.PRIMARY && this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            if (this._isStateInvalied) {
              this.bindStates();
            }
            var info = 'drawInfo' in infoOrAssembler ? infoOrAssembler.drawInfo : infoOrAssembler;
            var cmd = this._cmdAllocator.drawCmdPool.alloc(WebGLCmdDraw);
            cmd.drawInfo.copy(info);
            this.cmdPackage.drawCmds.push(cmd);
            this.cmdPackage.cmds.push(WebGLCmd.DRAW);
            ++this._numDrawCalls;
            this._numInstances += info.instanceCount;
            var indexCount = info.indexCount || info.vertexCount;
            if (this._curGPUPipelineState) {
              var glPrimitive = this._curGPUPipelineState.glPrimitive;
              switch (glPrimitive) {
                case 0x0004:
                  {
                    this._numTris += indexCount / 3 * Math.max(info.instanceCount, 1);
                    break;
                  }
                case 0x0005:
                case 0x0006:
                  {
                    this._numTris += (indexCount - 2) * Math.max(info.instanceCount, 1);
                    break;
                  }
              }
            }
          } else {
            console.error('Command \'draw\' must be recorded inside a render pass.');
          }
        };
        _proto.updateBuffer = function updateBuffer(buffer, data, size) {
          if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            var gpuBuffer = buffer.gpuBuffer;
            if (gpuBuffer) {
              var cmd = this._cmdAllocator.updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer);
              var buffSize = 0;
              var buff = null;
              if (buffer.usage & BufferUsageBit.INDIRECT) {
                buff = data;
              } else {
                if (size !== undefined) {
                  buffSize = size;
                } else {
                  buffSize = data.byteLength;
                }
                buff = data;
              }
              cmd.gpuBuffer = gpuBuffer;
              cmd.buffer = buff;
              cmd.offset = 0;
              cmd.size = buffSize;
              this.cmdPackage.updateBufferCmds.push(cmd);
              this.cmdPackage.cmds.push(WebGLCmd.UPDATE_BUFFER);
            }
          } else {
            console.error('Command \'updateBuffer\' must be recorded outside a render pass.');
          }
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            var gpuTexture = texture.gpuTexture;
            if (gpuTexture) {
              var cmd = this._cmdAllocator.copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture);
              if (cmd) {
                cmd.gpuTexture = gpuTexture;
                cmd.regions = regions;
                cmd.buffers = buffers;
                this.cmdPackage.copyBufferToTextureCmds.push(cmd);
                this.cmdPackage.cmds.push(WebGLCmd.COPY_BUFFER_TO_TEXTURE);
              }
            }
          } else {
            console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.');
          }
        };
        _proto.execute = function execute(cmdBuffs, count) {
          for (var i = 0; i < count; ++i) {
            var webGLCmdBuff = cmdBuffs[i];
            for (var c = 0; c < webGLCmdBuff.cmdPackage.beginRenderPassCmds.length; ++c) {
              var cmd = webGLCmdBuff.cmdPackage.beginRenderPassCmds.array[c];
              ++cmd.refCount;
              this.cmdPackage.beginRenderPassCmds.push(cmd);
            }
            for (var _c = 0; _c < webGLCmdBuff.cmdPackage.bindStatesCmds.length; ++_c) {
              var _cmd = webGLCmdBuff.cmdPackage.bindStatesCmds.array[_c];
              ++_cmd.refCount;
              this.cmdPackage.bindStatesCmds.push(_cmd);
            }
            for (var _c2 = 0; _c2 < webGLCmdBuff.cmdPackage.drawCmds.length; ++_c2) {
              var _cmd2 = webGLCmdBuff.cmdPackage.drawCmds.array[_c2];
              ++_cmd2.refCount;
              this.cmdPackage.drawCmds.push(_cmd2);
            }
            for (var _c3 = 0; _c3 < webGLCmdBuff.cmdPackage.updateBufferCmds.length; ++_c3) {
              var _cmd3 = webGLCmdBuff.cmdPackage.updateBufferCmds.array[_c3];
              ++_cmd3.refCount;
              this.cmdPackage.updateBufferCmds.push(_cmd3);
            }
            for (var _c4 = 0; _c4 < webGLCmdBuff.cmdPackage.copyBufferToTextureCmds.length; ++_c4) {
              var _cmd4 = webGLCmdBuff.cmdPackage.copyBufferToTextureCmds.array[_c4];
              ++_cmd4.refCount;
              this.cmdPackage.copyBufferToTextureCmds.push(_cmd4);
            }
            for (var _c5 = 0; _c5 < webGLCmdBuff.cmdPackage.blitTextureCmds.length; ++_c5) {
              var _cmd5 = webGLCmdBuff.cmdPackage.blitTextureCmds.array[_c5];
              ++_cmd5.refCount;
              this.cmdPackage.blitTextureCmds.push(_cmd5);
            }
            this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds.array);
            this._numDrawCalls += webGLCmdBuff._numDrawCalls;
            this._numInstances += webGLCmdBuff._numInstances;
            this._numTris += webGLCmdBuff._numTris;
          }
        };
        _proto.pipelineBarrier = function pipelineBarrier(GeneralBarrier, bufferBarriers, buffers, textureBarriers, textures) {};
        _proto.bindStates = function bindStates() {
          var bindStatesCmd = this._cmdAllocator.bindStatesCmdPool.alloc(WebGLCmdBindStates);
          if (bindStatesCmd) {
            bindStatesCmd.gpuPipelineState = this._curGPUPipelineState;
            Array.prototype.push.apply(bindStatesCmd.gpuDescriptorSets, this._curGPUDescriptorSets);
            Array.prototype.push.apply(bindStatesCmd.dynamicOffsets, this._curDynamicOffsets);
            bindStatesCmd.gpuInputAssembler = this._curGPUInputAssembler;
            bindStatesCmd.dynamicStates.copy(this._curDynamicStates);
            this.cmdPackage.bindStatesCmds.push(bindStatesCmd);
            this.cmdPackage.cmds.push(WebGLCmd.BIND_STATES);
            this._isStateInvalied = false;
          }
        };
        _proto.blitTexture = function blitTexture(srcTexture, dstTexture, regions, filter) {
          var blitTextureCmd = this._cmdAllocator.blitTextureCmdPool.alloc(WebGLCmdBlitTexture);
          blitTextureCmd.srcTexture = srcTexture.gpuTexture;
          blitTextureCmd.dstTexture = dstTexture.gpuTexture;
          blitTextureCmd.regions = regions;
          blitTextureCmd.filter = filter;
          ++this._numDrawCalls;
          this.cmdPackage.blitTextureCmds.push(blitTextureCmd);
          this.cmdPackage.cmds.push(WebGLCmd.BLIT_TEXTURE);
        };
        return WebGLCommandBuffer;
      }(CommandBuffer);

      var WebGLFramebuffer = function (_Framebuffer) {
        _inheritsLoose(WebGLFramebuffer, _Framebuffer);
        function WebGLFramebuffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Framebuffer.call.apply(_Framebuffer, [this].concat(args)) || this;
          _this._gpuFramebuffer = null;
          return _this;
        }
        var _proto = WebGLFramebuffer.prototype;
        _proto.initialize = function initialize(info) {
          this._renderPass = info.renderPass;
          this._colorTextures = info.colorTextures || [];
          this._depthStencilTexture = info.depthStencilTexture || null;
          var lodLevel = 0;
          var gpuColorTextures = [];
          for (var i = 0; i < info.colorTextures.length; ++i) {
            var colorTexture = info.colorTextures[i];
            if (colorTexture) {
              gpuColorTextures.push(colorTexture.gpuTexture);
              lodLevel = colorTexture.lodLevel;
            }
          }
          var gpuDepthStencilTexture = null;
          if (info.depthStencilTexture) {
            gpuDepthStencilTexture = info.depthStencilTexture.gpuTexture;
            lodLevel = info.depthStencilTexture.lodLevel;
          }
          var width = Number.MAX_SAFE_INTEGER;
          var height = Number.MAX_SAFE_INTEGER;
          this._gpuFramebuffer = {
            gpuRenderPass: info.renderPass.gpuRenderPass,
            gpuColorTextures: gpuColorTextures,
            gpuDepthStencilTexture: gpuDepthStencilTexture,
            glFramebuffer: null,
            isOffscreen: true,
            get width() {
              if (this.gpuColorTextures.length > 0) {
                return this.gpuColorTextures[0].width;
              } else if (this.gpuDepthStencilTexture) {
                return this.gpuDepthStencilTexture.width;
              }
              return width;
            },
            set width(val) {
              width = val;
            },
            get height() {
              if (this.gpuColorTextures.length > 0) {
                return this.gpuColorTextures[0].height;
              } else if (this.gpuDepthStencilTexture) {
                return this.gpuDepthStencilTexture.height;
              }
              return height;
            },
            set height(val) {
              height = val;
            },
            lodLevel: lodLevel
          };
          WebGLCmdFuncCreateFramebuffer(WebGLDeviceManager.instance, this._gpuFramebuffer);
          this._width = this._gpuFramebuffer.width;
          this._height = this._gpuFramebuffer.height;
        };
        _proto.destroy = function destroy() {
          if (this._gpuFramebuffer) {
            WebGLCmdFuncDestroyFramebuffer(WebGLDeviceManager.instance, this._gpuFramebuffer);
            this._gpuFramebuffer = null;
          }
        };
        _createClass(WebGLFramebuffer, [{
          key: "gpuFramebuffer",
          get: function get() {
            return this._gpuFramebuffer;
          }
        }]);
        return WebGLFramebuffer;
      }(Framebuffer);

      var WebGLInputAssembler = function (_InputAssembler) {
        _inheritsLoose(WebGLInputAssembler, _InputAssembler);
        function WebGLInputAssembler() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _InputAssembler.call.apply(_InputAssembler, [this].concat(args)) || this;
          _this._gpuInputAssembler = null;
          return _this;
        }
        var _proto = WebGLInputAssembler.prototype;
        _proto.initialize = function initialize(info) {
          if (info.vertexBuffers.length === 0) {
            console.error('InputAssemblerInfo.vertexBuffers is null.');
            return;
          }
          this._attributes = info.attributes;
          this._attributesHash = this.computeAttributesHash();
          this._vertexBuffers = info.vertexBuffers;
          if (info.indexBuffer) {
            this._indexBuffer = info.indexBuffer;
            this._drawInfo.indexCount = this._indexBuffer.size / this._indexBuffer.stride;
            this._drawInfo.firstIndex = 0;
          } else {
            var vertBuff = this._vertexBuffers[0];
            this._drawInfo.vertexCount = vertBuff.size / vertBuff.stride;
            this._drawInfo.firstVertex = 0;
            this._drawInfo.vertexOffset = 0;
          }
          this._drawInfo.instanceCount = 0;
          this._drawInfo.firstInstance = 0;
          this._indirectBuffer = info.indirectBuffer || null;
          var gpuVertexBuffers = new Array(info.vertexBuffers.length);
          for (var i = 0; i < info.vertexBuffers.length; ++i) {
            var vb = info.vertexBuffers[i];
            if (vb.gpuBuffer) {
              gpuVertexBuffers[i] = vb.gpuBuffer;
            }
          }
          var gpuIndexBuffer = null;
          var glIndexType = 0;
          if (info.indexBuffer) {
            gpuIndexBuffer = info.indexBuffer.gpuBuffer;
            if (gpuIndexBuffer) {
              switch (gpuIndexBuffer.stride) {
                case 1:
                  glIndexType = 0x1401;
                  break;
                case 2:
                  glIndexType = 0x1403;
                  break;
                case 4:
                  glIndexType = 0x1405;
                  break;
                default:
                  {
                    console.error('Error index buffer stride.');
                  }
              }
            }
          }
          var gpuIndirectBuffer = null;
          if (info.indirectBuffer) {
            gpuIndirectBuffer = info.indirectBuffer.gpuBuffer;
          }
          this._gpuInputAssembler = {
            attributes: info.attributes,
            gpuVertexBuffers: gpuVertexBuffers,
            gpuIndexBuffer: gpuIndexBuffer,
            gpuIndirectBuffer: gpuIndirectBuffer,
            glAttribs: [],
            glIndexType: glIndexType,
            glVAOs: new Map()
          };
          WebGLCmdFuncCreateInputAssember(WebGLDeviceManager.instance, this._gpuInputAssembler);
        };
        _proto.destroy = function destroy() {
          var device = WebGLDeviceManager.instance;
          if (this._gpuInputAssembler && device.extensions.useVAO) {
            WebGLCmdFuncDestroyInputAssembler(device, this._gpuInputAssembler);
          }
          this._gpuInputAssembler = null;
        };
        _createClass(WebGLInputAssembler, [{
          key: "gpuInputAssembler",
          get: function get() {
            return this._gpuInputAssembler;
          }
        }]);
        return WebGLInputAssembler;
      }(InputAssembler);

      var WebGLDescriptorSetLayout = function (_DescriptorSetLayout) {
        _inheritsLoose(WebGLDescriptorSetLayout, _DescriptorSetLayout);
        function WebGLDescriptorSetLayout() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _DescriptorSetLayout.call.apply(_DescriptorSetLayout, [this].concat(args)) || this;
          _this._gpuDescriptorSetLayout = null;
          return _this;
        }
        var _proto = WebGLDescriptorSetLayout.prototype;
        _proto.initialize = function initialize(info) {
          Array.prototype.push.apply(this._bindings, info.bindings);
          var descriptorCount = 0;
          var maxBinding = -1;
          var flattenedIndices = [];
          for (var i = 0; i < this._bindings.length; i++) {
            var binding = this._bindings[i];
            flattenedIndices.push(descriptorCount);
            descriptorCount += binding.count;
            if (binding.binding > maxBinding) maxBinding = binding.binding;
          }
          this._bindingIndices = Array(maxBinding + 1).fill(-1);
          var descriptorIndices = this._descriptorIndices = Array(maxBinding + 1).fill(-1);
          for (var _i = 0; _i < this._bindings.length; _i++) {
            var _binding = this._bindings[_i];
            this._bindingIndices[_binding.binding] = _i;
            descriptorIndices[_binding.binding] = flattenedIndices[_i];
          }
          var dynamicBindings = [];
          for (var _i2 = 0; _i2 < this._bindings.length; _i2++) {
            var _binding2 = this._bindings[_i2];
            if (_binding2.descriptorType & DESCRIPTOR_DYNAMIC_TYPE) {
              for (var j = 0; j < _binding2.count; j++) {
                dynamicBindings.push(_binding2.binding);
              }
            }
          }
          this._gpuDescriptorSetLayout = {
            bindings: this._bindings,
            dynamicBindings: dynamicBindings,
            descriptorIndices: descriptorIndices,
            descriptorCount: descriptorCount
          };
        };
        _proto.destroy = function destroy() {
          this._bindings.length = 0;
        };
        _createClass(WebGLDescriptorSetLayout, [{
          key: "gpuDescriptorSetLayout",
          get: function get() {
            return this._gpuDescriptorSetLayout;
          }
        }]);
        return WebGLDescriptorSetLayout;
      }(DescriptorSetLayout);

      var WebGLPipelineLayout = function (_PipelineLayout) {
        _inheritsLoose(WebGLPipelineLayout, _PipelineLayout);
        function WebGLPipelineLayout() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineLayout.call.apply(_PipelineLayout, [this].concat(args)) || this;
          _this._gpuPipelineLayout = null;
          return _this;
        }
        var _proto = WebGLPipelineLayout.prototype;
        _proto.initialize = function initialize(info) {
          Array.prototype.push.apply(this._setLayouts, info.setLayouts);
          var dynamicOffsetIndices = [];
          var gpuSetLayouts = [];
          var dynamicOffsetCount = 0;
          var dynamicOffsetOffsets = [];
          for (var i = 0; i < this._setLayouts.length; i++) {
            var setLayout = this._setLayouts[i];
            var dynamicBindings = setLayout.gpuDescriptorSetLayout.dynamicBindings;
            var indices = Array(setLayout.bindingIndices.length).fill(-1);
            for (var j = 0; j < dynamicBindings.length; j++) {
              var binding = dynamicBindings[j];
              if (indices[binding] < 0) indices[binding] = dynamicOffsetCount + j;
            }
            gpuSetLayouts.push(setLayout.gpuDescriptorSetLayout);
            dynamicOffsetIndices.push(indices);
            dynamicOffsetOffsets.push(dynamicOffsetCount);
            dynamicOffsetCount += dynamicBindings.length;
          }
          this._gpuPipelineLayout = {
            gpuSetLayouts: gpuSetLayouts,
            dynamicOffsetIndices: dynamicOffsetIndices,
            dynamicOffsetCount: dynamicOffsetCount,
            dynamicOffsetOffsets: dynamicOffsetOffsets
          };
        };
        _proto.destroy = function destroy() {
          this._setLayouts.length = 0;
        };
        _createClass(WebGLPipelineLayout, [{
          key: "gpuPipelineLayout",
          get: function get() {
            return this._gpuPipelineLayout;
          }
        }]);
        return WebGLPipelineLayout;
      }(PipelineLayout);

      var WebGLPrimitives$1 = [0x0000, 0x0001, 0x0003, 0x0002, 0x0000, 0x0000, 0x0000, 0x0004, 0x0005, 0x0006, 0x0000, 0x0000, 0x0000, 0x0000];
      var WebGLPipelineState = function (_PipelineState) {
        _inheritsLoose(WebGLPipelineState, _PipelineState);
        function WebGLPipelineState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineState.call.apply(_PipelineState, [this].concat(args)) || this;
          _this._gpuPipelineState = null;
          return _this;
        }
        var _proto = WebGLPipelineState.prototype;
        _proto.initialize = function initialize(info) {
          this._primitive = info.primitive;
          this._shader = info.shader;
          this._pipelineLayout = info.pipelineLayout;
          var bs = this._bs;
          if (info.blendState) {
            var bsInfo = info.blendState;
            var targets = bsInfo.targets;
            if (targets) {
              targets.forEach(function (t, i) {
                bs.setTarget(i, t);
              });
            }
            if (bsInfo.isA2C !== undefined) {
              bs.isA2C = bsInfo.isA2C;
            }
            if (bsInfo.isIndepend !== undefined) {
              bs.isIndepend = bsInfo.isIndepend;
            }
            if (bsInfo.blendColor !== undefined) {
              bs.blendColor = bsInfo.blendColor;
            }
          }
          Object.assign(this._rs, info.rasterizerState);
          Object.assign(this._dss, info.depthStencilState);
          this._is = info.inputState;
          this._renderPass = info.renderPass;
          this._dynamicStates = info.dynamicStates;
          var dynamicStates = [];
          for (var i = 0; i < 31; i++) {
            if (this._dynamicStates & 1 << i) {
              dynamicStates.push(1 << i);
            }
          }
          this._gpuPipelineState = {
            glPrimitive: WebGLPrimitives$1[info.primitive],
            gpuShader: info.shader.gpuShader,
            gpuPipelineLayout: info.pipelineLayout.gpuPipelineLayout,
            rs: info.rasterizerState,
            dss: info.depthStencilState,
            bs: info.blendState,
            gpuRenderPass: info.renderPass.gpuRenderPass,
            dynamicStates: dynamicStates
          };
        };
        _proto.destroy = function destroy() {
          this._gpuPipelineState = null;
        };
        _createClass(WebGLPipelineState, [{
          key: "gpuPipelineState",
          get: function get() {
            return this._gpuPipelineState;
          }
        }]);
        return WebGLPipelineState;
      }(PipelineState);

      var WebGLPrimaryCommandBuffer = function (_WebGLCommandBuffer) {
        _inheritsLoose(WebGLPrimaryCommandBuffer, _WebGLCommandBuffer);
        function WebGLPrimaryCommandBuffer() {
          return _WebGLCommandBuffer.apply(this, arguments) || this;
        }
        var _proto = WebGLPrimaryCommandBuffer.prototype;
        _proto.beginRenderPass = function beginRenderPass(renderPass, framebuffer, renderArea, clearColors, clearDepth, clearStencil) {
          WebGLCmdFuncBeginRenderPass(WebGLDeviceManager.instance, renderPass.gpuRenderPass, framebuffer.gpuFramebuffer, renderArea, clearColors, clearDepth, clearStencil);
          this._isInRenderPass = true;
        };
        _proto.draw = function draw(infoOrAssembler) {
          if (this._isInRenderPass) {
            if (this._isStateInvalied) {
              this.bindStates();
            }
            var info = 'drawInfo' in infoOrAssembler ? infoOrAssembler.drawInfo : infoOrAssembler;
            WebGLCmdFuncDraw(WebGLDeviceManager.instance, info);
            ++this._numDrawCalls;
            this._numInstances += info.instanceCount;
            var indexCount = info.indexCount || info.vertexCount;
            if (this._curGPUPipelineState) {
              var glPrimitive = this._curGPUPipelineState.glPrimitive;
              switch (glPrimitive) {
                case 0x0004:
                  {
                    this._numTris += indexCount / 3 * Math.max(info.instanceCount, 1);
                    break;
                  }
                case 0x0005:
                case 0x0006:
                  {
                    this._numTris += (indexCount - 2) * Math.max(info.instanceCount, 1);
                    break;
                  }
              }
            }
          } else {
            console.error('Command \'draw\' must be recorded inside a render pass.');
          }
        };
        _proto.setViewport = function setViewport(viewport) {
          var _WebGLDeviceManager$i = WebGLDeviceManager.instance,
            cache = _WebGLDeviceManager$i.stateCache,
            gl = _WebGLDeviceManager$i.gl;
          if (cache.viewport.left !== viewport.left || cache.viewport.top !== viewport.top || cache.viewport.width !== viewport.width || cache.viewport.height !== viewport.height) {
            gl.viewport(viewport.left, viewport.top, viewport.width, viewport.height);
            cache.viewport.left = viewport.left;
            cache.viewport.top = viewport.top;
            cache.viewport.width = viewport.width;
            cache.viewport.height = viewport.height;
          }
        };
        _proto.setScissor = function setScissor(scissor) {
          var _WebGLDeviceManager$i2 = WebGLDeviceManager.instance,
            cache = _WebGLDeviceManager$i2.stateCache,
            gl = _WebGLDeviceManager$i2.gl;
          if (cache.scissorRect.x !== scissor.x || cache.scissorRect.y !== scissor.y || cache.scissorRect.width !== scissor.width || cache.scissorRect.height !== scissor.height) {
            gl.scissor(scissor.x, scissor.y, scissor.width, scissor.height);
            cache.scissorRect.x = scissor.x;
            cache.scissorRect.y = scissor.y;
            cache.scissorRect.width = scissor.width;
            cache.scissorRect.height = scissor.height;
          }
        };
        _proto.updateBuffer = function updateBuffer(buffer, data, size) {
          if (!this._isInRenderPass) {
            var gpuBuffer = buffer.gpuBuffer;
            if (gpuBuffer) {
              var buffSize;
              if (size !== undefined) {
                buffSize = size;
              } else if (buffer.usage & BufferUsageBit.INDIRECT) {
                buffSize = 0;
              } else {
                buffSize = data.byteLength;
              }
              WebGLCmdFuncUpdateBuffer(WebGLDeviceManager.instance, gpuBuffer, data, 0, buffSize);
            }
          } else {
            console.error('Command \'updateBuffer\' must be recorded outside a render pass.');
          }
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          if (!this._isInRenderPass) {
            var gpuTexture = texture.gpuTexture;
            if (gpuTexture) {
              WebGLCmdFuncCopyBuffersToTexture(WebGLDeviceManager.instance, buffers, gpuTexture, regions);
            }
          } else {
            console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.');
          }
        };
        _proto.execute = function execute(cmdBuffs, count) {
          for (var i = 0; i < count; ++i) {
            var webGLCmdBuff = cmdBuffs[i];
            WebGLCmdFuncExecuteCmds(WebGLDeviceManager.instance, webGLCmdBuff.cmdPackage);
            this._numDrawCalls += webGLCmdBuff._numDrawCalls;
            this._numInstances += webGLCmdBuff._numInstances;
            this._numTris += webGLCmdBuff._numTris;
          }
        };
        _proto.bindStates = function bindStates() {
          WebGLCmdFuncBindStates(WebGLDeviceManager.instance, this._curGPUPipelineState, this._curGPUInputAssembler, this._curGPUDescriptorSets, this._curDynamicOffsets, this._curDynamicStates);
          this._isStateInvalied = false;
        };
        _proto.blitTexture = function blitTexture(srcTexture, dstTexture, regions, filter) {
          var gpuTextureSrc = srcTexture.gpuTexture;
          var gpuTextureDst = dstTexture.gpuTexture;
          WebGLCmdFuncBlitTexture(WebGLDeviceManager.instance, gpuTextureSrc, gpuTextureDst, regions, filter);
        };
        return WebGLPrimaryCommandBuffer;
      }(WebGLCommandBuffer);

      var WebGLQueue = function (_Queue) {
        _inheritsLoose(WebGLQueue, _Queue);
        function WebGLQueue() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Queue.call.apply(_Queue, [this].concat(args)) || this;
          _this.numDrawCalls = 0;
          _this.numInstances = 0;
          _this.numTris = 0;
          return _this;
        }
        var _proto = WebGLQueue.prototype;
        _proto.initialize = function initialize(info) {
          this._type = info.type;
        };
        _proto.destroy = function destroy() {};
        _proto.submit = function submit(cmdBuffs) {
          var len = cmdBuffs.length;
          for (var i = 0; i < len; i++) {
            var cmdBuff = cmdBuffs[i];
            this.numDrawCalls += cmdBuff.numDrawCalls;
            this.numInstances += cmdBuff.numInstances;
            this.numTris += cmdBuff.numTris;
          }
        };
        _proto.clear = function clear() {
          this.numDrawCalls = 0;
          this.numInstances = 0;
          this.numTris = 0;
        };
        return WebGLQueue;
      }(Queue);

      var WebGLRenderPass = function (_RenderPass) {
        _inheritsLoose(WebGLRenderPass, _RenderPass);
        function WebGLRenderPass() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderPass.call.apply(_RenderPass, [this].concat(args)) || this;
          _this._gpuRenderPass = null;
          return _this;
        }
        var _proto = WebGLRenderPass.prototype;
        _proto.initialize = function initialize(info) {
          this._colorInfos = info.colorAttachments;
          this._depthStencilInfo = info.depthStencilAttachment;
          this._subpasses = info.subpasses;
          this._gpuRenderPass = {
            colorAttachments: this._colorInfos,
            depthStencilAttachment: this._depthStencilInfo
          };
          this._hash = this.computeHash();
        };
        _proto.destroy = function destroy() {
          this._gpuRenderPass = null;
        };
        _createClass(WebGLRenderPass, [{
          key: "gpuRenderPass",
          get: function get() {
            return this._gpuRenderPass;
          }
        }]);
        return WebGLRenderPass;
      }(RenderPass);

      var WebGLWraps$1 = [0x2901, 0x8370, 0x812F, 0x812F];
      var WebGLSampler = function (_Sampler) {
        _inheritsLoose(WebGLSampler, _Sampler);
        function WebGLSampler(info, hash) {
          var _this;
          _this = _Sampler.call(this, info, hash) || this;
          _this._gpuSampler = null;
          var glMinFilter = 0;
          var glMagFilter = 0;
          var minFilter = _this._info.minFilter;
          var magFilter = _this._info.magFilter;
          var mipFilter = _this._info.mipFilter;
          if (minFilter === Filter$1.LINEAR || minFilter === Filter$1.ANISOTROPIC) {
            if (mipFilter === Filter$1.LINEAR || mipFilter === Filter$1.ANISOTROPIC) {
              glMinFilter = 0x2703;
            } else if (mipFilter === Filter$1.POINT) {
              glMinFilter = 0x2701;
            } else {
              glMinFilter = 0x2601;
            }
          } else if (mipFilter === Filter$1.LINEAR || mipFilter === Filter$1.ANISOTROPIC) {
            glMinFilter = 0x2702;
          } else if (mipFilter === Filter$1.POINT) {
            glMinFilter = 0x2700;
          } else {
            glMinFilter = 0x2600;
          }
          if (magFilter === Filter$1.LINEAR || magFilter === Filter$1.ANISOTROPIC) {
            glMagFilter = 0x2601;
          } else {
            glMagFilter = 0x2600;
          }
          var glWrapS = WebGLWraps$1[_this._info.addressU];
          var glWrapT = WebGLWraps$1[_this._info.addressV];
          var glWrapR = WebGLWraps$1[_this._info.addressW];
          _this._gpuSampler = {
            glMinFilter: glMinFilter,
            glMagFilter: glMagFilter,
            glWrapS: glWrapS,
            glWrapT: glWrapT,
            glWrapR: glWrapR
          };
          return _this;
        }
        _createClass(WebGLSampler, [{
          key: "gpuSampler",
          get: function get() {
            return this._gpuSampler;
          }
        }]);
        return WebGLSampler;
      }(Sampler);

      var WebGLShader = function (_Shader) {
        _inheritsLoose(WebGLShader, _Shader);
        function WebGLShader() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Shader.call.apply(_Shader, [this].concat(args)) || this;
          _this._gpuShader = null;
          return _this;
        }
        var _proto = WebGLShader.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name;
          this._stages = info.stages;
          this._attributes = info.attributes;
          this._blocks = info.blocks;
          this._samplers = info.samplers;
          this._gpuShader = {
            name: info.name,
            blocks: info.blocks.slice(),
            samplerTextures: info.samplerTextures.slice(),
            subpassInputs: info.subpassInputs.slice(),
            gpuStages: new Array(info.stages.length),
            glProgram: null,
            glInputs: [],
            glUniforms: [],
            glBlocks: [],
            glSamplerTextures: []
          };
          for (var i = 0; i < info.stages.length; ++i) {
            var stage = info.stages[i];
            this._gpuShader.gpuStages[i] = {
              type: stage.stage,
              source: stage.source,
              glShader: null
            };
          }
        };
        _proto.destroy = function destroy() {
          if (this._gpuShader) {
            WebGLCmdFuncDestroyShader(WebGLDeviceManager.instance, this._gpuShader);
            this._gpuShader = null;
          }
        };
        _createClass(WebGLShader, [{
          key: "gpuShader",
          get: function get() {
            if (this._gpuShader.glProgram === null) {
              WebGLCmdFuncCreateShader(WebGLDeviceManager.instance, this._gpuShader);
            }
            return this._gpuShader;
          }
        }]);
        return WebGLShader;
      }(Shader);

      var WebGLStateCache = function () {
        function WebGLStateCache() {
          this.glArrayBuffer = null;
          this.glElementArrayBuffer = null;
          this.glVAO = null;
          this.texUnit = 0;
          this.glTexUnits = [];
          this.glRenderbuffer = null;
          this.glFramebuffer = null;
          this.viewport = new Viewport();
          this.scissorRect = new Rect(0, 0, 0, 0);
          this.rs = new RasterizerState();
          this.dss = new DepthStencilState();
          this.bs = new BlendState$1();
          this.glProgram = null;
          this.glEnabledAttribLocs = [];
          this.glCurrentAttribLocs = [];
          this.texUnitCacheMap = {};
        }
        var _proto = WebGLStateCache.prototype;
        _proto.initialize = function initialize(texUnit, vertexAttributes) {
          for (var i = 0; i < texUnit; ++i) this.glTexUnits.push({
            glTexture: null
          });
          this.glEnabledAttribLocs.length = vertexAttributes;
          this.glEnabledAttribLocs.fill(false);
          this.glCurrentAttribLocs.length = vertexAttributes;
          this.glCurrentAttribLocs.fill(false);
        };
        return WebGLStateCache;
      }();

      var WebGLTexture = function (_Texture) {
        _inheritsLoose(WebGLTexture, _Texture);
        function WebGLTexture() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Texture.call.apply(_Texture, [this].concat(args)) || this;
          _this._gpuTexture = null;
          _this._lodLevel = 0;
          return _this;
        }
        var _proto = WebGLTexture.prototype;
        _proto.initialize = function initialize(info, isSwapchainTexture) {
          var texInfo = info;
          var viewInfo = info;
          if ('texture' in info) {
            texInfo = viewInfo.texture.info;
            this._isTextureView = true;
          }
          this._info.copy(texInfo);
          this._isPowerOf2 = IsPowerOf2(this._info.width) && IsPowerOf2(this._info.height);
          this._size = FormatSurfaceSize(this._info.format, this.width, this.height, this.depth, this._info.levelCount) * this._info.layerCount;
          if (!this._isTextureView) {
            this._gpuTexture = {
              type: texInfo.type,
              format: texInfo.format,
              usage: texInfo.usage,
              width: texInfo.width,
              height: texInfo.height,
              depth: texInfo.depth,
              size: this._size,
              arrayLayer: texInfo.layerCount,
              mipLevel: texInfo.levelCount,
              samples: texInfo.samples,
              flags: texInfo.flags,
              isPowerOf2: this._isPowerOf2,
              glTarget: 0,
              glInternalFmt: 0,
              glFormat: 0,
              glType: 0,
              glUsage: 0,
              glTexture: null,
              glRenderbuffer: null,
              glWrapS: 0,
              glWrapT: 0,
              glMinFilter: 0,
              glMagFilter: 0,
              isSwapchainTexture: isSwapchainTexture || false
            };
            if (!this._gpuTexture.isSwapchainTexture) {
              WebGLCmdFuncCreateTexture(WebGLDeviceManager.instance, this._gpuTexture);
              WebGLDeviceManager.instance.memoryStatus.textureSize += this._size;
            }
            this._viewInfo.texture = this;
            this._viewInfo.type = info.type;
            this._viewInfo.format = info.format;
            this._viewInfo.baseLevel = 0;
            this._viewInfo.levelCount = info.levelCount;
            this._viewInfo.baseLayer = 0;
            this._viewInfo.layerCount = info.layerCount;
          } else {
            this._viewInfo.copy(viewInfo);
            this._lodLevel = viewInfo.baseLevel;
            this._gpuTexture = viewInfo.texture._gpuTexture;
          }
        };
        _proto.destroy = function destroy() {
          if (!this._isTextureView && this._gpuTexture) {
            WebGLCmdFuncDestroyTexture(WebGLDeviceManager.instance, this._gpuTexture);
            WebGLDeviceManager.instance.memoryStatus.textureSize -= this._size;
            this._gpuTexture = null;
          }
        };
        _proto.getGLTextureHandle = function getGLTextureHandle() {
          var gpuTexture = this._gpuTexture;
          if (!gpuTexture) {
            return 0;
          }
          if (gpuTexture.glTexture) {
            return gpuTexture.glTexture;
          } else if (gpuTexture.glRenderbuffer) {
            return gpuTexture.glRenderbuffer;
          }
          return 0;
        };
        _proto.resize = function resize(width, height) {
          if (this._info.width === width && this._info.height === height) {
            return;
          }
          if (this._info.levelCount === WebGLTexture.getLevelCount(this._info.width, this._info.height)) {
            this._info.levelCount = WebGLTexture.getLevelCount(width, height);
          } else if (this._info.levelCount > 1) {
            this._info.levelCount = Math.min(this._info.levelCount, WebGLTexture.getLevelCount(width, height));
          }
          var oldSize = this._size;
          this._info.width = width;
          this._info.height = height;
          this._size = FormatSurfaceSize(this._info.format, this.width, this.height, this.depth, this._info.levelCount) * this._info.layerCount;
          if (!this._isTextureView && this._gpuTexture) {
            this._gpuTexture.width = width;
            this._gpuTexture.height = height;
            this._gpuTexture.size = this._size;
            if (!this._gpuTexture.isSwapchainTexture) {
              WebGLCmdFuncResizeTexture(WebGLDeviceManager.instance, this._gpuTexture);
              WebGLDeviceManager.instance.memoryStatus.textureSize -= oldSize;
              WebGLDeviceManager.instance.memoryStatus.textureSize += this._size;
            }
          }
        };
        _proto.initAsSwapchainTexture = function initAsSwapchainTexture(info) {
          var texInfo = new TextureInfo();
          texInfo.format = info.format;
          texInfo.usage = FormatInfos[info.format].hasDepth ? TextureUsageBit.DEPTH_STENCIL_ATTACHMENT : TextureUsageBit.COLOR_ATTACHMENT;
          texInfo.width = info.width;
          texInfo.height = info.height;
          this.initialize(texInfo, true);
        };
        _createClass(WebGLTexture, [{
          key: "gpuTexture",
          get: function get() {
            return this._gpuTexture;
          }
        }, {
          key: "lodLevel",
          get: function get() {
            return this._lodLevel;
          }
        }]);
        return WebGLTexture;
      }(Texture);

      var eventWebGLContextLost$1 = 'webglcontextlost';
      function initStates$1(gl) {
        gl.activeTexture(gl.TEXTURE0);
        gl.pixelStorei(gl.PACK_ALIGNMENT, 1);
        gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        gl.enable(gl.SCISSOR_TEST);
        gl.enable(gl.CULL_FACE);
        gl.cullFace(gl.BACK);
        gl.frontFace(gl.CCW);
        gl.disable(gl.POLYGON_OFFSET_FILL);
        gl.polygonOffset(0.0, 0.0);
        gl.enable(gl.DEPTH_TEST);
        gl.depthMask(true);
        gl.depthFunc(gl.LESS);
        gl.depthRange(0.0, 1.0);
        gl.stencilFuncSeparate(gl.FRONT, gl.ALWAYS, 1, 0xffff);
        gl.stencilOpSeparate(gl.FRONT, gl.KEEP, gl.KEEP, gl.KEEP);
        gl.stencilMaskSeparate(gl.FRONT, 0xffff);
        gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 1, 0xffff);
        gl.stencilOpSeparate(gl.BACK, gl.KEEP, gl.KEEP, gl.KEEP);
        gl.stencilMaskSeparate(gl.BACK, 0xffff);
        gl.disable(gl.STENCIL_TEST);
        gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
        gl.disable(gl.BLEND);
        gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
        gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
        gl.colorMask(true, true, true, true);
        gl.blendColor(0.0, 0.0, 0.0, 0.0);
      }
      function getExtension$1(gl, ext) {
        var prefixes = ['', 'WEBKIT_', 'MOZ_'];
        for (var i = 0; i < prefixes.length; ++i) {
          var _ext = gl.getExtension(prefixes[i] + ext);
          if (_ext) {
            return _ext;
          }
        }
        return null;
      }
      function getExtensions$1(gl) {
        var res = {
          EXT_texture_filter_anisotropic: getExtension$1(gl, 'EXT_texture_filter_anisotropic'),
          EXT_blend_minmax: getExtension$1(gl, 'EXT_blend_minmax'),
          EXT_frag_depth: getExtension$1(gl, 'EXT_frag_depth'),
          EXT_shader_texture_lod: getExtension$1(gl, 'EXT_shader_texture_lod'),
          EXT_sRGB: getExtension$1(gl, 'EXT_sRGB'),
          OES_vertex_array_object: getExtension$1(gl, 'OES_vertex_array_object'),
          EXT_color_buffer_half_float: getExtension$1(gl, 'EXT_color_buffer_half_float'),
          WEBGL_color_buffer_float: getExtension$1(gl, 'WEBGL_color_buffer_float'),
          WEBGL_compressed_texture_etc1: getExtension$1(gl, 'WEBGL_compressed_texture_etc1'),
          WEBGL_compressed_texture_etc: getExtension$1(gl, 'WEBGL_compressed_texture_etc'),
          WEBGL_compressed_texture_pvrtc: getExtension$1(gl, 'WEBGL_compressed_texture_pvrtc'),
          WEBGL_compressed_texture_s3tc: getExtension$1(gl, 'WEBGL_compressed_texture_s3tc'),
          WEBGL_compressed_texture_s3tc_srgb: getExtension$1(gl, 'WEBGL_compressed_texture_s3tc_srgb'),
          WEBGL_debug_shaders: getExtension$1(gl, 'WEBGL_debug_shaders'),
          WEBGL_draw_buffers: getExtension$1(gl, 'WEBGL_draw_buffers'),
          WEBGL_lose_context: getExtension$1(gl, 'WEBGL_lose_context'),
          WEBGL_depth_texture: getExtension$1(gl, 'WEBGL_depth_texture'),
          OES_texture_half_float: getExtension$1(gl, 'OES_texture_half_float'),
          OES_texture_half_float_linear: getExtension$1(gl, 'OES_texture_half_float_linear'),
          OES_texture_float: getExtension$1(gl, 'OES_texture_float'),
          OES_texture_float_linear: getExtension$1(gl, 'OES_texture_float_linear'),
          OES_standard_derivatives: getExtension$1(gl, 'OES_standard_derivatives'),
          OES_element_index_uint: getExtension$1(gl, 'OES_element_index_uint'),
          ANGLE_instanced_arrays: getExtension$1(gl, 'ANGLE_instanced_arrays'),
          WEBGL_debug_renderer_info: getExtension$1(gl, 'WEBGL_debug_renderer_info'),
          WEBGL_multi_draw: null,
          WEBGL_compressed_texture_astc: null,
          destroyShadersImmediately: true,
          noCompressedTexSubImage2D: false,
          isLocationActive: function isLocationActive(glLoc) {
            return !!glLoc;
          },
          useVAO: false
        };
        {
          if (systemInfo.os !== OS.IOS || systemInfo.osMainVersion !== 14 || !systemInfo.isBrowser) {
            res.WEBGL_compressed_texture_astc = getExtension$1(gl, 'WEBGL_compressed_texture_astc');
          }
          if (systemInfo.os !== OS.ANDROID && systemInfo.os !== OS.IOS) {
            res.WEBGL_multi_draw = getExtension$1(gl, 'WEBGL_multi_draw');
          }
          if (systemInfo.browserType === BrowserType.UC) {
            res.ANGLE_instanced_arrays = null;
          }
          if (systemInfo.os === OS.IOS && systemInfo.osMainVersion <= 10 || (WECHAT_MINI_PROGRAM) ) {
            res.destroyShadersImmediately = false;
          }
        }
        if (res.OES_vertex_array_object) {
          res.useVAO = true;
        }
        return res;
      }
      function getContext$1(canvas) {
        var context = null;
        try {
          var webGLCtxAttribs = {
            alpha: macro.ENABLE_TRANSPARENT_CANVAS,
            antialias: EDITOR || macro.ENABLE_WEBGL_ANTIALIAS,
            depth: true,
            stencil: true,
            premultipliedAlpha: false,
            preserveDrawingBuffer: false,
            powerPreference: 'default',
            failIfMajorPerformanceCaveat: false
          };
          context = canvas.getContext('webgl', webGLCtxAttribs);
        } catch (err) {
          return null;
        }
        return context;
      }
      var WebGLSwapchain = function (_Swapchain) {
        _inheritsLoose(WebGLSwapchain, _Swapchain);
        function WebGLSwapchain() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Swapchain.call.apply(_Swapchain, [this].concat(args)) || this;
          _this.stateCache = new WebGLStateCache();
          _this.cmdAllocator = new WebGLCommandAllocator();
          _this.nullTex2D = null;
          _this.nullTexCube = null;
          _this._canvas = null;
          _this._webGLContextLostHandler = null;
          _this._extensions = null;
          _this._blitManager = null;
          return _this;
        }
        var _proto = WebGLSwapchain.prototype;
        _proto.initialize = function initialize(info) {
          this._canvas = info.windowHandle;
          this._webGLContextLostHandler = this._onWebGLContextLost.bind(this);
          this._canvas.addEventListener(eventWebGLContextLost$1, this._onWebGLContextLost);
          var gl = WebGLDeviceManager.instance.gl;
          this.stateCache.initialize(WebGLDeviceManager.instance.capabilities.maxTextureUnits, WebGLDeviceManager.instance.capabilities.maxVertexAttributes);
          this._extensions = getExtensions$1(gl);
          initStates$1(gl);
          var colorFmt = Format.RGBA8;
          var depthStencilFmt = Format.DEPTH_STENCIL;
          var depthBits = gl.getParameter(gl.DEPTH_BITS);
          var stencilBits = gl.getParameter(gl.STENCIL_BITS);
          if (depthBits && stencilBits) depthStencilFmt = Format.DEPTH_STENCIL;else if (depthBits) depthStencilFmt = Format.DEPTH;
          this._colorTexture = new WebGLTexture();
          this._colorTexture.initAsSwapchainTexture({
            swapchain: this,
            format: colorFmt,
            width: info.width,
            height: info.height
          });
          this._depthStencilTexture = new WebGLTexture();
          this._depthStencilTexture.initAsSwapchainTexture({
            swapchain: this,
            format: depthStencilFmt,
            width: info.width,
            height: info.height
          });
          this.nullTex2D = WebGLDeviceManager.instance.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.GEN_MIPMAP));
          this.nullTexCube = WebGLDeviceManager.instance.createTexture(new TextureInfo(TextureType.CUBE, TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.GEN_MIPMAP, 6));
          var nullTexRegion = new BufferTextureCopy();
          nullTexRegion.texExtent.width = 2;
          nullTexRegion.texExtent.height = 2;
          var nullTexBuff = new Uint8Array(this.nullTex2D.size);
          nullTexBuff.fill(0);
          WebGLDeviceManager.instance.copyBuffersToTexture([nullTexBuff], this.nullTex2D, [nullTexRegion]);
          nullTexRegion.texSubres.layerCount = 6;
          WebGLDeviceManager.instance.copyBuffersToTexture([nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff], this.nullTexCube, [nullTexRegion]);
          this._blitManager = new IWebGLBlitManager();
        };
        _proto.destroy = function destroy() {
          if (this._canvas && this._webGLContextLostHandler) {
            this._canvas.removeEventListener(eventWebGLContextLost$1, this._webGLContextLostHandler);
            this._webGLContextLostHandler = null;
          }
          if (this.nullTex2D) {
            this.nullTex2D.destroy();
            this.nullTex2D = null;
          }
          if (this.nullTexCube) {
            this.nullTexCube.destroy();
            this.nullTexCube = null;
          }
          if (this._blitManager) {
            this._blitManager.destroy();
            this._blitManager = null;
          }
          this._extensions = null;
          this._canvas = null;
        };
        _proto.resize = function resize(width, height, surfaceTransform) {
          if (this._colorTexture.width !== width || this._colorTexture.height !== height) {
            debug("Resizing swapchain: " + width + "x" + height);
            this._canvas.width = width;
            this._canvas.height = height;
            this._colorTexture.resize(width, height);
            this._depthStencilTexture.resize(width, height);
          }
        };
        _proto._onWebGLContextLost = function _onWebGLContextLost(event) {
          warnID(11000);
          warn(event);
        };
        _createClass(WebGLSwapchain, [{
          key: "extensions",
          get: function get() {
            return this._extensions;
          }
        }, {
          key: "blitManager",
          get: function get() {
            return this._blitManager;
          }
        }]);
        return WebGLSwapchain;
      }(Swapchain);

      var WebGLDevice = exports('eT', function (_Device) {
        _inheritsLoose(WebGLDevice, _Device);
        function WebGLDevice() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Device.call.apply(_Device, [this].concat(args)) || this;
          _this._swapchain = null;
          _this._context = null;
          _this._bindingMappings = null;
          _this._textureExclusive = new Array(Format.COUNT);
          return _this;
        }
        var _proto = WebGLDevice.prototype;
        _proto.initialize = function initialize(info) {
          WebGLDeviceManager.setInstance(this);
          this._gfxAPI = API.WEBGL;
          var mapping = this._bindingMappingInfo = info.bindingMappingInfo;
          var blockOffsets = [];
          var samplerTextureOffsets = [];
          var firstSet = mapping.setIndices[0];
          blockOffsets[firstSet] = 0;
          samplerTextureOffsets[firstSet] = 0;
          for (var i = 1; i < mapping.setIndices.length; ++i) {
            var curSet = mapping.setIndices[i];
            var prevSet = mapping.setIndices[i - 1];
            blockOffsets[curSet] = mapping.maxBlockCounts[prevSet] + blockOffsets[prevSet];
            samplerTextureOffsets[curSet] = mapping.maxSamplerTextureCounts[prevSet] + samplerTextureOffsets[prevSet];
          }
          for (var _i = 0; _i < mapping.setIndices.length; ++_i) {
            var _curSet = mapping.setIndices[_i];
            samplerTextureOffsets[_curSet] -= mapping.maxBlockCounts[_curSet];
          }
          this._bindingMappings = {
            blockOffsets: blockOffsets,
            samplerTextureOffsets: samplerTextureOffsets,
            flexibleSet: mapping.setIndices[mapping.setIndices.length - 1]
          };
          var gl = this._context = getContext$1(Device.canvas);
          if (!gl) {
            console.error('This device does not support WebGL.');
            return false;
          }
          this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
          this._cmdBuff = this.createCommandBuffer(new CommandBufferInfo(this._queue));
          this._caps.maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
          this._caps.maxVertexUniformVectors = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
          this._caps.maxFragmentUniformVectors = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
          this._caps.maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
          this._caps.maxVertexTextureUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
          this._caps.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
          this._caps.maxCubeMapTextureSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
          this._caps.maxArrayTextureLayers = 0;
          this._caps.max3DTextureSize = 0;
          this._caps.maxUniformBufferBindings = 16;
          var extensions = gl.getSupportedExtensions();
          var extStr = '';
          if (extensions) {
            for (var _iterator = _createForOfIteratorHelperLoose(extensions), _step; !(_step = _iterator()).done;) {
              var ext = _step.value;
              extStr += ext + " ";
            }
          }
          var exts = getExtensions$1(gl);
          if (exts.WEBGL_debug_renderer_info) {
            this._renderer = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL);
            this._vendor = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL);
          } else {
            this._renderer = gl.getParameter(gl.RENDERER);
            this._vendor = gl.getParameter(gl.VENDOR);
          }
          var version = gl.getParameter(gl.VERSION);
          this._features.fill(false);
          this.initFormatFeatures(exts);
          if (exts.EXT_blend_minmax) {
            this._features[Feature.BLEND_MINMAX] = true;
          }
          if (exts.OES_element_index_uint) {
            this._features[Feature.ELEMENT_INDEX_UINT] = true;
          }
          if (exts.ANGLE_instanced_arrays) {
            this._features[Feature.INSTANCED_ARRAYS] = true;
          }
          if (exts.WEBGL_draw_buffers) {
            this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
          }
          var compressedFormat = '';
          if (this.getFormatFeatures(Format.ETC_RGB8)) {
            compressedFormat += 'etc1 ';
          }
          if (this.getFormatFeatures(Format.ETC2_RGB8)) {
            compressedFormat += 'etc2 ';
          }
          if (this.getFormatFeatures(Format.BC1)) {
            compressedFormat += 'dxt ';
          }
          if (this.getFormatFeatures(Format.PVRTC_RGB2)) {
            compressedFormat += 'pvrtc ';
          }
          if (this.getFormatFeatures(Format.ASTC_RGBA_4X4)) {
            compressedFormat += 'astc ';
          }
          debug('WebGL device initialized.');
          debug("RENDERER: " + this._renderer);
          debug("VENDOR: " + this._vendor);
          debug("VERSION: " + version);
          debug("COMPRESSED_FORMAT: " + compressedFormat);
          debug("EXTENSIONS: " + extStr);
          return true;
        };
        _proto.destroy = function destroy() {
          if (this._queue) {
            this._queue.destroy();
            this._queue = null;
          }
          if (this._cmdBuff) {
            this._cmdBuff.destroy();
            this._cmdBuff = null;
          }
          this._swapchain = null;
        };
        _proto.flushCommands = function flushCommands(cmdBuffs) {};
        _proto.acquire = function acquire(swapchains) {};
        _proto.present = function present() {
          var queue = this._queue;
          this._numDrawCalls = queue.numDrawCalls;
          this._numInstances = queue.numInstances;
          this._numTris = queue.numTris;
          queue.clear();
        };
        _proto.initFormatFeatures = function initFormatFeatures(exts) {
          this._formatFeatures.fill(FormatFeatureBit.NONE);
          this._textureExclusive.fill(true);
          var tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          this._formatFeatures[Format.RGB8] = tempFeature;
          this._formatFeatures[Format.R5G6B5] = tempFeature;
          this._textureExclusive[Format.R5G6B5] = false;
          this._formatFeatures[Format.RGBA8] = tempFeature;
          this._formatFeatures[Format.RGBA4] = tempFeature;
          this._textureExclusive[Format.RGBA4] = false;
          this._formatFeatures[Format.RGB5A1] = tempFeature;
          this._textureExclusive[Format.RGB5A1] = false;
          this._formatFeatures[Format.DEPTH] = FormatFeatureBit.RENDER_TARGET;
          this._textureExclusive[Format.DEPTH] = false;
          this._formatFeatures[Format.DEPTH_STENCIL] = FormatFeatureBit.RENDER_TARGET;
          this._textureExclusive[Format.DEPTH_STENCIL] = false;
          this._formatFeatures[Format.R8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RG8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGB8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGBA8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RG8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGB8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGBA8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RG8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGB8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGBA8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RG8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGB8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGBA8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R32F] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RG32F] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGB32F] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          if (exts.EXT_sRGB) {
            this._formatFeatures[Format.SRGB8] = tempFeature;
            this._formatFeatures[Format.SRGB8_A8] = tempFeature;
            this._textureExclusive[Format.SRGB8_A8] = false;
          }
          if (exts.WEBGL_depth_texture) {
            this._formatFeatures[Format.DEPTH] |= tempFeature;
            this._formatFeatures[Format.DEPTH_STENCIL] |= tempFeature;
          }
          if (exts.WEBGL_color_buffer_float) {
            this._formatFeatures[Format.RGB32F] |= FormatFeatureBit.RENDER_TARGET;
            this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.RENDER_TARGET;
            this._textureExclusive[Format.RGB32F] = false;
            this._textureExclusive[Format.RGBA32F] = false;
          }
          if (exts.EXT_color_buffer_half_float) {
            this._formatFeatures[Format.RGB16F] |= FormatFeatureBit.RENDER_TARGET;
            this._formatFeatures[Format.RGBA16F] |= FormatFeatureBit.RENDER_TARGET;
            this._textureExclusive[Format.RGB16F] = false;
            this._textureExclusive[Format.RGBA16F] = false;
          }
          if (exts.OES_texture_float) {
            this._formatFeatures[Format.RGB32F] |= FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE;
            this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE;
          }
          if (exts.OES_texture_half_float) {
            this._formatFeatures[Format.RGB16F] |= FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE;
            this._formatFeatures[Format.RGBA16F] |= FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE;
          }
          if (exts.OES_texture_float_linear) {
            this._formatFeatures[Format.RGB32F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.LINEAR_FILTER;
          }
          if (exts.OES_texture_half_float_linear) {
            this._formatFeatures[Format.RGB16F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RGBA16F] |= FormatFeatureBit.LINEAR_FILTER;
          }
          var compressedFeature = FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          if (exts.WEBGL_compressed_texture_etc1) {
            this._formatFeatures[Format.ETC_RGB8] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_etc) {
            this._formatFeatures[Format.ETC2_RGB8] = compressedFeature;
            this._formatFeatures[Format.ETC2_RGBA8] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8_A8] = compressedFeature;
            this._formatFeatures[Format.ETC2_RGB8_A1] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8_A1] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_s3tc) {
            this._formatFeatures[Format.BC1] = compressedFeature;
            this._formatFeatures[Format.BC1_ALPHA] = compressedFeature;
            this._formatFeatures[Format.BC1_SRGB] = compressedFeature;
            this._formatFeatures[Format.BC1_SRGB_ALPHA] = compressedFeature;
            this._formatFeatures[Format.BC2] = compressedFeature;
            this._formatFeatures[Format.BC2_SRGB] = compressedFeature;
            this._formatFeatures[Format.BC3] = compressedFeature;
            this._formatFeatures[Format.BC3_SRGB] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_pvrtc) {
            this._formatFeatures[Format.PVRTC_RGB2] |= compressedFeature;
            this._formatFeatures[Format.PVRTC_RGBA2] |= compressedFeature;
            this._formatFeatures[Format.PVRTC_RGB4] |= compressedFeature;
            this._formatFeatures[Format.PVRTC_RGBA4] |= compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_astc) {
            this._formatFeatures[Format.ASTC_RGBA_4X4] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_5X4] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_5X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_6X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_6X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X8] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X8] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X10] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_12X10] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_12X12] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_4X4] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_5X4] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_5X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_6X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_6X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X8] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X8] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X10] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_12X10] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_12X12] |= compressedFeature;
          }
        };
        _proto.createCommandBuffer = function createCommandBuffer(info) {
          var Ctor = info.type === CommandBufferType.PRIMARY ? WebGLPrimaryCommandBuffer : WebGLCommandBuffer;
          var cmdBuff = new Ctor();
          cmdBuff.initialize(info);
          return cmdBuff;
        };
        _proto.createSwapchain = function createSwapchain(info) {
          var swapchain = new WebGLSwapchain();
          this._swapchain = swapchain;
          swapchain.initialize(info);
          return swapchain;
        };
        _proto.createBuffer = function createBuffer(info) {
          var buffer = new WebGLBuffer();
          buffer.initialize(info);
          return buffer;
        };
        _proto.createTexture = function createTexture(info) {
          var texture = new WebGLTexture();
          texture.initialize(info);
          return texture;
        };
        _proto.createDescriptorSet = function createDescriptorSet(info) {
          var descriptorSet = new WebGLDescriptorSet();
          descriptorSet.initialize(info);
          return descriptorSet;
        };
        _proto.createShader = function createShader(info) {
          var shader = new WebGLShader();
          shader.initialize(info);
          return shader;
        };
        _proto.createInputAssembler = function createInputAssembler(info) {
          var inputAssembler = new WebGLInputAssembler();
          inputAssembler.initialize(info);
          return inputAssembler;
        };
        _proto.createRenderPass = function createRenderPass(info) {
          var renderPass = new WebGLRenderPass();
          renderPass.initialize(info);
          return renderPass;
        };
        _proto.createFramebuffer = function createFramebuffer(info) {
          var framebuffer = new WebGLFramebuffer();
          framebuffer.initialize(info);
          return framebuffer;
        };
        _proto.createDescriptorSetLayout = function createDescriptorSetLayout(info) {
          var descriptorSetLayout = new WebGLDescriptorSetLayout();
          descriptorSetLayout.initialize(info);
          return descriptorSetLayout;
        };
        _proto.createPipelineLayout = function createPipelineLayout(info) {
          var pipelineLayout = new WebGLPipelineLayout();
          pipelineLayout.initialize(info);
          return pipelineLayout;
        };
        _proto.createPipelineState = function createPipelineState(info) {
          var pipelineState = new WebGLPipelineState();
          pipelineState.initialize(info);
          return pipelineState;
        };
        _proto.createQueue = function createQueue(info) {
          var queue = new WebGLQueue();
          queue.initialize(info);
          return queue;
        };
        _proto.getSampler = function getSampler(info) {
          var hash = Sampler.computeHash(info);
          if (!this._samplers.has(hash)) {
            this._samplers.set(hash, new WebGLSampler(info, hash));
          }
          return this._samplers.get(hash);
        };
        _proto.getSwapchains = function getSwapchains() {
          return [this._swapchain];
        };
        _proto.getGeneralBarrier = function getGeneralBarrier(info) {
          var hash = GeneralBarrier.computeHash(info);
          if (!this._generalBarrierss.has(hash)) {
            this._generalBarrierss.set(hash, new GeneralBarrier(info, hash));
          }
          return this._generalBarrierss.get(hash);
        };
        _proto.getTextureBarrier = function getTextureBarrier(info) {
          var hash = TextureBarrier.computeHash(info);
          if (!this._textureBarriers.has(hash)) {
            this._textureBarriers.set(hash, new TextureBarrier(info, hash));
          }
          return this._textureBarriers.get(hash);
        };
        _proto.getBufferBarrier = function getBufferBarrier(info) {
          var hash = BufferBarrier.computeHash(info);
          if (!this._bufferBarriers.has(hash)) {
            this._bufferBarriers.set(hash, new BufferBarrier(info, hash));
          }
          return this._bufferBarriers.get(hash);
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          WebGLCmdFuncCopyBuffersToTexture(this, buffers, texture.gpuTexture, regions);
        };
        _proto.copyTextureToBuffers = function copyTextureToBuffers(texture, buffers, regions) {
          WebGLCmdFuncCopyTextureToBuffers(this, texture.gpuTexture, buffers, regions);
        };
        _proto.copyTexImagesToTexture = function copyTexImagesToTexture(texImages, texture, regions) {
          WebGLCmdFuncCopyTexImagesToTexture(this, texImages, texture.gpuTexture, regions);
        };
        _createClass(WebGLDevice, [{
          key: "gl",
          get: function get() {
            return this._context;
          }
        }, {
          key: "extensions",
          get: function get() {
            return this._swapchain.extensions;
          }
        }, {
          key: "stateCache",
          get: function get() {
            return this._swapchain.stateCache;
          }
        }, {
          key: "nullTex2D",
          get: function get() {
            return this._swapchain.nullTex2D;
          }
        }, {
          key: "nullTexCube",
          get: function get() {
            return this._swapchain.nullTexCube;
          }
        }, {
          key: "textureExclusive",
          get: function get() {
            return this._textureExclusive;
          }
        }, {
          key: "bindingMappings",
          get: function get() {
            return this._bindingMappings;
          }
        }, {
          key: "blitManager",
          get: function get() {
            return this._swapchain.blitManager;
          }
        }]);
        return WebGLDevice;
      }(Device));

      legacyCC.WebGLDevice = WebGLDevice;

      function lineLine(a1, a2, b1, b2) {
        var ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x);
        var ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x);
        var u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
        if (u_b !== 0) {
          var ua = ua_t / u_b;
          var ub = ub_t / u_b;
          if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) {
            return true;
          }
        }
        return false;
      }
      var tempR1 = new Vec2();
      var tempR2 = new Vec2();
      var tempR3 = new Vec2();
      var tempR4 = new Vec2();
      function lineRect(a1, a2, b) {
        var r0 = tempR1.set(b.x, b.y);
        var r1 = tempR2.set(b.x, b.yMax);
        var r2 = tempR3.set(b.xMax, b.yMax);
        var r3 = tempR4.set(b.xMax, b.y);
        if (lineLine(a1, a2, r0, r1)) return true;
        if (lineLine(a1, a2, r1, r2)) return true;
        if (lineLine(a1, a2, r2, r3)) return true;
        if (lineLine(a1, a2, r3, r0)) return true;
        return false;
      }
      function linePolygon(a1, a2, b) {
        var length = b.length;
        for (var i = 0; i < length; ++i) {
          var b1 = b[i];
          var b2 = b[(i + 1) % length];
          if (lineLine(a1, a2, b1, b2)) return true;
        }
        return false;
      }
      function rectRect(a, b) {
        var a_min_x = a.x;
        var a_min_y = a.y;
        var a_max_x = a.x + a.width;
        var a_max_y = a.y + a.height;
        var b_min_x = b.x;
        var b_min_y = b.y;
        var b_max_x = b.x + b.width;
        var b_max_y = b.y + b.height;
        return a_min_x <= b_max_x && a_max_x >= b_min_x && a_min_y <= b_max_y && a_max_y >= b_min_y;
      }
      function rectPolygon(a, b) {
        var r0 = tempR1.set(a.x, a.y);
        var r1 = tempR2.set(a.x, a.yMax);
        var r2 = tempR3.set(a.xMax, a.yMax);
        var r3 = tempR4.set(a.xMax, a.y);
        if (linePolygon(r0, r1, b)) return true;
        if (linePolygon(r1, r2, b)) return true;
        if (linePolygon(r2, r3, b)) return true;
        if (linePolygon(r3, r0, b)) return true;
        for (var i = 0, l = b.length; i < l; ++i) {
          if (a.contains(b[i])) return true;
        }
        if (pointInPolygon(r0, b)) return true;
        if (pointInPolygon(r1, b)) return true;
        if (pointInPolygon(r2, b)) return true;
        if (pointInPolygon(r3, b)) return true;
        return false;
      }
      function polygonPolygon(a, b) {
        var i;
        var l;
        for (i = 0, l = a.length; i < l; ++i) {
          var a1 = a[i];
          var a2 = a[(i + 1) % l];
          if (linePolygon(a1, a2, b)) return true;
        }
        for (i = 0, l = b.length; i < l; ++i) {
          if (pointInPolygon(b[i], a)) return true;
        }
        for (i = 0, l = a.length; i < l; ++i) {
          if (pointInPolygon(a[i], b)) return true;
        }
        return false;
      }
      function circleCircle(c1p, c1r, c2p, c2r) {
        var distance = Vec2.distance(c1p, c2p);
        return distance < c1r + c2r;
      }
      function polygonCircle(polygon, cp, cr) {
        var position = cp;
        if (pointInPolygon(position, polygon)) {
          return true;
        }
        for (var i = 0, l = polygon.length; i < l; i++) {
          var start = i === 0 ? polygon[polygon.length - 1] : polygon[i - 1];
          var end = polygon[i];
          if (pointLineDistance(position, start, end, true) < cr) {
            return true;
          }
        }
        return false;
      }
      function rectCircle(rect, cp, cr) {
        var cx = cp.x;
        var cy = cp.y;
        var rx = rect.x;
        var ry = rect.y;
        var rw = rect.width;
        var rh = rect.height;
        var testX = cx;
        var testY = cy;
        if (cx < rx) testX = rx;else if (cx > rx + rw) testX = rx + rw;
        if (cy < ry) testY = ry;else if (cy > ry + rh) testY = ry + rh;
        var distX = cx - testX;
        var distY = cy - testY;
        var distance = Math.sqrt(distX * distX + distY * distY);
        if (distance <= cr) {
          return true;
        }
        return false;
      }
      function pointInPolygon(point, polygon) {
        var inside = false;
        var x = point.x;
        var y = point.y;
        var length = polygon.length;
        for (var i = 0, j = length - 1; i < length; j = i++) {
          var xi = polygon[i].x;
          var yi = polygon[i].y;
          var xj = polygon[j].x;
          var yj = polygon[j].y;
          var intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi;
          if (intersect) inside = !inside;
        }
        return inside;
      }
      function pointLineDistance(point, start, end, isSegment) {
        var dx = end.x - start.x;
        var dy = end.y - start.y;
        var d = dx * dx + dy * dy;
        var t = ((point.x - start.x) * dx + (point.y - start.y) * dy) / d;
        var p;
        if (!isSegment) {
          p = tempR1.set(start.x + t * dx, start.y + t * dy);
        } else if (d) {
          if (t < 0) p = start;else if (t > 1) p = end;else p = tempR1.set(start.x + t * dx, start.y + t * dy);
        } else {
          p = start;
        }
        dx = point.x - p.x;
        dy = point.y - p.y;
        return Math.sqrt(dx * dx + dy * dy);
      }
      var Intersection2D = exports('eU', function Intersection2D() {});
      Intersection2D.lineLine = lineLine;
      Intersection2D.lineRect = lineRect;
      Intersection2D.linePolygon = linePolygon;
      Intersection2D.rectRect = rectRect;
      Intersection2D.rectPolygon = rectPolygon;
      Intersection2D.rectCircle = rectCircle;
      Intersection2D.polygonPolygon = polygonPolygon;
      Intersection2D.circleCircle = circleCircle;
      Intersection2D.polygonCircle = polygonCircle;
      Intersection2D.pointInPolygon = pointInPolygon;
      Intersection2D.pointLineDistance = pointLineDistance;

      var PlaceMethod = exports('eV', Enum({
        UNIFORM: 0,
        ADAPTIVE: 1
      }));
      var AutoPlacement = exports('eW', function () {
        function AutoPlacement() {}
        AutoPlacement.generate = function generate(info) {
          switch (info.method) {
            case PlaceMethod.UNIFORM:
              return this.doGenerateUniform(info);
            case PlaceMethod.ADAPTIVE:
              return this.doGenerateAdaptive(info);
            default:
              return [];
          }
        };
        AutoPlacement.doGenerateUniform = function doGenerateUniform(info) {
          if (info.nProbesX < 2 || info.nProbesY < 2 || info.nProbesZ < 2) {
            return [];
          }
          var probes = [];
          var position = new Vec3(0.0, 0.0, 0.0);
          var gridSize = new Vec3((info.maxPos.x - info.minPos.x) / (info.nProbesX - 1), (info.maxPos.y - info.minPos.y) / (info.nProbesY - 1), (info.maxPos.z - info.minPos.z) / (info.nProbesZ - 1));
          for (var x = 0; x < info.nProbesX; x++) {
            position.x = x * gridSize.x + info.minPos.x;
            for (var y = 0; y < info.nProbesY; y++) {
              position.y = y * gridSize.y + info.minPos.y;
              for (var z = 0; z < info.nProbesZ; z++) {
                position.z = z * gridSize.z + info.minPos.z;
                probes.push(new Vec3(position));
              }
            }
          }
          return probes;
        };
        AutoPlacement.doGenerateAdaptive = function doGenerateAdaptive(info) {
          return this.doGenerateUniform(info);
        };
        return AutoPlacement;
      }());

      var _dec$1q, _class$1n, _class2$1l, _initializer$1i, _initializer2$1b, _initializer3$W, _class4$6, _initializer4$O, _initializer5$G, _initializer6$z, _initializer7$s, _class6$2, _initializer8$o, _initializer9$k, _initializer10$i, _initializer11$i, _initializer12$g, _initializer13$d, _initializer14$a, _initializer15$8, _dec2$1j, _class8$4, _class9$1, _initializer16$8, _initializer17$6, _dec3$11, _class11$1, _class12$1, _initializer18$6, _initializer19$5, _initializer20$4, _initializer21$4, _initializer22$4, _initializer23$3, _initializer24$3, _initializer25$3, _initializer26$3;
      var ccclass$g = ccclass$M,
        serializable$2 = serializable$p;
      var _mat = new Mat3();
      var _n = new Vec3(0.0, 0.0, 0.0);
      var _a = new Vec3(0.0, 0.0, 0.0);
      var _ap = new Vec3(0.0, 0.0, 0.0);
      var _b = new Vec3(0.0, 0.0, 0.0);
      var _bp = new Vec3(0.0, 0.0, 0.0);
      var _p2 = new Vec3(0.0, 0.0, 0.0);
      var _cp = new Vec3(0.0, 0.0, 0.0);
      var Vertex$1 = exports('eX', (_dec$1q = ccclass$g('cc.Vertex'), _dec$1q(_class$1n = (_class2$1l = function Vertex(pos) {
        this.position = _initializer$1i && _initializer$1i();
        this.normal = _initializer2$1b && _initializer2$1b();
        this.coefficients = _initializer3$W && _initializer3$W();
        this.position.set(pos);
      }, (_initializer$1i = applyDecoratedInitializer(_class2$1l.prototype, "position", [serializable$2], function () {
        return new Vec3(0, 0, 0);
      }), _initializer2$1b = applyDecoratedInitializer(_class2$1l.prototype, "normal", [serializable$2], function () {
        return new Vec3(0, 0, 0);
      }), _initializer3$W = applyDecoratedInitializer(_class2$1l.prototype, "coefficients", [serializable$2], function () {
        return [];
      })), _class2$1l)) || _class$1n));
      var Edge = (_class4$6 = function () {
        function Edge(tet, i, v0, v1) {
          this.tetrahedron = _initializer4$O && _initializer4$O();
          this.index = _initializer5$G && _initializer5$G();
          this.vertex0 = _initializer6$z && _initializer6$z();
          this.vertex1 = _initializer7$s && _initializer7$s();
          this.tetrahedron = tet;
          this.index = i;
          if (v0 < v1) {
            this.vertex0 = v0;
            this.vertex1 = v1;
          } else {
            this.vertex0 = v1;
            this.vertex1 = v0;
          }
        }
        var _proto = Edge.prototype;
        _proto.set = function set(tet, i, v0, v1) {
          this.tetrahedron = tet;
          this.index = i;
          if (v0 < v1) {
            this.vertex0 = v0;
            this.vertex1 = v1;
          } else {
            this.vertex0 = v1;
            this.vertex1 = v0;
          }
        };
        _proto.isSame = function isSame(other) {
          return this.vertex0 === other.vertex0 && this.vertex1 === other.vertex1;
        };
        return Edge;
      }(), (_initializer4$O = applyDecoratedInitializer(_class4$6.prototype, "tetrahedron", [serializable$2], function () {
        return -1;
      }), _initializer5$G = applyDecoratedInitializer(_class4$6.prototype, "index", [serializable$2], function () {
        return -1;
      }), _initializer6$z = applyDecoratedInitializer(_class4$6.prototype, "vertex0", [serializable$2], function () {
        return -1;
      }), _initializer7$s = applyDecoratedInitializer(_class4$6.prototype, "vertex1", [serializable$2], function () {
        return -1;
      })), _class4$6);
      var Triangle = (_class6$2 = function () {
        function Triangle(tet, i, v0, v1, v2, v3) {
          this.invalid = _initializer8$o && _initializer8$o();
          this.isOuterFace = _initializer9$k && _initializer9$k();
          this.tetrahedron = _initializer10$i && _initializer10$i();
          this.index = _initializer11$i && _initializer11$i();
          this.vertex0 = _initializer12$g && _initializer12$g();
          this.vertex1 = _initializer13$d && _initializer13$d();
          this.vertex2 = _initializer14$a && _initializer14$a();
          this.vertex3 = _initializer15$8 && _initializer15$8();
          this.tetrahedron = tet;
          this.index = i;
          this.vertex3 = v3;
          if (v0 < v1 && v0 < v2) {
            this.vertex0 = v0;
            if (v1 < v2) {
              this.vertex1 = v1;
              this.vertex2 = v2;
            } else {
              this.vertex1 = v2;
              this.vertex2 = v1;
            }
          } else if (v1 < v0 && v1 < v2) {
            this.vertex0 = v1;
            if (v0 < v2) {
              this.vertex1 = v0;
              this.vertex2 = v2;
            } else {
              this.vertex1 = v2;
              this.vertex2 = v0;
            }
          } else {
            this.vertex0 = v2;
            if (v0 < v1) {
              this.vertex1 = v0;
              this.vertex2 = v1;
            } else {
              this.vertex1 = v1;
              this.vertex2 = v0;
            }
          }
        }
        var _proto2 = Triangle.prototype;
        _proto2.set = function set(tet, i, v0, v1, v2, v3) {
          this.invalid = false;
          this.isOuterFace = true;
          this.tetrahedron = tet;
          this.index = i;
          this.vertex3 = v3;
          if (v0 < v1 && v0 < v2) {
            this.vertex0 = v0;
            if (v1 < v2) {
              this.vertex1 = v1;
              this.vertex2 = v2;
            } else {
              this.vertex1 = v2;
              this.vertex2 = v1;
            }
          } else if (v1 < v0 && v1 < v2) {
            this.vertex0 = v1;
            if (v0 < v2) {
              this.vertex1 = v0;
              this.vertex2 = v2;
            } else {
              this.vertex1 = v2;
              this.vertex2 = v0;
            }
          } else {
            this.vertex0 = v2;
            if (v0 < v1) {
              this.vertex1 = v0;
              this.vertex2 = v1;
            } else {
              this.vertex1 = v1;
              this.vertex2 = v0;
            }
          }
        };
        _proto2.isSame = function isSame(other) {
          return this.vertex0 === other.vertex0 && this.vertex1 === other.vertex1 && this.vertex2 === other.vertex2;
        };
        return Triangle;
      }(), (_initializer8$o = applyDecoratedInitializer(_class6$2.prototype, "invalid", [serializable$2], function () {
        return false;
      }), _initializer9$k = applyDecoratedInitializer(_class6$2.prototype, "isOuterFace", [serializable$2], function () {
        return true;
      }), _initializer10$i = applyDecoratedInitializer(_class6$2.prototype, "tetrahedron", [serializable$2], function () {
        return -1;
      }), _initializer11$i = applyDecoratedInitializer(_class6$2.prototype, "index", [serializable$2], function () {
        return -1;
      }), _initializer12$g = applyDecoratedInitializer(_class6$2.prototype, "vertex0", [serializable$2], function () {
        return -1;
      }), _initializer13$d = applyDecoratedInitializer(_class6$2.prototype, "vertex1", [serializable$2], function () {
        return -1;
      }), _initializer14$a = applyDecoratedInitializer(_class6$2.prototype, "vertex2", [serializable$2], function () {
        return -1;
      }), _initializer15$8 = applyDecoratedInitializer(_class6$2.prototype, "vertex3", [serializable$2], function () {
        return -1;
      })), _class6$2);
      var CircumSphere = exports('eY', (_dec2$1j = ccclass$g('cc.CircumSphere'), _dec2$1j(_class8$4 = (_class9$1 = function () {
        function CircumSphere() {
          this.center = _initializer16$8 && _initializer16$8();
          this.radiusSquared = _initializer17$6 && _initializer17$6();
        }
        var _proto3 = CircumSphere.prototype;
        _proto3.init = function init(p0, p1, p2, p3) {
          _mat.set(p1.x - p0.x, p1.y - p0.y, p1.z - p0.z, p2.x - p0.x, p2.y - p0.y, p2.z - p0.z, p3.x - p0.x, p3.y - p0.y, p3.z - p0.z);
          _mat.invert();
          _mat.transpose();
          _n.set(((p1.x + p0.x) * (p1.x - p0.x) + (p1.y + p0.y) * (p1.y - p0.y) + (p1.z + p0.z) * (p1.z - p0.z)) * 0.5, ((p2.x + p0.x) * (p2.x - p0.x) + (p2.y + p0.y) * (p2.y - p0.y) + (p2.z + p0.z) * (p2.z - p0.z)) * 0.5, ((p3.x + p0.x) * (p3.x - p0.x) + (p3.y + p0.y) * (p3.y - p0.y) + (p3.z + p0.z) * (p3.z - p0.z)) * 0.5);
          Vec3.transformMat3(this.center, _n, _mat);
          this.radiusSquared = Vec3.squaredDistance(p0, this.center);
        };
        return CircumSphere;
      }(), (_initializer16$8 = applyDecoratedInitializer(_class9$1.prototype, "center", [serializable$2], function () {
        return new Vec3(0, 0, 0);
      }), _initializer17$6 = applyDecoratedInitializer(_class9$1.prototype, "radiusSquared", [serializable$2], function () {
        return 0.0;
      })), _class9$1)) || _class8$4));
      var Tetrahedron = exports('eZ', (_dec3$11 = ccclass$g('cc.Tetrahedron'), _dec3$11(_class11$1 = (_class12$1 = function () {
        function Tetrahedron(delaunay, v0, v1, v2, v3) {
          if (v3 === void 0) {
            v3 = -1;
          }
          this.invalid = _initializer18$6 && _initializer18$6();
          this.vertex0 = _initializer19$5 && _initializer19$5();
          this.vertex1 = _initializer20$4 && _initializer20$4();
          this.vertex2 = _initializer21$4 && _initializer21$4();
          this.vertex3 = _initializer22$4 && _initializer22$4();
          this.neighbours = _initializer23$3 && _initializer23$3();
          this.matrix = _initializer24$3 && _initializer24$3();
          this.offset = _initializer25$3 && _initializer25$3();
          this.sphere = _initializer26$3 && _initializer26$3();
          this.vertex0 = v0;
          this.vertex1 = v1;
          this.vertex2 = v2;
          this.vertex3 = v3;
          if (v3 >= 0) {
            var probes = delaunay._probes;
            var p0 = probes[this.vertex0].position;
            var p1 = probes[this.vertex1].position;
            var p2 = probes[this.vertex2].position;
            var p3 = probes[this.vertex3].position;
            this.sphere.init(p0, p1, p2, p3);
          }
        }
        var _proto4 = Tetrahedron.prototype;
        _proto4.isInCircumSphere = function isInCircumSphere(point) {
          return Vec3.squaredDistance(point, this.sphere.center) < this.sphere.radiusSquared - EPSILON$3;
        };
        _proto4.contain = function contain(vertexIndex) {
          return this.vertex0 === vertexIndex || this.vertex1 === vertexIndex || this.vertex2 === vertexIndex || this.vertex3 === vertexIndex;
        };
        _proto4.isInnerTetrahedron = function isInnerTetrahedron() {
          return this.vertex3 >= 0;
        };
        _proto4.isOuterCell = function isOuterCell() {
          return this.vertex3 < 0;
        };
        return Tetrahedron;
      }(), (_initializer18$6 = applyDecoratedInitializer(_class12$1.prototype, "invalid", [serializable$2], function () {
        return false;
      }), _initializer19$5 = applyDecoratedInitializer(_class12$1.prototype, "vertex0", [serializable$2], function () {
        return -1;
      }), _initializer20$4 = applyDecoratedInitializer(_class12$1.prototype, "vertex1", [serializable$2], function () {
        return -1;
      }), _initializer21$4 = applyDecoratedInitializer(_class12$1.prototype, "vertex2", [serializable$2], function () {
        return -1;
      }), _initializer22$4 = applyDecoratedInitializer(_class12$1.prototype, "vertex3", [serializable$2], function () {
        return -1;
      }), _initializer23$3 = applyDecoratedInitializer(_class12$1.prototype, "neighbours", [serializable$2], function () {
        return [-1, -1, -1, -1];
      }), _initializer24$3 = applyDecoratedInitializer(_class12$1.prototype, "matrix", [serializable$2], function () {
        return new Mat3();
      }), _initializer25$3 = applyDecoratedInitializer(_class12$1.prototype, "offset", [serializable$2], function () {
        return new Vec3(0.0, 0.0, 0.0);
      }), _initializer26$3 = applyDecoratedInitializer(_class12$1.prototype, "sphere", [serializable$2], function () {
        return new CircumSphere();
      })), _class12$1)) || _class11$1));
      var Delaunay = exports('e_', function () {
        function Delaunay(probes) {
          this._probes = [];
          this._tetrahedrons = [];
          this._triangles = [];
          this._edges = [];
          this._probes = probes;
        }
        var _proto5 = Delaunay.prototype;
        _proto5.build = function build() {
          this.reset();
          this.tetrahedralize();
          this.computeAdjacency();
          this.computeMatrices();
          return this._tetrahedrons;
        };
        _proto5.reset = function reset() {
          this._tetrahedrons.length = 0;
          this._triangles.length = 0;
          this._edges.length = 0;
        };
        _proto5.tetrahedralize = function tetrahedralize() {
          var probeCount = this._probes.length;
          var center = this.initTetrahedron();
          for (var i = 0; i < probeCount; i++) {
            this.addProbe(i);
          }
          this._tetrahedrons = this._tetrahedrons.filter(function (tetrahedron) {
            var vertexIndex = probeCount;
            var isSuperTetrahedron = tetrahedron.contain(vertexIndex) || tetrahedron.contain(vertexIndex + 1) || tetrahedron.contain(vertexIndex + 2) || tetrahedron.contain(vertexIndex + 3);
            return !isSuperTetrahedron;
          });
          this._probes.length = probeCount;
          this.reorder(center);
        };
        _proto5.initTetrahedron = function initTetrahedron() {
          var minPos = new Vec3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
          var maxPos = new Vec3(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);
          for (var i = 0; i < this._probes.length; i++) {
            var position = this._probes[i].position;
            minPos.x = Math.min(minPos.x, position.x);
            maxPos.x = Math.max(maxPos.x, position.x);
            minPos.y = Math.min(minPos.y, position.y);
            maxPos.y = Math.max(maxPos.y, position.y);
            minPos.z = Math.min(minPos.z, position.z);
            maxPos.z = Math.max(maxPos.z, position.z);
          }
          var center = new Vec3(0.0, 0.0, 0.0);
          Vec3.add(center, minPos, maxPos);
          Vec3.multiplyScalar(center, center, 0.5);
          var extent = new Vec3(0.0, 0.0, 0.0);
          Vec3.subtract(extent, maxPos, minPos);
          var offset = Math.max(extent.x, extent.y, extent.z) * 10.0;
          var p0 = new Vec3(center.x, center.y + offset, center.z);
          var p1 = new Vec3(center.x - offset, center.y - offset, center.z - offset);
          var p2 = new Vec3(center.x - offset, center.y - offset, center.z + offset);
          var p3 = new Vec3(center.x + offset, center.y - offset, center.z);
          var index = this._probes.length;
          this._probes.push(new Vertex$1(p0));
          this._probes.push(new Vertex$1(p1));
          this._probes.push(new Vertex$1(p2));
          this._probes.push(new Vertex$1(p3));
          this._tetrahedrons.push(new Tetrahedron(this, index, index + 1, index + 2, index + 3));
          return center;
        };
        _proto5.addTriangle = function addTriangle(index, tet, i, v0, v1, v2, v3) {
          if (index < this._triangles.length) {
            this._triangles[index].set(tet, i, v0, v1, v2, v3);
          } else {
            this._triangles.push(new Triangle(tet, i, v0, v1, v2, v3));
          }
        };
        _proto5.addEdge = function addEdge(index, tet, i, v0, v1) {
          if (index < this._edges.length) {
            this._edges[index].set(tet, i, v0, v1);
          } else {
            this._edges.push(new Edge(tet, i, v0, v1));
          }
        };
        _proto5.addProbe = function addProbe(vertexIndex) {
          var probe = this._probes[vertexIndex];
          var position = probe.position;
          var triangleIndex = 0;
          for (var i = 0; i < this._tetrahedrons.length; i++) {
            var tetrahedron = this._tetrahedrons[i];
            if (tetrahedron.isInCircumSphere(position)) {
              tetrahedron.invalid = true;
              this.addTriangle(triangleIndex, i, 0, tetrahedron.vertex1, tetrahedron.vertex3, tetrahedron.vertex2, tetrahedron.vertex0);
              this.addTriangle(triangleIndex + 1, i, 1, tetrahedron.vertex0, tetrahedron.vertex2, tetrahedron.vertex3, tetrahedron.vertex1);
              this.addTriangle(triangleIndex + 2, i, 2, tetrahedron.vertex0, tetrahedron.vertex3, tetrahedron.vertex1, tetrahedron.vertex2);
              this.addTriangle(triangleIndex + 3, i, 3, tetrahedron.vertex0, tetrahedron.vertex1, tetrahedron.vertex2, tetrahedron.vertex3);
              triangleIndex += 4;
            }
          }
          for (var _i = 0; _i < triangleIndex; _i++) {
            if (this._triangles[_i].invalid) {
              continue;
            }
            for (var k = _i + 1; k < triangleIndex; k++) {
              if (this._triangles[_i].isSame(this._triangles[k])) {
                this._triangles[_i].invalid = true;
                this._triangles[k].invalid = true;
                break;
              }
            }
          }
          this._tetrahedrons = this._tetrahedrons.filter(function (tetrahedron) {
            return !tetrahedron.invalid;
          });
          for (var _i2 = 0; _i2 < triangleIndex; _i2++) {
            var triangle = this._triangles[_i2];
            if (!triangle.invalid) {
              this._tetrahedrons.push(new Tetrahedron(this, triangle.vertex0, triangle.vertex1, triangle.vertex2, vertexIndex));
            }
          }
        };
        _proto5.reorder = function reorder(center) {
          this._tetrahedrons.sort(function (a, b) {
            return Vec3.squaredDistance(a.sphere.center, center) - Vec3.squaredDistance(b.sphere.center, center);
          });
        };
        _proto5.computeAdjacency = function computeAdjacency() {
          var normal = new Vec3(0.0, 0.0, 0.0);
          var edge1 = new Vec3(0.0, 0.0, 0.0);
          var edge2 = new Vec3(0.0, 0.0, 0.0);
          var edge3 = new Vec3(0.0, 0.0, 0.0);
          var tetrahedronCount = this._tetrahedrons.length;
          var triangleIndex = 0;
          for (var i = 0; i < this._tetrahedrons.length; i++) {
            var tetrahedron = this._tetrahedrons[i];
            this.addTriangle(triangleIndex, i, 0, tetrahedron.vertex1, tetrahedron.vertex3, tetrahedron.vertex2, tetrahedron.vertex0);
            this.addTriangle(triangleIndex + 1, i, 1, tetrahedron.vertex0, tetrahedron.vertex2, tetrahedron.vertex3, tetrahedron.vertex1);
            this.addTriangle(triangleIndex + 2, i, 2, tetrahedron.vertex0, tetrahedron.vertex3, tetrahedron.vertex1, tetrahedron.vertex2);
            this.addTriangle(triangleIndex + 3, i, 3, tetrahedron.vertex0, tetrahedron.vertex1, tetrahedron.vertex2, tetrahedron.vertex3);
            triangleIndex += 4;
          }
          for (var _i3 = 0; _i3 < triangleIndex; _i3++) {
            if (!this._triangles[_i3].isOuterFace) {
              continue;
            }
            for (var k = _i3 + 1; k < triangleIndex; k++) {
              if (this._triangles[_i3].isSame(this._triangles[k])) {
                this._tetrahedrons[this._triangles[_i3].tetrahedron].neighbours[this._triangles[_i3].index] = this._triangles[k].tetrahedron;
                this._tetrahedrons[this._triangles[k].tetrahedron].neighbours[this._triangles[k].index] = this._triangles[_i3].tetrahedron;
                this._triangles[_i3].isOuterFace = false;
                this._triangles[k].isOuterFace = false;
                break;
              }
            }
            if (this._triangles[_i3].isOuterFace) {
              var probe0 = this._probes[this._triangles[_i3].vertex0];
              var probe1 = this._probes[this._triangles[_i3].vertex1];
              var probe2 = this._probes[this._triangles[_i3].vertex2];
              var probe3 = this._probes[this._triangles[_i3].vertex3];
              Vec3.subtract(edge1, probe1.position, probe0.position);
              Vec3.subtract(edge2, probe2.position, probe0.position);
              Vec3.cross(normal, edge1, edge2);
              Vec3.subtract(edge3, probe3.position, probe0.position);
              var negative = Vec3.dot(normal, edge3);
              if (negative > 0.0) {
                Vec3.negate(normal, normal);
              }
              Vec3.add(probe0.normal, probe0.normal, normal);
              Vec3.add(probe1.normal, probe1.normal, normal);
              Vec3.add(probe2.normal, probe2.normal, normal);
              var v0 = this._triangles[_i3].vertex0;
              var v1 = negative > 0.0 ? this._triangles[_i3].vertex2 : this._triangles[_i3].vertex1;
              var v2 = negative > 0.0 ? this._triangles[_i3].vertex1 : this._triangles[_i3].vertex2;
              var _tetrahedron = new Tetrahedron(this, v0, v1, v2);
              _tetrahedron.neighbours[3] = this._triangles[_i3].tetrahedron;
              this._tetrahedrons[this._triangles[_i3].tetrahedron].neighbours[this._triangles[_i3].index] = this._tetrahedrons.length;
              this._tetrahedrons.push(_tetrahedron);
            }
          }
          var edgeIndex = 0;
          for (var _i4 = tetrahedronCount; _i4 < this._tetrahedrons.length; _i4++) {
            var _tetrahedron2 = this._tetrahedrons[_i4];
            this.addEdge(edgeIndex, _i4, 0, _tetrahedron2.vertex1, _tetrahedron2.vertex2);
            this.addEdge(edgeIndex + 1, _i4, 1, _tetrahedron2.vertex2, _tetrahedron2.vertex0);
            this.addEdge(edgeIndex + 2, _i4, 2, _tetrahedron2.vertex0, _tetrahedron2.vertex1);
            edgeIndex += 3;
          }
          for (var _i5 = 0; _i5 < edgeIndex; _i5++) {
            for (var _k = _i5 + 1; _k < edgeIndex; _k++) {
              if (this._edges[_i5].isSame(this._edges[_k])) {
                this._tetrahedrons[this._edges[_i5].tetrahedron].neighbours[this._edges[_i5].index] = this._edges[_k].tetrahedron;
                this._tetrahedrons[this._edges[_k].tetrahedron].neighbours[this._edges[_k].index] = this._edges[_i5].tetrahedron;
              }
            }
          }
          for (var _i6 = 0; _i6 < this._probes.length; _i6++) {
            this._probes[_i6].normal.normalize();
          }
        };
        _proto5.computeMatrices = function computeMatrices() {
          for (var i = 0; i < this._tetrahedrons.length; i++) {
            var tetrahedron = this._tetrahedrons[i];
            if (tetrahedron.vertex3 >= 0) {
              this.computeTetrahedronMatrix(tetrahedron);
            } else {
              this.computeOuterCellMatrix(tetrahedron);
            }
          }
        };
        _proto5.computeTetrahedronMatrix = function computeTetrahedronMatrix(tetrahedron) {
          var p0 = this._probes[tetrahedron.vertex0].position;
          var p1 = this._probes[tetrahedron.vertex1].position;
          var p2 = this._probes[tetrahedron.vertex2].position;
          var p3 = this._probes[tetrahedron.vertex3].position;
          tetrahedron.matrix.set(p0.x - p3.x, p1.x - p3.x, p2.x - p3.x, p0.y - p3.y, p1.y - p3.y, p2.y - p3.y, p0.z - p3.z, p1.z - p3.z, p2.z - p3.z);
          tetrahedron.matrix.invert();
          tetrahedron.matrix.transpose();
        };
        _proto5.computeOuterCellMatrix = function computeOuterCellMatrix(tetrahedron) {
          var v = [];
          var p = [];
          v[0] = this._probes[tetrahedron.vertex0].normal;
          v[1] = this._probes[tetrahedron.vertex1].normal;
          v[2] = this._probes[tetrahedron.vertex2].normal;
          p[0] = this._probes[tetrahedron.vertex0].position;
          p[1] = this._probes[tetrahedron.vertex1].position;
          p[2] = this._probes[tetrahedron.vertex2].position;
          Vec3.subtract(_a, p[0], p[2]);
          Vec3.subtract(_ap, v[0], v[2]);
          Vec3.subtract(_b, p[1], p[2]);
          Vec3.subtract(_bp, v[1], v[2]);
          _p2.set(p[2]);
          Vec3.negate(_cp, v[2]);
          var m = [];
          m[0] = _ap.y * _bp.z - _ap.z * _bp.y;
          m[3] = -_ap.x * _bp.z + _ap.z * _bp.x;
          m[6] = _ap.x * _bp.y - _ap.y * _bp.x;
          m[9] = _a.x * _bp.y * _cp.z - _a.y * _bp.x * _cp.z + _ap.x * _b.y * _cp.z - _ap.y * _b.x * _cp.z + _a.z * _bp.x * _cp.y - _a.z * _bp.y * _cp.x + _ap.z * _b.x * _cp.y - _ap.z * _b.y * _cp.x - _a.x * _bp.z * _cp.y + _a.y * _bp.z * _cp.x - _ap.x * _b.z * _cp.y + _ap.y * _b.z * _cp.x;
          m[9] -= _p2.x * m[0] + _p2.y * m[3] + _p2.z * m[6];
          m[1] = _ap.y * _b.z + _a.y * _bp.z - _ap.z * _b.y - _a.z * _bp.y;
          m[4] = -_a.x * _bp.z - _ap.x * _b.z + _a.z * _bp.x + _ap.z * _b.x;
          m[7] = _a.x * _bp.y - _a.y * _bp.x + _ap.x * _b.y - _ap.y * _b.x;
          m[10] = _a.x * _b.y * _cp.z - _a.y * _b.x * _cp.z - _a.x * _b.z * _cp.y + _a.y * _b.z * _cp.x + _a.z * _b.x * _cp.y - _a.z * _b.y * _cp.x;
          m[10] -= _p2.x * m[1] + _p2.y * m[4] + _p2.z * m[7];
          m[2] = -_a.z * _b.y + _a.y * _b.z;
          m[5] = -_a.x * _b.z + _a.z * _b.x;
          m[8] = _a.x * _b.y - _a.y * _b.x;
          m[11] = 0.0;
          m[11] -= _p2.x * m[2] + _p2.y * m[5] + _p2.z * m[8];
          var c = _ap.x * _bp.y * _cp.z - _ap.y * _bp.x * _cp.z + _ap.z * _bp.x * _cp.y - _ap.z * _bp.y * _cp.x + _ap.y * _bp.z * _cp.x - _ap.x * _bp.z * _cp.y;
          if (Math.abs(c) > EPSILON$3) {
            for (var k = 0; k < 12; k++) {
              m[k] /= c;
            }
          } else {
            tetrahedron.vertex3 = -2;
          }
          tetrahedron.matrix.set(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8]);
          tetrahedron.offset.set(m[9], m[10], m[11]);
        };
        return Delaunay;
      }());

      var SH_BASIS_COUNT = 9;
      var LightProbeSampler = exports('e$', function () {
        function LightProbeSampler() {}
        LightProbeSampler.uniformSampleSphere = function uniformSampleSphere(u1, u2) {
          var z = 1.0 - 2.0 * u1;
          var r = Math.sqrt(Math.max(0.0, 1.0 - z * z));
          var phi = 2.0 * Math.PI * u2;
          var x = r * Math.cos(phi);
          var y = r * Math.sin(phi);
          return new Vec3(x, y, z);
        };
        LightProbeSampler.uniformSampleSphereAll = function uniformSampleSphereAll(sampleCount) {
          assertIsTrue(sampleCount > 0);
          var uCount1 = Math.floor(Math.sqrt(sampleCount));
          var uCount2 = uCount1;
          var samples = [];
          var uDelta1 = 1.0 / uCount1;
          var uDelta2 = 1.0 / uCount2;
          for (var i = 0; i < uCount1; i++) {
            var u1 = (i + 0.5) * uDelta1;
            for (var j = 0; j < uCount2; j++) {
              var u2 = (j + 0.5) * uDelta2;
              var sample = this.uniformSampleSphere(u1, u2);
              samples.push(sample);
            }
          }
          return samples;
        };
        LightProbeSampler.uniformSpherePdf = function uniformSpherePdf() {
          return 1.0 / (4.0 * Math.PI);
        };
        return LightProbeSampler;
      }());
      var SH = exports('f0', function () {
        function SH() {}
        SH.updateUBOData = function updateUBOData(data, offset, coefficients) {
          data[offset++] = coefficients[3].x * this.basisOverPI[3];
          data[offset++] = coefficients[1].x * this.basisOverPI[1];
          data[offset++] = coefficients[2].x * this.basisOverPI[2];
          data[offset++] = coefficients[0].x * this.basisOverPI[0] - coefficients[6].x * this.basisOverPI[6] / 3.0;
          data[offset++] = coefficients[3].y * this.basisOverPI[3];
          data[offset++] = coefficients[1].y * this.basisOverPI[1];
          data[offset++] = coefficients[2].y * this.basisOverPI[2];
          data[offset++] = coefficients[0].y * this.basisOverPI[0] - coefficients[6].y * this.basisOverPI[6] / 3.0;
          data[offset++] = coefficients[3].z * this.basisOverPI[3];
          data[offset++] = coefficients[1].z * this.basisOverPI[1];
          data[offset++] = coefficients[2].z * this.basisOverPI[2];
          data[offset++] = coefficients[0].z * this.basisOverPI[0] - coefficients[6].z * this.basisOverPI[6] / 3.0;
          data[offset++] = coefficients[4].x * this.basisOverPI[4];
          data[offset++] = coefficients[5].x * this.basisOverPI[5];
          data[offset++] = coefficients[6].x * this.basisOverPI[6];
          data[offset++] = coefficients[7].x * this.basisOverPI[7];
          data[offset++] = coefficients[4].y * this.basisOverPI[4];
          data[offset++] = coefficients[5].y * this.basisOverPI[5];
          data[offset++] = coefficients[6].y * this.basisOverPI[6];
          data[offset++] = coefficients[7].y * this.basisOverPI[7];
          data[offset++] = coefficients[4].z * this.basisOverPI[4];
          data[offset++] = coefficients[5].z * this.basisOverPI[5];
          data[offset++] = coefficients[6].z * this.basisOverPI[6];
          data[offset++] = coefficients[7].z * this.basisOverPI[7];
          data[offset++] = coefficients[8].x * this.basisOverPI[8];
          data[offset++] = coefficients[8].y * this.basisOverPI[8];
          data[offset++] = coefficients[8].z * this.basisOverPI[8];
          data[offset++] = 0.0;
        };
        SH.shaderEvaluate = function shaderEvaluate(normal, coefficients) {
          var linearConstR = new Vec4(coefficients[3].x * this.basisOverPI[3], coefficients[1].x * this.basisOverPI[1], coefficients[2].x * this.basisOverPI[2], coefficients[0].x * this.basisOverPI[0] - coefficients[6].x * this.basisOverPI[6] / 3.0);
          var linearConstG = new Vec4(coefficients[3].y * this.basisOverPI[3], coefficients[1].y * this.basisOverPI[1], coefficients[2].y * this.basisOverPI[2], coefficients[0].y * this.basisOverPI[0] - coefficients[6].y * this.basisOverPI[6] / 3.0);
          var linearConstB = new Vec4(coefficients[3].z * this.basisOverPI[3], coefficients[1].z * this.basisOverPI[1], coefficients[2].z * this.basisOverPI[2], coefficients[0].z * this.basisOverPI[0] - coefficients[6].z * this.basisOverPI[6] / 3.0);
          var quadraticR = new Vec4(coefficients[4].x * this.basisOverPI[4], coefficients[5].x * this.basisOverPI[5], coefficients[6].x * this.basisOverPI[6], coefficients[7].x * this.basisOverPI[7]);
          var quadraticG = new Vec4(coefficients[4].y * this.basisOverPI[4], coefficients[5].y * this.basisOverPI[5], coefficients[6].y * this.basisOverPI[6], coefficients[7].y * this.basisOverPI[7]);
          var quadraticB = new Vec4(coefficients[4].z * this.basisOverPI[4], coefficients[5].z * this.basisOverPI[5], coefficients[6].z * this.basisOverPI[6], coefficients[7].z * this.basisOverPI[7]);
          var quadraticA = new Vec3(coefficients[8].x * this.basisOverPI[8], coefficients[8].y * this.basisOverPI[8], coefficients[8].z * this.basisOverPI[8]);
          var result = new Vec3(0.0, 0.0, 0.0);
          var normal4 = new Vec4(normal.x, normal.y, normal.z, 1.0);
          result.x = Vec4.dot(linearConstR, normal4);
          result.y = Vec4.dot(linearConstG, normal4);
          result.z = Vec4.dot(linearConstB, normal4);
          var n14 = new Vec4(normal.x * normal.y, normal.y * normal.z, normal.z * normal.z, normal.z * normal.x);
          var n5 = normal.x * normal.x - normal.y * normal.y;
          result.x += Vec4.dot(quadraticR, n14);
          result.y += Vec4.dot(quadraticG, n14);
          result.z += Vec4.dot(quadraticB, n14);
          Vec3.scaleAndAdd(result, result, quadraticA, n5);
          return result;
        };
        SH.evaluate = function evaluate(sample, coefficients) {
          var result = new Vec3(0.0, 0.0, 0.0);
          var size = coefficients.length;
          for (var i = 0; i < size; i++) {
            var c = coefficients[i];
            Vec3.scaleAndAdd(result, result, c, this.evaluateBasis(i, sample));
          }
          return result;
        };
        SH.project = function project(samples, values) {
          assertIsTrue(samples.length > 0 && samples.length === values.length);
          var basisCount = this.getBasisCount();
          var sampleCount = samples.length;
          var scale = 1.0 / (LightProbeSampler.uniformSpherePdf() * sampleCount);
          var coefficients = [];
          for (var i = 0; i < basisCount; i++) {
            var coefficient = new Vec3(0.0, 0.0, 0.0);
            for (var k = 0; k < sampleCount; k++) {
              Vec3.scaleAndAdd(coefficient, coefficient, values[k], this.evaluateBasis(i, samples[k]));
            }
            Vec3.multiplyScalar(coefficient, coefficient, scale);
            coefficients.push(coefficient);
          }
          return coefficients;
        };
        SH.convolveCosine = function convolveCosine(radianceCoefficients) {
          var cosTheta = [0.8862268925, 1.0233267546, 0.4954159260];
          var irradianceCoefficients = [];
          for (var l = 0; l <= this.LMAX; l++) {
            for (var m = -l; m <= l; m++) {
              var i = this.toIndex(l, m);
              var coefficient = new Vec3(0.0, 0.0, 0.0);
              Vec3.multiplyScalar(coefficient, radianceCoefficients[i], this.lambda(l) * cosTheta[l]);
              irradianceCoefficients.push(coefficient);
            }
          }
          return irradianceCoefficients;
        };
        SH.getBasisCount = function getBasisCount() {
          return SH_BASIS_COUNT;
        };
        SH.evaluateBasis = function evaluateBasis(index, sample) {
          assertIsTrue(index < this.getBasisCount());
          var func = this.basisFunctions[index];
          return func(sample);
        };
        SH.reduceRinging = function reduceRinging(coefficients, lambda) {
          if (lambda === 0.0) {
            return;
          }
          for (var l = 0; l <= this.LMAX; ++l) {
            var scale = 1.0 / (1.0 + lambda * l * l * (l + 1) * (l + 1));
            for (var m = -l; m <= l; ++m) {
              var i = this.toIndex(l, m);
              Vec3.multiplyScalar(coefficients[i], coefficients[i], scale);
            }
          }
        };
        SH.lambda = function lambda(l) {
          return Math.sqrt(4.0 * Math.PI / (2.0 * l + 1.0));
        };
        SH.toIndex = function toIndex(l, m) {
          return l * l + l + m;
        };
        return SH;
      }());
      SH.LMAX = 2;
      SH.basisFunctions = [function (v) {
        return 0.282095;
      }, function (v) {
        return 0.488603 * v.y;
      }, function (v) {
        return 0.488603 * v.z;
      }, function (v) {
        return 0.488603 * v.x;
      }, function (v) {
        return 1.09255 * v.y * v.x;
      }, function (v) {
        return 1.09255 * v.y * v.z;
      }, function (v) {
        return 0.946175 * (v.z * v.z - 1.0 / 3.0);
      }, function (v) {
        return 1.09255 * v.z * v.x;
      }, function (v) {
        return 0.546274 * (v.x * v.x - v.y * v.y);
      }];
      SH.basisOverPI = [0.0897936, 0.155527, 0.155527, 0.155527, 0.347769, 0.347769, 0.301177, 0.347769, 0.173884];
      legacyCC.internal.SH = SH;

      var PolynomialSolver = function () {
        function PolynomialSolver() {}
        PolynomialSolver.getQuadraticUniqueRoot = function getQuadraticUniqueRoot(b, c, d) {
          if (b !== 0.0) {
            return -c / (2.0 * b);
          }
          if (c !== 0.0) {
            return -d / c;
          }
          return 0.0;
        };
        PolynomialSolver.getCubicUniqueRoot = function getCubicUniqueRoot(b, c, d) {
          var roots = [];
          var offset = -b / 3.0;
          var p = c / 3.0 - b * b / 9.0;
          var q = d / 2.0 + b * b * b / 27.0 - b * c / 6.0;
          var delta = p * p * p + q * q;
          if (delta > 0.0) {
            var sqrtDelta = Math.sqrt(delta);
            roots.push(Math.cbrt(-q + sqrtDelta) + Math.cbrt(-q - sqrtDelta));
          } else if (delta < 0.0) {
            var angle = Math.acos(-q * Math.sqrt(-p) / (p * p)) / 3.0;
            roots.push(2.0 * Math.sqrt(-p) * Math.cos(angle));
            roots.push(2.0 * Math.sqrt(-p) * Math.cos(angle + 2.0 * Math.PI / 3.0));
            roots.push(2.0 * Math.sqrt(-p) * Math.cos(angle + 4.0 * Math.PI / 3.0));
          } else if (q === 0.0) {
            roots.push(0.0);
          } else {
            var root = Math.cbrt(q);
            roots.push(root);
            roots.push(-2.0 * root);
          }
          for (var i = 0; i < roots.length; i++) {
            if (roots[i] + offset >= 0.0) {
              return roots[i] + offset;
            }
          }
          return 0.0;
        };
        return PolynomialSolver;
      }();

      var _dec$1p, _dec2$1i, _dec3$10, _class$1m, _class2$1k, _initializer$1h, _initializer2$1a;
      var _v1 = new Vec3(0.0, 0.0, 0.0);
      var _v2 = new Vec3(0.0, 0.0, 0.0);
      var _normal$1 = new Vec3(0.0, 0.0, 0.0);
      var _edgeP0 = new Vec3(0.0, 0.0, 0.0);
      var _edgeP1 = new Vec3(0.0, 0.0, 0.0);
      var _edgeP2 = new Vec3(0.0, 0.0, 0.0);
      var _crossP12 = new Vec3(0.0, 0.0, 0.0);
      var _crossP20 = new Vec3(0.0, 0.0, 0.0);
      var _normal2 = new Vec3(0.0, 0.0, 0.0);
      var _edge1 = new Vec3(0.0, 0.0, 0.0);
      var _edge2 = new Vec3(0.0, 0.0, 0.0);
      var _v = new Vec3(0.0, 0.0, 0.0);
      var _vp0 = new Vec3(0.0, 0.0, 0.0);
      var _vp1 = new Vec3(0.0, 0.0, 0.0);
      var _vp2 = new Vec3(0.0, 0.0, 0.0);
      var LightProbesData = exports('f1', (_dec$1p = ccclass$M('cc.LightProbesData'), _dec2$1i = type$d([Vertex$1]), _dec3$10 = type$d([Tetrahedron]), _dec$1p(_class$1m = (_class2$1k = function () {
        function LightProbesData() {
          this._probes = _initializer$1h && _initializer$1h();
          this._tetrahedrons = _initializer2$1a && _initializer2$1a();
        }
        var _proto = LightProbesData.prototype;
        _proto.empty = function empty() {
          return this._probes.length === 0 || this._tetrahedrons.length === 0;
        };
        _proto.reset = function reset() {
          this._probes.length = 0;
          this._tetrahedrons.length = 0;
        };
        _proto.updateProbes = function updateProbes(points) {
          this._probes.length = points.length;
          var pointCount = this._probes.length;
          for (var i = 0; i < pointCount; i++) {
            var probe = this._probes[i];
            if (!probe) {
              probe = new Vertex$1(points[i]);
              for (var j = 0; j < SH.getBasisCount(); j++) {
                probe.coefficients[j] = Vec3.ZERO;
              }
              this._probes[i] = probe;
            } else {
              probe.position.set(points[i]);
            }
          }
        };
        _proto.updateTetrahedrons = function updateTetrahedrons() {
          var delaunay = new Delaunay(this._probes);
          this._tetrahedrons = delaunay.build();
        };
        _proto.getInterpolationSHCoefficients = function getInterpolationSHCoefficients(tetIndex, weights, coefficients) {
          if (!this.hasCoefficients()) {
            return false;
          }
          var length = SH.getBasisCount();
          var tetrahedron = this._tetrahedrons[tetIndex];
          var c0 = this._probes[tetrahedron.vertex0].coefficients;
          var c1 = this._probes[tetrahedron.vertex1].coefficients;
          var c2 = this._probes[tetrahedron.vertex2].coefficients;
          if (tetrahedron.vertex3 >= 0) {
            var c3 = this._probes[tetrahedron.vertex3].coefficients;
            for (var i = 0; i < length; i++) {
              coefficients[i] = new Vec3(0.0, 0.0, 0.0);
              Vec3.scaleAndAdd(coefficients[i], coefficients[i], c0[i], weights.x);
              Vec3.scaleAndAdd(coefficients[i], coefficients[i], c1[i], weights.y);
              Vec3.scaleAndAdd(coefficients[i], coefficients[i], c2[i], weights.z);
              Vec3.scaleAndAdd(coefficients[i], coefficients[i], c3[i], weights.w);
            }
          } else {
            for (var _i = 0; _i < length; _i++) {
              coefficients[_i] = new Vec3(0.0, 0.0, 0.0);
              Vec3.scaleAndAdd(coefficients[_i], coefficients[_i], c0[_i], weights.x);
              Vec3.scaleAndAdd(coefficients[_i], coefficients[_i], c1[_i], weights.y);
              Vec3.scaleAndAdd(coefficients[_i], coefficients[_i], c2[_i], weights.z);
            }
          }
          return true;
        };
        _proto.getInterpolationWeights = function getInterpolationWeights(position, tetIndex, weights) {
          var tetrahedronCount = this._tetrahedrons.length;
          if (tetIndex < 0 || tetIndex >= tetrahedronCount) {
            tetIndex = 0;
          }
          var lastIndex = -1;
          var nextIndex = -1;
          for (var i = 0; i < tetrahedronCount; i++) {
            var tetrahedron = this._tetrahedrons[tetIndex];
            this.getBarycentricCoord(position, tetrahedron, weights);
            if (weights.x >= 0.0 && weights.y >= 0.0 && weights.z >= 0.0 && weights.w >= 0.0) {
              break;
            }
            if (weights.x < weights.y && weights.x < weights.z && weights.x < weights.w) {
              nextIndex = tetrahedron.neighbours[0];
            } else if (weights.y < weights.z && weights.y < weights.w) {
              nextIndex = tetrahedron.neighbours[1];
            } else if (weights.z < weights.w) {
              nextIndex = tetrahedron.neighbours[2];
            } else {
              nextIndex = tetrahedron.neighbours[3];
            }
            if (lastIndex === nextIndex) {
              break;
            }
            lastIndex = tetIndex;
            tetIndex = nextIndex;
          }
          return tetIndex;
        };
        _proto.hasCoefficients = function hasCoefficients() {
          return !this.empty() && this._probes[0].coefficients.length !== 0;
        };
        LightProbesData.getTriangleBarycentricCoord = function getTriangleBarycentricCoord(p0, p1, p2, position) {
          Vec3.subtract(_v1, p1, p0);
          Vec3.subtract(_v2, p2, p0);
          Vec3.cross(_normal$1, _v1, _v2);
          if (_normal$1.lengthSqr() <= EPSILON$3) {
            return new Vec3(0.0, 0.0, 0.0);
          }
          var n = _normal$1.clone();
          n.normalize();
          var area012Inv = 1.0 / n.dot(_normal$1);
          Vec3.subtract(_edgeP0, p0, position);
          Vec3.subtract(_edgeP1, p1, position);
          Vec3.subtract(_edgeP2, p2, position);
          Vec3.cross(_crossP12, _edgeP1, _edgeP2);
          var areaP12 = n.dot(_crossP12);
          var alpha = areaP12 * area012Inv;
          Vec3.cross(_crossP20, _edgeP2, _edgeP0);
          var areaP20 = n.dot(_crossP20);
          var beta = areaP20 * area012Inv;
          return new Vec3(alpha, beta, 1.0 - alpha - beta);
        };
        _proto.getBarycentricCoord = function getBarycentricCoord(position, tetrahedron, weights) {
          if (tetrahedron.vertex3 >= 0) {
            this.getTetrahedronBarycentricCoord(position, tetrahedron, weights);
          } else {
            this.getOuterCellBarycentricCoord(position, tetrahedron, weights);
          }
        };
        _proto.getTetrahedronBarycentricCoord = function getTetrahedronBarycentricCoord(position, tetrahedron, weights) {
          var result = new Vec3(0.0, 0.0, 0.0);
          Vec3.subtract(result, position, this._probes[tetrahedron.vertex3].position);
          Vec3.transformMat3(result, result, tetrahedron.matrix);
          weights.set(result.x, result.y, result.z, 1.0 - result.x - result.y - result.z);
        };
        _proto.getOuterCellBarycentricCoord = function getOuterCellBarycentricCoord(position, tetrahedron, weights) {
          var p0 = this._probes[tetrahedron.vertex0].position;
          var p1 = this._probes[tetrahedron.vertex1].position;
          var p2 = this._probes[tetrahedron.vertex2].position;
          Vec3.subtract(_edge1, p1, p0);
          Vec3.subtract(_edge2, p2, p0);
          Vec3.cross(_normal2, _edge1, _edge2);
          Vec3.subtract(_v, position, p0);
          var t = Vec3.dot(_v, _normal2);
          if (t < 0.0) {
            weights.set(0.0, 0.0, 0.0, -1.0);
            return;
          }
          var coefficients = new Vec3(0.0, 0.0, 0.0);
          Vec3.transformMat3(coefficients, position, tetrahedron.matrix);
          Vec3.add(coefficients, coefficients, tetrahedron.offset);
          if (tetrahedron.vertex3 === -1) {
            t = PolynomialSolver.getCubicUniqueRoot(coefficients.x, coefficients.y, coefficients.z);
          } else {
            t = PolynomialSolver.getQuadraticUniqueRoot(coefficients.x, coefficients.y, coefficients.z);
          }
          Vec3.scaleAndAdd(_vp0, p0, this._probes[tetrahedron.vertex0].normal, t);
          Vec3.scaleAndAdd(_vp1, p1, this._probes[tetrahedron.vertex1].normal, t);
          Vec3.scaleAndAdd(_vp2, p2, this._probes[tetrahedron.vertex2].normal, t);
          var result = LightProbesData.getTriangleBarycentricCoord(_vp0, _vp1, _vp2, position);
          weights.set(result.x, result.y, result.z, 0.0);
        };
        _createClass(LightProbesData, [{
          key: "probes",
          get: function get() {
            return this._probes;
          }
        }, {
          key: "tetrahedrons",
          get: function get() {
            return this._tetrahedrons;
          }
        }]);
        return LightProbesData;
      }(), (_initializer$1h = applyDecoratedInitializer(_class2$1k.prototype, "_probes", [serializable$p, _dec2$1i], function () {
        return [];
      }), _initializer2$1a = applyDecoratedInitializer(_class2$1k.prototype, "_tetrahedrons", [serializable$p, _dec3$10], function () {
        return [];
      })), _class2$1k)) || _class$1m));
      legacyCC.internal.LightProbesData = LightProbesData;
      var LightProbes = exports('f2', function () {
        function LightProbes() {
          this._giScale = 1.0;
          this._giSamples = 1024;
          this._bounces = 2;
          this._reduceRinging = 0.0;
          this._showProbe = true;
          this._showWireframe = true;
          this._showConvex = false;
          this._data = null;
          this._lightProbeSphereVolume = 1.0;
        }
        var _proto2 = LightProbes.prototype;
        _proto2.initialize = function initialize(info) {
          this._giScale = info.giScale;
          this._giSamples = info.giSamples;
          this._bounces = info.bounces;
          this._reduceRinging = info.reduceRinging;
          this._showProbe = info.showProbe;
          this._showWireframe = info.showWireframe;
          this._showConvex = info.showConvex;
          this._data = info.data;
          this._lightProbeSphereVolume = info.lightProbeSphereVolume;
        };
        _proto2.empty = function empty() {
          if (!this._data) {
            return true;
          }
          return this._data.empty();
        };
        _createClass(LightProbes, [{
          key: "giScale",
          get: function get() {
            return this._giScale;
          },
          set: function set(val) {
            this._giScale = val;
          }
        }, {
          key: "giSamples",
          get: function get() {
            return this._giSamples;
          },
          set: function set(val) {
            this._giSamples = val;
          }
        }, {
          key: "bounces",
          get: function get() {
            return this._bounces;
          },
          set: function set(val) {
            this._bounces = val;
          }
        }, {
          key: "reduceRinging",
          get: function get() {
            return this._reduceRinging;
          },
          set: function set(val) {
            this._reduceRinging = val;
          }
        }, {
          key: "showProbe",
          get: function get() {
            return this._showProbe;
          },
          set: function set(val) {
            this._showProbe = val;
          }
        }, {
          key: "showWireframe",
          get: function get() {
            return this._showWireframe;
          },
          set: function set(val) {
            this._showWireframe = val;
          }
        }, {
          key: "showConvex",
          get: function get() {
            return this._showConvex;
          },
          set: function set(val) {
            this._showConvex = val;
          }
        }, {
          key: "data",
          get: function get() {
            return this._data;
          },
          set: function set(val) {
            this._data = val;
          }
        }, {
          key: "lightProbeSphereVolume",
          get: function get() {
            return this._lightProbeSphereVolume;
          },
          set: function set(val) {
            this._lightProbeSphereVolume = val;
          }
        }]);
        return LightProbes;
      }());
      legacyCC.internal.LightProbes = LightProbes;

      var _dec$1o, _dec2$1h, _dec3$$, _dec4$O, _dec5$K, _dec6$w, _class$1l, _class2$1j, _initializer$1g, _initializer2$19, _initializer3$V, _initializer4$N, _initializer5$F, _initializer6$y, _initializer7$r;
      var LightProbeGroup = exports('f3', (_dec$1o = ccclass$M('cc.LightProbeGroup'), _dec2$1h = type$d([Vec3]), _dec3$$ = type$d(PlaceMethod), _dec4$O = type$d(CCInteger), _dec5$K = type$d(CCInteger), _dec6$w = type$d(CCInteger), _dec$1o(_class$1l = disallowMultiple$1(_class$1l = (_class2$1j = function (_Component) {
        _inheritsLoose(LightProbeGroup, _Component);
        function LightProbeGroup() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._probes = _initializer$1g && _initializer$1g();
          _this._method = _initializer2$19 && _initializer2$19();
          _this._minPos = _initializer3$V && _initializer3$V();
          _this._maxPos = _initializer4$N && _initializer4$N();
          _this._nProbesX = _initializer5$F && _initializer5$F();
          _this._nProbesY = _initializer6$y && _initializer6$y();
          _this._nProbesZ = _initializer7$r && _initializer7$r();
          return _this;
        }
        var _proto = LightProbeGroup.prototype;
        _proto.onLoad = function onLoad() {
          {
            return;
          }
        };
        _proto.onEnable = function onEnable() {
          {
            return;
          }
        };
        _proto.onDisable = function onDisable() {
          {
            return;
          }
        };
        _proto.generateLightProbes = function generateLightProbes() {
          if (!this.node) {
            return;
          }
          this._probes = AutoPlacement.generate({
            method: this._method,
            nProbesX: this._nProbesX,
            nProbesY: this._nProbesY,
            nProbesZ: this._nProbesZ,
            minPos: this._minPos,
            maxPos: this._maxPos
          });
          this.onProbeChanged();
        };
        _proto.onProbeChanged = function onProbeChanged(updateTet, emitEvent) {
          if (updateTet === void 0) {
            updateTet = true;
          }
          if (emitEvent === void 0) {
            emitEvent = true;
          }
          this.node.scene.globals.lightProbeInfo.syncData(this.node, this.probes);
          this.node.scene.globals.lightProbeInfo.update(updateTet);
          if (emitEvent) {
            this.node.emit(NodeEventType.LIGHT_PROBE_CHANGED);
          }
        };
        _createClass(LightProbeGroup, [{
          key: "probes",
          get: function get() {
            return this._probes;
          },
          set: function set(val) {
            this._probes = val;
          }
        }, {
          key: "method",
          get: function get() {
            return this._method;
          }
        }, {
          key: "minPos",
          get: function get() {
            return this._minPos;
          },
          set: function set(val) {
            this._minPos = val;
          }
        }, {
          key: "maxPos",
          get: function get() {
            return this._maxPos;
          },
          set: function set(val) {
            this._maxPos = val;
          }
        }, {
          key: "nProbesX",
          get: function get() {
            return this._nProbesX;
          },
          set: function set(val) {
            this._nProbesX = val;
          }
        }, {
          key: "nProbesY",
          get: function get() {
            return this._nProbesY;
          },
          set: function set(val) {
            this._nProbesY = val;
          }
        }, {
          key: "nProbesZ",
          get: function get() {
            return this._nProbesZ;
          },
          set: function set(val) {
            this._nProbesZ = val;
          }
        }]);
        return LightProbeGroup;
      }(Component), (_initializer$1g = applyDecoratedInitializer(_class2$1j.prototype, "_probes", [serializable$p], function () {
        return [];
      }), _initializer2$19 = applyDecoratedInitializer(_class2$1j.prototype, "_method", [serializable$p], function () {
        return PlaceMethod.UNIFORM;
      }), _initializer3$V = applyDecoratedInitializer(_class2$1j.prototype, "_minPos", [serializable$p], function () {
        return new Vec3(-5, -5, -5);
      }), _initializer4$N = applyDecoratedInitializer(_class2$1j.prototype, "_maxPos", [serializable$p], function () {
        return new Vec3(5, 5, 5);
      }), _initializer5$F = applyDecoratedInitializer(_class2$1j.prototype, "_nProbesX", [serializable$p], function () {
        return 3;
      }), _initializer6$y = applyDecoratedInitializer(_class2$1j.prototype, "_nProbesY", [serializable$p], function () {
        return 3;
      }), _initializer7$r = applyDecoratedInitializer(_class2$1j.prototype, "_nProbesZ", [serializable$p], function () {
        return 3;
      }), _applyDecoratedDescriptor(_class2$1j.prototype, "probes", [_dec2$1h], Object.getOwnPropertyDescriptor(_class2$1j.prototype, "probes"), _class2$1j.prototype), _applyDecoratedDescriptor(_class2$1j.prototype, "method", [_dec3$$], Object.getOwnPropertyDescriptor(_class2$1j.prototype, "method"), _class2$1j.prototype), _applyDecoratedDescriptor(_class2$1j.prototype, "nProbesX", [_dec4$O], Object.getOwnPropertyDescriptor(_class2$1j.prototype, "nProbesX"), _class2$1j.prototype), _applyDecoratedDescriptor(_class2$1j.prototype, "nProbesY", [_dec5$K], Object.getOwnPropertyDescriptor(_class2$1j.prototype, "nProbesY"), _class2$1j.prototype), _applyDecoratedDescriptor(_class2$1j.prototype, "nProbesZ", [_dec6$w], Object.getOwnPropertyDescriptor(_class2$1j.prototype, "nProbesZ"), _class2$1j.prototype)), _class2$1j)) || _class$1l) || _class$1l));

      var _dec$1n, _dec2$1g, _dec3$_, _class$1k, _class2$1i, _initializer$1f, _initializer2$18, _initializer3$U, _initializer4$M, _initializer5$E;
      var Billboard = exports('f4', (_dec$1n = ccclass$M('cc.Billboard'), _dec2$1g = type$d(Texture2D), _dec3$_ = type$d(Texture2D), _dec$1n(_class$1k = (_class2$1i = function (_Component) {
        _inheritsLoose(Billboard, _Component);
        var _proto = Billboard.prototype;
        _proto.updateTexture = function updateTexture() {
          if (this._material) {
            this._material.setProperty('mainTexture', this._texture);
          }
        };
        _proto.updateHeight = function updateHeight() {
          if (this._material) {
            this._uniform.y = this._height;
            this._material.setProperty('cc_size_rotation', this._uniform);
          }
        };
        _proto.updateWidth = function updateWidth() {
          if (this._material) {
            this._uniform.x = this._width;
            this._material.setProperty('cc_size_rotation', this._uniform);
          }
        };
        _proto.updateRotation = function updateRotation() {
          if (this._material) {
            this._uniform.z = this._rotation;
            this._material.setProperty('cc_size_rotation', this._uniform);
          }
        };
        _proto.updateTechnique = function updateTechnique() {
          if (this._model && this._mesh && this._material && this._material.technique !== this._techIndex) {
            this.detachFromScene();
            this._model.destroy();
            this._model = null;
            this._material.destroy();
            this._material = null;
            this._mesh.destroy();
            this._mesh = null;
            this.createModel();
            this.updateWidth();
            this.updateHeight();
            this.updateRotation();
            this.updateTexture();
            if (this.enabled) {
              this.attachToScene();
              this._model.enabled = true;
            } else {
              this._model.enabled = false;
            }
          }
        };
        function Billboard() {
          var _this;
          _this = _Component.call(this) || this;
          _this._texture = _initializer$1f && _initializer$1f();
          _this._height = _initializer2$18 && _initializer2$18();
          _this._width = _initializer3$U && _initializer3$U();
          _this._rotation = _initializer4$M && _initializer4$M();
          _this._techIndex = _initializer5$E && _initializer5$E();
          _this._model = null;
          _this._mesh = null;
          _this._material = null;
          _this._uniform = new Vec4(1, 1, 0, 0);
          return _this;
        }
        _proto.onLoad = function onLoad() {
          this.createModel();
        };
        _proto.onEnable = function onEnable() {
          this.attachToScene();
          this._model.enabled = true;
          this.updateWidth();
          this.updateHeight();
          this.updateRotation();
          this.updateTexture();
          this.updateTechnique();
        };
        _proto.onDisable = function onDisable() {
          this.detachFromScene();
        };
        _proto.attachToScene = function attachToScene() {
          if (this._model && this.node && this.node.scene) {
            if (this._model.scene) {
              this.detachFromScene();
            }
            this._getRenderScene().addModel(this._model);
          }
        };
        _proto.detachFromScene = function detachFromScene() {
          if (this._model && this._model.scene) {
            this._model.scene.removeModel(this._model);
          }
        };
        _proto.createModel = function createModel() {
          this._mesh = _createMesh({
            primitiveMode: PrimitiveMode.TRIANGLE_LIST,
            positions: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            uvs: [0, 0, 1, 0, 0, 1, 1, 1],
            colors: [Color$1.WHITE.r, Color$1.WHITE.g, Color$1.WHITE.b, Color$1.WHITE.a, Color$1.WHITE.r, Color$1.WHITE.g, Color$1.WHITE.b, Color$1.WHITE.a, Color$1.WHITE.r, Color$1.WHITE.g, Color$1.WHITE.b, Color$1.WHITE.a, Color$1.WHITE.r, Color$1.WHITE.g, Color$1.WHITE.b, Color$1.WHITE.a],
            attributes: [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8UI, true)],
            indices: [0, 1, 2, 1, 2, 3]
          }, undefined, {
            calculateBounds: false
          });
          var model = this._model = legacyCC.director.root.createModel(Model, this.node);
          model.node = model.transform = this.node;
          if (this._material == null) {
            this._material = new Material();
            this._material.copy(builtinResMgr.get('default-billboard-material'), {
              technique: this._techIndex
            });
          }
          model.initSubModel(0, this._mesh.renderingSubMeshes[0], this._material);
        };
        _createClass(Billboard, [{
          key: "texture",
          get: function get() {
            return this._texture;
          },
          set: function set(val) {
            this._texture = val;
            this.updateTexture();
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          },
          set: function set(val) {
            this._height = val;
            this.updateHeight();
          }
        }, {
          key: "width",
          get: function get() {
            return this._width;
          },
          set: function set(val) {
            this._width = val;
            this.updateWidth();
          }
        }, {
          key: "rotation",
          get: function get() {
            return Math.round(toDegree(this._rotation) * 100) / 100;
          },
          set: function set(val) {
            this._rotation = toRadian(val);
            this.updateRotation();
          }
        }, {
          key: "technique",
          get: function get() {
            return this._techIndex;
          },
          set: function set(val) {
            var _this$_material, _this$_material$effec;
            val = Math.floor(val);
            var techs = (_this$_material = this._material) === null || _this$_material === void 0 ? void 0 : (_this$_material$effec = _this$_material.effectAsset) === null || _this$_material$effec === void 0 ? void 0 : _this$_material$effec.techniques;
            if (techs && val >= techs.length) {
              val = techs.length - 1;
            }
            if (val < 0) {
              val = 0;
            }
            this._techIndex = val;
            this.updateTechnique();
          }
        }]);
        return Billboard;
      }(Component), (_initializer$1f = applyDecoratedInitializer(_class2$1i.prototype, "_texture", [_dec2$1g], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$1i.prototype, "texture", [_dec3$_], Object.getOwnPropertyDescriptor(_class2$1i.prototype, "texture"), _class2$1i.prototype), _initializer2$18 = applyDecoratedInitializer(_class2$1i.prototype, "_height", [serializable$p], function () {
        return 0;
      }), _initializer3$U = applyDecoratedInitializer(_class2$1i.prototype, "_width", [serializable$p], function () {
        return 0;
      }), _initializer4$M = applyDecoratedInitializer(_class2$1i.prototype, "_rotation", [serializable$p], function () {
        return 0;
      }), _initializer5$E = applyDecoratedInitializer(_class2$1i.prototype, "_techIndex", [serializable$p], function () {
        return 0;
      })), _class2$1i)) || _class$1k));

      var _vertex_attrs$1 = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGBA32F), new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true)];
      var _temp_v1 = new Vec3();
      var _temp_v2 = new Vec3();
      var LineModel = function (_scene$Model) {
        _inheritsLoose(LineModel, _scene$Model);
        function LineModel() {
          var _this;
          _this = _scene$Model.call(this) || this;
          _this._capacity = void 0;
          _this._vertSize = 0;
          _this._vBuffer = null;
          _this._vertAttrsFloatCount = 0;
          _this._vdataF32 = null;
          _this._vdataUint32 = null;
          _this._subMeshData = null;
          _this._vertCount = 0;
          _this._indexCount = 0;
          _this._material = null;
          _this._iaVertCount = 0;
          _this._iaIndexCount = 0;
          _this.type = ModelType.LINE;
          _this._capacity = 100;
          return _this;
        }
        var _proto = LineModel.prototype;
        _proto.setCapacity = function setCapacity(capacity) {
          this._capacity = capacity;
          this.createBuffer();
        };
        _proto.createBuffer = function createBuffer() {
          this._vertSize = 0;
          for (var _i = 0, _vertex_attrs2 = _vertex_attrs$1; _i < _vertex_attrs2.length; _i++) {
            var a = _vertex_attrs2[_i];
            a.offset = this._vertSize;
            this._vertSize += FormatInfos[a.format].size;
          }
          this._vertAttrsFloatCount = this._vertSize / 4;
          this._vBuffer = this.createSubMeshData();
          this._vdataF32 = new Float32Array(this._vBuffer);
          this._vdataUint32 = new Uint32Array(this._vBuffer);
        };
        _proto.updateMaterial = function updateMaterial(mat) {
          this._material = mat;
          _scene$Model.prototype.setSubModelMaterial.call(this, 0, mat);
        };
        _proto.createSubMeshData = function createSubMeshData() {
          if (this._subMeshData) {
            this.destroySubMeshData();
          }
          this._vertCount = 2;
          this._indexCount = 6;
          var vertexBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, this._vertSize * this._capacity * this._vertCount, this._vertSize));
          var vBuffer = new ArrayBuffer(this._vertSize * this._capacity * this._vertCount);
          vertexBuffer.update(vBuffer);
          var indices = new Uint16Array((this._capacity - 1) * this._indexCount);
          var dst = 0;
          for (var i = 0; i < this._capacity - 1; ++i) {
            var baseIdx = 2 * i;
            indices[dst++] = baseIdx;
            indices[dst++] = baseIdx + 1;
            indices[dst++] = baseIdx + 2;
            indices[dst++] = baseIdx + 3;
            indices[dst++] = baseIdx + 2;
            indices[dst++] = baseIdx + 1;
          }
          var indexBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, (this._capacity - 1) * this._indexCount * Uint16Array.BYTES_PER_ELEMENT, Uint16Array.BYTES_PER_ELEMENT));
          indexBuffer.update(indices);
          this._iaVertCount = this._capacity * this._vertCount;
          this._iaIndexCount = (this._capacity - 1) * this._indexCount;
          this._subMeshData = new RenderingSubMesh([vertexBuffer], _vertex_attrs$1, PrimitiveMode.TRIANGLE_LIST, indexBuffer);
          this.initSubModel(0, this._subMeshData, this._material);
          return vBuffer;
        };
        _proto.addLineVertexData = function addLineVertexData(positions, width, color) {
          if (positions.length > 1) {
            var offset = 0;
            Vec3.subtract(_temp_v1, positions[1], positions[0]);
            this._vdataF32[offset++] = positions[0].x;
            this._vdataF32[offset++] = positions[0].y;
            this._vdataF32[offset++] = positions[0].z;
            this._vdataF32[offset++] = 0;
            this._vdataF32[offset++] = width.evaluate(0, 1);
            this._vdataF32[offset++] = 0;
            this._vdataF32[offset++] = 0;
            this._vdataF32[offset++] = _temp_v1.x;
            this._vdataF32[offset++] = _temp_v1.y;
            this._vdataF32[offset++] = _temp_v1.z;
            this._vdataUint32[offset++] = color.evaluate(0, 1)._val;
            this._vdataF32[offset++] = positions[0].x;
            this._vdataF32[offset++] = positions[0].y;
            this._vdataF32[offset++] = positions[0].z;
            this._vdataF32[offset++] = 1;
            this._vdataF32[offset++] = width.evaluate(0, 1);
            this._vdataF32[offset++] = 0;
            this._vdataF32[offset++] = 1;
            this._vdataF32[offset++] = _temp_v1.x;
            this._vdataF32[offset++] = _temp_v1.y;
            this._vdataF32[offset++] = _temp_v1.z;
            this._vdataUint32[offset++] = color.evaluate(0, 1)._val;
            for (var i = 1; i < positions.length - 1; i++) {
              Vec3.subtract(_temp_v1, positions[i - 1], positions[i]);
              Vec3.subtract(_temp_v2, positions[i + 1], positions[i]);
              Vec3.subtract(_temp_v2, _temp_v2, _temp_v1);
              var seg = i / positions.length;
              this._vdataF32[offset++] = positions[i].x;
              this._vdataF32[offset++] = positions[i].y;
              this._vdataF32[offset++] = positions[i].z;
              this._vdataF32[offset++] = 0;
              this._vdataF32[offset++] = width.evaluate(seg, 1);
              this._vdataF32[offset++] = seg;
              this._vdataF32[offset++] = 0;
              this._vdataF32[offset++] = _temp_v2.x;
              this._vdataF32[offset++] = _temp_v2.y;
              this._vdataF32[offset++] = _temp_v2.z;
              this._vdataUint32[offset++] = color.evaluate(seg, 1)._val;
              this._vdataF32[offset++] = positions[i].x;
              this._vdataF32[offset++] = positions[i].y;
              this._vdataF32[offset++] = positions[i].z;
              this._vdataF32[offset++] = 1;
              this._vdataF32[offset++] = width.evaluate(seg, 1);
              this._vdataF32[offset++] = seg;
              this._vdataF32[offset++] = 1;
              this._vdataF32[offset++] = _temp_v2.x;
              this._vdataF32[offset++] = _temp_v2.y;
              this._vdataF32[offset++] = _temp_v2.z;
              this._vdataUint32[offset++] = color.evaluate(seg, 1)._val;
            }
            Vec3.subtract(_temp_v1, positions[positions.length - 1], positions[positions.length - 2]);
            this._vdataF32[offset++] = positions[positions.length - 1].x;
            this._vdataF32[offset++] = positions[positions.length - 1].y;
            this._vdataF32[offset++] = positions[positions.length - 1].z;
            this._vdataF32[offset++] = 0;
            this._vdataF32[offset++] = width.evaluate(1, 1);
            this._vdataF32[offset++] = 1;
            this._vdataF32[offset++] = 0;
            this._vdataF32[offset++] = _temp_v1.x;
            this._vdataF32[offset++] = _temp_v1.y;
            this._vdataF32[offset++] = _temp_v1.z;
            this._vdataUint32[offset++] = color.evaluate(1, 1)._val;
            this._vdataF32[offset++] = positions[positions.length - 1].x;
            this._vdataF32[offset++] = positions[positions.length - 1].y;
            this._vdataF32[offset++] = positions[positions.length - 1].z;
            this._vdataF32[offset++] = 1;
            this._vdataF32[offset++] = width.evaluate(1, 1);
            this._vdataF32[offset++] = 1;
            this._vdataF32[offset++] = 1;
            this._vdataF32[offset++] = _temp_v1.x;
            this._vdataF32[offset++] = _temp_v1.y;
            this._vdataF32[offset++] = _temp_v1.z;
            this._vdataUint32[offset++] = color.evaluate(1, 1)._val;
          }
          this.updateIA(Math.max(0, positions.length - 1));
        };
        _proto.updateIA = function updateIA(count) {
          var ia = this._subModels[0].inputAssembler;
          ia.vertexBuffers[0].update(this._vdataF32);
          ia.firstIndex = 0;
          ia.indexCount = this._indexCount * count;
          ia.vertexCount = this._iaVertCount;
        };
        _proto.destroySubMeshData = function destroySubMeshData() {
          if (this._subMeshData) {
            this._subMeshData.destroy();
            this._subMeshData = null;
          }
        };
        return LineModel;
      }(Model);

      var _dec$1m, _class$1j, _class2$1h;
      var setClassAttr = CCClass.Attr.setClassAttr;
      var SerializableTable$1 = [['mode', 'constant', 'multiplier'], ['mode', 'spline', 'multiplier'], ['mode', 'splineMin', 'splineMax', 'multiplier'], ['mode', 'constantMin', 'constantMax', 'multiplier']];
      var Mode$3 = Enum({
        Constant: 0,
        Curve: 1,
        TwoCurves: 2,
        TwoConstants: 3
      });
      var CurveRange = exports('f8', (_dec$1m = ccclass$M('cc.CurveRange'), _dec$1m(_class$1j = (_class2$1h = function () {
        function CurveRange() {
          this.constant = 0;
          this.constantMin = 0;
          this.constantMax = 0;
          this.multiplier = 1;
          this._mode = Mode$3.Constant;
        }
        var _proto = CurveRange.prototype;
        _proto.evaluate = function evaluate(time, rndRatio) {
          switch (this._mode) {
            default:
            case Mode$3.Constant:
              return this.constant;
            case Mode$3.Curve:
              return this.spline.evaluate(time) * this.multiplier;
            case Mode$3.TwoCurves:
              return lerp(this.splineMin.evaluate(time), this.splineMax.evaluate(time), rndRatio) * this.multiplier;
            case Mode$3.TwoConstants:
              return lerp(this.constantMin, this.constantMax, rndRatio);
          }
        };
        _proto.getMax = function getMax() {
          switch (this._mode) {
            default:
            case Mode$3.Constant:
              return this.constant;
            case Mode$3.Curve:
              return this.multiplier;
            case Mode$3.TwoConstants:
              return this.constantMax;
            case Mode$3.TwoCurves:
              return this.multiplier;
          }
        };
        _proto.isZero = function isZero() {
          switch (this._mode) {
            default:
            case Mode$3.Constant:
              return approx(this.constant, 0.0, EPSILON$3);
            case Mode$3.Curve:
              return approx(this.multiplier, 0.0, EPSILON$3);
            case Mode$3.TwoConstants:
              return approx(Math.max(Math.abs(this.constantMax), Math.abs(this.constantMin)), 0.0, EPSILON$3);
            case Mode$3.TwoCurves:
              return approx(this.multiplier, 0.0, EPSILON$3);
          }
        };
        _proto._onBeforeSerialize = function _onBeforeSerialize(props) {
          return SerializableTable$1[this._mode];
        };
        _createClass(CurveRange, [{
          key: "mode",
          get: function get() {
            return this._mode;
          },
          set: function set(mode) {
            this._mode = mode;
            switch (mode) {
              case Mode$3.Constant:
                break;
              case Mode$3.TwoConstants:
                break;
              case Mode$3.Curve:
                if (!this.spline) this.spline = constructLegacyCurveAndConvert();
                break;
              case Mode$3.TwoCurves:
                if (!this.splineMax) this.splineMax = constructLegacyCurveAndConvert();
                if (!this.splineMin) this.splineMin = constructLegacyCurveAndConvert();
                break;
            }
          }
        }, {
          key: "curve",
          get: function get() {
            var _this$_curve;
            return (_this$_curve = this._curve) !== null && _this$_curve !== void 0 ? _this$_curve : this._curve = new AnimationCurve(this.spline);
          },
          set: function set(value) {
            this._curve = value;
            this.spline = value._internalCurve;
          }
        }, {
          key: "curveMin",
          get: function get() {
            var _this$_curveMin;
            return (_this$_curveMin = this._curveMin) !== null && _this$_curveMin !== void 0 ? _this$_curveMin : this._curveMin = new AnimationCurve(this.splineMin);
          },
          set: function set(value) {
            this._curveMin = value;
            this.splineMin = value._internalCurve;
          }
        }, {
          key: "curveMax",
          get: function get() {
            var _this$_curveMax;
            return (_this$_curveMax = this._curveMax) !== null && _this$_curveMax !== void 0 ? _this$_curveMax : this._curveMax = new AnimationCurve(this.splineMax);
          },
          set: function set(value) {
            this._curveMax = value;
            this.splineMax = value._internalCurve;
          }
        }]);
        return CurveRange;
      }(), _class2$1h.Mode = Mode$3, _class2$1h)) || _class$1j));
      CCClass.fastDefine('cc.CurveRange', CurveRange, {
        multiplier: 1,
        constantMax: 0,
        constantMin: 0,
        constant: 0,
        mode: Mode$3.Constant,
        splineMax: Object.freeze(constructLegacyCurveAndConvert()),
        splineMin: Object.freeze(constructLegacyCurveAndConvert()),
        spline: Object.freeze(constructLegacyCurveAndConvert())
      });
      setClassAttr(CurveRange, 'multiplier', 'visible', true);
      setClassAttr(CurveRange, 'constantMax', 'visible', true);
      setClassAttr(CurveRange, 'constantMin', 'visible', true);
      setClassAttr(CurveRange, 'constant', 'visible', true);
      setPropertyEnumType(CurveRange, 'mode', Mode$3);
      setClassAttr(CurveRange, 'mode', 'visible', true);
      setClassAttr(CurveRange, 'splineMax', 'type', 'Object');
      setClassAttr(CurveRange, 'splineMax', 'ctor', RealCurve);
      setClassAttr(CurveRange, 'splineMax', 'visible', true);
      setClassAttr(CurveRange, 'splineMin', 'type', 'Object');
      setClassAttr(CurveRange, 'splineMin', 'ctor', RealCurve);
      setClassAttr(CurveRange, 'splineMin', 'visible', true);
      setClassAttr(CurveRange, 'spline', 'type', 'Object');
      setClassAttr(CurveRange, 'spline', 'ctor', RealCurve);
      setClassAttr(CurveRange, 'spline', 'visible', true);
      function evaluateCurve(cr, time, index) {
        switch (cr.mode) {
          case Mode$3.Constant:
            return cr.constant;
          case Mode$3.Curve:
            return cr.spline.evaluate(time) * cr.multiplier;
          case Mode$3.TwoCurves:
            return index === 0 ? cr.splineMin.evaluate(time) * cr.multiplier : cr.splineMax.evaluate(time) * cr.multiplier;
          case Mode$3.TwoConstants:
            return index === 0 ? cr.constantMin : cr.constantMax;
          default:
            return 0;
        }
      }
      function evaluateHeight$1(cr) {
        switch (cr.mode) {
          case Mode$3.TwoConstants:
            return 2;
          case Mode$3.TwoCurves:
            return 2;
          default:
            return 1;
        }
      }
      function packTexture(data, width, height) {
        var image = new ImageAsset({
          width: width,
          height: height,
          _data: data,
          _compressed: false,
          format: PixelFormat.RGBA32F
        });
        var texture = new Texture2D();
        texture.setFilters(Filter.NEAREST, Filter.NEAREST);
        texture.setMipFilter(Filter.NONE);
        texture.setWrapMode(WrapMode$1.CLAMP_TO_EDGE, WrapMode$1.CLAMP_TO_EDGE, WrapMode$1.CLAMP_TO_EDGE);
        texture.image = image;
        return texture;
      }
      function updateTexture(tex, data, width, height) {
        if (tex === null || width !== tex.width || height !== tex.height) {
          if (tex) {
            tex.destroy();
          }
          tex = packTexture(data, width, height);
        } else {
          tex.uploadData(data);
        }
        return tex;
      }
      function packCurveRangeZ(tex, data, samples, cr, discrete) {
        var height = evaluateHeight$1(cr);
        var len = samples * height * 4;
        if (data === null || data.length !== len) {
          data = new Float32Array(samples * height * 4);
        }
        var interval = 1.0 / (samples - 1);
        var offset = 0;
        for (var h = 0; h < height; h++) {
          for (var j = 0; j < samples; j++) {
            var value = evaluateCurve(cr, interval * j, h);
            data[offset + 2] = value;
            offset += 4;
          }
        }
        return {
          texture: updateTexture(tex, data, samples, height),
          texdata: data
        };
      }
      function packCurveRangeN(tex, data, samples, cr, discrete) {
        var height = evaluateHeight$1(cr);
        var len = samples * height * 4;
        if (data === null || data.length !== len) {
          data = new Float32Array(samples * height * 4);
        }
        var interval = 1.0 / (samples - 1);
        var sum = 0;
        var average = 0;
        var offset = 0;
        for (var h = 0; h < height; h++) {
          sum = 0;
          for (var j = 0; j < samples; j++) {
            var value = evaluateCurve(cr, interval * j, h);
            if (discrete) {
              average = value;
            } else {
              sum += value;
              average = sum / (j + 1);
            }
            data[offset] = average;
            data[offset + 1] = average;
            data[offset + 2] = average;
            offset += 4;
          }
        }
        return {
          texture: updateTexture(tex, data, samples, height),
          texdata: data
        };
      }
      function packCurveRangeXY(tex, data, samples, x, y, discrete) {
        var height = Math.max(evaluateHeight$1(x), evaluateHeight$1(y));
        var len = samples * height * 4;
        if (data === null || data.length !== len) {
          data = new Float32Array(samples * height * 4);
        }
        var curves = [x, y];
        var interval = 1.0 / (samples - 1);
        for (var h = 0; h < height; h++) {
          for (var i = 0; i < 2; i++) {
            var cr = curves[i];
            var sum = 0;
            var average = 0;
            for (var j = 0; j < samples; j++) {
              var value = evaluateCurve(cr, interval * j, h);
              if (discrete) {
                average = value;
              } else {
                sum += value;
                average = sum / (j + 1);
              }
              data[(h * samples + j) * 4 + i] = average;
            }
          }
        }
        return {
          texture: updateTexture(tex, data, samples, height),
          texdata: data
        };
      }
      function packCurveRangeXYZ(tex, data, samples, x, y, z, discrete) {
        var height = Math.max(evaluateHeight$1(x), evaluateHeight$1(y), evaluateHeight$1(z));
        var len = samples * height * 4;
        if (data === null || data.length !== len) {
          data = new Float32Array(samples * height * 4);
        }
        var curves = [x, y, z];
        var interval = 1.0 / (samples - 1);
        for (var h = 0; h < height; h++) {
          for (var i = 0; i < 3; i++) {
            var cr = curves[i];
            var sum = 0;
            var average = 0;
            for (var j = 0; j < samples; j++) {
              var value = evaluateCurve(cr, interval * j, h);
              if (discrete) {
                average = value;
              } else {
                sum += value;
                average = sum / (j + 1);
              }
              data[(h * samples + j) * 4 + i] = average;
            }
          }
        }
        return {
          texture: updateTexture(tex, data, samples, height),
          texdata: data
        };
      }
      function packCurveRangeXYZW(tex, data, samples, x, y, z, w, discrete) {
        var height = Math.max(evaluateHeight$1(x), evaluateHeight$1(y), evaluateHeight$1(z), evaluateHeight$1(w));
        var len = samples * height * 4;
        if (data === null || data.length !== len) {
          data = new Float32Array(samples * height * 4);
        }
        var curves = [x, y, z, w];
        var interval = 1.0 / (samples - 1);
        for (var h = 0; h < height; h++) {
          for (var i = 0; i < 4; i++) {
            var cr = curves[i];
            var sum = 0;
            var average = 0;
            for (var j = 0; j < samples; j++) {
              var value = evaluateCurve(cr, interval * j, h);
              if (discrete) {
                average = value;
              } else {
                sum += value;
                average = sum / (j + 1);
              }
              data[(h * samples + j) * 4 + i] = average;
            }
          }
        }
        return {
          texture: updateTexture(tex, data, samples, height),
          texdata: data
        };
      }

      var _dec$1l, _dec2$1f, _dec3$Z, _dec4$N, _dec5$J, _dec6$v, _class$1i, _class2$1g, _initializer$1e, _initializer2$17, _initializer3$T, _initializer4$L, _initializer5$D, _initializer6$x, _initializer7$q, _class3$r;
      var SerializableTable = EDITOR ;
      var Mode$2 = Enum({
        Color: 0,
        Gradient: 1,
        TwoColors: 2,
        TwoGradients: 3,
        RandomColor: 4
      });
      var tempColor = new Color$1();
      var tempColor2 = new Color$1();
      var GradientRange = exports('f9', (_dec$1l = ccclass$M('cc.GradientRange'), _dec2$1f = type$d(Mode$2), _dec3$Z = type$d(Gradient), _dec4$N = type$d(Gradient), _dec5$J = type$d(Gradient), _dec6$v = type$d(Mode$2), _dec$1l(_class$1i = (_class2$1g = (_class3$r = function () {
        function GradientRange() {
          this.color = _initializer$1e && _initializer$1e();
          this.colorMin = _initializer2$17 && _initializer2$17();
          this.colorMax = _initializer3$T && _initializer3$T();
          this.gradient = _initializer4$L && _initializer4$L();
          this.gradientMin = _initializer5$D && _initializer5$D();
          this.gradientMax = _initializer6$x && _initializer6$x();
          this._mode = _initializer7$q && _initializer7$q();
          this._color = Color$1.WHITE.clone();
        }
        var _proto = GradientRange.prototype;
        _proto.evaluate = function evaluate(time, rndRatio) {
          switch (this._mode) {
            case Mode$2.Color:
              return this.color;
            case Mode$2.TwoColors:
              Color$1.lerp(this._color, this.colorMin, this.colorMax, rndRatio);
              return this._color;
            case Mode$2.RandomColor:
              return this.gradient.getRandomColor(this._color);
            case Mode$2.Gradient:
              return this.gradient.evaluateFast(this._color, time);
            case Mode$2.TwoGradients:
              Color$1.lerp(this._color, this.gradientMin.evaluateFast(tempColor, time), this.gradientMax.evaluateFast(tempColor2, time), rndRatio);
              return this._color;
            default:
              return this.color;
          }
        };
        _proto._onBeforeSerialize = function _onBeforeSerialize(props) {
          return SerializableTable[this._mode];
        };
        _createClass(GradientRange, [{
          key: "mode",
          get: function get() {
            return this._mode;
          },
          set: function set(m) {
            this._mode = m;
          }
        }]);
        return GradientRange;
      }(), _class3$r.Mode = Mode$2, _class3$r), (_applyDecoratedDescriptor(_class2$1g.prototype, "mode", [_dec2$1f], Object.getOwnPropertyDescriptor(_class2$1g.prototype, "mode"), _class2$1g.prototype), _initializer$1e = applyDecoratedInitializer(_class2$1g.prototype, "color", [serializable$p], function () {
        return Color$1.WHITE.clone();
      }), _initializer2$17 = applyDecoratedInitializer(_class2$1g.prototype, "colorMin", [serializable$p], function () {
        return Color$1.WHITE.clone();
      }), _initializer3$T = applyDecoratedInitializer(_class2$1g.prototype, "colorMax", [serializable$p], function () {
        return Color$1.WHITE.clone();
      }), _initializer4$L = applyDecoratedInitializer(_class2$1g.prototype, "gradient", [_dec3$Z], function () {
        return new Gradient();
      }), _initializer5$D = applyDecoratedInitializer(_class2$1g.prototype, "gradientMin", [_dec4$N], function () {
        return new Gradient();
      }), _initializer6$x = applyDecoratedInitializer(_class2$1g.prototype, "gradientMax", [_dec5$J], function () {
        return new Gradient();
      }), _initializer7$q = applyDecoratedInitializer(_class2$1g.prototype, "_mode", [_dec6$v], function () {
        return Mode$2.Color;
      })), _class2$1g)) || _class$1i));
      function evaluateGradient(gr, time, index) {
        switch (gr.mode) {
          case Mode$2.Color:
            return gr.color;
          case Mode$2.TwoColors:
            return index === 0 ? gr.colorMin : gr.colorMax;
          case Mode$2.RandomColor:
            return gr.gradient.getRandomColor(tempColor);
          case Mode$2.Gradient:
            return gr.gradient.evaluateFast(tempColor, time);
          case Mode$2.TwoGradients:
            return index === 0 ? gr.gradientMin.evaluateFast(tempColor, time) : gr.gradientMax.evaluateFast(tempColor, time);
          default:
            return gr.color;
        }
      }
      function evaluateHeight(gr) {
        switch (gr.mode) {
          case Mode$2.TwoColors:
            return 2;
          case Mode$2.TwoGradients:
            return 2;
          default:
            return 1;
        }
      }
      function packGradientRange(tex, data, samples, gr) {
        var height = evaluateHeight(gr);
        var len = samples * height * 4;
        if (data === null || data.length !== len) {
          data = new Uint8Array(samples * height * 4);
        }
        var interval = 1.0 / (samples - 1);
        var offset = 0;
        for (var h = 0; h < height; h++) {
          for (var j = 0; j < samples; j++) {
            var color = evaluateGradient(gr, interval * j, h);
            data[offset] = color.r;
            data[offset + 1] = color.g;
            data[offset + 2] = color.b;
            data[offset + 3] = color.a;
            offset += 4;
          }
        }
        if (tex === null || samples !== tex.width || height !== tex.height) {
          if (tex) {
            tex.destroy();
          }
          tex = new Texture2D();
          tex.create(samples, height, PixelFormat.RGBA8888);
          tex.setFilters(Filter.LINEAR, Filter.LINEAR);
          tex.setWrapMode(WrapMode$1.CLAMP_TO_EDGE, WrapMode$1.CLAMP_TO_EDGE);
        }
        tex.uploadData(data);
        return {
          texture: tex,
          texdata: data
        };
      }

      var _dec$1k, _dec2$1e, _dec3$Y, _dec4$M, _dec5$I, _dec6$u, _dec7$o, _dec8$h, _dec9$e, _dec10$8, _class$1h, _class2$1f, _initializer$1d, _initializer2$16, _initializer3$S, _initializer4$K, _initializer5$C, _initializer6$w, _initializer7$p, _initializer8$n;
      var CC_USE_WORLD_SPACE$2 = 'CC_USE_WORLD_SPACE';
      var define = {
        CC_USE_WORLD_SPACE: false,
        CC_USE_WORLD_SCALE: true
      };
      var Line = exports('f5', (_dec$1k = ccclass$M('cc.Line'), _dec2$1e = type$d(Texture2D), _dec3$Y = type$d(Texture2D), _dec4$M = type$d(Material), _dec5$I = type$d([Vec3]), _dec6$u = type$d([Vec3]), _dec7$o = type$d(CurveRange), _dec8$h = type$d(GradientRange), _dec9$e = type$d(Vec2), _dec10$8 = type$d(Vec2), _dec$1k(_class$1h = (_class2$1f = function (_ModelRenderer) {
        _inheritsLoose(Line, _ModelRenderer);
        function Line() {
          var _this;
          _this = _ModelRenderer.call(this) || this;
          _this._texture = _initializer$1d && _initializer$1d();
          _this._material = _initializer2$16 && _initializer2$16();
          _this._worldSpace = _initializer3$S && _initializer3$S();
          _this._positions = _initializer4$K && _initializer4$K();
          _this._width = _initializer5$C && _initializer5$C();
          _this._color = _initializer6$w && _initializer6$w();
          _this._tile = _initializer7$p && _initializer7$p();
          _this._tile_offset = new Vec4();
          _this._offset = _initializer8$n && _initializer8$n();
          return _this;
        }
        var _proto = Line.prototype;
        _proto.onLoad = function onLoad() {
          var model = legacyCC.director.root.createModel(LineModel);
          if (this._models.length === 0) {
            this._models.push(model);
          } else {
            this._models[0] = model;
          }
          model.node = model.transform = this.node;
          if (this._material) {
            this.lineMaterial = this._material;
            this._material = null;
          }
          if (this.lineMaterial === null) {
            var mat = builtinResMgr.get('default-trail-material');
            this.material = mat;
          }
          var matIns = this.getMaterialInstance(0);
          if (matIns) {
            define[CC_USE_WORLD_SPACE$2] = this.worldSpace;
            matIns.recompileShaders(define);
            model.updateMaterial(matIns);
          }
          model.setCapacity(100);
        };
        _proto.onEnable = function onEnable() {
          _ModelRenderer.prototype.onEnable.call(this);
          if (this._models.length === 0 || !this._models[0]) {
            return;
          }
          this._attachToScene();
          this.texture = this._texture;
          this.tile = this._tile;
          this.offset = this._offset;
          var lineModel = this._models[0];
          lineModel.addLineVertexData(this._positions, this.width, this.color);
        };
        _proto.onDisable = function onDisable() {
          if (this._models.length > 0 && this._models[0]) {
            this._detachFromScene();
          }
        };
        _proto._attachToScene = function _attachToScene() {
          _ModelRenderer.prototype._attachToScene.call(this);
          if (this._models.length > 0 && this._models[0] && this.node && this.node.scene) {
            var lineModel = this._models[0];
            if (lineModel.scene) {
              this._detachFromScene();
            }
            this._getRenderScene().addModel(lineModel);
          }
        };
        _proto._detachFromScene = function _detachFromScene() {
          _ModelRenderer.prototype._detachFromScene.call(this);
          if (this._models.length > 0 && this._models[0]) {
            var lineModel = this._models[0];
            if (lineModel.scene) {
              lineModel.scene.removeModel(lineModel);
            }
          }
        };
        _proto._onMaterialModified = function _onMaterialModified(index, material) {
          _ModelRenderer.prototype._onMaterialModified.call(this, index, material);
          var matIns = this.getMaterialInstance(0);
          if (matIns) {
            define[CC_USE_WORLD_SPACE$2] = this.worldSpace;
            matIns.recompileShaders(define);
            if (this._models[0]) {
              var lineModel = this._models[0];
              lineModel.updateMaterial(matIns);
            }
          }
        };
        _createClass(Line, [{
          key: "texture",
          get: function get() {
            return this._texture;
          },
          set: function set(val) {
            this._texture = val;
            if (this.material) {
              this.material.setProperty('mainTexture', val);
            }
          }
        }, {
          key: "lineMaterial",
          get: function get() {
            return this.getSharedMaterial(0);
          },
          set: function set(val) {
            this.setSharedMaterial(val, 0);
          }
        }, {
          key: "sharedMaterials",
          get: function get() {
            return _ModelRenderer.prototype.sharedMaterials;
          },
          set: function set(val) {
            this.sharedMaterials = val;
          }
        }, {
          key: "worldSpace",
          get: function get() {
            return this._worldSpace;
          },
          set: function set(val) {
            this._worldSpace = val;
            var matIns = this.getMaterialInstance(0);
            if (matIns) {
              define[CC_USE_WORLD_SPACE$2] = this.worldSpace;
              matIns.recompileShaders(define);
              if (this._models[0]) {
                this._models[0].setSubModelMaterial(0, matIns);
              }
            }
          }
        }, {
          key: "positions",
          get: function get() {
            return this._positions;
          },
          set: function set(val) {
            this._positions = val;
            if (this._models[0]) {
              var lineModel = this._models[0];
              lineModel.addLineVertexData(this._positions, this.width, this.color);
            }
          }
        }, {
          key: "width",
          get: function get() {
            return this._width;
          },
          set: function set(val) {
            this._width = val;
            if (this._models[0]) {
              var lineModel = this._models[0];
              lineModel.addLineVertexData(this._positions, this._width, this._color);
            }
          }
        }, {
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(val) {
            this._color = val;
            if (this._models[0]) {
              var lineModel = this._models[0];
              lineModel.addLineVertexData(this._positions, this._width, this._color);
            }
          }
        }, {
          key: "tile",
          get: function get() {
            return this._tile;
          },
          set: function set(val) {
            this._tile.set(val);
            if (this.material) {
              this._tile_offset.x = this._tile.x;
              this._tile_offset.y = this._tile.y;
              this.material.setProperty('mainTiling_Offset', this._tile_offset);
            }
          }
        }, {
          key: "offset",
          get: function get() {
            return this._offset;
          },
          set: function set(val) {
            this._offset.set(val);
            if (this.material) {
              this._tile_offset.z = this._offset.x;
              this._tile_offset.w = this._offset.y;
              this.material.setProperty('mainTiling_Offset', this._tile_offset);
            }
          }
        }]);
        return Line;
      }(ModelRenderer), (_initializer$1d = applyDecoratedInitializer(_class2$1f.prototype, "_texture", [_dec2$1e], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$1f.prototype, "texture", [_dec3$Y], Object.getOwnPropertyDescriptor(_class2$1f.prototype, "texture"), _class2$1f.prototype), _initializer2$16 = applyDecoratedInitializer(_class2$1f.prototype, "_material", [serializable$p], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$1f.prototype, "lineMaterial", [_dec4$M], Object.getOwnPropertyDescriptor(_class2$1f.prototype, "lineMaterial"), _class2$1f.prototype), _applyDecoratedDescriptor(_class2$1f.prototype, "sharedMaterials", [override$1, serializable$p], Object.getOwnPropertyDescriptor(_class2$1f.prototype, "sharedMaterials"), _class2$1f.prototype), _initializer3$S = applyDecoratedInitializer(_class2$1f.prototype, "_worldSpace", [serializable$p], function () {
        return false;
      }), _initializer4$K = applyDecoratedInitializer(_class2$1f.prototype, "_positions", [_dec5$I], function () {
        return [];
      }), _applyDecoratedDescriptor(_class2$1f.prototype, "positions", [_dec6$u], Object.getOwnPropertyDescriptor(_class2$1f.prototype, "positions"), _class2$1f.prototype), _applyDecoratedDescriptor(_class2$1f.prototype, "width", [_dec7$o], Object.getOwnPropertyDescriptor(_class2$1f.prototype, "width"), _class2$1f.prototype), _initializer5$C = applyDecoratedInitializer(_class2$1f.prototype, "_width", [serializable$p], function () {
        return new CurveRange();
      }), _applyDecoratedDescriptor(_class2$1f.prototype, "color", [_dec8$h], Object.getOwnPropertyDescriptor(_class2$1f.prototype, "color"), _class2$1f.prototype), _initializer6$w = applyDecoratedInitializer(_class2$1f.prototype, "_color", [serializable$p], function () {
        return new GradientRange();
      }), _initializer7$p = applyDecoratedInitializer(_class2$1f.prototype, "_tile", [serializable$p], function () {
        return new Vec2(1, 1);
      }), _applyDecoratedDescriptor(_class2$1f.prototype, "tile", [_dec9$e], Object.getOwnPropertyDescriptor(_class2$1f.prototype, "tile"), _class2$1f.prototype), _initializer8$n = applyDecoratedInitializer(_class2$1f.prototype, "_offset", [serializable$p], function () {
        return new Vec2(0, 0);
      }), _applyDecoratedDescriptor(_class2$1f.prototype, "offset", [_dec10$8], Object.getOwnPropertyDescriptor(_class2$1f.prototype, "offset"), _class2$1f.prototype)), _class2$1f)) || _class$1h));

      var Particle$1 = function () {
        function Particle(particleSystem) {
          this.particleSystem = void 0;
          this.position = void 0;
          this.velocity = void 0;
          this.animatedVelocity = void 0;
          this.ultimateVelocity = void 0;
          this.angularVelocity = void 0;
          this.axisOfRotation = void 0;
          this.rotation = void 0;
          this.startEuler = void 0;
          this.startRotation = void 0;
          this.startRotated = void 0;
          this.deltaQuat = void 0;
          this.deltaMat = void 0;
          this.localMat = void 0;
          this.startSize = void 0;
          this.size = void 0;
          this.startColor = void 0;
          this.color = void 0;
          this.randomSeed = void 0;
          this.remainingLifetime = void 0;
          this.loopCount = void 0;
          this.lastLoop = void 0;
          this.trailDelay = void 0;
          this.startLifetime = void 0;
          this.emitAccumulator0 = void 0;
          this.emitAccumulator1 = void 0;
          this.frameIndex = void 0;
          this.startRow = void 0;
          this.particleSystem = particleSystem;
          this.position = new Vec3(0, 0, 0);
          this.velocity = new Vec3(0, 0, 0);
          this.animatedVelocity = new Vec3(0, 0, 0);
          this.ultimateVelocity = new Vec3(0, 0, 0);
          this.angularVelocity = new Vec3(0, 0, 0);
          this.axisOfRotation = new Vec3(0, 0, 0);
          this.rotation = new Vec3(0, 0, 0);
          this.startEuler = new Vec3(0, 0, 0);
          this.startRotation = new Quat();
          this.startRotated = false;
          this.deltaQuat = new Quat();
          this.deltaMat = new Mat4();
          this.localMat = new Mat4();
          this.startSize = new Vec3(0, 0, 0);
          this.size = new Vec3(0, 0, 0);
          this.startColor = Color$1.WHITE.clone();
          this.color = Color$1.WHITE.clone();
          this.randomSeed = 0;
          this.remainingLifetime = 0.0;
          this.loopCount = 0;
          this.lastLoop = 0;
          this.trailDelay = 0;
          this.startLifetime = 0.0;
          this.emitAccumulator0 = 0.0;
          this.emitAccumulator1 = 0.0;
          this.frameIndex = 0.0;
          this.startRow = 0;
        }
        var _proto = Particle.prototype;
        _proto.reset = function reset() {
          this.rotation.set(0, 0, 0);
          this.startEuler.set(0, 0, 0);
          this.startRotation.set(0, 0, 0, 1);
          this.startRotated = false;
          this.deltaQuat.set(0, 0, 0, 1);
          this.deltaMat.identity();
          this.localMat.identity();
        };
        return Particle;
      }();
      Particle$1.INDENTIFY_NEG_QUAT = 10;
      Particle$1.R2D = 180.0 / Math.PI;
      var PARTICLE_MODULE_NAME = {
        COLOR: 'colorModule',
        FORCE: 'forceModule',
        LIMIT: 'limitModule',
        ROTATION: 'rotationModule',
        SIZE: 'sizeModule',
        VELOCITY: 'velocityModule',
        TEXTURE: 'textureModule',
        NOISE: 'noiseModule'
      };
      var PARTICLE_MODULE_ORDER = ['sizeModule', 'colorModule', 'forceModule', 'velocityModule', 'limitModule', 'rotationModule', 'textureModule', 'noiseModule'];
      var PARTICLE_MODULE_PROPERTY = ['_colorOverLifetimeModule', '_shapeModule', '_sizeOvertimeModule', '_velocityOvertimeModule', '_forceOvertimeModule', '_limitVelocityOvertimeModule', '_rotationOvertimeModule', '_textureAnimationModule', '_noiseModule', '_trailModule'];
      var ParticleModuleBase = function () {
        function ParticleModuleBase() {
          this.target = null;
          this.needUpdate = false;
          this.needAnimate = true;
          this.name = void 0;
        }
        var _proto2 = ParticleModuleBase.prototype;
        _proto2.bindTarget = function bindTarget(target) {
          this.target = target;
        };
        _proto2.update = function update(space, trans) {};
        return ParticleModuleBase;
      }();

      var Space = Enum({
        World: 0,
        Local: 1,
        Custom: 2
      });
      var CullingMode = Enum({
        Pause: 0,
        PauseAndCatchup: 1,
        AlwaysSimulate: 2
      });
      var AlignmentSpace = Enum({
        World: 0,
        Local: 1,
        View: 2
      });
      var RenderMode = Enum({
        Billboard: 0,
        StrecthedBillboard: 1,
        HorizontalBillboard: 2,
        VerticalBillboard: 3,
        Mesh: 4
      });
      var ShapeType = Enum({
        Box: 0,
        Circle: 1,
        Cone: 2,
        Sphere: 3,
        Hemisphere: 4
      });
      var EmitLocation = Enum({
        Base: 0,
        Edge: 1,
        Shell: 2,
        Volume: 3
      });
      var ArcMode = Enum({
        Random: 0,
        Loop: 1,
        PingPong: 2
      });
      var TrailMode = Enum({
        Particles: 0
      });
      var TextureMode = Enum({
        Stretch: 0
      });
      var ModuleRandSeed = {
        LIMIT: 23541,
        SIZE: 39825,
        TEXTURE: 90794,
        COLOR: 91041,
        FORCE: 212165,
        ROTATION: 125292,
        VELOCITY_X: 197866,
        VELOCITY_Y: 156497,
        VELOCITY_Z: 984136
      };

      var particleEmitZAxis = new Vec3(0, 0, -1);
      function calculateTransform(systemSpace, moduleSpace, worldTransform, outQuat) {
        if (moduleSpace !== systemSpace) {
          if (systemSpace === Space.World) {
            Mat4.getRotation(outQuat, worldTransform);
          } else {
            Mat4.invert(worldTransform, worldTransform);
            Mat4.getRotation(outQuat, worldTransform);
          }
          return true;
        } else {
          Quat.set(outQuat, 0, 0, 0, 1);
          return false;
        }
      }
      function fixedAngleUnitVector2(out, theta) {
        Vec2.set(out, Math.cos(theta), Math.sin(theta));
      }
      function randomUnitVector(out) {
        var z = randomRange(-1, 1);
        var a = randomRange(0, 2 * Math.PI);
        var r = Math.sqrt(1 - z * z);
        var x = r * Math.cos(a);
        var y = r * Math.sin(a);
        Vec3.set(out, x, y, z);
      }
      function randomPointBetweenSphere(out, minRadius, maxRadius) {
        randomUnitVector(out);
        Vec3.multiplyScalar(out, out, minRadius + (maxRadius - minRadius) * random());
      }
      function randomPointBetweenCircleAtFixedAngle(out, minRadius, maxRadius, theta) {
        fixedAngleUnitVector2(out, theta);
        out.z = 0;
        Vec3.multiplyScalar(out, out, minRadius + (maxRadius - minRadius) * random());
      }
      function randomPointInCube(out, extents) {
        Vec3.set(out, randomRange(-extents.x, extents.x), randomRange(-extents.y, extents.y), randomRange(-extents.z, extents.z));
      }
      function randomSortArray(arr) {
        for (var i = 0; i < arr.length; i++) {
          var transpose = i + randomRangeInt(0, arr.length - i);
          var val = arr[transpose];
          arr[transpose] = arr[i];
          arr[i] = val;
        }
      }
      function randomSign() {
        var sgn = randomRange(-1, 1);
        if (sgn === 0) {
          sgn++;
        }
        return sign$1(sgn);
      }
      function isCurveTwoValues(curve) {
        var Mode = CurveRange.Mode;
        switch (curve.mode) {
          case Mode.TwoCurves:
          case Mode.TwoConstants:
            return true;
          default:
            return false;
        }
      }
      function isGradientTwoValues(color) {
        var Mode = GradientRange.Mode;
        switch (color.mode) {
          case Mode.TwoGradients:
          case Mode.TwoColors:
            return true;
          default:
            return false;
        }
      }

      var _dec$1j, _dec2$1d, _class$1g, _class2$1e, _initializer$1c, _initializer2$15;
      var COLOR_OVERTIME_RAND_OFFSET = ModuleRandSeed.COLOR;
      var ColorOvertimeModule = (_dec$1j = ccclass$M('cc.ColorOvertimeModule'), _dec2$1d = type$d(GradientRange), _dec$1j(_class$1g = (_class2$1e = function (_ParticleModuleBase) {
        _inheritsLoose(ColorOvertimeModule, _ParticleModuleBase);
        function ColorOvertimeModule() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ParticleModuleBase.call.apply(_ParticleModuleBase, [this].concat(args)) || this;
          _this._enable = _initializer$1c && _initializer$1c();
          _this.color = _initializer2$15 && _initializer2$15();
          _this.name = PARTICLE_MODULE_NAME.COLOR;
          return _this;
        }
        var _proto = ColorOvertimeModule.prototype;
        _proto.animate = function animate(particle) {
          particle.color.set(particle.startColor);
          var rand = isGradientTwoValues(this.color) ? pseudoRandom(particle.randomSeed + COLOR_OVERTIME_RAND_OFFSET) : 0;
          particle.color.multiply(this.color.evaluate(1.0 - particle.remainingLifetime / particle.startLifetime, rand));
        };
        _createClass(ColorOvertimeModule, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(val) {
            if (this._enable === val) return;
            this._enable = val;
            if (!this.target) return;
            this.target.enableModule(this.name, val, this);
          }
        }]);
        return ColorOvertimeModule;
      }(ParticleModuleBase), (_initializer$1c = applyDecoratedInitializer(_class2$1e.prototype, "_enable", [serializable$p], function () {
        return false;
      }), _initializer2$15 = applyDecoratedInitializer(_class2$1e.prototype, "color", [_dec2$1d, serializable$p], function () {
        return new GradientRange();
      })), _class2$1e)) || _class$1g);

      var _dec$1i, _dec2$1c, _dec3$X, _dec4$L, _dec5$H, _class$1f, _class2$1d, _initializer$1b, _initializer2$14, _initializer3$R, _initializer4$J, _initializer5$B;
      var FORCE_OVERTIME_RAND_OFFSET = ModuleRandSeed.FORCE;
      var _temp_v3$2 = new Vec3();
      var ForceOvertimeModule = (_dec$1i = ccclass$M('cc.ForceOvertimeModule'), _dec2$1c = type$d(CurveRange), _dec3$X = type$d(CurveRange), _dec4$L = type$d(CurveRange), _dec5$H = type$d(Space), _dec$1i(_class$1f = (_class2$1d = function (_ParticleModuleBase) {
        _inheritsLoose(ForceOvertimeModule, _ParticleModuleBase);
        function ForceOvertimeModule() {
          var _this;
          _this = _ParticleModuleBase.call(this) || this;
          _this._enable = _initializer$1b && _initializer$1b();
          _this.x = _initializer2$14 && _initializer2$14();
          _this.y = _initializer3$R && _initializer3$R();
          _this.z = _initializer4$J && _initializer4$J();
          _this.space = _initializer5$B && _initializer5$B();
          _this.randomized = false;
          _this.rotation = void 0;
          _this.needTransform = void 0;
          _this.name = PARTICLE_MODULE_NAME.FORCE;
          _this.rotation = new Quat();
          _this.needTransform = false;
          _this.needUpdate = true;
          return _this;
        }
        var _proto = ForceOvertimeModule.prototype;
        _proto.update = function update(space, worldTransform) {
          this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation);
        };
        _proto.animate = function animate(p, dt) {
          var normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
          var randX = isCurveTwoValues(this.x) ? pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET) : 0;
          var randY = isCurveTwoValues(this.y) ? pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET) : 0;
          var randZ = isCurveTwoValues(this.z) ? pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET) : 0;
          var force = Vec3.set(_temp_v3$2, this.x.evaluate(normalizedTime, randX), this.y.evaluate(normalizedTime, randY), this.z.evaluate(normalizedTime, randZ));
          if (this.needTransform) {
            Vec3.transformQuat(force, force, this.rotation);
          }
          Vec3.scaleAndAdd(p.velocity, p.velocity, force, dt);
          Vec3.copy(p.ultimateVelocity, p.velocity);
        };
        _createClass(ForceOvertimeModule, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(val) {
            if (this._enable === val) return;
            this._enable = val;
            if (!this.target) return;
            this.target.enableModule(this.name, val, this);
          }
        }]);
        return ForceOvertimeModule;
      }(ParticleModuleBase), (_initializer$1b = applyDecoratedInitializer(_class2$1d.prototype, "_enable", [serializable$p], function () {
        return false;
      }), _initializer2$14 = applyDecoratedInitializer(_class2$1d.prototype, "x", [_dec2$1c, serializable$p], function () {
        return new CurveRange();
      }), _initializer3$R = applyDecoratedInitializer(_class2$1d.prototype, "y", [_dec3$X, serializable$p], function () {
        return new CurveRange();
      }), _initializer4$J = applyDecoratedInitializer(_class2$1d.prototype, "z", [_dec4$L, serializable$p], function () {
        return new CurveRange();
      }), _initializer5$B = applyDecoratedInitializer(_class2$1d.prototype, "space", [_dec5$H, serializable$p], function () {
        return Space.Local;
      })), _class2$1d)) || _class$1f);

      var _dec$1h, _dec2$1b, _dec3$W, _dec4$K, _dec5$G, _dec6$t, _class$1e, _class2$1c, _initializer$1a, _initializer2$13, _initializer3$Q, _initializer4$I, _initializer5$A, _initializer6$v, _initializer7$o, _initializer8$m;
      var LIMIT_VELOCITY_RAND_OFFSET = ModuleRandSeed.LIMIT;
      var _temp_v3$1 = new Vec3();
      var _temp_v3_1 = new Vec3();
      var LimitVelocityOvertimeModule = (_dec$1h = ccclass$M('cc.LimitVelocityOvertimeModule'), _dec2$1b = type$d(CurveRange), _dec3$W = type$d(CurveRange), _dec4$K = type$d(CurveRange), _dec5$G = type$d(CurveRange), _dec6$t = type$d(Space), _dec$1h(_class$1e = (_class2$1c = function (_ParticleModuleBase) {
        _inheritsLoose(LimitVelocityOvertimeModule, _ParticleModuleBase);
        function LimitVelocityOvertimeModule() {
          var _this;
          _this = _ParticleModuleBase.call(this) || this;
          _this._enable = _initializer$1a && _initializer$1a();
          _this.limitX = _initializer2$13 && _initializer2$13();
          _this.limitY = _initializer3$Q && _initializer3$Q();
          _this.limitZ = _initializer4$I && _initializer4$I();
          _this.limit = _initializer5$A && _initializer5$A();
          _this.dampen = _initializer6$v && _initializer6$v();
          _this.separateAxes = _initializer7$o && _initializer7$o();
          _this.space = _initializer8$m && _initializer8$m();
          _this.drag = null;
          _this.multiplyDragByParticleSize = false;
          _this.multiplyDragByParticleVelocity = false;
          _this.name = PARTICLE_MODULE_NAME.LIMIT;
          _this.rotation = void 0;
          _this.needTransform = void 0;
          _this.rotation = new Quat();
          _this.needTransform = false;
          _this.needUpdate = true;
          return _this;
        }
        var _proto = LimitVelocityOvertimeModule.prototype;
        _proto.update = function update(space, worldTransform) {
          this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation);
        };
        _proto.animate = function animate(p, dt) {
          var normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
          var dampedVel = _temp_v3$1;
          if (this.separateAxes) {
            var randX = isCurveTwoValues(this.limitX) ? pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET) : 0;
            var randY = isCurveTwoValues(this.limitY) ? pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET) : 0;
            var randZ = isCurveTwoValues(this.limitZ) ? pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET) : 0;
            Vec3.set(_temp_v3_1, this.limitX.evaluate(normalizedTime, randX), this.limitY.evaluate(normalizedTime, randY), this.limitZ.evaluate(normalizedTime, randZ));
            if (this.needTransform) {
              Vec3.transformQuat(_temp_v3_1, _temp_v3_1, this.rotation);
            }
            Vec3.set(dampedVel, dampenBeyondLimit(p.ultimateVelocity.x, _temp_v3_1.x, this.dampen), dampenBeyondLimit(p.ultimateVelocity.y, _temp_v3_1.y, this.dampen), dampenBeyondLimit(p.ultimateVelocity.z, _temp_v3_1.z, this.dampen));
          } else {
            Vec3.normalize(dampedVel, p.ultimateVelocity);
            var rand = isCurveTwoValues(this.limit) ? pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET) : 0;
            Vec3.multiplyScalar(dampedVel, dampedVel, dampenBeyondLimit(p.ultimateVelocity.length(), this.limit.evaluate(normalizedTime, rand), this.dampen));
          }
          Vec3.copy(p.ultimateVelocity, dampedVel);
          Vec3.copy(p.velocity, p.ultimateVelocity);
        };
        _createClass(LimitVelocityOvertimeModule, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(val) {
            if (this._enable === val) return;
            this._enable = val;
            if (!this.target) return;
            this.target.enableModule(this.name, val, this);
          }
        }]);
        return LimitVelocityOvertimeModule;
      }(ParticleModuleBase), (_initializer$1a = applyDecoratedInitializer(_class2$1c.prototype, "_enable", [serializable$p], function () {
        return false;
      }), _initializer2$13 = applyDecoratedInitializer(_class2$1c.prototype, "limitX", [_dec2$1b, serializable$p], function () {
        return new CurveRange();
      }), _initializer3$Q = applyDecoratedInitializer(_class2$1c.prototype, "limitY", [_dec3$W, serializable$p], function () {
        return new CurveRange();
      }), _initializer4$I = applyDecoratedInitializer(_class2$1c.prototype, "limitZ", [_dec4$K, serializable$p], function () {
        return new CurveRange();
      }), _initializer5$A = applyDecoratedInitializer(_class2$1c.prototype, "limit", [_dec5$G, serializable$p], function () {
        return new CurveRange();
      }), _initializer6$v = applyDecoratedInitializer(_class2$1c.prototype, "dampen", [serializable$p], function () {
        return 3;
      }), _initializer7$o = applyDecoratedInitializer(_class2$1c.prototype, "separateAxes", [serializable$p], function () {
        return false;
      }), _initializer8$m = applyDecoratedInitializer(_class2$1c.prototype, "space", [_dec6$t, serializable$p], function () {
        return Space.Local;
      })), _class2$1c)) || _class$1e);
      function dampenBeyondLimit(vel, limit, dampen) {
        var sgn = Math.sign(vel);
        var abs = Math.abs(vel);
        if (abs > limit) {
          var absToGive = abs - abs * dampen;
          if (absToGive > limit) {
            abs = absToGive;
          } else {
            abs = limit;
          }
        }
        return abs * sgn;
      }

      var _dec$1g, _dec2$1a, _dec3$V, _dec4$J, _class$1d, _class2$1b, _initializer$19, _initializer2$12, _initializer3$P, _initializer4$H, _initializer5$z;
      var ROTATION_OVERTIME_RAND_OFFSET = ModuleRandSeed.ROTATION;
      var RotationOvertimeModule = (_dec$1g = ccclass$M('cc.RotationOvertimeModule'), _dec2$1a = type$d(CurveRange), _dec3$V = type$d(CurveRange), _dec4$J = type$d(CurveRange), _dec$1g(_class$1d = (_class2$1b = function (_ParticleModuleBase) {
        _inheritsLoose(RotationOvertimeModule, _ParticleModuleBase);
        function RotationOvertimeModule() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ParticleModuleBase.call.apply(_ParticleModuleBase, [this].concat(args)) || this;
          _this._enable = _initializer$19 && _initializer$19();
          _this._separateAxes = _initializer2$12 && _initializer2$12();
          _this.x = _initializer3$P && _initializer3$P();
          _this.y = _initializer4$H && _initializer4$H();
          _this.z = _initializer5$z && _initializer5$z();
          _this.name = PARTICLE_MODULE_NAME.ROTATION;
          _this._startMat = new Mat4();
          _this._matRot = new Mat4();
          _this._quatRot = new Quat();
          _this._otherEuler = new Vec3();
          return _this;
        }
        var _proto = RotationOvertimeModule.prototype;
        _proto._processRotation = function _processRotation(p, r2d) {
          var renderMode = p.particleSystem.processor.getInfo().renderMode;
          if (renderMode !== RenderMode.Mesh) {
            if (renderMode === RenderMode.StrecthedBillboard) {
              this._quatRot.set(0, 0, 0, 1);
            }
          }
          Quat.normalize(this._quatRot, this._quatRot);
          if (this._quatRot.w < 0.0) {
            this._quatRot.x += Particle$1.INDENTIFY_NEG_QUAT;
          }
        };
        _proto.animate = function animate(p, dt) {
          var normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
          var randZ = isCurveTwoValues(this.z) ? pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET) : 0;
          var renderMode = p.particleSystem.processor.getInfo().renderMode;
          if (!this._separateAxes || renderMode === RenderMode.VerticalBillboard || renderMode === RenderMode.HorizontalBillboard) {
            Quat.fromEuler(p.deltaQuat, 0, 0, this.z.evaluate(normalizedTime, randZ) * dt * Particle$1.R2D);
          } else {
            var randX = isCurveTwoValues(this.x) ? pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET) : 0;
            var randY = isCurveTwoValues(this.y) ? pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET) : 0;
            Quat.fromEuler(p.deltaQuat, this.x.evaluate(normalizedTime, randX) * dt * Particle$1.R2D, this.y.evaluate(normalizedTime, randY) * dt * Particle$1.R2D, this.z.evaluate(normalizedTime, randZ) * dt * Particle$1.R2D);
          }
          p.deltaMat = Mat4.fromQuat(p.deltaMat, p.deltaQuat);
          p.localMat = p.localMat.multiply(p.deltaMat);
          if (!p.startRotated) {
            if (renderMode !== RenderMode.Mesh) {
              if (renderMode === RenderMode.StrecthedBillboard) {
                p.startEuler.set(0, 0, 0);
              } else if (renderMode !== RenderMode.Billboard) {
                p.startEuler.set(0, 0, p.startEuler.z);
              }
            }
            Quat.fromEuler(p.startRotation, p.startEuler.x * Particle$1.R2D, p.startEuler.y * Particle$1.R2D, p.startEuler.z * Particle$1.R2D);
            p.startRotated = true;
          }
          this._startMat = Mat4.fromQuat(this._startMat, p.startRotation);
          this._matRot = this._startMat.multiply(p.localMat);
          Mat4.getRotation(this._quatRot, this._matRot);
          this._processRotation(p, Particle$1.R2D);
          p.rotation.set(this._quatRot.x, this._quatRot.y, this._quatRot.z);
        };
        _createClass(RotationOvertimeModule, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(val) {
            if (this._enable === val) return;
            this._enable = val;
            if (!this.target) return;
            this.target.enableModule(this.name, val, this);
          }
        }, {
          key: "separateAxes",
          get: function get() {
            return this._separateAxes;
          },
          set: function set(val) {
            this._separateAxes = val;
          }
        }]);
        return RotationOvertimeModule;
      }(ParticleModuleBase), (_initializer$19 = applyDecoratedInitializer(_class2$1b.prototype, "_enable", [serializable$p], function () {
        return false;
      }), _initializer2$12 = applyDecoratedInitializer(_class2$1b.prototype, "_separateAxes", [serializable$p], function () {
        return false;
      }), _initializer3$P = applyDecoratedInitializer(_class2$1b.prototype, "x", [_dec2$1a, serializable$p], function () {
        return new CurveRange();
      }), _initializer4$H = applyDecoratedInitializer(_class2$1b.prototype, "y", [_dec3$V, serializable$p], function () {
        return new CurveRange();
      }), _initializer5$z = applyDecoratedInitializer(_class2$1b.prototype, "z", [_dec4$J, serializable$p], function () {
        return new CurveRange();
      })), _class2$1b)) || _class$1d);

      var _dec$1f, _dec2$19, _dec3$U, _dec4$I, _dec5$F, _class$1c, _class2$1a, _initializer$18, _initializer2$11, _initializer3$O, _initializer4$G, _initializer5$y, _initializer6$u;
      var SIZE_OVERTIME_RAND_OFFSET = ModuleRandSeed.SIZE;
      var SizeOvertimeModule = (_dec$1f = ccclass$M('cc.SizeOvertimeModule'), _dec2$19 = type$d(CurveRange), _dec3$U = type$d(CurveRange), _dec4$I = type$d(CurveRange), _dec5$F = type$d(CurveRange), _dec$1f(_class$1c = (_class2$1a = function (_ParticleModuleBase) {
        _inheritsLoose(SizeOvertimeModule, _ParticleModuleBase);
        function SizeOvertimeModule() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ParticleModuleBase.call.apply(_ParticleModuleBase, [this].concat(args)) || this;
          _this._enable = _initializer$18 && _initializer$18();
          _this.separateAxes = _initializer2$11 && _initializer2$11();
          _this.size = _initializer3$O && _initializer3$O();
          _this.x = _initializer4$G && _initializer4$G();
          _this.y = _initializer5$y && _initializer5$y();
          _this.z = _initializer6$u && _initializer6$u();
          _this.name = PARTICLE_MODULE_NAME.SIZE;
          return _this;
        }
        var _proto = SizeOvertimeModule.prototype;
        _proto.animate = function animate(particle, dt) {
          if (!this.separateAxes) {
            var rand = isCurveTwoValues(this.size) ? pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET) : 0;
            Vec3.multiplyScalar(particle.size, particle.startSize, this.size.evaluate(1 - particle.remainingLifetime / particle.startLifetime, rand));
          } else {
            var currLifetime = 1 - particle.remainingLifetime / particle.startLifetime;
            var randX = isCurveTwoValues(this.x) ? pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET) : 0;
            var randY = isCurveTwoValues(this.y) ? pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET) : 0;
            var randZ = isCurveTwoValues(this.z) ? pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET) : 0;
            particle.size.x = particle.startSize.x * this.x.evaluate(currLifetime, randX);
            particle.size.y = particle.startSize.y * this.y.evaluate(currLifetime, randY);
            particle.size.z = particle.startSize.z * this.z.evaluate(currLifetime, randZ);
          }
        };
        _createClass(SizeOvertimeModule, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(val) {
            if (this._enable === val) return;
            this._enable = val;
            if (!this.target) return;
            this.target.enableModule(this.name, val, this);
          }
        }]);
        return SizeOvertimeModule;
      }(ParticleModuleBase), (_initializer$18 = applyDecoratedInitializer(_class2$1a.prototype, "_enable", [serializable$p], function () {
        return false;
      }), _initializer2$11 = applyDecoratedInitializer(_class2$1a.prototype, "separateAxes", [serializable$p], function () {
        return false;
      }), _initializer3$O = applyDecoratedInitializer(_class2$1a.prototype, "size", [_dec2$19, serializable$p], function () {
        return new CurveRange();
      }), _initializer4$G = applyDecoratedInitializer(_class2$1a.prototype, "x", [_dec3$U, serializable$p], function () {
        return new CurveRange();
      }), _initializer5$y = applyDecoratedInitializer(_class2$1a.prototype, "y", [_dec4$I, serializable$p], function () {
        return new CurveRange();
      }), _initializer6$u = applyDecoratedInitializer(_class2$1a.prototype, "z", [_dec5$F, serializable$p], function () {
        return new CurveRange();
      })), _class2$1a)) || _class$1c);

      var _dec$1e, _dec2$18, _dec3$T, _dec4$H, _dec5$E, _dec6$s, _dec7$n, _dec8$g, _class$1b, _class2$19, _initializer$17, _initializer2$10, _initializer3$N, _initializer4$F, _initializer5$x, _initializer6$t, _initializer7$n, _initializer8$l, _initializer9$j, _initializer10$h, _initializer11$h, _initializer12$f, _initializer13$c;
      var TEXTURE_ANIMATION_RAND_OFFSET = ModuleRandSeed.TEXTURE;
      var Mode$1 = Enum({
        Grid: 0
      });
      var Animation = Enum({
        WholeSheet: 0,
        SingleRow: 1
      });
      var TextureAnimationModule = (_dec$1e = ccclass$M('cc.TextureAnimationModule'), _dec2$18 = formerlySerializedAs$4('numTilesX'), _dec3$T = formerlySerializedAs$4('numTilesY'), _dec4$H = type$d(Mode$1), _dec5$E = type$d(Mode$1), _dec6$s = type$d(Animation), _dec7$n = type$d(CurveRange), _dec8$g = type$d(CurveRange), _dec$1e(_class$1b = (_class2$19 = function (_ParticleModuleBase) {
        _inheritsLoose(TextureAnimationModule, _ParticleModuleBase);
        function TextureAnimationModule() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ParticleModuleBase.call.apply(_ParticleModuleBase, [this].concat(args)) || this;
          _this._enable = _initializer$17 && _initializer$17();
          _this._numTilesX = _initializer2$10 && _initializer2$10();
          _this._numTilesY = _initializer3$N && _initializer3$N();
          _this._mode = _initializer4$F && _initializer4$F();
          _this.animation = _initializer5$x && _initializer5$x();
          _this.frameOverTime = _initializer6$t && _initializer6$t();
          _this.startFrame = _initializer7$n && _initializer7$n();
          _this.cycleCount = _initializer8$l && _initializer8$l();
          _this._flipU = _initializer9$j && _initializer9$j();
          _this._flipV = _initializer10$h && _initializer10$h();
          _this._uvChannelMask = _initializer11$h && _initializer11$h();
          _this.randomRow = _initializer12$f && _initializer12$f();
          _this.rowIndex = _initializer13$c && _initializer13$c();
          _this.name = PARTICLE_MODULE_NAME.TEXTURE;
          return _this;
        }
        var _proto = TextureAnimationModule.prototype;
        _proto.init = function init(p) {
          p.startRow = Math.floor(random() * this.numTilesY);
        };
        _proto.animate = function animate(p, dt) {
          var normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
          var randStart = isCurveTwoValues(this.startFrame) ? pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET) : 0;
          var randFrame = isCurveTwoValues(this.frameOverTime) ? pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET) : 0;
          var startFrame = this.startFrame.evaluate(normalizedTime, randStart) / (this.numTilesX * this.numTilesY);
          if (this.animation === Animation.WholeSheet) {
            p.frameIndex = repeat$2(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, randFrame) + startFrame), 1);
          } else if (this.animation === Animation.SingleRow) {
            var rowLength = 1 / this.numTilesY;
            if (this.randomRow) {
              var f = repeat$2(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, randFrame) + startFrame), 1);
              var from = p.startRow * rowLength;
              var to = from + rowLength;
              p.frameIndex = lerp(from, to, f);
            } else {
              var _from = this.rowIndex * rowLength;
              var _to = _from + rowLength;
              p.frameIndex = lerp(_from, _to, repeat$2(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, randFrame) + startFrame), 1));
            }
          }
        };
        _createClass(TextureAnimationModule, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(val) {
            if (this._enable === val) return;
            this._enable = val;
            if (!this.target) return;
            this.target.updateMaterialParams();
            this.target.enableModule(this.name, val, this);
          }
        }, {
          key: "mode",
          get: function get() {
            return this._mode;
          },
          set: function set(val) {
            if (val !== Mode$1.Grid) {
              error('particle texture animation\'s sprites is not supported!');
            }
          }
        }, {
          key: "numTilesX",
          get: function get() {
            return this._numTilesX;
          },
          set: function set(val) {
            if (this._numTilesX !== val) {
              this._numTilesX = val;
              this.target.updateMaterialParams();
            }
          }
        }, {
          key: "numTilesY",
          get: function get() {
            return this._numTilesY;
          },
          set: function set(val) {
            if (this._numTilesY !== val) {
              this._numTilesY = val;
              this.target.updateMaterialParams();
            }
          }
        }, {
          key: "flipU",
          get: function get() {
            return this._flipU;
          },
          set: function set(val) {
            error('particle texture animation\'s flipU is not supported!');
          }
        }, {
          key: "flipV",
          get: function get() {
            return this._flipV;
          },
          set: function set(val) {
            error('particle texture animation\'s flipV is not supported!');
          }
        }, {
          key: "uvChannelMask",
          get: function get() {
            return this._uvChannelMask;
          },
          set: function set(val) {
            error('particle texture animation\'s uvChannelMask is not supported!');
          }
        }]);
        return TextureAnimationModule;
      }(ParticleModuleBase), (_initializer$17 = applyDecoratedInitializer(_class2$19.prototype, "_enable", [serializable$p], function () {
        return false;
      }), _initializer2$10 = applyDecoratedInitializer(_class2$19.prototype, "_numTilesX", [_dec2$18], function () {
        return 0;
      }), _initializer3$N = applyDecoratedInitializer(_class2$19.prototype, "_numTilesY", [_dec3$T], function () {
        return 0;
      }), _initializer4$F = applyDecoratedInitializer(_class2$19.prototype, "_mode", [_dec4$H], function () {
        return Mode$1.Grid;
      }), _applyDecoratedDescriptor(_class2$19.prototype, "mode", [_dec5$E], Object.getOwnPropertyDescriptor(_class2$19.prototype, "mode"), _class2$19.prototype), _initializer5$x = applyDecoratedInitializer(_class2$19.prototype, "animation", [_dec6$s, serializable$p], function () {
        return Animation.WholeSheet;
      }), _initializer6$t = applyDecoratedInitializer(_class2$19.prototype, "frameOverTime", [_dec7$n, serializable$p], function () {
        return new CurveRange();
      }), _initializer7$n = applyDecoratedInitializer(_class2$19.prototype, "startFrame", [_dec8$g, serializable$p], function () {
        return new CurveRange();
      }), _initializer8$l = applyDecoratedInitializer(_class2$19.prototype, "cycleCount", [serializable$p], function () {
        return 0;
      }), _initializer9$j = applyDecoratedInitializer(_class2$19.prototype, "_flipU", [serializable$p], function () {
        return 0;
      }), _initializer10$h = applyDecoratedInitializer(_class2$19.prototype, "_flipV", [serializable$p], function () {
        return 0;
      }), _initializer11$h = applyDecoratedInitializer(_class2$19.prototype, "_uvChannelMask", [serializable$p], function () {
        return -1;
      }), _initializer12$f = applyDecoratedInitializer(_class2$19.prototype, "randomRow", [serializable$p], function () {
        return false;
      }), _initializer13$c = applyDecoratedInitializer(_class2$19.prototype, "rowIndex", [serializable$p], function () {
        return 0;
      })), _class2$19)) || _class$1b);

      var _dec$1d, _dec2$17, _dec3$S, _dec4$G, _dec5$D, _dec6$r, _class$1a, _class2$18, _initializer$16, _initializer2$$, _initializer3$M, _initializer4$E, _initializer5$w, _initializer6$s;
      var VELOCITY_X_OVERTIME_RAND_OFFSET = ModuleRandSeed.VELOCITY_X;
      var VELOCITY_Y_OVERTIME_RAND_OFFSET = ModuleRandSeed.VELOCITY_Y;
      var VELOCITY_Z_OVERTIME_RAND_OFFSET = ModuleRandSeed.VELOCITY_Z;
      var _temp_v3 = new Vec3();
      var VelocityOvertimeModule = (_dec$1d = ccclass$M('cc.VelocityOvertimeModule'), _dec2$17 = type$d(CurveRange), _dec3$S = type$d(CurveRange), _dec4$G = type$d(CurveRange), _dec5$D = type$d(CurveRange), _dec6$r = type$d(Space), _dec$1d(_class$1a = (_class2$18 = function (_ParticleModuleBase) {
        _inheritsLoose(VelocityOvertimeModule, _ParticleModuleBase);
        function VelocityOvertimeModule() {
          var _this;
          _this = _ParticleModuleBase.call(this) || this;
          _this._enable = _initializer$16 && _initializer$16();
          _this.x = _initializer2$$ && _initializer2$$();
          _this.y = _initializer3$M && _initializer3$M();
          _this.z = _initializer4$E && _initializer4$E();
          _this.speedModifier = _initializer5$w && _initializer5$w();
          _this.space = _initializer6$s && _initializer6$s();
          _this.rotation = void 0;
          _this.needTransform = void 0;
          _this.name = PARTICLE_MODULE_NAME.VELOCITY;
          _this.rotation = new Quat();
          _this.speedModifier.constant = 1;
          _this.needTransform = false;
          _this.needUpdate = true;
          return _this;
        }
        var _proto = VelocityOvertimeModule.prototype;
        _proto.update = function update(space, worldTransform) {
          this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation);
        };
        _proto.animate = function animate(p, dt) {
          var normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
          var randX = isCurveTwoValues(this.x) ? pseudoRandom(p.randomSeed ^ VELOCITY_X_OVERTIME_RAND_OFFSET) : 0;
          var randY = isCurveTwoValues(this.y) ? pseudoRandom(p.randomSeed ^ VELOCITY_Y_OVERTIME_RAND_OFFSET) : 0;
          var randZ = isCurveTwoValues(this.z) ? pseudoRandom(p.randomSeed ^ VELOCITY_Z_OVERTIME_RAND_OFFSET) : 0;
          var randSpeed = isCurveTwoValues(this.speedModifier) ? pseudoRandom(p.randomSeed + VELOCITY_X_OVERTIME_RAND_OFFSET) : 0;
          var vel = Vec3.set(_temp_v3, this.x.evaluate(normalizedTime, randX), this.y.evaluate(normalizedTime, randY), this.z.evaluate(normalizedTime, randZ));
          if (this.needTransform) {
            Vec3.transformQuat(vel, vel, this.rotation);
          }
          Vec3.add(p.animatedVelocity, p.animatedVelocity, vel);
          Vec3.add(p.ultimateVelocity, p.velocity, p.animatedVelocity);
          Vec3.multiplyScalar(p.ultimateVelocity, p.ultimateVelocity, this.speedModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, randSpeed));
        };
        _createClass(VelocityOvertimeModule, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(val) {
            if (this._enable === val) return;
            this._enable = val;
            if (!this.target) return;
            this.target.enableModule(this.name, val, this);
          }
        }]);
        return VelocityOvertimeModule;
      }(ParticleModuleBase), (_initializer$16 = applyDecoratedInitializer(_class2$18.prototype, "_enable", [serializable$p], function () {
        return false;
      }), _initializer2$$ = applyDecoratedInitializer(_class2$18.prototype, "x", [_dec2$17, serializable$p], function () {
        return new CurveRange();
      }), _initializer3$M = applyDecoratedInitializer(_class2$18.prototype, "y", [_dec3$S, serializable$p], function () {
        return new CurveRange();
      }), _initializer4$E = applyDecoratedInitializer(_class2$18.prototype, "z", [_dec4$G, serializable$p], function () {
        return new CurveRange();
      }), _initializer5$w = applyDecoratedInitializer(_class2$18.prototype, "speedModifier", [_dec5$D, serializable$p], function () {
        return new CurveRange();
      }), _initializer6$s = applyDecoratedInitializer(_class2$18.prototype, "space", [_dec6$r, serializable$p], function () {
        return Space.Local;
      })), _class2$18)) || _class$1a);

      var _dec$1c, _dec2$16, _class$19, _class2$17, _initializer$15, _initializer2$_, _initializer3$L, _initializer4$D;
      var Burst = exports('fa', (_dec$1c = ccclass$M('cc.Burst'), _dec2$16 = type$d(CurveRange), _dec$1c(_class$19 = (_class2$17 = function () {
        function Burst() {
          this._time = _initializer$15 && _initializer$15();
          this._repeatCount = _initializer2$_ && _initializer2$_();
          this.repeatInterval = _initializer3$L && _initializer3$L();
          this.count = _initializer4$D && _initializer4$D();
          this._remainingCount = void 0;
          this._curTime = void 0;
          this._remainingCount = 0;
          this._curTime = 0.0;
        }
        var _proto = Burst.prototype;
        _proto.update = function update(psys, dt) {
          if (this._remainingCount === 0) {
            this._remainingCount = this._repeatCount;
            this._curTime = this._time;
          }
          if (this._remainingCount > 0) {
            var preFrameTime = repeat$2(psys._time - psys.startDelay.evaluate(0, 1), psys.duration) - dt;
            preFrameTime = preFrameTime > 0.0 ? preFrameTime : 0.0;
            var curFrameTime = repeat$2(psys.time - psys.startDelay.evaluate(0, 1), psys.duration);
            if (this._curTime >= preFrameTime && this._curTime < curFrameTime) {
              psys.emit(this.count.evaluate(this._curTime / psys.duration, 1), dt - (curFrameTime - this._curTime));
              this._curTime += this.repeatInterval;
              --this._remainingCount;
            }
          }
        };
        _proto.reset = function reset() {
          this._remainingCount = 0;
          this._curTime = 0.0;
        };
        _proto.getMaxCount = function getMaxCount(psys) {
          return this.count.getMax() * Math.min(Math.ceil(psys.duration / this.repeatInterval), this.repeatCount);
        };
        _createClass(Burst, [{
          key: "time",
          get: function get() {
            return this._time;
          },
          set: function set(val) {
            this._time = val;
            this._curTime = val;
          }
        }, {
          key: "repeatCount",
          get: function get() {
            return this._repeatCount;
          },
          set: function set(val) {
            this._repeatCount = val;
            this._remainingCount = val;
          }
        }]);
        return Burst;
      }(), (_initializer$15 = applyDecoratedInitializer(_class2$17.prototype, "_time", [serializable$p], function () {
        return 0;
      }), _initializer2$_ = applyDecoratedInitializer(_class2$17.prototype, "_repeatCount", [serializable$p], function () {
        return 1;
      }), _initializer3$L = applyDecoratedInitializer(_class2$17.prototype, "repeatInterval", [serializable$p], function () {
        return 1;
      }), _initializer4$D = applyDecoratedInitializer(_class2$17.prototype, "count", [_dec2$16, serializable$p], function () {
        return new CurveRange();
      })), _class2$17)) || _class$19));

      var _dec$1b, _dec2$15, _dec3$R, _dec4$F, _dec5$C, _dec6$q, _dec7$m, _class$18, _class2$16, _initializer$14, _initializer2$Z, _initializer3$K, _initializer4$C, _initializer5$v, _initializer6$r, _initializer7$m, _initializer8$k, _initializer9$i, _initializer10$g, _initializer11$g, _initializer12$e, _initializer13$b, _initializer14$9, _initializer15$7, _initializer16$7, _initializer17$5, _initializer18$5, _initializer19$4;
      var _intermediVec = new Vec3(0, 0, 0);
      var _intermediArr = [];
      var _unitBoxExtent = new Vec3(0.5, 0.5, 0.5);
      var ShapeModule = (_dec$1b = ccclass$M('cc.ShapeModule'), _dec2$15 = type$d(ShapeType), _dec3$R = formerlySerializedAs$4('shapeType'), _dec4$F = type$d(ShapeType), _dec5$C = type$d(EmitLocation), _dec6$q = type$d(ArcMode), _dec7$m = type$d(CurveRange), _dec$1b(_class$18 = (_class2$16 = function () {
        function ShapeModule() {
          this._enable = _initializer$14 && _initializer$14();
          this._shapeType = _initializer2$Z && _initializer2$Z();
          this.emitFrom = _initializer3$K && _initializer3$K();
          this.alignToDirection = _initializer4$C && _initializer4$C();
          this.randomDirectionAmount = _initializer5$v && _initializer5$v();
          this.sphericalDirectionAmount = _initializer6$r && _initializer6$r();
          this.randomPositionAmount = _initializer7$m && _initializer7$m();
          this.radius = _initializer8$k && _initializer8$k();
          this.radiusThickness = _initializer9$i && _initializer9$i();
          this.arcMode = _initializer10$g && _initializer10$g();
          this.arcSpread = _initializer11$g && _initializer11$g();
          this.arcSpeed = _initializer12$e && _initializer12$e();
          this.length = _initializer13$b && _initializer13$b();
          this.boxThickness = _initializer14$9 && _initializer14$9();
          this._position = _initializer15$7 && _initializer15$7();
          this._rotation = _initializer16$7 && _initializer16$7();
          this._scale = _initializer17$5 && _initializer17$5();
          this._arc = _initializer18$5 && _initializer18$5();
          this._angle = _initializer19$4 && _initializer19$4();
          this.mat = void 0;
          this.quat = void 0;
          this.particleSystem = void 0;
          this.lastTime = void 0;
          this.totalAngle = void 0;
          this.mat = new Mat4();
          this.quat = new Quat();
          this.particleSystem = null;
          this.lastTime = 0;
          this.totalAngle = 0;
        }
        var _proto = ShapeModule.prototype;
        _proto.onInit = function onInit(ps) {
          this.particleSystem = ps;
          this.constructMat();
          this.lastTime = this.particleSystem._time;
        };
        _proto.emit = function emit(p) {
          switch (this.shapeType) {
            case ShapeType.Box:
              boxEmit(this.emitFrom, this.boxThickness, p.position, p.velocity);
              break;
            case ShapeType.Circle:
              circleEmit(this.radius, this.radiusThickness, this.generateArcAngle(), p.position, p.velocity);
              break;
            case ShapeType.Cone:
              coneEmit(this.emitFrom, this.radius, this.radiusThickness, this.generateArcAngle(), this._angle, this.length, p.position, p.velocity);
              break;
            case ShapeType.Sphere:
              sphereEmit(this.emitFrom, this.radius, this.radiusThickness, p.position, p.velocity);
              break;
            case ShapeType.Hemisphere:
              hemisphereEmit(this.emitFrom, this.radius, this.radiusThickness, p.position, p.velocity);
              break;
            default:
              console.warn(this.shapeType + " shapeType is not supported by ShapeModule.");
          }
          if (this.randomPositionAmount > 0) {
            p.position.x += randomRange(-this.randomPositionAmount, this.randomPositionAmount);
            p.position.y += randomRange(-this.randomPositionAmount, this.randomPositionAmount);
            p.position.z += randomRange(-this.randomPositionAmount, this.randomPositionAmount);
          }
          Vec3.transformQuat(p.velocity, p.velocity, this.quat);
          Vec3.transformMat4(p.position, p.position, this.mat);
          if (this.sphericalDirectionAmount > 0) {
            var sphericalVel = Vec3.normalize(_intermediVec, p.position);
            Vec3.lerp(p.velocity, p.velocity, sphericalVel, this.sphericalDirectionAmount);
          }
          this.lastTime = this.particleSystem._time;
        };
        _proto.constructMat = function constructMat() {
          Quat.fromEuler(this.quat, this._rotation.x, this._rotation.y, this._rotation.z);
          Mat4.fromRTS(this.mat, this.quat, this._position, this._scale);
        };
        _proto.generateArcAngle = function generateArcAngle() {
          if (this.arcMode === ArcMode.Random) {
            return randomRange(0, this._arc);
          }
          var angle = this.totalAngle + 2 * Math.PI * this.arcSpeed.evaluate(this.particleSystem._time, 1) * (this.particleSystem._time - this.lastTime);
          this.totalAngle = angle;
          if (this.arcSpread !== 0) {
            angle = Math.floor(angle / (this._arc * this.arcSpread)) * this._arc * this.arcSpread;
          }
          switch (this.arcMode) {
            case ArcMode.Loop:
              return repeat$2(angle, this._arc);
            case ArcMode.PingPong:
              return pingPong(angle, this._arc);
            default:
              return repeat$2(angle, this._arc);
          }
        };
        _createClass(ShapeModule, [{
          key: "position",
          get: function get() {
            return this._position;
          },
          set: function set(val) {
            this._position = val;
            this.constructMat();
          }
        }, {
          key: "rotation",
          get: function get() {
            return this._rotation;
          },
          set: function set(val) {
            this._rotation = val;
            this.constructMat();
          }
        }, {
          key: "scale",
          get: function get() {
            return this._scale;
          },
          set: function set(val) {
            this._scale = val;
            this.constructMat();
          }
        }, {
          key: "arc",
          get: function get() {
            return toDegree(this._arc);
          },
          set: function set(val) {
            this._arc = toRadian(val);
          }
        }, {
          key: "angle",
          get: function get() {
            return Math.round(toDegree(this._angle) * 100) / 100;
          },
          set: function set(val) {
            this._angle = toRadian(val);
          }
        }, {
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(val) {
            this._enable = val;
          }
        }, {
          key: "shapeType",
          get: function get() {
            return this._shapeType;
          },
          set: function set(val) {
            this._shapeType = val;
            switch (this._shapeType) {
              case ShapeType.Box:
                if (this.emitFrom === EmitLocation.Base) {
                  this.emitFrom = EmitLocation.Volume;
                }
                break;
              case ShapeType.Cone:
                if (this.emitFrom === EmitLocation.Edge) {
                  this.emitFrom = EmitLocation.Base;
                }
                break;
              case ShapeType.Sphere:
              case ShapeType.Hemisphere:
                if (this.emitFrom === EmitLocation.Base || this.emitFrom === EmitLocation.Edge) {
                  this.emitFrom = EmitLocation.Volume;
                }
                break;
            }
          }
        }]);
        return ShapeModule;
      }(), (_initializer$14 = applyDecoratedInitializer(_class2$16.prototype, "_enable", [serializable$p], function () {
        return false;
      }), _initializer2$Z = applyDecoratedInitializer(_class2$16.prototype, "_shapeType", [_dec2$15, _dec3$R], function () {
        return ShapeType.Cone;
      }), _applyDecoratedDescriptor(_class2$16.prototype, "shapeType", [_dec4$F], Object.getOwnPropertyDescriptor(_class2$16.prototype, "shapeType"), _class2$16.prototype), _initializer3$K = applyDecoratedInitializer(_class2$16.prototype, "emitFrom", [_dec5$C, serializable$p], function () {
        return EmitLocation.Volume;
      }), _initializer4$C = applyDecoratedInitializer(_class2$16.prototype, "alignToDirection", [serializable$p], function () {
        return false;
      }), _initializer5$v = applyDecoratedInitializer(_class2$16.prototype, "randomDirectionAmount", [serializable$p], function () {
        return 0;
      }), _initializer6$r = applyDecoratedInitializer(_class2$16.prototype, "sphericalDirectionAmount", [serializable$p], function () {
        return 0;
      }), _initializer7$m = applyDecoratedInitializer(_class2$16.prototype, "randomPositionAmount", [serializable$p], function () {
        return 0;
      }), _initializer8$k = applyDecoratedInitializer(_class2$16.prototype, "radius", [serializable$p], function () {
        return 1;
      }), _initializer9$i = applyDecoratedInitializer(_class2$16.prototype, "radiusThickness", [serializable$p], function () {
        return 1;
      }), _initializer10$g = applyDecoratedInitializer(_class2$16.prototype, "arcMode", [_dec6$q, serializable$p], function () {
        return ArcMode.Random;
      }), _initializer11$g = applyDecoratedInitializer(_class2$16.prototype, "arcSpread", [serializable$p], function () {
        return 0;
      }), _initializer12$e = applyDecoratedInitializer(_class2$16.prototype, "arcSpeed", [_dec7$m, serializable$p], function () {
        return new CurveRange();
      }), _initializer13$b = applyDecoratedInitializer(_class2$16.prototype, "length", [serializable$p], function () {
        return 5;
      }), _initializer14$9 = applyDecoratedInitializer(_class2$16.prototype, "boxThickness", [serializable$p], function () {
        return new Vec3(0, 0, 0);
      }), _initializer15$7 = applyDecoratedInitializer(_class2$16.prototype, "_position", [serializable$p], function () {
        return new Vec3(0, 0, 0);
      }), _initializer16$7 = applyDecoratedInitializer(_class2$16.prototype, "_rotation", [serializable$p], function () {
        return new Vec3(0, 0, 0);
      }), _initializer17$5 = applyDecoratedInitializer(_class2$16.prototype, "_scale", [serializable$p], function () {
        return new Vec3(1, 1, 1);
      }), _initializer18$5 = applyDecoratedInitializer(_class2$16.prototype, "_arc", [serializable$p], function () {
        return toRadian(360);
      }), _initializer19$4 = applyDecoratedInitializer(_class2$16.prototype, "_angle", [serializable$p], function () {
        return toRadian(25);
      })), _class2$16)) || _class$18);
      function sphereEmit(emitFrom, radius, radiusThickness, pos, dir) {
        switch (emitFrom) {
          case EmitLocation.Volume:
            randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius);
            Vec3.normalize(dir, pos);
            break;
          case EmitLocation.Shell:
            randomUnitVector(pos);
            Vec3.multiplyScalar(pos, pos, radius);
            Vec3.normalize(dir, pos);
            break;
          default:
            console.warn(emitFrom + " is not supported for sphere emitter.");
        }
      }
      function hemisphereEmit(emitFrom, radius, radiusThickness, pos, dir) {
        switch (emitFrom) {
          case EmitLocation.Volume:
            randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius);
            if (pos.z > 0) {
              pos.z *= -1;
            }
            Vec3.normalize(dir, pos);
            break;
          case EmitLocation.Shell:
            randomUnitVector(pos);
            Vec3.multiplyScalar(pos, pos, radius);
            if (pos.z > 0) {
              pos.z *= -1;
            }
            Vec3.normalize(dir, pos);
            break;
          default:
            console.warn(emitFrom + " is not supported for hemisphere emitter.");
        }
      }
      function coneEmit(emitFrom, radius, radiusThickness, theta, angle, length, pos, dir) {
        switch (emitFrom) {
          case EmitLocation.Base:
            randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta);
            Vec2.multiplyScalar(dir, pos, Math.sin(angle));
            dir.z = -Math.cos(angle) * radius;
            Vec3.normalize(dir, dir);
            pos.z = 0;
            break;
          case EmitLocation.Shell:
            fixedAngleUnitVector2(pos, theta);
            Vec2.multiplyScalar(dir, pos, Math.sin(angle));
            dir.z = -Math.cos(angle);
            Vec3.normalize(dir, dir);
            Vec2.multiplyScalar(pos, pos, radius);
            pos.z = 0;
            break;
          case EmitLocation.Volume:
            randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta);
            Vec2.multiplyScalar(dir, pos, Math.sin(angle));
            dir.z = -Math.cos(angle) * radius;
            Vec3.normalize(dir, dir);
            pos.z = 0;
            Vec3.add(pos, pos, Vec3.multiplyScalar(_intermediVec, dir, length * random() / -dir.z));
            break;
          default:
            console.warn(emitFrom + " is not supported for cone emitter.");
        }
      }
      function boxEmit(emitFrom, boxThickness, pos, dir) {
        switch (emitFrom) {
          case EmitLocation.Volume:
            randomPointInCube(pos, _unitBoxExtent);
            break;
          case EmitLocation.Shell:
            _intermediArr.splice(0, _intermediArr.length);
            _intermediArr.push(randomRange(-0.5, 0.5));
            _intermediArr.push(randomRange(-0.5, 0.5));
            _intermediArr.push(randomSign() * 0.5);
            randomSortArray(_intermediArr);
            applyBoxThickness(_intermediArr, boxThickness);
            Vec3.set(pos, _intermediArr[0], _intermediArr[1], _intermediArr[2]);
            break;
          case EmitLocation.Edge:
            _intermediArr.splice(0, _intermediArr.length);
            _intermediArr.push(randomRange(-0.5, 0.5));
            _intermediArr.push(randomSign() * 0.5);
            _intermediArr.push(randomSign() * 0.5);
            randomSortArray(_intermediArr);
            applyBoxThickness(_intermediArr, boxThickness);
            Vec3.set(pos, _intermediArr[0], _intermediArr[1], _intermediArr[2]);
            break;
          default:
            console.warn(emitFrom + " is not supported for box emitter.");
        }
        Vec3.copy(dir, particleEmitZAxis);
      }
      function circleEmit(radius, radiusThickness, theta, pos, dir) {
        randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta);
        Vec3.normalize(dir, pos);
      }
      function applyBoxThickness(pos, thickness) {
        if (thickness.x > 0) {
          pos[0] += 0.5 * randomRange(-thickness.x, thickness.x);
          pos[0] = clamp$1(pos[0], -0.5, 0.5);
        }
        if (thickness.y > 0) {
          pos[1] += 0.5 * randomRange(-thickness.y, thickness.y);
          pos[1] = clamp$1(pos[1], -0.5, 0.5);
        }
        if (thickness.z > 0) {
          pos[2] += 0.5 * randomRange(-thickness.z, thickness.z);
          pos[2] = clamp$1(pos[2], -0.5, 0.5);
        }
      }

      var _uvs$1 = [0, 0, 1, 0, 0, 1, 1, 1];
      var _uvs_ins = [0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0];
      var ParticleBatchModel = function (_scene$Model) {
        _inheritsLoose(ParticleBatchModel, _scene$Model);
        function ParticleBatchModel() {
          var _this;
          _this = _scene$Model.call(this) || this;
          _this._capacity = void 0;
          _this._bufferSize = void 0;
          _this._vertAttrs = void 0;
          _this._vertAttribSize = void 0;
          _this._vBuffer = void 0;
          _this._vertAttrsFloatCount = void 0;
          _this._vdataF32 = void 0;
          _this._vdataUint32 = void 0;
          _this._subMeshData = void 0;
          _this._mesh = void 0;
          _this._vertCount = 0;
          _this._indexCount = 0;
          _this._startTimeOffset = 0;
          _this._lifeTimeOffset = 0;
          _this._material = null;
          _this._vertAttribSizeStatic = void 0;
          _this._vertStaticAttrsFloatCount = void 0;
          _this._insBuffers = void 0;
          _this._insIndices = void 0;
          _this._useInstance = void 0;
          _this._iaVertCount = 0;
          _this._iaIndexCount = 0;
          _this.type = ModelType.PARTICLE_BATCH;
          _this._capacity = 0;
          _this._bufferSize = 16;
          _this._vertAttrs = null;
          _this._vertAttribSize = 0;
          _this._vBuffer = null;
          _this._vertAttrsFloatCount = 0;
          _this._vdataF32 = null;
          _this._vdataUint32 = null;
          _this._vertAttribSizeStatic = 0;
          _this._vertStaticAttrsFloatCount = 0;
          _this._insBuffers = [];
          _this._insIndices = null;
          if (!deviceManager.gfxDevice.hasFeature(Feature.INSTANCED_ARRAYS)) {
            _this._useInstance = false;
          } else {
            _this._useInstance = true;
          }
          _this._subMeshData = null;
          _this._mesh = null;
          return _this;
        }
        var _proto = ParticleBatchModel.prototype;
        _proto.setCapacity = function setCapacity(capacity) {
          var capChanged = this._capacity !== capacity;
          this._capacity = capacity;
          this._bufferSize = Math.max(this._capacity, 16);
          if (this._subMeshData && capChanged) {
            this.rebuild();
          }
        };
        _proto.setVertexAttributes = function setVertexAttributes(mesh, attrs) {
          if (!this._useInstance) {
            if (this._mesh === mesh && this._vertAttrs === attrs) {
              return;
            }
            this._mesh = mesh;
            this._vertAttrs = attrs;
            this._vertAttribSize = 0;
            for (var _iterator = _createForOfIteratorHelperLoose(this._vertAttrs), _step; !(_step = _iterator()).done;) {
              var a = _step.value;
              a.offset = this._vertAttribSize;
              this._vertAttribSize += FormatInfos[a.format].size;
            }
            this._vertAttrsFloatCount = this._vertAttribSize / 4;
            this.rebuild();
          } else {
            this.setVertexAttributesIns(mesh, attrs);
          }
        };
        _proto.setVertexAttributesIns = function setVertexAttributesIns(mesh, attrs) {
          if (this._mesh === mesh && this._vertAttrs === attrs) {
            return;
          }
          this._mesh = mesh;
          this._vertAttrs = attrs;
          this._vertAttribSize = 0;
          this._vertAttribSizeStatic = 0;
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._vertAttrs), _step2; !(_step2 = _iterator2()).done;) {
            var a = _step2.value;
            if (a.stream === 0) {
              a.offset = this._vertAttribSize;
              this._vertAttribSize += FormatInfos[a.format].size;
            } else if (a.stream === 1) {
              a.offset = this._vertAttribSizeStatic;
              this._vertAttribSizeStatic += FormatInfos[a.format].size;
            }
          }
          this._vertAttrsFloatCount = this._vertAttribSize / 4;
          this._vertStaticAttrsFloatCount = this._vertAttribSizeStatic / 4;
          this.rebuild();
        };
        _proto.createSubMeshData = function createSubMeshData() {
          this.destroySubMeshData();
          this._vertCount = 4;
          this._indexCount = 6;
          if (this._mesh) {
            this._vertCount = this._mesh.struct.vertexBundles[this._mesh.struct.primitives[0].vertexBundelIndices[0]].view.count;
            this._indexCount = this._mesh.struct.primitives[0].indexView.count;
          }
          var vertexBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, this._vertAttribSize * this._bufferSize * this._vertCount, this._vertAttribSize));
          var vBuffer = new ArrayBuffer(this._vertAttribSize * this._bufferSize * this._vertCount);
          if (this._mesh && this._capacity > 0) {
            var vOffset = this._vertAttrs[this._vertAttrs.findIndex(function (val) {
              return val.name === AttributeName.ATTR_TEX_COORD;
            })].offset;
            this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSize, vOffset);
            var vIdx = this._vertAttrs.findIndex(function (val) {
              return val.name === AttributeName.ATTR_TEX_COORD3;
            });
            vOffset = this._vertAttrs[vIdx++].offset;
            this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSize, vOffset);
            vOffset = this._vertAttrs[vIdx++].offset;
            this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertAttribSize, vOffset);
            vOffset = this._vertAttrs[vIdx++].offset;
            if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSize, vOffset)) {
              var vb = new Uint32Array(vBuffer);
              for (var iVertex = 0; iVertex < this._vertCount; ++iVertex) {
                vb[iVertex * this._vertAttrsFloatCount + vOffset / 4] = Color$1.WHITE._val;
              }
            }
            var vbFloatArray = new Float32Array(vBuffer);
            for (var i = 1; i < this._capacity; i++) {
              vbFloatArray.copyWithin(i * this._vertAttribSize * this._vertCount / 4, 0, this._vertAttribSize * this._vertCount / 4);
            }
          }
          vertexBuffer.update(vBuffer);
          var indices = new Uint16Array(this._bufferSize * this._indexCount);
          if (this._mesh && this._capacity > 0) {
            this._mesh.copyIndices(0, indices);
            for (var _i = 1; _i < this._capacity; _i++) {
              for (var j = 0; j < this._indexCount; j++) {
                indices[_i * this._indexCount + j] = indices[j] + _i * this._vertCount;
              }
            }
          } else {
            var dst = 0;
            for (var _i2 = 0; _i2 < this._capacity; ++_i2) {
              var baseIdx = 4 * _i2;
              indices[dst++] = baseIdx;
              indices[dst++] = baseIdx + 1;
              indices[dst++] = baseIdx + 2;
              indices[dst++] = baseIdx + 3;
              indices[dst++] = baseIdx + 2;
              indices[dst++] = baseIdx + 1;
            }
          }
          var indexBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, this._bufferSize * this._indexCount * Uint16Array.BYTES_PER_ELEMENT, Uint16Array.BYTES_PER_ELEMENT));
          indexBuffer.update(indices);
          this._iaVertCount = this._capacity * this._vertCount;
          this._iaIndexCount = this._capacity * this._indexCount;
          this._subMeshData = new RenderingSubMesh([vertexBuffer], this._vertAttrs, PrimitiveMode.TRIANGLE_LIST, indexBuffer);
          this.initSubModel(0, this._subMeshData, this._material);
          return vBuffer;
        };
        _proto.createSubMeshDataInsDynamic = function createSubMeshDataInsDynamic() {
          this._insBuffers.length = 0;
          this.destroySubMeshData();
          var vertexBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, this._vertAttribSize * this._bufferSize, this._vertAttribSize));
          var vBuffer = new ArrayBuffer(this._vertAttribSize * this._bufferSize);
          vertexBuffer.update(vBuffer);
          this._insBuffers.push(vertexBuffer);
          return vBuffer;
        };
        _proto.createSubMeshDataInsStatic = function createSubMeshDataInsStatic() {
          this._vertCount = 4;
          this._indexCount = 6;
          if (this._mesh) {
            this._vertCount = this._mesh.struct.vertexBundles[this._mesh.struct.primitives[0].vertexBundelIndices[0]].view.count;
            this._indexCount = this._mesh.struct.primitives[0].indexView.count;
          }
          var vertexBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, this._vertAttribSizeStatic * this._vertCount, this._vertAttribSizeStatic));
          var vBuffer = new ArrayBuffer(this._vertAttribSizeStatic * this._vertCount);
          if (this._mesh) {
            var vIdx = this._vertAttrs.findIndex(function (val) {
              return val.name === AttributeName.ATTR_TEX_COORD;
            });
            var vOffset = this._vertAttrs[vIdx].offset;
            this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSizeStatic, vOffset);
            vIdx = this._vertAttrs.findIndex(function (val) {
              return val.name === AttributeName.ATTR_TEX_COORD3;
            });
            vOffset = this._vertAttrs[vIdx++].offset;
            this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSizeStatic, vOffset);
            vOffset = this._vertAttrs[vIdx++].offset;
            this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertAttribSizeStatic, vOffset);
            vOffset = this._vertAttrs[vIdx++].offset;
            if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSizeStatic, vOffset)) {
              var vb = new Uint32Array(vBuffer);
              for (var iVertex = 0; iVertex < this._vertCount; ++iVertex) {
                vb[iVertex * this._vertStaticAttrsFloatCount + vOffset / 4] = Color$1.WHITE._val;
              }
            }
          } else {
            var vbFloatArray = new Float32Array(vBuffer);
            for (var i = 0; i < _uvs_ins.length; ++i) {
              vbFloatArray[i] = _uvs_ins[i];
            }
          }
          vertexBuffer.update(vBuffer);
          var indices = new Uint16Array(this._indexCount);
          if (this._mesh) {
            this._mesh.copyIndices(0, indices);
          } else {
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;
            indices[3] = 3;
            indices[4] = 2;
            indices[5] = 1;
          }
          var indexBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, this._indexCount * Uint16Array.BYTES_PER_ELEMENT, Uint16Array.BYTES_PER_ELEMENT));
          indexBuffer.update(indices);
          this._insIndices = indexBuffer;
          this._iaVertCount = this._vertCount;
          this._iaIndexCount = this._indexCount;
          this._insBuffers.push(vertexBuffer);
        };
        _proto.createInsSubmesh = function createInsSubmesh() {
          this._subMeshData = new RenderingSubMesh(this._insBuffers, this._vertAttrs, PrimitiveMode.TRIANGLE_LIST, this._insIndices);
          this.initSubModel(0, this._subMeshData, this._material);
        };
        _proto.updateMaterial = function updateMaterial(mat) {
          this._material = mat;
          this.setSubModelMaterial(0, mat);
        };
        _proto.addParticleVertexData = function addParticleVertexData(index, pvdata) {
          if (!this._useInstance) {
            if (!this._mesh) {
              var offset = index * this._vertAttrsFloatCount;
              this._vdataF32[offset++] = pvdata.position.x;
              this._vdataF32[offset++] = pvdata.position.y;
              this._vdataF32[offset++] = pvdata.position.z;
              this._vdataF32[offset++] = pvdata.texcoord.x;
              this._vdataF32[offset++] = pvdata.texcoord.y;
              this._vdataF32[offset++] = pvdata.texcoord.z;
              this._vdataF32[offset++] = pvdata.size.x;
              this._vdataF32[offset++] = pvdata.size.y;
              this._vdataF32[offset++] = pvdata.size.z;
              this._vdataF32[offset++] = pvdata.rotation.x;
              this._vdataF32[offset++] = pvdata.rotation.y;
              this._vdataF32[offset++] = pvdata.rotation.z;
              this._vdataUint32[offset++] = pvdata.color;
              if (pvdata.velocity) {
                this._vdataF32[offset++] = pvdata.velocity.x;
                this._vdataF32[offset++] = pvdata.velocity.y;
                this._vdataF32[offset++] = pvdata.velocity.z;
              }
            } else {
              for (var i = 0; i < this._vertCount; i++) {
                var _offset = (index * this._vertCount + i) * this._vertAttrsFloatCount;
                this._vdataF32[_offset++] = pvdata.position.x;
                this._vdataF32[_offset++] = pvdata.position.y;
                this._vdataF32[_offset++] = pvdata.position.z;
                _offset += 2;
                this._vdataF32[_offset++] = pvdata.texcoord.z;
                this._vdataF32[_offset++] = pvdata.size.x;
                this._vdataF32[_offset++] = pvdata.size.y;
                this._vdataF32[_offset++] = pvdata.size.z;
                this._vdataF32[_offset++] = pvdata.rotation.x;
                this._vdataF32[_offset++] = pvdata.rotation.y;
                this._vdataF32[_offset++] = pvdata.rotation.z;
                this._vdataUint32[_offset++] = pvdata.color;
              }
            }
          } else {
            this.addParticleVertexDataIns(index, pvdata);
          }
        };
        _proto.addParticleVertexDataIns = function addParticleVertexDataIns(index, pvdata) {
          var offset = index * this._vertAttrsFloatCount;
          if (!this._mesh) {
            this._vdataF32[offset++] = pvdata.position.x;
            this._vdataF32[offset++] = pvdata.position.y;
            this._vdataF32[offset++] = pvdata.position.z;
            this._vdataF32[offset++] = pvdata.texcoord.z;
            this._vdataF32[offset++] = pvdata.size.x;
            this._vdataF32[offset++] = pvdata.size.y;
            this._vdataF32[offset++] = pvdata.size.z;
            this._vdataF32[offset++] = pvdata.rotation.x;
            this._vdataF32[offset++] = pvdata.rotation.y;
            this._vdataF32[offset++] = pvdata.rotation.z;
            this._vdataUint32[offset++] = pvdata.color;
            if (pvdata.velocity) {
              this._vdataF32[offset++] = pvdata.velocity.x;
              this._vdataF32[offset++] = pvdata.velocity.y;
              this._vdataF32[offset++] = pvdata.velocity.z;
            }
          } else {
            this._vdataF32[offset++] = pvdata.position.x;
            this._vdataF32[offset++] = pvdata.position.y;
            this._vdataF32[offset++] = pvdata.position.z;
            this._vdataF32[offset++] = pvdata.texcoord.z;
            this._vdataF32[offset++] = pvdata.size.x;
            this._vdataF32[offset++] = pvdata.size.y;
            this._vdataF32[offset++] = pvdata.size.z;
            this._vdataF32[offset++] = pvdata.rotation.x;
            this._vdataF32[offset++] = pvdata.rotation.y;
            this._vdataF32[offset++] = pvdata.rotation.z;
            this._vdataUint32[offset++] = pvdata.color;
          }
        };
        _proto.addGPUParticleVertexData = function addGPUParticleVertexData(p, num, time) {
          if (!this._useInstance) {
            var offset = num * this._vertAttrsFloatCount * this._vertCount;
            for (var i = 0; i < this._vertCount; i++) {
              var idx = offset;
              this._vdataF32[idx++] = p.position.x;
              this._vdataF32[idx++] = p.position.y;
              this._vdataF32[idx++] = p.position.z;
              this._vdataF32[idx++] = time;
              this._vdataF32[idx++] = p.startSize.x;
              this._vdataF32[idx++] = p.startSize.y;
              this._vdataF32[idx++] = p.startSize.z;
              this._vdataF32[idx++] = _uvs$1[2 * i];
              this._vdataF32[idx++] = p.rotation.x;
              this._vdataF32[idx++] = p.rotation.y;
              this._vdataF32[idx++] = p.rotation.z;
              this._vdataF32[idx++] = _uvs$1[2 * i + 1];
              this._vdataF32[idx++] = p.startColor.r / 255.0;
              this._vdataF32[idx++] = p.startColor.g / 255.0;
              this._vdataF32[idx++] = p.startColor.b / 255.0;
              this._vdataF32[idx++] = p.startColor.a / 255.0;
              this._vdataF32[idx++] = p.velocity.x;
              this._vdataF32[idx++] = p.velocity.y;
              this._vdataF32[idx++] = p.velocity.z;
              this._vdataF32[idx++] = p.startLifetime;
              this._vdataF32[idx++] = p.randomSeed;
              offset += this._vertAttrsFloatCount;
            }
          } else {
            this.addGPUParticleVertexDataIns(p, num, time);
          }
        };
        _proto.addGPUParticleVertexDataIns = function addGPUParticleVertexDataIns(p, num, time) {
          var offset = num * this._vertAttrsFloatCount;
          var idx = offset;
          this._vdataF32[idx++] = p.position.x;
          this._vdataF32[idx++] = p.position.y;
          this._vdataF32[idx++] = p.position.z;
          this._vdataF32[idx++] = time;
          this._vdataF32[idx++] = p.startSize.x;
          this._vdataF32[idx++] = p.startSize.y;
          this._vdataF32[idx++] = p.startSize.z;
          this._vdataF32[idx++] = p.frameIndex;
          this._vdataF32[idx++] = p.rotation.x;
          this._vdataF32[idx++] = p.rotation.y;
          this._vdataF32[idx++] = p.rotation.z;
          this._vdataF32[idx++] = p.startColor.r / 255.0;
          this._vdataF32[idx++] = p.startColor.g / 255.0;
          this._vdataF32[idx++] = p.startColor.b / 255.0;
          this._vdataF32[idx++] = p.startColor.a / 255.0;
          this._vdataF32[idx++] = p.velocity.x;
          this._vdataF32[idx++] = p.velocity.y;
          this._vdataF32[idx++] = p.velocity.z;
          this._vdataF32[idx++] = p.startLifetime;
          this._vdataF32[idx++] = p.randomSeed;
          offset += this._vertAttrsFloatCount;
        };
        _proto.updateGPUParticles = function updateGPUParticles(num, time, dt) {
          if (!this._useInstance) {
            var pSize = this._vertAttrsFloatCount * this._vertCount;
            var pBaseIndex = 0;
            var startTime = 0;
            var lifeTime = 0;
            var lastBaseIndex = 0;
            var interval = 0;
            for (var i = 0; i < num; ++i) {
              pBaseIndex = i * pSize;
              startTime = this._vdataF32[pBaseIndex + this._startTimeOffset];
              lifeTime = this._vdataF32[pBaseIndex + this._lifeTimeOffset];
              interval = time - startTime;
              if (lifeTime - interval < dt) {
                lastBaseIndex = --num * pSize;
                this._vdataF32.copyWithin(pBaseIndex, lastBaseIndex, lastBaseIndex + pSize);
                i--;
              }
            }
            return num;
          } else {
            return this.updateGPUParticlesIns(num, time, dt);
          }
        };
        _proto.updateGPUParticlesIns = function updateGPUParticlesIns(num, time, dt) {
          var pSize = this._vertAttrsFloatCount;
          var pBaseIndex = 0;
          var startTime = 0;
          var lifeTime = 0;
          var lastBaseIndex = 0;
          var interval = 0;
          for (var i = 0; i < num; ++i) {
            pBaseIndex = i * pSize;
            startTime = this._vdataF32[pBaseIndex + this._startTimeOffset];
            lifeTime = this._vdataF32[pBaseIndex + this._lifeTimeOffset];
            interval = time - startTime;
            if (lifeTime - interval < dt) {
              lastBaseIndex = --num * pSize;
              this._vdataF32.copyWithin(pBaseIndex, lastBaseIndex, lastBaseIndex + pSize);
              i--;
            }
          }
          return num;
        };
        _proto.constructAttributeIndex = function constructAttributeIndex() {
          if (!this._vertAttrs) {
            return;
          }
          var vIdx = this._vertAttrs.findIndex(function (val) {
            return val.name === 'a_position_starttime';
          });
          var vOffset = this._vertAttrs[vIdx].offset;
          this._startTimeOffset = vOffset / 4 + 3;
          vIdx = this._vertAttrs.findIndex(function (val) {
            return val.name === 'a_dir_life';
          });
          vOffset = this._vertAttrs[vIdx].offset;
          this._lifeTimeOffset = vOffset / 4 + 3;
        };
        _proto.updateIA = function updateIA(count) {
          if (!this._useInstance) {
            if (count <= 0) {
              return;
            }
            var ia = this._subModels[0].inputAssembler;
            ia.vertexBuffers[0].update(this._vdataF32);
            ia.firstIndex = 0;
            ia.indexCount = this._indexCount * count;
            ia.vertexCount = this._iaVertCount;
          } else {
            this.updateIAIns(count);
          }
        };
        _proto.updateIAIns = function updateIAIns(count) {
          if (count <= 0) {
            return;
          }
          var ia = this._subModels[0].inputAssembler;
          ia.vertexBuffers[0].update(this._vdataF32);
          ia.instanceCount = count;
          ia.firstIndex = 0;
          ia.indexCount = this._indexCount;
          ia.instanceCount = count;
          ia.vertexCount = this._iaVertCount;
        };
        _proto.clear = function clear() {
          if (!this._useInstance) {
            this._subModels[0].inputAssembler.indexCount = 0;
          } else {
            this.clearIns();
          }
        };
        _proto.clearIns = function clearIns() {
          this._subModels[0].inputAssembler.instanceCount = 0;
        };
        _proto.destroy = function destroy() {
          _scene$Model.prototype.destroy.call(this);
          this.doDestroy();
        };
        _proto.doDestroy = function doDestroy() {
          this._vBuffer = null;
          this._vdataF32 = null;
          this._vdataUint32 = null;
          this._insBuffers = [];
          this._insIndices = null;
          this._vertAttrs = null;
          this._material = null;
          this._mesh = null;
          this.destroySubMeshData();
        };
        _proto.rebuild = function rebuild() {
          if (!this._useInstance) {
            this._vBuffer = this.createSubMeshData();
            this._vdataF32 = new Float32Array(this._vBuffer);
            this._vdataUint32 = new Uint32Array(this._vBuffer);
          } else {
            this.rebuildIns();
          }
        };
        _proto.rebuildIns = function rebuildIns() {
          this._vBuffer = this.createSubMeshDataInsDynamic();
          this._vdataF32 = new Float32Array(this._vBuffer);
          this._vdataUint32 = new Uint32Array(this._vBuffer);
          this.createSubMeshDataInsStatic();
          this.createInsSubmesh();
        };
        _proto.destroySubMeshData = function destroySubMeshData() {
          if (this._subMeshData) {
            this._subMeshData.destroy();
            this._subMeshData = null;
          }
        };
        _createClass(ParticleBatchModel, [{
          key: "useInstance",
          get: function get() {
            return this._useInstance;
          },
          set: function set(value) {
            if (this._useInstance !== value) {
              this._useInstance = value;
            }
          }
        }]);
        return ParticleBatchModel;
      }(Model);

      var ParticleSystemRendererBase = function () {
        function ParticleSystemRendererBase(info) {
          this._particleSystem = null;
          this._model = null;
          this._renderInfo = null;
          this._vertAttrs = [];
          this._useInstance = void 0;
          this._renderInfo = info;
          if (!deviceManager.gfxDevice.hasFeature(Feature.INSTANCED_ARRAYS)) {
            this._useInstance = false;
          } else {
            this._useInstance = true;
          }
        }
        var _proto = ParticleSystemRendererBase.prototype;
        _proto.getUseInstance = function getUseInstance() {
          return this._useInstance;
        };
        _proto.getInfo = function getInfo() {
          return this._renderInfo;
        };
        _proto.onInit = function onInit(ps) {
          this._particleSystem = ps;
        };
        _proto.onEnable = function onEnable() {
          if (!this._particleSystem) {
            return;
          }
          this.attachToScene();
          var model = this._model;
          if (model) {
            model.node = model.transform = this._particleSystem.node;
          }
        };
        _proto.onDisable = function onDisable() {
          this.detachFromScene();
        };
        _proto.onDestroy = function onDestroy() {
          if (this._model) {
            legacyCC.director.root.destroyModel(this._model);
            this._model = null;
          }
        };
        _proto.attachToScene = function attachToScene() {
          if (this._model) {
            var _this$_particleSystem;
            if (this._model.scene) {
              this.detachFromScene();
            }
            (_this$_particleSystem = this._particleSystem) === null || _this$_particleSystem === void 0 ? void 0 : _this$_particleSystem._getRenderScene().addModel(this._model);
          }
        };
        _proto.detachFromScene = function detachFromScene() {
          if (this._model && this._model.scene) {
            this._model.scene.removeModel(this._model);
          }
        };
        _proto.setVertexAttributes = function setVertexAttributes() {
          if (this._model) {
            this.updateVertexAttrib();
            this._model.setVertexAttributes(this._renderInfo.renderMode === RenderMode.Mesh ? this._renderInfo.mesh : null, this._vertAttrs);
          }
        };
        _proto.clear = function clear() {
          if (this._model) this._model.enabled = false;
        };
        _proto.getModel = function getModel() {
          return this._model;
        };
        _proto._initModel = function _initModel() {
          if (!this._model && this._particleSystem) {
            this._model = legacyCC.director.root.createModel(ParticleBatchModel);
            this._model.setCapacity(this._particleSystem.capacity);
            this._model.visFlags = this._particleSystem.visibility;
          }
        };
        _proto.updateTrailMaterial = function updateTrailMaterial() {};
        _proto.getDefaultTrailMaterial = function getDefaultTrailMaterial() {
          return null;
        };
        _createClass(ParticleSystemRendererBase, [{
          key: "model",
          get: function get() {
            return this._model;
          }
        }]);
        return ParticleSystemRendererBase;
      }();

      var ParticleNoise = function () {
        function ParticleNoise(permutation) {
          this.permutation = [151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180];
          this.accSpeed = new Vec3();
          this.noiseSpeed = new Vec3();
          this.noiseFrequency = 0.0;
          this.noiseAbs = new Vec3();
          this.noiseAmplitude = new Vec3();
          this.octaves = new Vec3();
          this.dt = 0.0;
          this.point = new Vec3();
          this.result = new Vec3();
          this.mixOut = new Vec2();
          if (permutation) {
            this.permutation = permutation;
          }
        }
        var _proto = ParticleNoise.prototype;
        _proto.noise = function noise(x, y, z, min, max) {
          if (min === void 0) {
            min = 0;
          }
          if (max === void 0) {
            max = 1;
          }
          var p = new Array(512);
          for (var i = 0; i < 256; i++) {
            p[256 + i] = p[i] = this.permutation[i];
          }
          var X = Math.floor(x) & 255;
          var Y = Math.floor(y) & 255;
          var Z = Math.floor(z) & 255;
          x -= Math.floor(x);
          y -= Math.floor(y);
          z -= Math.floor(z);
          var u = this.fade(x);
          var v = this.fade(y);
          var w = this.fade(z);
          var A = p[X] + Y;
          var AA = p[A] + Z;
          var AB = p[A + 1] + Z;
          var B = p[X + 1] + Y;
          var BA = p[B] + Z;
          var BB = p[B + 1] + Z;
          var val = this.scale(this.lerp(w, this.lerp(v, this.lerp(u, this.grad(p[AA], x, y, z), this.grad(p[BA], x - 1, y, z)), this.lerp(u, this.grad(p[AB], x, y - 1, z), this.grad(p[BB], x - 1, y - 1, z))), this.lerp(v, this.lerp(u, this.grad(p[AA + 1], x, y, z - 1), this.grad(p[BA + 1], x - 1, y, z - 1)), this.lerp(u, this.grad(p[AB + 1], x, y - 1, z - 1), this.grad(p[BB + 1], x - 1, y - 1, z - 1)))));
          return min + val * (max - min);
        };
        _proto.fade = function fade(t) {
          return t * t * t * (t * (t * 6 - 15) + 10);
        };
        _proto.lerp = function lerp(t, a, b) {
          return a + t * (b - a);
        };
        _proto.grad = function grad(hash, x, y, z) {
          var h = hash & 15;
          var u = h < 8 ? x : y;
          var v = h < 4 ? y : h === 12 || h === 14 ? x : z;
          return ((h & 1) === 0 ? u : -u) + ((h & 2) === 0 ? v : -v);
        };
        _proto.scale = function scale(n) {
          return (1 + n) / 2;
        };
        _proto.setSpeed = function setSpeed(x, y, z) {
          this.noiseSpeed.set(x, y, z);
        };
        _proto.setFrequency = function setFrequency(f) {
          this.noiseFrequency = f;
        };
        _proto.setAbs = function setAbs(x, y, z) {
          this.noiseAbs.set(x, y, z);
        };
        _proto.setAmplititude = function setAmplititude(x, y, z) {
          this.noiseAmplitude.set(x, y, z);
        };
        _proto.setOctaves = function setOctaves(x, y, z) {
          this.octaves.set(x, y, z);
        };
        _proto.setTime = function setTime(t) {
          this.dt = t;
        };
        _proto.setSamplePoint = function setSamplePoint(p) {
          this.point.set(p);
        };
        _proto.getResult = function getResult() {
          return this.result;
        };
        _proto.getNoise = function getNoise(sx, sy, sz, time, offset, noiseFrequency, octaves) {
          var frequency = noiseFrequency;
          var sum = 0.0;
          sum += this.noise(sx * frequency, sy * frequency, sz * frequency, -1.0, 1.0);
          if (octaves.x === 1) {
            return sum;
          }
          var amplitude = 1.0;
          var range = 1.0;
          for (var i = 1; i < octaves.x; ++i) {
            amplitude *= octaves.y;
            frequency *= octaves.z;
            range += amplitude;
            sum += this.noise(sx * frequency, sy * frequency, sz * frequency, -1.0, 1.0) * amplitude;
          }
          return sum / range;
        };
        _proto.getNoiseMix = function getNoiseMix(out, point, time, offSpeed, noiseFrequency, octaves) {
          out.x = this.getNoise(point.x, point.y, point.z, time, offSpeed, noiseFrequency, octaves);
          out.y = this.getNoise(point.y, point.z, point.x, time, offSpeed, noiseFrequency, octaves);
        };
        _proto.getNoiseParticle = function getNoiseParticle() {
          this.accSpeed.set(this.noiseSpeed.x * this.dt, this.noiseSpeed.y * this.dt, this.noiseSpeed.z * this.dt);
          var axisOffset = 1000.0;
          var sampX = this.getNoise(this.point.z + this.accSpeed.x, this.point.y, this.point.x, this.dt, this.accSpeed, this.noiseFrequency, this.octaves);
          var sampY = this.getNoise(this.point.x + axisOffset, this.point.z + this.accSpeed.y, this.point.y, this.dt, this.accSpeed, this.noiseFrequency, this.octaves);
          var sampZ = this.getNoise(this.point.y, this.point.x + axisOffset, this.point.z + this.accSpeed.z, this.dt, this.accSpeed, this.noiseFrequency, this.octaves);
          this.result.set(sampX * this.noiseAmplitude.x, sampY * this.noiseAmplitude.y, sampZ * this.noiseAmplitude.z);
        };
        _proto.getPreview = function getPreview(out, width, height) {
          for (var h = 0; h < height; ++h) {
            for (var w = 0; w < width; ++w) {
              var sampx = (w - width * 0.5) / width + this.noiseSpeed.x * this.dt;
              var sampy = (h - height * 0.5) / height + this.noiseSpeed.y * this.dt;
              var pix = this.getNoise(sampx, sampy, 0.0, this.dt, this.accSpeed, this.noiseFrequency, this.octaves);
              out[h * width + w] = (pix + 1.0) * 0.5;
            }
          }
        };
        return ParticleNoise;
      }();

      var _tempNodeScale$1 = new Vec4();
      var _tempAttribUV = new Vec3();
      var _tempWorldTrans$1 = new Mat4();
      var _tempParentInverse = new Mat4();
      var _node_rot$1 = new Quat();
      new Vec3();
      var _anim_module$1 = ['_colorOverLifetimeModule', '_sizeOvertimeModule', '_velocityOvertimeModule', '_forceOvertimeModule', '_limitVelocityOvertimeModule', '_rotationOvertimeModule', '_textureAnimationModule', '_noiseModule'];
      var _uvs = [0, 0, 1, 0, 0, 1, 1, 1];
      var CC_USE_WORLD_SPACE$1 = 'CC_USE_WORLD_SPACE';
      var CC_RENDER_MODE$1 = 'CC_RENDER_MODE';
      var ROTATION_OVER_TIME_MODULE_ENABLE$1 = 'ROTATION_OVER_TIME_MODULE_ENABLE';
      var INSTANCE_PARTICLE$1 = 'CC_INSTANCE_PARTICLE';
      var RENDER_MODE_BILLBOARD$1 = 0;
      var RENDER_MODE_STRETCHED_BILLBOARD$1 = 1;
      var RENDER_MODE_HORIZONTAL_BILLBOARD$1 = 2;
      var RENDER_MODE_VERTICAL_BILLBOARD$1 = 3;
      var RENDER_MODE_MESH$1 = 4;
      var _vertex_attrs = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true)];
      var _vertex_attrs_stretch = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true), new Attribute(AttributeName.ATTR_COLOR1, Format.RGB32F)];
      var _vertex_attrs_mesh = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true), new Attribute(AttributeName.ATTR_TEX_COORD3, Format.RGB32F), new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F), new Attribute(AttributeName.ATTR_COLOR1, Format.RGBA8, true)];
      var _vertex_attrs_ins = [new Attribute(AttributeName.ATTR_TEX_COORD4, Format.RGBA32F, false, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F, false, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F, false, 0, true), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F, false, 1)];
      var _vertex_attrs_stretch_ins = [new Attribute(AttributeName.ATTR_TEX_COORD4, Format.RGBA32F, false, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F, false, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F, false, 0, true), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true, 0, true), new Attribute(AttributeName.ATTR_COLOR1, Format.RGB32F, false, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F, false, 1)];
      var _vertex_attrs_mesh_ins = [new Attribute(AttributeName.ATTR_TEX_COORD4, Format.RGBA32F, false, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F, false, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F, false, 0, true), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F, false, 1), new Attribute(AttributeName.ATTR_TEX_COORD3, Format.RGB32F, false, 1), new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F, false, 1), new Attribute(AttributeName.ATTR_COLOR1, Format.RGBA8, true, 1)];
      var _matInsInfo$1 = {
        parent: null,
        owner: null,
        subModelIdx: 0
      };
      var PVData = function PVData() {
        this.position = void 0;
        this.texcoord = void 0;
        this.size = void 0;
        this.rotation = void 0;
        this.color = void 0;
        this.velocity = void 0;
        this.position = new Vec3();
        this.texcoord = new Vec3();
        this.size = new Vec3();
        this.rotation = new Vec3();
        this.color = 0;
        this.velocity = null;
      };
      var ParticleSystemRendererCPU = function (_ParticleSystemRender) {
        _inheritsLoose(ParticleSystemRendererCPU, _ParticleSystemRender);
        function ParticleSystemRendererCPU(info) {
          var _this;
          _this = _ParticleSystemRender.call(this, info) || this;
          _this._defines = void 0;
          _this._trailDefines = void 0;
          _this._frameTile_velLenScale = void 0;
          _this._tmp_velLenScale = void 0;
          _this._defaultMat = null;
          _this._node_scale = void 0;
          _this._particleVertexData = void 0;
          _this._particles = null;
          _this._defaultTrailMat = null;
          _this._updateList = new Map();
          _this._animateList = new Map();
          _this._runAnimateList = new Array();
          _this._fillDataFunc = null;
          _this._uScaleHandle = 0;
          _this._uLenHandle = 0;
          _this._uNodeRotHandle = 0;
          _this._alignSpace = AlignmentSpace.View;
          _this._inited = false;
          _this._localMat = new Mat4();
          _this._gravity = new Vec4();
          _this.noise = new ParticleNoise();
          _this._model = null;
          _this._frameTile_velLenScale = new Vec4(1, 1, 0, 0);
          _this._tmp_velLenScale = _this._frameTile_velLenScale.clone();
          _this._node_scale = new Vec3();
          _this._particleVertexData = new PVData();
          _this._defines = {
            CC_USE_WORLD_SPACE: true,
            CC_USE_BILLBOARD: true,
            CC_USE_STRETCHED_BILLBOARD: false,
            CC_USE_HORIZONTAL_BILLBOARD: false,
            CC_USE_VERTICAL_BILLBOARD: false
          };
          _this._trailDefines = {
            CC_USE_WORLD_SPACE: true
          };
          return _this;
        }
        var _proto = ParticleSystemRendererCPU.prototype;
        _proto.onInit = function onInit(ps) {
          var _this2 = this;
          _ParticleSystemRender.prototype.onInit.call(this, ps);
          this._particles = new RecyclePool(function () {
            return new Particle$1(_this2);
          }, 16);
          this._setVertexAttrib();
          this._setFillFunc();
          this._initModuleList();
          this._initModel();
          this.updateMaterialParams();
          this.updateTrailMaterial();
          this.setVertexAttributes();
          this._inited = true;
        };
        _proto.clear = function clear() {
          _ParticleSystemRender.prototype.clear.call(this);
          this._particles.reset();
          if (this._particleSystem && this._particleSystem._trailModule) {
            this._particleSystem._trailModule.clear();
          }
          this.updateRenderData();
          this._model.enabled = false;
        };
        _proto.updateRenderMode = function updateRenderMode() {
          this._setVertexAttrib();
          this._setFillFunc();
          this.updateMaterialParams();
          this.setVertexAttributes();
        };
        _proto.onDestroy = function onDestroy() {
          var _this$_particles;
          (_this$_particles = this._particles) === null || _this$_particles === void 0 ? void 0 : _this$_particles.destroy();
          _ParticleSystemRender.prototype.onDestroy.call(this);
        };
        _proto.getFreeParticle = function getFreeParticle() {
          if (this._particleSystem && this._particles.length >= this._particleSystem.capacity) {
            return null;
          }
          return this._particles.add();
        };
        _proto.getDefaultTrailMaterial = function getDefaultTrailMaterial() {
          return this._defaultTrailMat;
        };
        _proto.setNewParticle = function setNewParticle(p) {};
        _proto._initModuleList = function _initModuleList() {
          var _this3 = this;
          _anim_module$1.forEach(function (val) {
            if (!_this3._particleSystem) {
              return;
            }
            var pm = _this3._particleSystem[val];
            if (pm && pm.enable) {
              if (pm.needUpdate) {
                _this3._updateList[pm.name] = pm;
              }
              if (pm.needAnimate) {
                _this3._animateList[pm.name] = pm;
              }
            }
          });
          this._runAnimateList.length = 0;
          for (var i = 0, len = PARTICLE_MODULE_ORDER.length; i < len; i++) {
            var _p = this._animateList[PARTICLE_MODULE_ORDER[i]];
            if (_p) {
              this._runAnimateList.push(_p);
            }
          }
        };
        _proto.enableModule = function enableModule(name, val, pm) {
          if (val) {
            if (pm.needUpdate) {
              this._updateList[pm.name] = pm;
            }
            if (pm.needAnimate) {
              this._animateList[pm.name] = pm;
            }
          } else {
            delete this._animateList[name];
            delete this._updateList[name];
          }
          this._runAnimateList.length = 0;
          for (var i = 0, len = PARTICLE_MODULE_ORDER.length; i < len; i++) {
            var _p2 = this._animateList[PARTICLE_MODULE_ORDER[i]];
            if (_p2) {
              this._runAnimateList.push(_p2);
            }
          }
          this.updateMaterialParams();
        };
        _proto.updateAlignSpace = function updateAlignSpace(space) {
          this._alignSpace = space;
        };
        _proto.getDefaultMaterial = function getDefaultMaterial() {
          return this._defaultMat;
        };
        _proto.updateRotation = function updateRotation(pass) {
          if (pass) {
            this.doUpdateRotation(pass);
          }
        };
        _proto.doUpdateRotation = function doUpdateRotation(pass) {
          var mode = this._renderInfo.renderMode;
          if (mode !== RenderMode.Mesh && this._alignSpace === AlignmentSpace.View) {
            return;
          }
          if (this._alignSpace === AlignmentSpace.Local) {
            var _this$_particleSystem;
            (_this$_particleSystem = this._particleSystem) === null || _this$_particleSystem === void 0 ? void 0 : _this$_particleSystem.node.getRotation(_node_rot$1);
          } else if (this._alignSpace === AlignmentSpace.World) {
            var _this$_particleSystem2;
            (_this$_particleSystem2 = this._particleSystem) === null || _this$_particleSystem2 === void 0 ? void 0 : _this$_particleSystem2.node.getWorldRotation(_node_rot$1);
          } else if (this._alignSpace === AlignmentSpace.View) {
            var _this$_particleSystem3, _this$_particleSystem4;
            _node_rot$1.set(0.0, 0.0, 0.0, 1.0);
            var cameraLst = (_this$_particleSystem3 = this._particleSystem) === null || _this$_particleSystem3 === void 0 ? void 0 : (_this$_particleSystem4 = _this$_particleSystem3.node.scene.renderScene) === null || _this$_particleSystem4 === void 0 ? void 0 : _this$_particleSystem4.cameras;
            if (cameraLst !== undefined) {
              for (var i = 0; i < (cameraLst === null || cameraLst === void 0 ? void 0 : cameraLst.length); ++i) {
                var camera = cameraLst[i];
                var checkCamera = (camera.visibility & this._particleSystem.node.layer) === this._particleSystem.node.layer ;
                if (checkCamera) {
                  Quat.fromViewUp(_node_rot$1, camera.forward);
                  break;
                }
              }
            }
          } else {
            _node_rot$1.set(0.0, 0.0, 0.0, 1.0);
          }
          pass.setUniform(this._uNodeRotHandle, _node_rot$1);
        };
        _proto.updateScale = function updateScale(pass) {
          if (pass) {
            this.doUpdateScale(pass);
          }
        };
        _proto.doUpdateScale = function doUpdateScale(pass) {
          var _this$_particleSystem5, _this$_particleSystem6, _this$_particleSystem7;
          var nodeScale = this._node_scale;
          switch ((_this$_particleSystem5 = this._particleSystem) === null || _this$_particleSystem5 === void 0 ? void 0 : _this$_particleSystem5.scaleSpace) {
            case Space.Local:
              (_this$_particleSystem6 = this._particleSystem) === null || _this$_particleSystem6 === void 0 ? void 0 : _this$_particleSystem6.node.getScale(nodeScale);
              break;
            case Space.World:
              (_this$_particleSystem7 = this._particleSystem) === null || _this$_particleSystem7 === void 0 ? void 0 : _this$_particleSystem7.node.getWorldScale(nodeScale);
              break;
          }
          pass.setUniform(this._uScaleHandle, _tempNodeScale$1.set(nodeScale.x, nodeScale.y, nodeScale.z));
        };
        _proto.updateParticles = function updateParticles(dt) {
          var _this4 = this;
          var ps = this._particleSystem;
          if (!ps) {
            return this._particles.length;
          }
          ps.node.getWorldMatrix(_tempWorldTrans$1);
          var mat = ps.getMaterialInstance(0) || this._defaultMat;
          var pass = mat.passes[0];
          this.doUpdateScale(pass);
          this.doUpdateRotation(pass);
          this._updateList.forEach(function (value, key) {
            value.update(ps.simulationSpace, _tempWorldTrans$1);
          });
          var trailModule = ps._trailModule;
          var trailEnable = trailModule && trailModule.enable;
          if (trailEnable) {
            trailModule.update();
          }
          var useGravity = !ps.gravityModifier.isZero();
          if (useGravity) {
            if (ps.simulationSpace === Space.Local) {
              var r = ps.node.getRotation();
              Mat4.fromQuat(this._localMat, r);
              this._localMat.transpose();
            }
            if (ps.node.parent) {
              var _r = ps.node.parent.getWorldRotation();
              Mat4.fromQuat(_tempParentInverse, _r);
              _tempParentInverse.transpose();
            }
          }
          var _loop = function _loop(_i) {
            var p = _this4._particles.data[_i];
            p.remainingLifetime -= dt;
            Vec3.set(p.animatedVelocity, 0, 0, 0);
            if (p.remainingLifetime < 0.0) {
              if (trailEnable) {
                trailModule.removeParticle(p);
              }
              _this4._particles.removeAt(_i);
              --_i;
              i = _i;
              return 1;
            }
            if (useGravity) {
              var rand = isCurveTwoValues(ps.gravityModifier) ? pseudoRandom(p.randomSeed) : 0;
              if (ps.simulationSpace === Space.Local) {
                var time = 1 - p.remainingLifetime / p.startLifetime;
                var gravityFactor = -ps.gravityModifier.evaluate(time, rand) * 9.8 * dt;
                _this4._gravity.x = 0.0;
                _this4._gravity.y = gravityFactor;
                _this4._gravity.z = 0.0;
                _this4._gravity.w = 1.0;
                if (!approx(gravityFactor, 0.0, EPSILON$3)) {
                  if (ps.node.parent) {
                    _this4._gravity = _this4._gravity.transformMat4(_tempParentInverse);
                  }
                  _this4._gravity = _this4._gravity.transformMat4(_this4._localMat);
                  p.velocity.x += _this4._gravity.x;
                  p.velocity.y += _this4._gravity.y;
                  p.velocity.z += _this4._gravity.z;
                }
              } else {
                p.velocity.y -= ps.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, rand) * 9.8 * dt;
              }
            }
            Vec3.copy(p.ultimateVelocity, p.velocity);
            _this4._runAnimateList.forEach(function (value) {
              value.animate(p, dt);
            });
            Vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt);
            if (trailEnable) {
              trailModule.animate(p, dt);
            }
            i = _i;
          };
          for (var i = 0; i < this._particles.length; ++i) {
            if (_loop(i)) continue;
          }
          this._model.enabled = this._particles.length > 0;
          return this._particles.length;
        };
        _proto.getNoisePreview = function getNoisePreview(out, width, height) {
          var _this5 = this;
          this._runAnimateList.forEach(function (value) {
            if (value.name === PARTICLE_MODULE_NAME.NOISE) {
              var m = value;
              m.getNoisePreview(out, _this5._particleSystem, width, height);
            }
          });
        };
        _proto.updateRenderData = function updateRenderData() {
          var idx = 0;
          for (var i = 0; i < this._particles.length; ++i) {
            var _p3 = this._particles.data[i];
            var _fi = 0;
            var textureModule = this._particleSystem._textureAnimationModule;
            if (textureModule && textureModule.enable) {
              _fi = _p3.frameIndex;
            }
            idx = i * 4;
            this._fillDataFunc(_p3, idx, _fi);
          }
        };
        _proto.beforeRender = function beforeRender() {
          this._model.updateIA(this._particles.length);
        };
        _proto.getParticleCount = function getParticleCount() {
          return this._particles.length;
        };
        _proto.onMaterialModified = function onMaterialModified(index, material) {
          if (!this._inited) {
            return;
          }
          if (index === 0) {
            this.updateMaterialParams();
          } else {
            this.updateTrailMaterial();
          }
        };
        _proto.onRebuildPSO = function onRebuildPSO(index, material) {
          if (this._model && index === 0) {
            this._model.setSubModelMaterial(0, material);
          }
          var trailModule = this._particleSystem._trailModule;
          var trailModel = trailModule === null || trailModule === void 0 ? void 0 : trailModule.getModel();
          if (trailModel && index === 1) {
            trailModel.setSubModelMaterial(0, material);
          }
        };
        _proto._setFillFunc = function _setFillFunc() {
          if (this._renderInfo.renderMode === RenderMode.Mesh) {
            this._fillDataFunc = this._fillMeshData;
          } else if (this._renderInfo.renderMode === RenderMode.StrecthedBillboard) {
            this._fillDataFunc = this._fillStrecthedData;
          } else {
            this._fillDataFunc = this._fillNormalData;
          }
        };
        _proto._fillMeshData = function _fillMeshData(p, idx, fi) {
          var i = idx / 4;
          Vec3.copy(this._particleVertexData.position, p.position);
          _tempAttribUV.z = fi;
          Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV);
          Vec3.copy(this._particleVertexData.size, p.size);
          Vec3.copy(this._particleVertexData.rotation, p.rotation);
          this._particleVertexData.color = p.color._val;
          this._model.addParticleVertexData(i, this._particleVertexData);
        };
        _proto._fillStrecthedData = function _fillStrecthedData(p, idx, fi) {
          if (!this._useInstance) {
            for (var j = 0; j < 4; ++j) {
              Vec3.copy(this._particleVertexData.position, p.position);
              _tempAttribUV.x = _uvs[2 * j];
              _tempAttribUV.y = _uvs[2 * j + 1];
              _tempAttribUV.z = fi;
              Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV);
              Vec3.copy(this._particleVertexData.size, p.size);
              Vec3.copy(this._particleVertexData.rotation, p.rotation);
              this._particleVertexData.color = p.color._val;
              this._particleVertexData.velocity = p.ultimateVelocity;
              this._model.addParticleVertexData(idx++, this._particleVertexData);
            }
          } else {
            this._fillStrecthedDataIns(p, idx, fi);
          }
        };
        _proto._fillStrecthedDataIns = function _fillStrecthedDataIns(p, idx, fi) {
          var i = idx / 4;
          Vec3.copy(this._particleVertexData.position, p.position);
          _tempAttribUV.z = fi;
          Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV);
          Vec3.copy(this._particleVertexData.size, p.size);
          Vec3.copy(this._particleVertexData.rotation, p.rotation);
          this._particleVertexData.color = p.color._val;
          this._particleVertexData.velocity = p.ultimateVelocity;
          this._model.addParticleVertexData(i, this._particleVertexData);
        };
        _proto._fillNormalData = function _fillNormalData(p, idx, fi) {
          if (!this._useInstance) {
            for (var j = 0; j < 4; ++j) {
              Vec3.copy(this._particleVertexData.position, p.position);
              _tempAttribUV.x = _uvs[2 * j];
              _tempAttribUV.y = _uvs[2 * j + 1];
              _tempAttribUV.z = fi;
              Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV);
              Vec3.copy(this._particleVertexData.size, p.size);
              Vec3.copy(this._particleVertexData.rotation, p.rotation);
              this._particleVertexData.color = p.color._val;
              this._model.addParticleVertexData(idx++, this._particleVertexData);
            }
          } else {
            this._fillNormalDataIns(p, idx, fi);
          }
        };
        _proto._fillNormalDataIns = function _fillNormalDataIns(p, idx, fi) {
          var i = idx / 4;
          Vec3.copy(this._particleVertexData.position, p.position);
          _tempAttribUV.z = fi;
          Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV);
          Vec3.copy(this._particleVertexData.size, p.size);
          Vec3.copy(this._particleVertexData.rotation, p.rotation);
          this._particleVertexData.color = p.color._val;
          this._model.addParticleVertexData(i, this._particleVertexData);
        };
        _proto.updateVertexAttrib = function updateVertexAttrib() {
          if (this._renderInfo.renderMode !== RenderMode.Mesh) {
            return;
          }
          if (this._renderInfo.mesh) {
            var format = this._renderInfo.mesh.readAttributeFormat(0, AttributeName.ATTR_COLOR);
            if (format) {
              var type = Format.RGBA8;
              for (var i = 0; i < FormatInfos.length; ++i) {
                if (FormatInfos[i].name === format.name) {
                  type = i;
                  break;
                }
              }
              this._vertAttrs[7] = new Attribute(AttributeName.ATTR_COLOR1, type, true, !this._useInstance ? 0 : 1);
            } else {
              var _type = Format.RGBA8;
              this._vertAttrs[7] = new Attribute(AttributeName.ATTR_COLOR1, _type, true, !this._useInstance ? 0 : 1);
            }
          }
        };
        _proto._setVertexAttrib = function _setVertexAttrib() {
          if (!this._useInstance) {
            switch (this._renderInfo.renderMode) {
              case RenderMode.StrecthedBillboard:
                this._vertAttrs = _vertex_attrs_stretch.slice();
                break;
              case RenderMode.Mesh:
                this._vertAttrs = _vertex_attrs_mesh.slice();
                break;
              default:
                this._vertAttrs = _vertex_attrs.slice();
            }
          } else {
            this._setVertexAttribIns();
          }
        };
        _proto._setVertexAttribIns = function _setVertexAttribIns() {
          switch (this._renderInfo.renderMode) {
            case RenderMode.StrecthedBillboard:
              this._vertAttrs = _vertex_attrs_stretch_ins.slice();
              break;
            case RenderMode.Mesh:
              this._vertAttrs = _vertex_attrs_mesh_ins.slice();
              break;
            default:
              this._vertAttrs = _vertex_attrs_ins.slice();
          }
        };
        _proto.updateMaterialParams = function updateMaterialParams() {
          if (!this._particleSystem) {
            return;
          }
          var ps = this._particleSystem;
          var shareMaterial = ps.sharedMaterial;
          if (shareMaterial != null) {
            this._renderInfo.mainTexture = shareMaterial.getProperty('mainTexture', 0);
          }
          if (ps.sharedMaterial == null && this._defaultMat == null) {
            _matInsInfo$1.parent = builtinResMgr.get('default-particle-material');
            _matInsInfo$1.owner = this._particleSystem;
            _matInsInfo$1.subModelIdx = 0;
            this._defaultMat = new MaterialInstance(_matInsInfo$1);
            _matInsInfo$1.parent = null;
            _matInsInfo$1.owner = null;
            _matInsInfo$1.subModelIdx = 0;
            if (this._renderInfo.mainTexture !== null) {
              this._defaultMat.setProperty('mainTexture', this._renderInfo.mainTexture);
            }
          }
          var mat = ps.getMaterialInstance(0) || this._defaultMat;
          if (ps.simulationSpace === Space.World) {
            this._defines[CC_USE_WORLD_SPACE$1] = true;
          } else {
            this._defines[CC_USE_WORLD_SPACE$1] = false;
          }
          var pass = mat.passes[0];
          this._uScaleHandle = pass.getHandle('scale');
          this._uLenHandle = pass.getHandle('frameTile_velLenScale');
          this._uNodeRotHandle = pass.getHandle('nodeRotation');
          var renderMode = this._renderInfo.renderMode;
          var vlenScale = this._frameTile_velLenScale;
          if (renderMode === RenderMode.Billboard) {
            this._defines[CC_RENDER_MODE$1] = RENDER_MODE_BILLBOARD$1;
          } else if (renderMode === RenderMode.StrecthedBillboard) {
            this._defines[CC_RENDER_MODE$1] = RENDER_MODE_STRETCHED_BILLBOARD$1;
            vlenScale.z = this._renderInfo.velocityScale;
            vlenScale.w = this._renderInfo.lengthScale;
          } else if (renderMode === RenderMode.HorizontalBillboard) {
            this._defines[CC_RENDER_MODE$1] = RENDER_MODE_HORIZONTAL_BILLBOARD$1;
          } else if (renderMode === RenderMode.VerticalBillboard) {
            this._defines[CC_RENDER_MODE$1] = RENDER_MODE_VERTICAL_BILLBOARD$1;
          } else if (renderMode === RenderMode.Mesh) {
            this._defines[CC_RENDER_MODE$1] = RENDER_MODE_MESH$1;
          } else {
            warn("particle system renderMode " + renderMode + " not support.");
          }
          var textureModule = ps._textureAnimationModule;
          if (textureModule && textureModule.enable) {
            Vec4.copy(this._tmp_velLenScale, vlenScale);
            Vec2.set(this._tmp_velLenScale, textureModule.numTilesX, textureModule.numTilesY);
            pass.setUniform(this._uLenHandle, this._tmp_velLenScale);
          } else {
            pass.setUniform(this._uLenHandle, vlenScale);
          }
          var enable = false;
          var roationModule = this._particleSystem._rotationOvertimeModule;
          enable = roationModule ? roationModule.enable : false;
          this._defines[ROTATION_OVER_TIME_MODULE_ENABLE$1] = enable;
          this._defines[INSTANCE_PARTICLE$1] = this._useInstance;
          mat.recompileShaders(this._defines);
          if (this._model) {
            this._model.updateMaterial(mat);
          }
        };
        _proto.updateTrailMaterial = function updateTrailMaterial() {
          if (!this._particleSystem) {
            return;
          }
          var ps = this._particleSystem;
          var trailModule = ps._trailModule;
          if (trailModule && trailModule.enable) {
            if (ps.simulationSpace === Space.World || trailModule.space === Space.World) {
              this._trailDefines[CC_USE_WORLD_SPACE$1] = true;
            } else {
              this._trailDefines[CC_USE_WORLD_SPACE$1] = false;
            }
            var mat = ps.getMaterialInstance(1);
            if (mat === null && this._defaultTrailMat === null) {
              _matInsInfo$1.parent = builtinResMgr.get('default-trail-material');
              _matInsInfo$1.owner = this._particleSystem;
              _matInsInfo$1.subModelIdx = 1;
              this._defaultTrailMat = new MaterialInstance(_matInsInfo$1);
              _matInsInfo$1.parent = null;
              _matInsInfo$1.owner = null;
              _matInsInfo$1.subModelIdx = 0;
            }
            mat = mat || this._defaultTrailMat;
            mat.recompileShaders(this._trailDefines);
            trailModule.updateMaterial();
          }
        };
        _proto.setUseInstance = function setUseInstance(value) {
          if (this._useInstance === value) {
            return;
          }
          this._useInstance = value;
          if (this._model) {
            this._model.useInstance = value;
            this._model.doDestroy();
          }
          this.updateRenderMode();
        };
        return ParticleSystemRendererCPU;
      }(ParticleSystemRendererBase);

      var _tempNodeScale = new Vec4();
      var _tempWorldTrans = new Mat4();
      var _tempVec4 = new Vec4();
      var _world_rot = new Quat();
      var _node_rot = new Quat();
      new Vec3();
      var _sample_num = 32;
      var _sample_interval = 1.0 / _sample_num;
      var CC_USE_WORLD_SPACE = 'CC_USE_WORLD_SPACE';
      var CC_RENDER_MODE = 'CC_RENDER_MODE';
      var RENDER_MODE_BILLBOARD = 0;
      var RENDER_MODE_STRETCHED_BILLBOARD = 1;
      var RENDER_MODE_HORIZONTAL_BILLBOARD = 2;
      var RENDER_MODE_VERTICAL_BILLBOARD = 3;
      var RENDER_MODE_MESH = 4;
      var COLOR_OVER_TIME_MODULE_ENABLE = 'COLOR_OVER_TIME_MODULE_ENABLE';
      var ROTATION_OVER_TIME_MODULE_ENABLE = 'ROTATION_OVER_TIME_MODULE_ENABLE';
      var SIZE_OVER_TIME_MODULE_ENABLE = 'SIZE_OVER_TIME_MODULE_ENABLE';
      var VELOCITY_OVER_TIME_MODULE_ENABLE = 'VELOCITY_OVER_TIME_MODULE_ENABLE';
      var FORCE_OVER_TIME_MODULE_ENABLE = 'FORCE_OVER_TIME_MODULE_ENABLE';
      var TEXTURE_ANIMATION_MODULE_ENABLE = 'TEXTURE_ANIMATION_MODULE_ENABLE';
      var USE_VK_SHADER = 'USE_VK_SHADER';
      var INSTANCE_PARTICLE = 'CC_INSTANCE_PARTICLE';
      var _vert_attr_name = {
        POSITION_STARTTIME: 'a_position_starttime',
        VERT_SIZE_UV: 'a_size_uv',
        VERT_ROTATION_UV: 'a_rotation_uv',
        COLOR: 'a_color',
        DIR_LIFE: 'a_dir_life',
        RANDOM_SEED: 'a_rndSeed',
        VERT_SIZE_FID: 'a_size_fid',
        VERT_ROTATION: 'a_rotation',
        VERT_UV: 'a_uv'
      };
      var _gpu_vert_attr = [new Attribute(_vert_attr_name.POSITION_STARTTIME, Format.RGBA32F), new Attribute(_vert_attr_name.VERT_SIZE_UV, Format.RGBA32F), new Attribute(_vert_attr_name.VERT_ROTATION_UV, Format.RGBA32F), new Attribute(_vert_attr_name.COLOR, Format.RGBA32F), new Attribute(_vert_attr_name.DIR_LIFE, Format.RGBA32F), new Attribute(_vert_attr_name.RANDOM_SEED, Format.R32F)];
      var _gpu_vert_attr_mesh = [new Attribute(_vert_attr_name.POSITION_STARTTIME, Format.RGBA32F), new Attribute(_vert_attr_name.VERT_SIZE_UV, Format.RGBA32F), new Attribute(_vert_attr_name.VERT_ROTATION_UV, Format.RGBA32F), new Attribute(_vert_attr_name.COLOR, Format.RGBA32F), new Attribute(_vert_attr_name.DIR_LIFE, Format.RGBA32F), new Attribute(_vert_attr_name.RANDOM_SEED, Format.R32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD3, Format.RGB32F), new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F), new Attribute(AttributeName.ATTR_COLOR1, Format.RGBA8, true)];
      var _gpu_vert_attr_ins = [new Attribute(_vert_attr_name.POSITION_STARTTIME, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.VERT_SIZE_FID, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.VERT_ROTATION, Format.RGB32F, false, 0, true), new Attribute(_vert_attr_name.COLOR, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.DIR_LIFE, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.RANDOM_SEED, Format.R32F, false, 0, true), new Attribute(_vert_attr_name.VERT_UV, Format.RGB32F, false, 1)];
      var _gpu_vert_attr_mesh_ins = [new Attribute(_vert_attr_name.POSITION_STARTTIME, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.VERT_SIZE_FID, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.VERT_ROTATION, Format.RGB32F, false, 0, true), new Attribute(_vert_attr_name.COLOR, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.DIR_LIFE, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.RANDOM_SEED, Format.R32F, false, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F, false, 1), new Attribute(AttributeName.ATTR_TEX_COORD3, Format.RGB32F, false, 1), new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F, false, 1), new Attribute(AttributeName.ATTR_COLOR1, Format.RGBA8, true, 1)];
      var _matInsInfo = {
        parent: null,
        owner: null,
        subModelIdx: 0
      };
      var ParticleSystemRendererGPU = function (_ParticleSystemRender) {
        _inheritsLoose(ParticleSystemRendererGPU, _ParticleSystemRender);
        function ParticleSystemRendererGPU(info) {
          var _this;
          _this = _ParticleSystemRender.call(this, info) || this;
          _this._defines = void 0;
          _this._frameTile_velLenScale = void 0;
          _this._unifrom_velLenScale = void 0;
          _this._tmp_velLenScale = void 0;
          _this._node_scale = void 0;
          _this._vertAttrs = [];
          _this._defaultMat = null;
          _this._particleNum = 0;
          _this._tempParticle = null;
          _this._colorTexture = null;
          _this._forceTexture = null;
          _this._velocityTexture = null;
          _this._rotationTexture = null;
          _this._sizeTexture = null;
          _this._animTexture = null;
          _this._colorData = null;
          _this._forceData = null;
          _this._velocityData = null;
          _this._rotationData = null;
          _this._sizeData = null;
          _this._animData = null;
          _this._uTimeHandle = 0;
          _this._uRotHandle = 0;
          _this._uNodeRotHandle = 0;
          _this._alignSpace = AlignmentSpace.View;
          _this._inited = false;
          _this._frameTile_velLenScale = new Vec4(1, 1, 0, 0);
          _this._unifrom_velLenScale = _this._frameTile_velLenScale.clone();
          _this._tmp_velLenScale = _this._frameTile_velLenScale.clone();
          _this._node_scale = new Vec3();
          _this._defines = {
            CC_USE_WORLD_SPACE: true,
            CC_USE_BILLBOARD: true,
            CC_USE_STRETCHED_BILLBOARD: false,
            CC_USE_HORIZONTAL_BILLBOARD: false,
            CC_USE_VERTICAL_BILLBOARD: false,
            COLOR_OVER_TIME_MODULE_ENABLE: false
          };
          _this._tempParticle = new Particle$1(null);
          _this._particleNum = 0;
          return _this;
        }
        var _proto = ParticleSystemRendererGPU.prototype;
        _proto.onInit = function onInit(ps) {
          _ParticleSystemRender.prototype.onInit.call(this, ps);
          this._setVertexAttrib();
          this._initModel();
          this.updateMaterialParams();
          this.setVertexAttributes();
          this._inited = true;
        };
        _proto.updateRenderMode = function updateRenderMode() {
          this._setVertexAttrib();
          this.updateMaterialParams();
          this.setVertexAttributes();
        };
        _proto.setVertexAttributes = function setVertexAttributes() {
          _ParticleSystemRender.prototype.setVertexAttributes.call(this);
          this._model.constructAttributeIndex();
        };
        _proto.clear = function clear() {
          _ParticleSystemRender.prototype.clear.call(this);
          this._particleNum = 0;
          this.updateRenderData();
        };
        _proto.onDestroy = function onDestroy() {
          _ParticleSystemRender.prototype.onDestroy.call(this);
          if (this._forceTexture) this._forceTexture.destroy();
          if (this._velocityTexture) this._velocityTexture.destroy();
          if (this._colorTexture) this._colorTexture.destroy();
          if (this._sizeTexture) this._sizeTexture.destroy();
          if (this._rotationTexture) this._rotationTexture.destroy();
          if (this._animTexture) this._animTexture.destroy();
          this._forceData = null;
          this._velocityData = null;
          this._colorData = null;
          this._sizeData = null;
          this._rotationData = null;
          this._animData = null;
        };
        _proto.enableModule = function enableModule(name, val, pm) {
          var _this$_particleSystem;
          var mat = ((_this$_particleSystem = this._particleSystem) === null || _this$_particleSystem === void 0 ? void 0 : _this$_particleSystem.getMaterialInstance(0)) || this._defaultMat;
          if (!mat) {
            return;
          }
          this.initShaderUniform(mat);
          mat.recompileShaders(this._defines);
          if (this._model) {
            this._model.setSubModelMaterial(0, mat);
          }
        };
        _proto.getFreeParticle = function getFreeParticle() {
          var _this$_particleSystem2;
          if (this._particleSystem && this._particleNum >= ((_this$_particleSystem2 = this._particleSystem) === null || _this$_particleSystem2 === void 0 ? void 0 : _this$_particleSystem2.capacity)) {
            return null;
          }
          return this._tempParticle;
        };
        _proto.setNewParticle = function setNewParticle(p) {
          if (!this._particleSystem) {
            return;
          }
          this._model.addGPUParticleVertexData(p, this._particleNum, this._particleSystem.time);
          this._particleNum++;
        };
        _proto.getDefaultMaterial = function getDefaultMaterial() {
          return this._defaultMat;
        };
        _proto.updateRotation = function updateRotation(pass) {
          if (pass) {
            this.doUpdateRotation(pass);
          }
        };
        _proto.doUpdateRotation = function doUpdateRotation(pass) {
          var mode = this._renderInfo.renderMode;
          if (mode !== RenderMode.Mesh && this._alignSpace === AlignmentSpace.View) {
            return;
          }
          if (this._alignSpace === AlignmentSpace.Local) {
            var _this$_particleSystem3;
            (_this$_particleSystem3 = this._particleSystem) === null || _this$_particleSystem3 === void 0 ? void 0 : _this$_particleSystem3.node.getRotation(_node_rot);
          } else if (this._alignSpace === AlignmentSpace.World) {
            var _this$_particleSystem4;
            (_this$_particleSystem4 = this._particleSystem) === null || _this$_particleSystem4 === void 0 ? void 0 : _this$_particleSystem4.node.getWorldRotation(_node_rot);
          } else if (this._alignSpace === AlignmentSpace.View) {
            var _this$_particleSystem5, _this$_particleSystem6;
            _node_rot.set(0.0, 0.0, 0.0, 1.0);
            var cameraLst = (_this$_particleSystem5 = this._particleSystem) === null || _this$_particleSystem5 === void 0 ? void 0 : (_this$_particleSystem6 = _this$_particleSystem5.node.scene.renderScene) === null || _this$_particleSystem6 === void 0 ? void 0 : _this$_particleSystem6.cameras;
            if (cameraLst !== undefined && this._particleSystem) {
              for (var i = 0; i < (cameraLst === null || cameraLst === void 0 ? void 0 : cameraLst.length); ++i) {
                var camera = cameraLst[i];
                var checkCamera = (camera.visibility & this._particleSystem.node.layer) === this._particleSystem.node.layer ;
                if (checkCamera) {
                  Quat.fromViewUp(_node_rot, camera.forward);
                  break;
                }
              }
            }
          } else {
            _node_rot.set(0.0, 0.0, 0.0, 1.0);
          }
          pass.setUniform(this._uNodeRotHandle, _node_rot);
        };
        _proto.updateScale = function updateScale(pass) {
          if (pass) {
            this.doUpdateScale(pass);
          }
        };
        _proto.doUpdateScale = function doUpdateScale(pass) {
          var _this$_particleSystem7;
          var nodeScale = this._node_scale;
          switch ((_this$_particleSystem7 = this._particleSystem) === null || _this$_particleSystem7 === void 0 ? void 0 : _this$_particleSystem7.scaleSpace) {
            case Space.Local:
              this._particleSystem.node.getScale(nodeScale);
              break;
            case Space.World:
              this._particleSystem.node.getWorldScale(nodeScale);
              break;
          }
          pass.setUniform(pass.getHandle('scale'), _tempNodeScale.set(nodeScale.x, nodeScale.y, nodeScale.z));
        };
        _proto.updateParticles = function updateParticles(dt) {
          if (!this._particleSystem) {
            return this._particleNum;
          }
          this._particleNum = this._model.updateGPUParticles(this._particleNum, this._particleSystem.time, dt);
          this.updateShaderUniform(dt);
          this._model.enabled = this._particleNum > 0;
          return this._particleNum;
        };
        _proto.updateRenderData = function updateRenderData() {};
        _proto.beforeRender = function beforeRender() {
          this._model.updateIA(this._particleNum);
        };
        _proto.updateAlignSpace = function updateAlignSpace(space) {
          this._alignSpace = space;
        };
        _proto.updateShaderUniform = function updateShaderUniform(dt) {
          if (!this._particleSystem) {
            return;
          }
          var mat = this._particleSystem.getMaterialInstance(0) || this._defaultMat;
          if (!mat) {
            return;
          }
          var pass = mat.passes[0];
          _tempVec4.x = this._particleSystem.time;
          _tempVec4.y = dt;
          pass.setUniform(this._uTimeHandle, _tempVec4);
          this._particleSystem.node.getWorldRotation(_world_rot);
          pass.setUniform(this._uRotHandle, _world_rot);
          this.doUpdateRotation(pass);
        };
        _proto.initShaderUniform = function initShaderUniform(mat) {
          var _this$_particleSystem8, _this$_particleSystem9, _this$_particleSystem10, _this$_particleSystem11, _this$_particleSystem12, _this$_particleSystem13;
          var pass = mat.passes[0];
          this._uTimeHandle = pass.getHandle('u_timeDelta');
          this._uRotHandle = pass.getHandle('u_worldRot');
          this._uNodeRotHandle = pass.getHandle('nodeRotation');
          this.doUpdateScale(pass);
          pass.setUniform(pass.getHandle('frameTile_velLenScale'), this._unifrom_velLenScale);
          _tempVec4.x = _sample_num;
          _tempVec4.y = _sample_interval;
          pass.setUniform(pass.getHandle('u_sampleInfo'), _tempVec4);
          var enable = false;
          var forceModule = (_this$_particleSystem8 = this._particleSystem) === null || _this$_particleSystem8 === void 0 ? void 0 : _this$_particleSystem8._forceOvertimeModule;
          enable = forceModule ? forceModule.enable : false;
          this._defines[FORCE_OVER_TIME_MODULE_ENABLE] = enable;
          if (enable) {
            var packed = packCurveRangeXYZ(this._forceTexture, this._forceData, _sample_num, forceModule.x, forceModule.y, forceModule.z);
            this._forceTexture = packed.texture;
            this._forceData = packed.texdata;
            var handle = pass.getHandle('force_over_time_tex0');
            var binding = Pass.getBindingFromHandle(handle);
            pass.bindSampler(binding, this._forceTexture.getGFXSampler());
            pass.bindTexture(binding, this._forceTexture.getGFXTexture());
            var spaceHandle = pass.getHandle('u_force_space');
            pass.setUniform(spaceHandle, forceModule.space);
            var modeHandle = pass.getHandle('u_force_mode');
            pass.setUniform(modeHandle, this._forceTexture.height);
          }
          var velocityModule = (_this$_particleSystem9 = this._particleSystem) === null || _this$_particleSystem9 === void 0 ? void 0 : _this$_particleSystem9._velocityOvertimeModule;
          enable = velocityModule ? velocityModule.enable : false;
          this._defines[VELOCITY_OVER_TIME_MODULE_ENABLE] = enable;
          if (enable) {
            var _packed = packCurveRangeXYZW(this._velocityTexture, this._velocityData, _sample_num, velocityModule.x, velocityModule.y, velocityModule.z, velocityModule.speedModifier);
            this._velocityTexture = _packed.texture;
            this._velocityData = _packed.texdata;
            var _handle = pass.getHandle('velocity_over_time_tex0');
            var _binding = Pass.getBindingFromHandle(_handle);
            pass.bindSampler(_binding, this._velocityTexture.getGFXSampler());
            pass.bindTexture(_binding, this._velocityTexture.getGFXTexture());
            var _spaceHandle = pass.getHandle('u_velocity_space');
            pass.setUniform(_spaceHandle, velocityModule.space);
            var _modeHandle = pass.getHandle('u_velocity_mode');
            pass.setUniform(_modeHandle, this._velocityTexture.height);
          }
          var colorModule = (_this$_particleSystem10 = this._particleSystem) === null || _this$_particleSystem10 === void 0 ? void 0 : _this$_particleSystem10._colorOverLifetimeModule;
          enable = colorModule ? colorModule.enable : false;
          this._defines[COLOR_OVER_TIME_MODULE_ENABLE] = enable;
          if (enable) {
            var _packed2 = packGradientRange(this._colorTexture, this._colorData, _sample_num, colorModule.color);
            this._colorTexture = _packed2.texture;
            this._colorData = _packed2.texdata;
            var _handle2 = pass.getHandle('color_over_time_tex0');
            var _binding2 = Pass.getBindingFromHandle(_handle2);
            pass.bindSampler(_binding2, this._colorTexture.getGFXSampler());
            pass.bindTexture(_binding2, this._colorTexture.getGFXTexture());
            var _modeHandle2 = pass.getHandle('u_color_mode');
            pass.setUniform(_modeHandle2, this._colorTexture.height);
          }
          var roationModule = (_this$_particleSystem11 = this._particleSystem) === null || _this$_particleSystem11 === void 0 ? void 0 : _this$_particleSystem11._rotationOvertimeModule;
          enable = roationModule ? roationModule.enable : false;
          this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable;
          if (enable) {
            var _packed3;
            if (roationModule.separateAxes) {
              _packed3 = packCurveRangeXYZ(this._rotationTexture, this._rotationData, _sample_num, roationModule.x, roationModule.y, roationModule.z);
            } else {
              _packed3 = packCurveRangeZ(this._rotationTexture, this._rotationData, _sample_num, roationModule.z);
            }
            this._rotationTexture = _packed3.texture;
            this._rotationData = _packed3.texdata;
            if (this._rotationTexture) {
              var _handle3 = pass.getHandle('rotation_over_time_tex0');
              var _binding3 = Pass.getBindingFromHandle(_handle3);
              pass.bindSampler(_binding3, this._rotationTexture.getGFXSampler());
              pass.bindTexture(_binding3, this._rotationTexture.getGFXTexture());
              var _modeHandle3 = pass.getHandle('u_rotation_mode');
              pass.setUniform(_modeHandle3, this._rotationTexture.height);
            }
          }
          var sizeModule = (_this$_particleSystem12 = this._particleSystem) === null || _this$_particleSystem12 === void 0 ? void 0 : _this$_particleSystem12._sizeOvertimeModule;
          enable = sizeModule ? sizeModule.enable : false;
          this._defines[SIZE_OVER_TIME_MODULE_ENABLE] = enable;
          if (enable) {
            var _packed4;
            if (sizeModule.separateAxes) {
              _packed4 = packCurveRangeXYZ(this._sizeTexture, this._sizeData, _sample_num, sizeModule.x, sizeModule.y, sizeModule.z, true);
            } else {
              _packed4 = packCurveRangeN(this._sizeTexture, this._sizeData, _sample_num, sizeModule.size, true);
            }
            this._sizeTexture = _packed4.texture;
            this._sizeData = _packed4.texdata;
            if (this._sizeTexture) {
              var _handle4 = pass.getHandle('size_over_time_tex0');
              var _binding4 = Pass.getBindingFromHandle(_handle4);
              pass.bindSampler(_binding4, this._sizeTexture.getGFXSampler());
              pass.bindTexture(_binding4, this._sizeTexture.getGFXTexture());
              var _modeHandle4 = pass.getHandle('u_size_mode');
              pass.setUniform(_modeHandle4, this._sizeTexture.height);
            }
          }
          var textureModule = (_this$_particleSystem13 = this._particleSystem) === null || _this$_particleSystem13 === void 0 ? void 0 : _this$_particleSystem13._textureAnimationModule;
          enable = textureModule ? textureModule.enable : false;
          this._defines[TEXTURE_ANIMATION_MODULE_ENABLE] = enable;
          if (enable) {
            var _packed5 = packCurveRangeXY(this._animTexture, this._animData, _sample_num, textureModule.startFrame, textureModule.frameOverTime, true);
            this._animTexture = _packed5.texture;
            this._animData = _packed5.texdata;
            var _handle5 = pass.getHandle('texture_animation_tex0');
            var _binding5 = Pass.getBindingFromHandle(_handle5);
            pass.bindSampler(_binding5, this._animTexture.getGFXSampler());
            pass.bindTexture(_binding5, this._animTexture.getGFXTexture());
            var infoHandle = pass.getHandle('u_anim_info');
            _tempVec4.x = this._animTexture.height;
            _tempVec4.y = textureModule.numTilesX * textureModule.numTilesY;
            _tempVec4.z = textureModule.cycleCount;
            pass.setUniform(infoHandle, _tempVec4);
          }
          this._defines[USE_VK_SHADER] = deviceManager.gfxDevice.gfxAPI === API.VULKAN;
          this._defines[INSTANCE_PARTICLE] = this._useInstance;
        };
        _proto.getParticleCount = function getParticleCount() {
          return this._particleNum;
        };
        _proto.onMaterialModified = function onMaterialModified(index, material) {
          if (!this._inited) {
            return;
          }
          this.updateMaterialParams();
        };
        _proto.onRebuildPSO = function onRebuildPSO(index, material) {
          if (this._model && index === 0) {
            this._model.setSubModelMaterial(0, material);
          }
        };
        _proto.updateVertexAttrib = function updateVertexAttrib() {
          if (this._renderInfo.renderMode !== RenderMode.Mesh) {
            return;
          }
          if (this._renderInfo.mesh) {
            var format = this._renderInfo.mesh.readAttributeFormat(0, AttributeName.ATTR_COLOR);
            if (format) {
              var type = Format.RGBA8;
              for (var i = 0; i < FormatInfos.length; ++i) {
                if (FormatInfos[i].name === format.name) {
                  type = i;
                  break;
                }
              }
              this._vertAttrs[9] = new Attribute(AttributeName.ATTR_COLOR1, type, true, !this._useInstance ? 0 : 1);
            } else {
              var _type = Format.RGBA8;
              this._vertAttrs[9] = new Attribute(AttributeName.ATTR_COLOR1, _type, true, !this._useInstance ? 0 : 1);
            }
          }
        };
        _proto._setVertexAttrib = function _setVertexAttrib() {
          if (!this._useInstance) {
            switch (this._renderInfo.renderMode) {
              case RenderMode.StrecthedBillboard:
                this._vertAttrs = _gpu_vert_attr.slice();
                break;
              case RenderMode.Mesh:
                this._vertAttrs = _gpu_vert_attr_mesh.slice();
                break;
              default:
                this._vertAttrs = _gpu_vert_attr.slice();
            }
          } else {
            this._setVertexAttribIns();
          }
        };
        _proto._setVertexAttribIns = function _setVertexAttribIns() {
          switch (this._renderInfo.renderMode) {
            case RenderMode.StrecthedBillboard:
              this._vertAttrs = _gpu_vert_attr_ins.slice();
              break;
            case RenderMode.Mesh:
              this._vertAttrs = _gpu_vert_attr_mesh_ins.slice();
              break;
            default:
              this._vertAttrs = _gpu_vert_attr_ins.slice();
          }
        };
        _proto.updateMaterialParams = function updateMaterialParams() {
          if (!this._particleSystem) {
            return;
          }
          var ps = this._particleSystem;
          var shareMaterial = ps.sharedMaterial;
          if (shareMaterial !== null) {
            this._renderInfo.mainTexture = shareMaterial.getProperty('mainTexture', 0);
          }
          if (ps.sharedMaterial == null && this._defaultMat == null) {
            _matInsInfo.parent = builtinResMgr.get('default-particle-gpu-material');
            _matInsInfo.owner = ps;
            _matInsInfo.subModelIdx = 0;
            this._defaultMat = new MaterialInstance(_matInsInfo);
            _matInsInfo.parent = null;
            _matInsInfo.owner = null;
            _matInsInfo.subModelIdx = 0;
            if (this._renderInfo.mainTexture !== null) {
              this._defaultMat.setProperty('mainTexture', this._renderInfo.mainTexture);
            }
          }
          var mat = ps.getMaterialInstance(0) || this._defaultMat;
          ps.node.getWorldMatrix(_tempWorldTrans);
          if (ps.simulationSpace === Space.World) {
            this._defines[CC_USE_WORLD_SPACE] = true;
          } else {
            this._defines[CC_USE_WORLD_SPACE] = false;
          }
          var renderMode = this._renderInfo.renderMode;
          if (renderMode === RenderMode.Billboard) {
            this._defines[CC_RENDER_MODE] = RENDER_MODE_BILLBOARD;
          } else if (renderMode === RenderMode.StrecthedBillboard) {
            this._defines[CC_RENDER_MODE] = RENDER_MODE_STRETCHED_BILLBOARD;
            this._frameTile_velLenScale.z = this._renderInfo.velocityScale;
            this._frameTile_velLenScale.w = this._renderInfo.lengthScale;
          } else if (renderMode === RenderMode.HorizontalBillboard) {
            this._defines[CC_RENDER_MODE] = RENDER_MODE_HORIZONTAL_BILLBOARD;
          } else if (renderMode === RenderMode.VerticalBillboard) {
            this._defines[CC_RENDER_MODE] = RENDER_MODE_VERTICAL_BILLBOARD;
          } else if (renderMode === RenderMode.Mesh) {
            this._defines[CC_RENDER_MODE] = RENDER_MODE_MESH;
          } else {
            warn("particle system renderMode " + renderMode + " not support.");
          }
          var textureModule = ps._textureAnimationModule;
          if (textureModule && textureModule.enable) {
            Vec2.set(this._frameTile_velLenScale, textureModule.numTilesX, textureModule.numTilesY);
            Vec4.copy(this._unifrom_velLenScale, this._frameTile_velLenScale);
          } else {
            this._tmp_velLenScale.z = this._frameTile_velLenScale.z;
            this._tmp_velLenScale.w = this._frameTile_velLenScale.w;
            Vec4.copy(this._unifrom_velLenScale, this._tmp_velLenScale);
          }
          this.initShaderUniform(mat);
          mat.recompileShaders(this._defines);
          if (this._model) {
            this._model.updateMaterial(mat);
          }
        };
        _proto.setUseInstance = function setUseInstance(value) {
          if (this._useInstance === value) {
            return;
          }
          this._useInstance = value;
          if (this._model) {
            this._model.useInstance = value;
            this._model.doDestroy();
          }
          this.updateRenderMode();
        };
        _proto.getNoisePreview = function getNoisePreview(out, width, height) {};
        return ParticleSystemRendererGPU;
      }(ParticleSystemRendererBase);

      var _dec$1a, _dec2$14, _dec3$Q, _dec4$E, _dec5$B, _dec6$p, _dec7$l, _dec8$f, _dec9$d, _class$17, _class2$15, _initializer$13, _initializer2$Y, _initializer3$J, _initializer4$B, _initializer5$u, _initializer6$q, _initializer7$l, _initializer8$j, _initializer9$h, _class3$q;
      function isSupportGPUParticle() {
        var device = director.root.device;
        if (device.capabilities.maxVertexTextureUnits >= 8 && device.getFormatFeatures(Format.RGBA32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) {
          return true;
        }
        legacyCC.warn('Maybe the device has restrictions on vertex textures or does not support float textures.');
        return false;
      }
      var ParticleSystemRenderer = (_dec$1a = ccclass$M('cc.ParticleSystemRenderer'), _dec2$14 = type$d(RenderMode), _dec3$Q = type$d(RenderMode), _dec4$E = type$d(Mesh), _dec5$B = type$d(Material), _dec6$p = type$d(Material), _dec7$l = type$d(Material), _dec8$f = type$d(Material), _dec9$d = type$d(AlignmentSpace), _dec$1a(_class$17 = (_class2$15 = (_class3$q = function () {
        function ParticleSystemRenderer() {
          this._renderMode = _initializer$13 && _initializer$13();
          this._velocityScale = _initializer2$Y && _initializer2$Y();
          this._lengthScale = _initializer3$J && _initializer3$J();
          this._mesh = _initializer4$B && _initializer4$B();
          this._cpuMaterial = _initializer5$u && _initializer5$u();
          this._gpuMaterial = _initializer6$q && _initializer6$q();
          this._mainTexture = _initializer7$l && _initializer7$l();
          this._useGPU = _initializer8$j && _initializer8$j();
          this._alignSpace = _initializer9$h && _initializer9$h();
          this._particleSystem = null;
        }
        var _proto = ParticleSystemRenderer.prototype;
        _proto.create = function create(ps) {
          if (this._particleSystem === null) {
            this._particleSystem = ps;
          } else if (this._particleSystem !== ps) {
            errorID(6033);
          }
        };
        _proto.onInit = function onInit(ps) {
          this.create(ps);
          var useGPU = this._useGPU && isSupportGPUParticle();
          if (!this._particleSystem.processor) {
            this._particleSystem.processor = useGPU ? new ParticleSystemRendererGPU(this) : new ParticleSystemRendererCPU(this);
            this._particleSystem.processor.updateAlignSpace(this.alignSpace);
            this._particleSystem.processor.onInit(ps);
          } else {
            errorID(6034);
          }
          if (!useGPU) {
            if (this.particleMaterial && this.particleMaterial.effectName.indexOf('particle-gpu') !== -1) {
              this.particleMaterial = null;
              warnID(6035);
            }
            this.cpuMaterial = this.particleMaterial;
          } else {
            this.gpuMaterial = this.particleMaterial;
          }
        };
        _proto._switchProcessor = function _switchProcessor() {
          if (!this._particleSystem) {
            return;
          }
          if (this._particleSystem.processor) {
            this._particleSystem.processor.detachFromScene();
            this._particleSystem.processor.clear();
            this._particleSystem.processor = null;
          }
          var useGPU = this._useGPU && isSupportGPUParticle();
          if (!useGPU && this.cpuMaterial) {
            this.particleMaterial = this.cpuMaterial;
          }
          if (useGPU && this.gpuMaterial) {
            this.particleMaterial = this.gpuMaterial;
          }
          this._particleSystem.processor = useGPU ? new ParticleSystemRendererGPU(this) : new ParticleSystemRendererCPU(this);
          this._particleSystem.processor.updateAlignSpace(this.alignSpace);
          this._particleSystem.processor.onInit(this._particleSystem);
          this._particleSystem.processor.onEnable();
          this._particleSystem.bindModule();
        };
        _createClass(ParticleSystemRenderer, [{
          key: "renderMode",
          get: function get() {
            return this._renderMode;
          },
          set: function set(val) {
            if (this._renderMode === val) {
              return;
            }
            this._renderMode = val;
            if (this._particleSystem) {
              this._particleSystem.processor.updateRenderMode();
            }
          }
        }, {
          key: "velocityScale",
          get: function get() {
            return this._velocityScale;
          },
          set: function set(val) {
            this._velocityScale = val;
            if (this._particleSystem) {
              this._particleSystem.processor.updateMaterialParams();
            }
          }
        }, {
          key: "lengthScale",
          get: function get() {
            return this._lengthScale;
          },
          set: function set(val) {
            this._lengthScale = val;
            if (this._particleSystem) {
              this._particleSystem.processor.updateMaterialParams();
            }
          }
        }, {
          key: "mesh",
          get: function get() {
            return this._mesh;
          },
          set: function set(val) {
            this._mesh = val;
            if (this._particleSystem) {
              this._particleSystem.processor.setVertexAttributes();
            }
          }
        }, {
          key: "particleMaterial",
          get: function get() {
            if (!this._particleSystem) {
              return null;
            }
            return this._particleSystem.getSharedMaterial(0);
          },
          set: function set(val) {
            if (this._particleSystem) {
              this._particleSystem.setSharedMaterial(val, 0);
            }
          }
        }, {
          key: "cpuMaterial",
          get: function get() {
            return this._cpuMaterial;
          },
          set: function set(val) {
            if (val === null) {
              return;
            } else {
              var effectName = val.effectName;
              if (effectName.indexOf('particle') === -1 || effectName.indexOf('particle-gpu') !== -1) {
                warnID(6035);
                return;
              }
            }
            this._cpuMaterial = val;
            this.particleMaterial = this._cpuMaterial;
          }
        }, {
          key: "gpuMaterial",
          get: function get() {
            return this._gpuMaterial;
          },
          set: function set(val) {
            if (val === null) {
              return;
            } else {
              var effectName = val.effectName;
              if (effectName.indexOf('particle-gpu') === -1) {
                warnID(6035);
                return;
              }
            }
            this._gpuMaterial = val;
            this.particleMaterial = this._gpuMaterial;
          }
        }, {
          key: "trailMaterial",
          get: function get() {
            if (!this._particleSystem) {
              return null;
            }
            return this._particleSystem.getSharedMaterial(1);
          },
          set: function set(val) {
            if (this._particleSystem) {
              this._particleSystem.setSharedMaterial(val, 1);
            }
          }
        }, {
          key: "mainTexture",
          get: function get() {
            return this._mainTexture;
          },
          set: function set(val) {
            this._mainTexture = val;
          }
        }, {
          key: "useGPU",
          get: function get() {
            return this._useGPU;
          },
          set: function set(val) {
            if (this._useGPU === val) {
              return;
            }
            if (!isSupportGPUParticle()) {
              this._useGPU = false;
            } else {
              this._useGPU = val;
            }
            this._switchProcessor();
          }
        }, {
          key: "alignSpace",
          get: function get() {
            return this._alignSpace;
          },
          set: function set(val) {
            this._alignSpace = val;
            this._particleSystem.processor.updateAlignSpace(this._alignSpace);
          }
        }]);
        return ParticleSystemRenderer;
      }(), _class3$q.AlignmentSpace = AlignmentSpace, _class3$q), (_applyDecoratedDescriptor(_class2$15.prototype, "renderMode", [_dec2$14], Object.getOwnPropertyDescriptor(_class2$15.prototype, "renderMode"), _class2$15.prototype), _initializer$13 = applyDecoratedInitializer(_class2$15.prototype, "_renderMode", [_dec3$Q, serializable$p], function () {
        return RenderMode.Billboard;
      }), _initializer2$Y = applyDecoratedInitializer(_class2$15.prototype, "_velocityScale", [serializable$p], function () {
        return 1;
      }), _initializer3$J = applyDecoratedInitializer(_class2$15.prototype, "_lengthScale", [serializable$p], function () {
        return 1;
      }), _initializer4$B = applyDecoratedInitializer(_class2$15.prototype, "_mesh", [serializable$p], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$15.prototype, "mesh", [_dec4$E], Object.getOwnPropertyDescriptor(_class2$15.prototype, "mesh"), _class2$15.prototype), _applyDecoratedDescriptor(_class2$15.prototype, "particleMaterial", [_dec5$B], Object.getOwnPropertyDescriptor(_class2$15.prototype, "particleMaterial"), _class2$15.prototype), _applyDecoratedDescriptor(_class2$15.prototype, "cpuMaterial", [_dec6$p], Object.getOwnPropertyDescriptor(_class2$15.prototype, "cpuMaterial"), _class2$15.prototype), _initializer5$u = applyDecoratedInitializer(_class2$15.prototype, "_cpuMaterial", [serializable$p], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$15.prototype, "gpuMaterial", [_dec7$l], Object.getOwnPropertyDescriptor(_class2$15.prototype, "gpuMaterial"), _class2$15.prototype), _initializer6$q = applyDecoratedInitializer(_class2$15.prototype, "_gpuMaterial", [serializable$p], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$15.prototype, "trailMaterial", [_dec8$f], Object.getOwnPropertyDescriptor(_class2$15.prototype, "trailMaterial"), _class2$15.prototype), _initializer7$l = applyDecoratedInitializer(_class2$15.prototype, "_mainTexture", [serializable$p], function () {
        return null;
      }), _initializer8$j = applyDecoratedInitializer(_class2$15.prototype, "_useGPU", [serializable$p], function () {
        return false;
      }), _applyDecoratedDescriptor(_class2$15.prototype, "alignSpace", [_dec9$d], Object.getOwnPropertyDescriptor(_class2$15.prototype, "alignSpace"), _class2$15.prototype), _initializer9$h = applyDecoratedInitializer(_class2$15.prototype, "_alignSpace", [serializable$p], function () {
        return AlignmentSpace.View;
      })), _class2$15)) || _class$17);

      var _dec$19, _dec2$13, _dec3$P, _dec4$D, _dec5$A, _dec6$o, _dec7$k, _dec8$e, _dec9$c, _class2$14, _class3$p, _initializer$12, _initializer2$X, _initializer3$I, _initializer4$A, _initializer5$t, _initializer6$p, _initializer7$k, _initializer8$i, _initializer9$g, _initializer10$f, _initializer11$f, _initializer12$d, _initializer13$a;
      var PRE_TRIANGLE_INDEX = 1;
      var NEXT_TRIANGLE_INDEX = 1 << 2;
      var DIRECTION_THRESHOLD = Math.cos(toRadian(100));
      var _temp_trailEle = {
        position: new Vec3(),
        velocity: new Vec3()
      };
      var _temp_quat = new Quat();
      var _temp_vec3 = new Vec3();
      var _temp_vec3_1 = new Vec3();
      var _temp_color = new Color$1();
      var TrailSegment = function () {
        function TrailSegment(maxTrailElementNum) {
          this.start = void 0;
          this.end = void 0;
          this.trailElements = void 0;
          this.start = -1;
          this.end = -1;
          this.trailElements = [];
          while (maxTrailElementNum--) {
            this.trailElements.push({
              position: new Vec3(),
              lifetime: 0,
              width: 0,
              velocity: new Vec3(),
              direction: 0,
              color: new Color$1()
            });
          }
        }
        var _proto = TrailSegment.prototype;
        _proto.getElement = function getElement(idx) {
          if (this.start === -1) {
            return null;
          }
          if (idx < 0) {
            idx = (idx + this.trailElements.length) % this.trailElements.length;
          }
          if (idx >= this.trailElements.length) {
            idx %= this.trailElements.length;
          }
          return this.trailElements[idx];
        };
        _proto.addElement = function addElement() {
          if (this.trailElements.length === 0) {
            return null;
          }
          if (this.start === -1) {
            this.start = 0;
            this.end = 1;
            return this.trailElements[0];
          }
          if (this.start === this.end) {
            this.trailElements.splice(this.end, 0, {
              position: new Vec3(),
              lifetime: 0,
              width: 0,
              velocity: new Vec3(),
              direction: 0,
              color: new Color$1()
            });
            this.start++;
            this.start %= this.trailElements.length;
          }
          var newEleLoc = this.end++;
          this.end %= this.trailElements.length;
          return this.trailElements[newEleLoc];
        };
        _proto.iterateElement = function iterateElement(target, f, p, dt) {
          var end = this.start >= this.end ? this.end + this.trailElements.length : this.end;
          for (var i = this.start; i < end; i++) {
            if (f(target, this.trailElements[i % this.trailElements.length], p, dt)) {
              this.start++;
              this.start %= this.trailElements.length;
            }
          }
          if (this.start === end) {
            this.start = -1;
            this.end = -1;
          }
        };
        _proto.count = function count() {
          if (this.start < this.end) {
            return this.end - this.start;
          } else {
            return this.trailElements.length + this.end - this.start;
          }
        };
        _proto.clear = function clear() {
          this.start = -1;
          this.end = -1;
        };
        return TrailSegment;
      }();
      var TrailModule = (_dec$19 = ccclass$M('cc.TrailModule'), _dec2$13 = type$d(TrailMode), _dec3$P = type$d(CurveRange), _dec4$D = type$d(Space), _dec5$A = type$d(TextureMode), _dec6$o = type$d(CurveRange), _dec7$k = type$d(GradientRange), _dec8$e = type$d(GradientRange), _dec9$c = type$d(Space), _dec$19(_class2$14 = (_class3$p = function () {
        var _proto2 = TrailModule.prototype;
        _proto2.getModel = function getModel() {
          return this._trailModel;
        };
        function TrailModule() {
          this._enable = _initializer$12 && _initializer$12();
          this.mode = _initializer2$X && _initializer2$X();
          this.lifeTime = _initializer3$I && _initializer3$I();
          this._minParticleDistance = _initializer4$A && _initializer4$A();
          this.existWithParticles = _initializer5$t && _initializer5$t();
          this.textureMode = _initializer6$p && _initializer6$p();
          this.widthFromParticle = _initializer7$k && _initializer7$k();
          this.widthRatio = _initializer8$i && _initializer8$i();
          this.colorFromParticle = _initializer9$g && _initializer9$g();
          this.colorOverTrail = _initializer10$f && _initializer10$f();
          this.colorOvertime = _initializer11$f && _initializer11$f();
          this._space = _initializer12$d && _initializer12$d();
          this._particleSystem = _initializer13$a && _initializer13$a();
          this._minSquaredDistance = 0;
          this._vertSize = void 0;
          this._trailNum = 0;
          this._trailLifetime = 0;
          this.vbOffset = 0;
          this.ibOffset = 0;
          this._trailSegments = null;
          this._particleTrail = void 0;
          this._trailModel = null;
          this._subMeshData = null;
          this._vertAttrs = void 0;
          this._vbF32 = null;
          this._vbUint32 = null;
          this._iBuffer = null;
          this._needTransform = false;
          this._material = null;
          this._psTransform = new Mat4();
          this._iaVertCount = 0;
          this._iaIndexCount = 0;
          this._inited = void 0;
          this._vertAttrs = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGBA32F), new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true)];
          this._vertSize = 0;
          for (var _iterator = _createForOfIteratorHelperLoose(this._vertAttrs), _step; !(_step = _iterator()).done;) {
            var a = _step.value;
            this._vertSize += FormatInfos[a.format].size;
          }
          this._particleTrail = new Map();
          this._inited = false;
        }
        _proto2.onInit = function onInit(ps) {
          this._particleSystem = ps;
          this.minParticleDistance = this._minParticleDistance;
          var burstCount = 0;
          var psTime = ps.startLifetime.getMax();
          var psRate = ps.rateOverTime.getMax();
          var duration = ps.duration;
          for (var i = 0, len = ps.bursts.length; i < len; i++) {
            var b = ps.bursts[i];
            burstCount += b.getMaxCount(ps) * Math.ceil(psTime / duration);
          }
          if (this.lifeTime.getMax() < 1.0) {
            warnID(6036);
          }
          this._trailNum = Math.ceil(psTime * Math.ceil(this.lifeTime.getMax()) * 60 * (psRate * duration + burstCount));
          this._trailSegments = new Pool(function () {
            return new TrailSegment(10);
          }, Math.ceil(psRate * duration), function (obj) {
            return obj.trailElements.length = 0;
          });
          if (this._enable) {
            this.enable = this._enable;
          }
          this._inited = true;
        };
        _proto2.onEnable = function onEnable() {
          this._attachToScene();
        };
        _proto2.onDisable = function onDisable() {
          this._particleTrail.clear();
          this._detachFromScene();
        };
        _proto2._attachToScene = function _attachToScene() {
          if (this._trailModel) {
            if (this._trailModel.scene) {
              this._detachFromScene();
            }
            this._particleSystem._getRenderScene().addModel(this._trailModel);
          }
        };
        _proto2._detachFromScene = function _detachFromScene() {
          if (this._trailModel && this._trailModel.scene) {
            this._trailModel.scene.removeModel(this._trailModel);
          }
        };
        _proto2.destroy = function destroy() {
          this.destroySubMeshData();
          if (this._trailModel) {
            director.root.destroyModel(this._trailModel);
            this._trailModel = null;
          }
          if (this._trailSegments) {
            this._trailSegments.destroy();
            this._trailSegments = null;
          }
        };
        _proto2.play = function play() {
          if (this._trailModel && this._enable) {
            this._trailModel.enabled = true;
          }
        };
        _proto2.clear = function clear() {
          if (this.enable) {
            var trailIter = this._particleTrail.values();
            var trail = trailIter.next();
            while (!trail.done) {
              trail.value.clear();
              trail = trailIter.next();
            }
            this._particleTrail.clear();
            this.updateRenderData();
            if (this._trailModel) this._trailModel.enabled = false;
          }
        };
        _proto2.updateMaterial = function updateMaterial() {
          if (this._particleSystem) {
            this._material = this._particleSystem.getMaterialInstance(1) || this._particleSystem.processor._defaultTrailMat;
            if (this._trailModel) {
              this._trailModel.setSubModelMaterial(0, this._material);
            }
          }
        };
        _proto2.update = function update() {
          this._trailLifetime = this.lifeTime.evaluate(this._particleSystem._time, 1);
          if (this.space === Space.World && this._particleSystem._simulationSpace === Space.Local) {
            this._needTransform = true;
            this._particleSystem.node.getWorldMatrix(this._psTransform);
            this._particleSystem.node.getWorldRotation(_temp_quat);
          } else {
            this._needTransform = false;
          }
        };
        _proto2.animate = function animate(p, scaledDt) {
          if (!this._trailSegments) {
            return;
          }
          if (p.loopCount > p.lastLoop) {
            if (p.trailDelay > 1) {
              p.lastLoop = p.loopCount;
              p.trailDelay = 0;
            } else {
              p.trailDelay++;
            }
            return;
          }
          var trail = this._particleTrail.get(p);
          if (!trail) {
            trail = this._trailSegments.alloc();
            this._particleTrail.set(p, trail);
            return;
          }
          var lastSeg = trail.getElement(trail.end - 1);
          if (this._needTransform) {
            Vec3.transformMat4(_temp_vec3, p.position, this._psTransform);
          } else {
            Vec3.copy(_temp_vec3, p.position);
          }
          if (lastSeg) {
            trail.iterateElement(this, this._updateTrailElement, p, scaledDt);
            if (Vec3.squaredDistance(lastSeg.position, _temp_vec3) < this._minSquaredDistance) {
              return;
            }
          }
          lastSeg = trail.addElement();
          if (!lastSeg) {
            return;
          }
          Vec3.copy(lastSeg.position, _temp_vec3);
          lastSeg.lifetime = 0;
          if (this.widthFromParticle) {
            lastSeg.width = p.size.x * this.widthRatio.evaluate(0, 1);
          } else {
            lastSeg.width = this.widthRatio.evaluate(0, 1);
          }
          var trailNum = trail.count();
          if (trailNum === 2) {
            var lastSecondTrail = trail.getElement(trail.end - 2);
            Vec3.subtract(lastSecondTrail.velocity, lastSeg.position, lastSecondTrail.position);
          } else if (trailNum > 2) {
            var _lastSecondTrail = trail.getElement(trail.end - 2);
            var lastThirdTrail = trail.getElement(trail.end - 3);
            Vec3.subtract(_temp_vec3, lastThirdTrail.position, _lastSecondTrail.position);
            Vec3.subtract(_temp_vec3_1, lastSeg.position, _lastSecondTrail.position);
            Vec3.subtract(_lastSecondTrail.velocity, _temp_vec3_1, _temp_vec3);
            if (Vec3.equals(Vec3.ZERO, _lastSecondTrail.velocity)) {
              Vec3.copy(_lastSecondTrail.velocity, _temp_vec3);
            }
            Vec3.normalize(_lastSecondTrail.velocity, _lastSecondTrail.velocity);
            this._checkDirectionReverse(_lastSecondTrail, lastThirdTrail);
          }
          if (this.colorFromParticle) {
            lastSeg.color.set(p.color);
          } else {
            lastSeg.color.set(this.colorOvertime.evaluate(0, 1));
          }
        };
        _proto2.removeParticle = function removeParticle(p) {
          var trail = this._particleTrail.get(p);
          if (trail && this._trailSegments) {
            trail.clear();
            this._trailSegments.free(trail);
            this._particleTrail["delete"](p);
          }
        };
        _proto2.updateRenderData = function updateRenderData() {
          this.vbOffset = 0;
          this.ibOffset = 0;
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._particleTrail.keys()), _step2; !(_step2 = _iterator2()).done;) {
            var p = _step2.value;
            var trailSeg = this._particleTrail.get(p);
            if (trailSeg.start === -1) {
              continue;
            }
            var indexOffset = this.vbOffset * 4 / this._vertSize;
            var end = trailSeg.start >= trailSeg.end ? trailSeg.end + trailSeg.trailElements.length : trailSeg.end;
            var trailNum = end - trailSeg.start;
            var textCoordSeg = 1 / trailNum;
            var startSegEle = trailSeg.trailElements[trailSeg.start];
            this._fillVertexBuffer(startSegEle, this.colorOverTrail.evaluate(1, 1), indexOffset, 1, 0, NEXT_TRIANGLE_INDEX);
            for (var i = trailSeg.start + 1; i < end; i++) {
              var segEle = trailSeg.trailElements[i % trailSeg.trailElements.length];
              var j = i - trailSeg.start;
              this._fillVertexBuffer(segEle, this.colorOverTrail.evaluate(1 - j / trailNum, 1), indexOffset, 1 - j * textCoordSeg, j, PRE_TRIANGLE_INDEX | NEXT_TRIANGLE_INDEX);
            }
            if (this._needTransform) {
              Vec3.transformMat4(_temp_trailEle.position, p.position, this._psTransform);
            } else {
              Vec3.copy(_temp_trailEle.position, p.position);
            }
            var trailModel = this._trailModel;
            if (trailModel) {
              trailModel.node.invalidateChildren(TransformBit.POSITION);
            }
            if (trailNum === 1 || trailNum === 2) {
              var lastSecondTrail = trailSeg.getElement(trailSeg.end - 1);
              Vec3.subtract(lastSecondTrail.velocity, _temp_trailEle.position, lastSecondTrail.position);
              this._vbF32[this.vbOffset - this._vertSize / 4 - 4] = lastSecondTrail.velocity.x;
              this._vbF32[this.vbOffset - this._vertSize / 4 - 3] = lastSecondTrail.velocity.y;
              this._vbF32[this.vbOffset - this._vertSize / 4 - 2] = lastSecondTrail.velocity.z;
              this._vbF32[this.vbOffset - 4] = lastSecondTrail.velocity.x;
              this._vbF32[this.vbOffset - 3] = lastSecondTrail.velocity.y;
              this._vbF32[this.vbOffset - 2] = lastSecondTrail.velocity.z;
              Vec3.subtract(_temp_trailEle.velocity, _temp_trailEle.position, lastSecondTrail.position);
              this._checkDirectionReverse(_temp_trailEle, lastSecondTrail);
            } else if (trailNum > 2) {
              var _lastSecondTrail2 = trailSeg.getElement(trailSeg.end - 1);
              var lastThirdTrail = trailSeg.getElement(trailSeg.end - 2);
              Vec3.subtract(_temp_vec3, lastThirdTrail.position, _lastSecondTrail2.position);
              Vec3.subtract(_temp_vec3_1, _temp_trailEle.position, _lastSecondTrail2.position);
              Vec3.normalize(_temp_vec3, _temp_vec3);
              Vec3.normalize(_temp_vec3_1, _temp_vec3_1);
              Vec3.subtract(_lastSecondTrail2.velocity, _temp_vec3_1, _temp_vec3);
              Vec3.normalize(_lastSecondTrail2.velocity, _lastSecondTrail2.velocity);
              this._checkDirectionReverse(_lastSecondTrail2, lastThirdTrail);
              this.vbOffset -= this._vertSize / 4 * 2;
              this.ibOffset -= 6;
              this._fillVertexBuffer(_lastSecondTrail2, this.colorOverTrail.evaluate(textCoordSeg, 1), indexOffset, textCoordSeg, trailNum - 1, PRE_TRIANGLE_INDEX | NEXT_TRIANGLE_INDEX);
              Vec3.subtract(_temp_trailEle.velocity, _temp_trailEle.position, _lastSecondTrail2.position);
              Vec3.normalize(_temp_trailEle.velocity, _temp_trailEle.velocity);
              this._checkDirectionReverse(_temp_trailEle, _lastSecondTrail2);
            }
            if (this.widthFromParticle) {
              _temp_trailEle.width = p.size.x * this.widthRatio.evaluate(0, 1);
            } else {
              _temp_trailEle.width = this.widthRatio.evaluate(0, 1);
            }
            _temp_trailEle.color = p.color;
            if (Vec3.equals(_temp_trailEle.velocity, Vec3.ZERO)) {
              this.ibOffset -= 3;
            } else {
              this._fillVertexBuffer(_temp_trailEle, this.colorOverTrail.evaluate(0, 1), indexOffset, 0, trailNum, PRE_TRIANGLE_INDEX);
            }
          }
          if (this._trailModel) {
            this._trailModel.enabled = this.ibOffset > 0;
          }
        };
        _proto2.updateIA = function updateIA(count) {
          var subModels = this._trailModel && this._trailModel.subModels;
          if (subModels && subModels.length > 0) {
            var subModel = subModels[0];
            subModel.inputAssembler.vertexBuffers[0].update(this._vbF32);
            subModel.inputAssembler.indexBuffer.update(this._iBuffer);
            subModel.inputAssembler.firstIndex = 0;
            subModel.inputAssembler.indexCount = count;
            subModel.inputAssembler.vertexCount = this._iaVertCount;
          }
        };
        _proto2.beforeRender = function beforeRender() {
          this.updateIA(this.ibOffset);
        };
        _proto2._createModel = function _createModel() {
          if (this._trailModel) {
            return;
          }
          this._trailModel = legacyCC.director.root.createModel(Model);
        };
        _proto2.rebuild = function rebuild() {
          var device = director.root.device;
          var vertexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, this._vertSize * (this._trailNum + 1) * 2, this._vertSize));
          var vBuffer = new ArrayBuffer(this._vertSize * (this._trailNum + 1) * 2);
          this._vbF32 = new Float32Array(vBuffer);
          this._vbUint32 = new Uint32Array(vBuffer);
          vertexBuffer.update(vBuffer);
          var indexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, Math.max(1, this._trailNum) * 6 * Uint16Array.BYTES_PER_ELEMENT, Uint16Array.BYTES_PER_ELEMENT));
          this._iBuffer = new Uint16Array(Math.max(1, this._trailNum) * 6);
          indexBuffer.update(this._iBuffer);
          this._iaVertCount = (this._trailNum + 1) * 2;
          this._iaIndexCount = this._trailNum * 6;
          this._subMeshData = new RenderingSubMesh([vertexBuffer], this._vertAttrs, PrimitiveMode.TRIANGLE_LIST, indexBuffer);
          var trailModel = this._trailModel;
          if (trailModel && this._material) {
            trailModel.node = trailModel.transform = this._particleSystem.node;
            trailModel.visFlags = this._particleSystem.visibility;
            trailModel.initSubModel(0, this._subMeshData, this._material);
            trailModel.enabled = true;
          }
        };
        _proto2._updateTrailElement = function _updateTrailElement(module, trailEle, p, dt) {
          trailEle.lifetime += dt;
          if (module.colorFromParticle) {
            trailEle.color.set(p.color);
            trailEle.color.multiply(module.colorOvertime.evaluate(1.0 - p.remainingLifetime / p.startLifetime, 1));
          } else {
            trailEle.color.set(module.colorOvertime.evaluate(1.0 - p.remainingLifetime / p.startLifetime, 1));
          }
          if (module.widthFromParticle) {
            trailEle.width = p.size.x * module.widthRatio.evaluate(trailEle.lifetime / module._trailLifetime, 1);
          } else {
            trailEle.width = module.widthRatio.evaluate(trailEle.lifetime / module._trailLifetime, 1);
          }
          return trailEle.lifetime > module._trailLifetime;
        };
        _proto2._fillVertexBuffer = function _fillVertexBuffer(trailSeg, colorModifer, indexOffset, xTexCoord, trailEleIdx, indexSet) {
          this._vbF32[this.vbOffset++] = trailSeg.position.x;
          this._vbF32[this.vbOffset++] = trailSeg.position.y;
          this._vbF32[this.vbOffset++] = trailSeg.position.z;
          this._vbF32[this.vbOffset++] = trailSeg.direction;
          this._vbF32[this.vbOffset++] = trailSeg.width;
          this._vbF32[this.vbOffset++] = xTexCoord;
          this._vbF32[this.vbOffset++] = 0;
          this._vbF32[this.vbOffset++] = trailSeg.velocity.x;
          this._vbF32[this.vbOffset++] = trailSeg.velocity.y;
          this._vbF32[this.vbOffset++] = trailSeg.velocity.z;
          _temp_color.set(trailSeg.color);
          _temp_color.multiply(colorModifer);
          this._vbUint32[this.vbOffset++] = _temp_color._val;
          this._vbF32[this.vbOffset++] = trailSeg.position.x;
          this._vbF32[this.vbOffset++] = trailSeg.position.y;
          this._vbF32[this.vbOffset++] = trailSeg.position.z;
          this._vbF32[this.vbOffset++] = 1 - trailSeg.direction;
          this._vbF32[this.vbOffset++] = trailSeg.width;
          this._vbF32[this.vbOffset++] = xTexCoord;
          this._vbF32[this.vbOffset++] = 1;
          this._vbF32[this.vbOffset++] = trailSeg.velocity.x;
          this._vbF32[this.vbOffset++] = trailSeg.velocity.y;
          this._vbF32[this.vbOffset++] = trailSeg.velocity.z;
          this._vbUint32[this.vbOffset++] = _temp_color._val;
          if (indexSet & PRE_TRIANGLE_INDEX) {
            this._iBuffer[this.ibOffset++] = indexOffset + 2 * trailEleIdx;
            this._iBuffer[this.ibOffset++] = indexOffset + 2 * trailEleIdx - 1;
            this._iBuffer[this.ibOffset++] = indexOffset + 2 * trailEleIdx + 1;
          }
          if (indexSet & NEXT_TRIANGLE_INDEX) {
            this._iBuffer[this.ibOffset++] = indexOffset + 2 * trailEleIdx;
            this._iBuffer[this.ibOffset++] = indexOffset + 2 * trailEleIdx + 1;
            this._iBuffer[this.ibOffset++] = indexOffset + 2 * trailEleIdx + 2;
          }
        };
        _proto2._checkDirectionReverse = function _checkDirectionReverse(currElement, prevElement) {
          if (Vec3.dot(currElement.velocity, prevElement.velocity) < DIRECTION_THRESHOLD) {
            currElement.direction = 1 - prevElement.direction;
          } else {
            currElement.direction = prevElement.direction;
          }
        };
        _proto2.destroySubMeshData = function destroySubMeshData() {
          if (this._subMeshData) {
            this._subMeshData.destroy();
            this._subMeshData = null;
          }
        };
        _createClass(TrailModule, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(val) {
            if (val === this._enable && this._trailModel) {
              return;
            }
            if (val && !this._enable) {
              this._enable = val;
              if (this._particleSystem.processor) this._particleSystem.processor.updateTrailMaterial();
            }
            if (val && !this._trailModel) {
              this._createModel();
              this.rebuild();
            }
            this._enable = val;
            if (this._trailModel) {
              this._trailModel.enabled = val;
            }
            if (val) this.onEnable();else this.onDisable();
          }
        }, {
          key: "minParticleDistance",
          get: function get() {
            return this._minParticleDistance;
          },
          set: function set(val) {
            this._minParticleDistance = val;
            this._minSquaredDistance = val * val;
          }
        }, {
          key: "space",
          get: function get() {
            return this._space;
          },
          set: function set(val) {
            this._space = val;
            var ps = this._particleSystem;
            if (ps && ps.processor) {
              ps.processor.updateTrailMaterial();
            }
          }
        }, {
          key: "inited",
          get: function get() {
            return this._inited;
          }
        }]);
        return TrailModule;
      }(), (_initializer$12 = applyDecoratedInitializer(_class3$p.prototype, "_enable", [serializable$p], function () {
        return false;
      }), _initializer2$X = applyDecoratedInitializer(_class3$p.prototype, "mode", [_dec2$13, serializable$p], function () {
        return TrailMode.Particles;
      }), _initializer3$I = applyDecoratedInitializer(_class3$p.prototype, "lifeTime", [_dec3$P, serializable$p], function () {
        return new CurveRange();
      }), _initializer4$A = applyDecoratedInitializer(_class3$p.prototype, "_minParticleDistance", [serializable$p], function () {
        return 0.1;
      }), _applyDecoratedDescriptor(_class3$p.prototype, "space", [_dec4$D], Object.getOwnPropertyDescriptor(_class3$p.prototype, "space"), _class3$p.prototype), _initializer5$t = applyDecoratedInitializer(_class3$p.prototype, "existWithParticles", [serializable$p], function () {
        return true;
      }), _initializer6$p = applyDecoratedInitializer(_class3$p.prototype, "textureMode", [_dec5$A, serializable$p], function () {
        return TextureMode.Stretch;
      }), _initializer7$k = applyDecoratedInitializer(_class3$p.prototype, "widthFromParticle", [serializable$p], function () {
        return true;
      }), _initializer8$i = applyDecoratedInitializer(_class3$p.prototype, "widthRatio", [_dec6$o, serializable$p], function () {
        return new CurveRange();
      }), _initializer9$g = applyDecoratedInitializer(_class3$p.prototype, "colorFromParticle", [serializable$p], function () {
        return false;
      }), _initializer10$f = applyDecoratedInitializer(_class3$p.prototype, "colorOverTrail", [_dec7$k, serializable$p], function () {
        return new GradientRange();
      }), _initializer11$f = applyDecoratedInitializer(_class3$p.prototype, "colorOvertime", [_dec8$e, serializable$p], function () {
        return new GradientRange();
      }), _initializer12$d = applyDecoratedInitializer(_class3$p.prototype, "_space", [_dec9$c], function () {
        return Space.World;
      }), _initializer13$a = applyDecoratedInitializer(_class3$p.prototype, "_particleSystem", [serializable$p], function () {
        return null;
      })), _class3$p)) || _class2$14);

      var _node_mat = new Mat4();
      var _node_parent_inv = new Mat4();
      var _node_rol = new Quat();
      var _node_scale = new Vec3();
      var _anim_module = ['_colorOverLifetimeModule', '_sizeOvertimeModule', '_velocityOvertimeModule', '_forceOvertimeModule', '_limitVelocityOvertimeModule', '_rotationOvertimeModule', '_textureAnimationModule'];
      var ParticleCuller = function () {
        function ParticleCuller(ps) {
          this._particleSystem = void 0;
          this._processor = void 0;
          this._node = void 0;
          this._particlesAll = void 0;
          this._updateList = new Map();
          this._animateList = new Map();
          this._runAnimateList = new Array();
          this._localMat = new Mat4();
          this._gravity = new Vec4();
          this.minPos = new Vec3();
          this.maxPos = new Vec3();
          this._nodePos = new Vec3();
          this._nodeSize = new Vec3();
          this._particleSystem = ps;
          this._processor = this._particleSystem.processor;
          this._node = ps.node;
          this._particlesAll = [];
          this._initModuleList();
        }
        var _proto = ParticleCuller.prototype;
        _proto._updateBoundingNode = function _updateBoundingNode() {
          this._nodeSize.set(this.maxPos.x - this.minPos.x, this.maxPos.y - this.minPos.y, this.maxPos.z - this.minPos.z);
          this._nodePos.set(this.minPos.x + this._nodeSize.x * 0.5, this.minPos.y + this._nodeSize.y * 0.5, this.minPos.z + this._nodeSize.z * 0.5);
        };
        _proto.setBoundingBoxSize = function setBoundingBoxSize(halfExt) {
          this.maxPos.x = this._nodePos.x + halfExt.x;
          this.maxPos.y = this._nodePos.y + halfExt.y;
          this.maxPos.z = this._nodePos.z + halfExt.z;
          this.minPos.x = this._nodePos.x - halfExt.x;
          this.minPos.y = this._nodePos.y - halfExt.y;
          this.minPos.z = this._nodePos.z - halfExt.z;
          this._updateBoundingNode();
        };
        _proto.setBoundingBoxCenter = function setBoundingBoxCenter(px, py, pz) {
          this.maxPos.x = px + this._nodeSize.x * 0.5;
          this.maxPos.y = py + this._nodeSize.y * 0.5;
          this.maxPos.z = pz + this._nodeSize.z * 0.5;
          this.minPos.x = px - this._nodeSize.x * 0.5;
          this.minPos.y = py - this._nodeSize.y * 0.5;
          this.minPos.z = pz - this._nodeSize.z * 0.5;
          this._updateBoundingNode();
        };
        _proto._initModuleList = function _initModuleList() {
          var _this = this;
          _anim_module.forEach(function (val) {
            var pm = _this._particleSystem[val];
            if (pm && pm.enable) {
              if (pm.needUpdate) {
                _this._updateList[pm.name] = pm;
              }
              if (pm.needAnimate) {
                _this._animateList[pm.name] = pm;
              }
            }
          });
          this._runAnimateList.length = 0;
          for (var i = 0, len = PARTICLE_MODULE_ORDER.length; i < len; i++) {
            var p = this._animateList[PARTICLE_MODULE_ORDER[i]];
            if (p) {
              this._runAnimateList.push(p);
            }
          }
        };
        _proto._emit = function _emit(count, dt, particleLst) {
          var ps = this._particleSystem;
          var node = this._node;
          var loopDelta = ps.time % ps.duration / ps.duration;
          node.invalidateChildren(TransformBit.POSITION);
          if (ps.simulationSpace === Space.World) {
            node.getWorldMatrix(_node_mat);
            node.getWorldRotation(_node_rol);
          }
          for (var i = 0; i < count; ++i) {
            var particle = new Particle$1(ps);
            particle.particleSystem = ps;
            particle.reset();
            var rand = pseudoRandom(randomRangeInt(0, INT_MAX));
            if (ps._shapeModule && ps._shapeModule.enable) {
              ps._shapeModule.emit(particle);
            } else {
              Vec3.set(particle.position, 0, 0, 0);
              Vec3.copy(particle.velocity, particleEmitZAxis);
            }
            if (ps._textureAnimationModule && ps._textureAnimationModule.enable) {
              ps._textureAnimationModule.init(particle);
            }
            var curveStartSpeed = ps.startSpeed.evaluate(loopDelta, rand);
            Vec3.multiplyScalar(particle.velocity, particle.velocity, curveStartSpeed);
            if (ps.simulationSpace === Space.World) {
              Vec3.transformMat4(particle.position, particle.position, _node_mat);
              Vec3.transformQuat(particle.velocity, particle.velocity, _node_rol);
            }
            Vec3.copy(particle.ultimateVelocity, particle.velocity);
            Vec3.set(particle.rotation, 0, 0, 0);
            if (ps.startSize3D) {
              Vec3.set(particle.startSize, ps.startSizeX.evaluate(loopDelta, rand), ps.startSizeY.evaluate(loopDelta, rand), ps.startSizeZ.evaluate(loopDelta, rand));
            } else {
              Vec3.set(particle.startSize, ps.startSizeX.evaluate(loopDelta, rand), 1, 1);
              particle.startSize.y = particle.startSize.x;
            }
            Vec3.copy(particle.size, particle.startSize);
            particle.startLifetime = ps.startLifetime.evaluate(loopDelta, rand) + dt;
            particle.remainingLifetime = particle.startLifetime;
            particleLst.push(particle);
          }
        };
        _proto._updateParticles = function _updateParticles(dt, particleLst) {
          var _this2 = this;
          var ps = this._particleSystem;
          ps.node.getWorldMatrix(_node_mat);
          switch (ps.scaleSpace) {
            case Space.Local:
              ps.node.getScale(_node_scale);
              break;
            case Space.World:
              ps.node.getWorldScale(_node_scale);
              break;
          }
          this._updateList.forEach(function (value, key) {
            value.update(ps.simulationSpace, _node_mat);
          });
          if (ps.simulationSpace === Space.Local) {
            var r = ps.node.getRotation();
            Mat4.fromQuat(this._localMat, r);
            this._localMat.transpose();
          }
          if (ps.node.parent) {
            ps.node.parent.getWorldMatrix(_node_parent_inv);
            _node_parent_inv.invert();
          }
          var _loop = function _loop() {
            var p = particleLst[i];
            p.remainingLifetime -= dt;
            Vec3.set(p.animatedVelocity, 0, 0, 0);
            var useGravity = ps.gravityModifier.mode !== Mode$3.Constant || ps.gravityModifier.constant !== 0;
            if (useGravity) {
              var rand = isCurveTwoValues(ps.gravityModifier) ? pseudoRandom(p.randomSeed) : 0;
              if (ps.simulationSpace === Space.Local) {
                var gravityFactor = -ps.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, rand) * 9.8 * dt;
                _this2._gravity.x = 0.0;
                _this2._gravity.y = gravityFactor;
                _this2._gravity.z = 0.0;
                _this2._gravity.w = 1.0;
                if (!approx(gravityFactor, 0.0, EPSILON$3)) {
                  if (ps.node.parent) {
                    _this2._gravity = _this2._gravity.transformMat4(_node_parent_inv);
                  }
                  _this2._gravity = _this2._gravity.transformMat4(_this2._localMat);
                  p.velocity.x += _this2._gravity.x;
                  p.velocity.y += _this2._gravity.y;
                  p.velocity.z += _this2._gravity.z;
                }
              } else {
                p.velocity.y -= ps.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, rand) * 9.8 * dt;
              }
            }
            Vec3.copy(p.ultimateVelocity, p.velocity);
            _this2._runAnimateList.forEach(function (value) {
              value.animate(p, dt);
            });
            Vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt);
          };
          for (var i = 0; i < particleLst.length; ++i) {
            _loop();
          }
        };
        _proto._calculateBounding = function _calculateBounding(isInit) {
          var size = new Vec3();
          var position = new Vec3();
          var subPos = new Vec3();
          var addPos = new Vec3();
          var meshSize = new Vec3(1.0, 1.0, 1.0);
          if (this._processor.getInfo().renderMode === RenderMode.Mesh) {
            var mesh = this._processor.getInfo().mesh;
            if (mesh && mesh.struct.minPosition && mesh.struct.maxPosition) {
              var meshAABB = new AABB();
              AABB.fromPoints(meshAABB, mesh.struct.minPosition, mesh.struct.maxPosition);
              var meshMax = Math.max(meshAABB.halfExtents.x, meshAABB.halfExtents.y, meshAABB.halfExtents.z);
              meshSize.set(meshMax, meshMax, meshMax);
            }
          }
          var worldMat = this._particleSystem.node.worldMatrix;
          for (var i = 0; i < this._particlesAll.length; ++i) {
            var p = this._particlesAll[i];
            Vec3.multiply(size, _node_scale, p.size);
            Vec3.multiply(size, size, meshSize);
            position.set(p.position);
            if (this._particleSystem.simulationSpace !== Space.World) {
              Vec3.transformMat4(position, position, worldMat);
            }
            if (isInit && i === 0) {
              Vec3.subtract(this.minPos, position, size);
              Vec3.add(this.maxPos, position, size);
            } else {
              Vec3.subtract(subPos, position, size);
              Vec3.add(addPos, position, size);
              Vec3.min(this.minPos, this.minPos, subPos);
              Vec3.max(this.maxPos, this.maxPos, addPos);
            }
          }
        };
        _proto.calculatePositions = function calculatePositions() {
          this._emit(this._particleSystem.capacity, 0, this._particlesAll);
          var rand = isCurveTwoValues(this._particleSystem.startLifetime) ? pseudoRandom(randomRangeInt(0, INT_MAX)) : 0;
          this._updateParticles(0, this._particlesAll);
          this._calculateBounding(true);
          this._updateParticles(this._particleSystem.startLifetime.evaluate(0, rand), this._particlesAll);
          this._calculateBounding(false);
          this._updateBoundingNode();
        };
        _proto.clear = function clear() {
          this._particlesAll.length = 0;
        };
        _proto.destroy = function destroy() {};
        return ParticleCuller;
      }();

      var _dec$18, _dec2$12, _dec3$O, _dec4$C, _dec5$z, _dec6$n, _dec7$j, _dec8$d, _dec9$b, _dec10$7, _dec11$5, _dec12$4, _dec13$4, _dec14$3, _class$16, _class2$13, _initializer$11, _initializer2$W, _initializer3$H, _initializer4$z, _initializer5$s, _initializer6$o, _initializer7$j, _initializer8$h, _initializer9$f, _initializer10$e, _initializer11$e, _initializer12$c, _initializer13$9, _initializer14$8;
      var ccclass$f = ccclass$M,
        serializable$1 = serializable$p,
        type$3 = type$d;
      var NoiseModule = (_dec$18 = ccclass$f('cc.NoiseModule'), _dec2$12 = type$3(CCFloat), _dec3$O = type$3(CCFloat), _dec4$C = type$3(CCFloat), _dec5$z = type$3(CCFloat), _dec6$n = type$3(CCFloat), _dec7$j = type$3(CCFloat), _dec8$d = type$3(CCFloat), _dec9$b = type$3(CCFloat), _dec10$7 = type$3(CCFloat), _dec11$5 = type$3(CCFloat), _dec12$4 = type$3(CCInteger), _dec13$4 = type$3(CCFloat), _dec14$3 = type$3(CCFloat), _dec$18(_class$16 = (_class2$13 = function (_ParticleModuleBase) {
        _inheritsLoose(NoiseModule, _ParticleModuleBase);
        function NoiseModule() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ParticleModuleBase.call.apply(_ParticleModuleBase, [this].concat(args)) || this;
          _this._enable = _initializer$11 && _initializer$11();
          _this._strengthX = _initializer2$W && _initializer2$W();
          _this._strengthY = _initializer3$H && _initializer3$H();
          _this._strengthZ = _initializer4$z && _initializer4$z();
          _this._noiseSpeedX = _initializer5$s && _initializer5$s();
          _this._noiseSpeedY = _initializer6$o && _initializer6$o();
          _this._noiseSpeedZ = _initializer7$j && _initializer7$j();
          _this._noiseFrequency = _initializer8$h && _initializer8$h();
          _this._remapX = _initializer9$f && _initializer9$f();
          _this._remapY = _initializer10$e && _initializer10$e();
          _this._remapZ = _initializer11$e && _initializer11$e();
          _this._octaves = _initializer12$c && _initializer12$c();
          _this._octaveMultiplier = _initializer13$9 && _initializer13$9();
          _this._octaveScale = _initializer14$8 && _initializer14$8();
          _this.name = PARTICLE_MODULE_NAME.NOISE;
          _this.noise = new ParticleNoise();
          _this.samplePosition = new Vec3();
          return _this;
        }
        var _proto = NoiseModule.prototype;
        _proto.animate = function animate(particle, dt) {
          this.noise.setTime(particle.particleSystem.time);
          this.noise.setSpeed(this.noiseSpeedX, this.noiseSpeedY, this.noiseSpeedZ);
          this.noise.setFrequency(this.noiseFrequency);
          this.noise.setAbs(this.remapX, this.remapY, this.remapZ);
          this.noise.setAmplititude(this.strengthX, this.strengthY, this.strengthZ);
          this.noise.setOctaves(this.octaves, this.octaveMultiplier, this.octaveScale);
          this.samplePosition.set(particle.position);
          this.samplePosition.add3f(random() * 1.0, random() * 1.0, random() * 1.0);
          this.noise.setSamplePoint(this.samplePosition);
          this.noise.getNoiseParticle();
          var noisePosition = this.noise.getResult();
          noisePosition.multiply3f(random(), random(), random());
          Vec3.add(particle.position, particle.position, noisePosition.multiplyScalar(dt));
        };
        _proto.getNoisePreview = function getNoisePreview(out, ps, width, height) {
          this.noise.setTime(ps.time);
          this.noise.setSpeed(this.noiseSpeedX, this.noiseSpeedY, this.noiseSpeedZ);
          this.noise.setFrequency(this.noiseFrequency);
          this.noise.setAbs(this.remapX, this.remapY, this.remapZ);
          this.noise.setAmplititude(this.strengthX, this.strengthY, this.strengthZ);
          this.noise.setOctaves(this.octaves, this.octaveMultiplier, this.octaveScale);
          this.noise.getNoiseParticle();
          this.noise.getPreview(out, width, height);
        };
        _createClass(NoiseModule, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(val) {
            if (this._enable === val) return;
            this._enable = val;
            if (!this.target) return;
            this.target.enableModule(this.name, val, this);
          }
        }, {
          key: "strengthX",
          get: function get() {
            return this._strengthX;
          },
          set: function set(value) {
            this._strengthX = value;
          }
        }, {
          key: "strengthY",
          get: function get() {
            return this._strengthY;
          },
          set: function set(value) {
            this._strengthY = value;
          }
        }, {
          key: "strengthZ",
          get: function get() {
            return this._strengthZ;
          },
          set: function set(value) {
            this._strengthZ = value;
          }
        }, {
          key: "noiseSpeedX",
          get: function get() {
            return this._noiseSpeedX;
          },
          set: function set(value) {
            this._noiseSpeedX = value;
          }
        }, {
          key: "noiseSpeedY",
          get: function get() {
            return this._noiseSpeedY;
          },
          set: function set(value) {
            this._noiseSpeedY = value;
          }
        }, {
          key: "noiseSpeedZ",
          get: function get() {
            return this._noiseSpeedZ;
          },
          set: function set(value) {
            this._noiseSpeedZ = value;
          }
        }, {
          key: "noiseFrequency",
          get: function get() {
            return this._noiseFrequency;
          },
          set: function set(value) {
            this._noiseFrequency = value;
          }
        }, {
          key: "remapX",
          get: function get() {
            return this._remapX;
          },
          set: function set(value) {
            this._remapX = value;
          }
        }, {
          key: "remapY",
          get: function get() {
            return this._remapY;
          },
          set: function set(value) {
            this._remapY = value;
          }
        }, {
          key: "remapZ",
          get: function get() {
            return this._remapZ;
          },
          set: function set(value) {
            this._remapZ = value;
          }
        }, {
          key: "octaves",
          get: function get() {
            return this._octaves;
          },
          set: function set(value) {
            this._octaves = value;
          }
        }, {
          key: "octaveMultiplier",
          get: function get() {
            return this._octaveMultiplier;
          },
          set: function set(value) {
            this._octaveMultiplier = value;
          }
        }, {
          key: "octaveScale",
          get: function get() {
            return this._octaveScale;
          },
          set: function set(value) {
            this._octaveScale = value;
          }
        }]);
        return NoiseModule;
      }(ParticleModuleBase), (_initializer$11 = applyDecoratedInitializer(_class2$13.prototype, "_enable", [serializable$1], function () {
        return false;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "strengthX", [_dec2$12], Object.getOwnPropertyDescriptor(_class2$13.prototype, "strengthX"), _class2$13.prototype), _initializer2$W = applyDecoratedInitializer(_class2$13.prototype, "_strengthX", [serializable$1], function () {
        return 10;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "strengthY", [_dec3$O], Object.getOwnPropertyDescriptor(_class2$13.prototype, "strengthY"), _class2$13.prototype), _initializer3$H = applyDecoratedInitializer(_class2$13.prototype, "_strengthY", [serializable$1], function () {
        return 10;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "strengthZ", [_dec4$C], Object.getOwnPropertyDescriptor(_class2$13.prototype, "strengthZ"), _class2$13.prototype), _initializer4$z = applyDecoratedInitializer(_class2$13.prototype, "_strengthZ", [serializable$1], function () {
        return 10;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "noiseSpeedX", [_dec5$z], Object.getOwnPropertyDescriptor(_class2$13.prototype, "noiseSpeedX"), _class2$13.prototype), _initializer5$s = applyDecoratedInitializer(_class2$13.prototype, "_noiseSpeedX", [serializable$1], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "noiseSpeedY", [_dec6$n], Object.getOwnPropertyDescriptor(_class2$13.prototype, "noiseSpeedY"), _class2$13.prototype), _initializer6$o = applyDecoratedInitializer(_class2$13.prototype, "_noiseSpeedY", [serializable$1], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "noiseSpeedZ", [_dec7$j], Object.getOwnPropertyDescriptor(_class2$13.prototype, "noiseSpeedZ"), _class2$13.prototype), _initializer7$j = applyDecoratedInitializer(_class2$13.prototype, "_noiseSpeedZ", [serializable$1], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "noiseFrequency", [_dec8$d], Object.getOwnPropertyDescriptor(_class2$13.prototype, "noiseFrequency"), _class2$13.prototype), _initializer8$h = applyDecoratedInitializer(_class2$13.prototype, "_noiseFrequency", [serializable$1], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "remapX", [_dec9$b], Object.getOwnPropertyDescriptor(_class2$13.prototype, "remapX"), _class2$13.prototype), _initializer9$f = applyDecoratedInitializer(_class2$13.prototype, "_remapX", [serializable$1], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "remapY", [_dec10$7], Object.getOwnPropertyDescriptor(_class2$13.prototype, "remapY"), _class2$13.prototype), _initializer10$e = applyDecoratedInitializer(_class2$13.prototype, "_remapY", [serializable$1], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "remapZ", [_dec11$5], Object.getOwnPropertyDescriptor(_class2$13.prototype, "remapZ"), _class2$13.prototype), _initializer11$e = applyDecoratedInitializer(_class2$13.prototype, "_remapZ", [serializable$1], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "octaves", [_dec12$4], Object.getOwnPropertyDescriptor(_class2$13.prototype, "octaves"), _class2$13.prototype), _initializer12$c = applyDecoratedInitializer(_class2$13.prototype, "_octaves", [serializable$1], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "octaveMultiplier", [_dec13$4], Object.getOwnPropertyDescriptor(_class2$13.prototype, "octaveMultiplier"), _class2$13.prototype), _initializer13$9 = applyDecoratedInitializer(_class2$13.prototype, "_octaveMultiplier", [serializable$1], function () {
        return 0.5;
      }), _applyDecoratedDescriptor(_class2$13.prototype, "octaveScale", [_dec14$3], Object.getOwnPropertyDescriptor(_class2$13.prototype, "octaveScale"), _class2$13.prototype), _initializer14$8 = applyDecoratedInitializer(_class2$13.prototype, "_octaveScale", [serializable$1], function () {
        return 2;
      })), _class2$13)) || _class$16);

      var _dec$17, _dec2$11, _dec3$N, _dec4$B, _dec5$y, _dec6$m, _dec7$i, _dec8$c, _dec9$a, _dec10$6, _dec11$4, _dec12$3, _dec13$3, _dec14$2, _dec15$2, _dec16$2, _dec17$2, _dec18$2, _dec19$2, _dec20$2, _dec21$2, _dec22$2, _dec23$2, _dec24$2, _dec25$2, _dec26$2, _dec27$2, _dec28$2, _dec29$2, _dec30$1, _dec31$1, _dec32$1, _dec33$1, _dec34$1, _dec35$1, _dec36$1, _dec37$1, _dec38$1, _dec39$1, _dec40$1, _dec41$1, _dec42$1, _dec43$1, _dec44$1, _dec45$1, _dec46$1, _dec47$1, _class$15, _class2$12, _initializer$10, _initializer2$V, _initializer3$G, _initializer4$y, _initializer5$r, _initializer6$n, _initializer7$i, _initializer8$g, _initializer9$e, _initializer10$d, _initializer11$d, _initializer12$b, _initializer13$8, _initializer14$7, _initializer15$6, _initializer16$6, _initializer17$4, _initializer18$4, _initializer19$3, _initializer20$3, _initializer21$3, _initializer22$3, _initializer23$2, _initializer24$2, _initializer25$2, _initializer26$2, _initializer27$2, _initializer28$2, _initializer29$2, _initializer30$2, _initializer31$2, _initializer32$2, _initializer33$2, _initializer34$2, _initializer35$2, _initializer36$2, _initializer37$2, _initializer38$2, _initializer39$2, _initializer40$2, _initializer41$2, _class3$o;
      var _world_mat = new Mat4();
      var _world_rol = new Quat();
      var superMaterials = Object.getOwnPropertyDescriptor(Renderer.prototype, 'sharedMaterials');
      var ParticleSystem = exports('f6', (_dec$17 = ccclass$M('cc.ParticleSystem'), _dec2$11 = executionOrder$1(99), _dec3$N = type$d(GradientRange), _dec4$B = type$d(Space), _dec5$y = formerlySerializedAs$4('startSize'), _dec6$m = type$d(CurveRange), _dec7$i = type$d(CurveRange), _dec8$c = type$d(CurveRange), _dec9$a = type$d(CurveRange), _dec10$6 = type$d(CurveRange), _dec11$4 = type$d(CurveRange), _dec12$3 = type$d(CurveRange), _dec13$3 = formerlySerializedAs$4('startRotation'), _dec14$2 = type$d(CurveRange), _dec15$2 = type$d(CurveRange), _dec16$2 = type$d(Space), _dec17$2 = type$d(CurveRange), _dec18$2 = type$d(CurveRange), _dec19$2 = type$d(CurveRange), _dec20$2 = type$d([Burst]), _dec21$2 = type$d(CCBoolean), _dec22$2 = type$d(CullingMode), _dec23$2 = type$d(CCFloat), _dec24$2 = type$d(CCFloat), _dec25$2 = type$d(CCFloat), _dec26$2 = formerlySerializedAs$4('enableCulling'), _dec27$2 = type$d(ColorOvertimeModule), _dec28$2 = type$d(ColorOvertimeModule), _dec29$2 = type$d(ShapeModule), _dec30$1 = type$d(ShapeModule), _dec31$1 = type$d(SizeOvertimeModule), _dec32$1 = type$d(SizeOvertimeModule), _dec33$1 = type$d(VelocityOvertimeModule), _dec34$1 = type$d(VelocityOvertimeModule), _dec35$1 = type$d(ForceOvertimeModule), _dec36$1 = type$d(ForceOvertimeModule), _dec37$1 = type$d(LimitVelocityOvertimeModule), _dec38$1 = type$d(LimitVelocityOvertimeModule), _dec39$1 = type$d(RotationOvertimeModule), _dec40$1 = type$d(RotationOvertimeModule), _dec41$1 = type$d(TextureAnimationModule), _dec42$1 = type$d(TextureAnimationModule), _dec43$1 = type$d(NoiseModule), _dec44$1 = type$d(NoiseModule), _dec45$1 = type$d(TrailModule), _dec46$1 = type$d(TrailModule), _dec47$1 = type$d(ParticleSystemRenderer), _dec$17(_class$15 = _dec2$11(_class$15 = (_class2$12 = (_class3$o = function (_ModelRenderer) {
        _inheritsLoose(ParticleSystem, _ModelRenderer);
        function ParticleSystem() {
          var _this;
          _this = _ModelRenderer.call(this) || this;
          _this.startColor = _initializer$10 && _initializer$10();
          _this.scaleSpace = _initializer2$V && _initializer2$V();
          _this.startSize3D = _initializer3$G && _initializer3$G();
          _this.startSizeX = _initializer4$y && _initializer4$y();
          _this.startSizeY = _initializer5$r && _initializer5$r();
          _this.startSizeZ = _initializer6$n && _initializer6$n();
          _this.startSpeed = _initializer7$i && _initializer7$i();
          _this.startRotation3D = _initializer8$g && _initializer8$g();
          _this.startRotationX = _initializer9$e && _initializer9$e();
          _this.startRotationY = _initializer10$d && _initializer10$d();
          _this.startRotationZ = _initializer11$d && _initializer11$d();
          _this.startDelay = _initializer12$b && _initializer12$b();
          _this.startLifetime = _initializer13$8 && _initializer13$8();
          _this.duration = _initializer14$7 && _initializer14$7();
          _this.loop = _initializer15$6 && _initializer15$6();
          _this.simulationSpeed = _initializer16$6 && _initializer16$6();
          _this.playOnAwake = _initializer17$4 && _initializer17$4();
          _this.gravityModifier = _initializer18$4 && _initializer18$4();
          _this.rateOverTime = _initializer19$3 && _initializer19$3();
          _this.rateOverDistance = _initializer20$3 && _initializer20$3();
          _this.bursts = _initializer21$3 && _initializer21$3();
          _this._renderCulling = _initializer22$3 && _initializer22$3();
          _this._cullingMode = _initializer23$2 && _initializer23$2();
          _this._aabbHalfX = _initializer24$2 && _initializer24$2();
          _this._aabbHalfY = _initializer25$2 && _initializer25$2();
          _this._aabbHalfZ = _initializer26$2 && _initializer26$2();
          _this._dataCulling = _initializer27$2 && _initializer27$2();
          _this._colorOverLifetimeModule = _initializer28$2 && _initializer28$2();
          _this._shapeModule = _initializer29$2 && _initializer29$2();
          _this._sizeOvertimeModule = _initializer30$2 && _initializer30$2();
          _this._velocityOvertimeModule = _initializer31$2 && _initializer31$2();
          _this._forceOvertimeModule = _initializer32$2 && _initializer32$2();
          _this._limitVelocityOvertimeModule = _initializer33$2 && _initializer33$2();
          _this._rotationOvertimeModule = _initializer34$2 && _initializer34$2();
          _this._textureAnimationModule = _initializer35$2 && _initializer35$2();
          _this._noiseModule = _initializer36$2 && _initializer36$2();
          _this._trailModule = _initializer37$2 && _initializer37$2();
          _this.renderer = _initializer38$2 && _initializer38$2();
          _this._isPlaying = void 0;
          _this._isPaused = void 0;
          _this._isStopped = void 0;
          _this._isEmitting = void 0;
          _this._needToRestart = void 0;
          _this._needRefresh = void 0;
          _this._time = void 0;
          _this._emitRateTimeCounter = void 0;
          _this._emitRateDistanceCounter = void 0;
          _this._oldWPos = void 0;
          _this._curWPos = void 0;
          _this._boundingBox = void 0;
          _this._culler = void 0;
          _this._oldPos = void 0;
          _this._curPos = void 0;
          _this._isCulled = void 0;
          _this._isSimulating = void 0;
          _this._customData1 = void 0;
          _this._customData2 = void 0;
          _this._subEmitters = void 0;
          _this._needAttach = void 0;
          _this._prewarm = _initializer39$2 && _initializer39$2();
          _this._capacity = _initializer40$2 && _initializer40$2();
          _this._simulationSpace = _initializer41$2 && _initializer41$2();
          _this.processor = null;
          _this.rateOverTime.constant = 10;
          _this.startLifetime.constant = 5;
          _this.startSizeX.constant = 1;
          _this.startSpeed.constant = 5;
          _this._isPlaying = false;
          _this._isPaused = false;
          _this._isStopped = true;
          _this._isEmitting = false;
          _this._needToRestart = false;
          _this._needRefresh = true;
          _this._needAttach = false;
          _this._time = 0.0;
          _this._emitRateTimeCounter = 0.0;
          _this._emitRateDistanceCounter = 0.0;
          _this._oldWPos = new Vec3();
          _this._curWPos = new Vec3();
          _this._boundingBox = null;
          _this._culler = null;
          _this._oldPos = null;
          _this._curPos = null;
          _this._isCulled = false;
          _this._isSimulating = true;
          _this._customData1 = new Vec2();
          _this._customData2 = new Vec2();
          _this._subEmitters = [];
          return _this;
        }
        var _proto = ParticleSystem.prototype;
        _proto.onFocusInEditor = function onFocusInEditor() {
          this.renderer.create(this);
        };
        _proto.onLoad = function onLoad() {
          this.renderer.onInit(this);
          if (this._shapeModule) this._shapeModule.onInit(this);
          if (this._trailModule && !this.renderer.useGPU && this._trailModule.enable) {
            this._trailModule.onInit(this);
          }
          this.bindModule();
          this._resetPosition();
        };
        _proto._onMaterialModified = function _onMaterialModified(index, material) {
          if (this.processor !== null) {
            this.processor.onMaterialModified(index, material);
          }
        };
        _proto._onRebuildPSO = function _onRebuildPSO(index, material) {
          this.processor.onRebuildPSO(index, material);
        };
        _proto._collectModels = function _collectModels() {
          this._models.length = 0;
          this._models.push(this.processor._model);
          if (this._trailModule && this._trailModule.enable && this._trailModule._trailModel) {
            this._models.push(this._trailModule._trailModel);
          }
          return this._models;
        };
        _proto._attachToScene = function _attachToScene() {
          this.processor.attachToScene();
          if (this._trailModule && this._trailModule.enable) {
            this._trailModule._attachToScene();
          }
        };
        _proto._detachFromScene = function _detachFromScene() {
          this.processor.detachFromScene();
          if (this._trailModule && this._trailModule.enable) {
            this._trailModule._detachFromScene();
          }
          if (this._boundingBox) {
            this._boundingBox = null;
          }
          if (this._culler) {
            this._culler.clear();
            this._culler.destroy();
            this._culler = null;
          }
        };
        _proto.bindModule = function bindModule() {
          if (this._colorOverLifetimeModule) this._colorOverLifetimeModule.bindTarget(this.processor);
          if (this._sizeOvertimeModule) this._sizeOvertimeModule.bindTarget(this.processor);
          if (this._rotationOvertimeModule) this._rotationOvertimeModule.bindTarget(this.processor);
          if (this._forceOvertimeModule) this._forceOvertimeModule.bindTarget(this.processor);
          if (this._limitVelocityOvertimeModule) this._limitVelocityOvertimeModule.bindTarget(this.processor);
          if (this._velocityOvertimeModule) this._velocityOvertimeModule.bindTarget(this.processor);
          if (this._textureAnimationModule) this._textureAnimationModule.bindTarget(this.processor);
          if (this._noiseModule) this._noiseModule.bindTarget(this.processor);
        };
        _proto.play = function play() {
          if (this._needToRestart) {
            this.reset();
            this._needToRestart = false;
          }
          if (this._isPaused) {
            this._isPaused = false;
          }
          if (this._isStopped) {
            this._isStopped = false;
          }
          this._isPlaying = true;
          this._isEmitting = true;
          this._resetPosition();
          if (this._prewarm) {
            this._prewarmSystem();
          }
          if (this._trailModule) {
            this._trailModule.play();
          }
          if (this.processor) {
            var model = this.processor.getModel();
            if (model) {
              model.enabled = this.enabledInHierarchy;
            }
          }
        };
        _proto.pause = function pause() {
          if (this._isStopped) {
            warn('pause(): particle system is already stopped.');
            return;
          }
          if (this._isPlaying) {
            this._isPlaying = false;
          }
          this._isPaused = true;
        };
        _proto.stopEmitting = function stopEmitting() {
          this._isEmitting = false;
          this._needToRestart = true;
        };
        _proto.stop = function stop() {
          if (this._isPlaying || this._isPaused) {
            this.clear();
          }
          if (this._isPlaying) {
            this._isPlaying = false;
          }
          if (this._isPaused) {
            this._isPaused = false;
          }
          if (this._isEmitting) {
            this._isEmitting = false;
          }
          this._isStopped = true;
          this._needRefresh = true;
          this.reset();
        };
        _proto.reset = function reset() {
          this._time = 0.0;
          this._emitRateTimeCounter = 0.0;
          this._emitRateDistanceCounter = 0.0;
          this._resetPosition();
          for (var _iterator = _createForOfIteratorHelperLoose(this.bursts), _step; !(_step = _iterator()).done;) {
            var burst = _step.value;
            burst.reset();
          }
        };
        _proto.clear = function clear() {
          if (this.enabledInHierarchy) {
            this.processor.clear();
            if (this._trailModule) this._trailModule.clear();
          }
          this._calculateBounding(false);
        };
        _proto.getParticleCount = function getParticleCount() {
          if (this.processor) {
            return this.processor.getParticleCount();
          } else {
            return 0;
          }
        };
        _proto.setCustomData1 = function setCustomData1(x, y) {
          Vec2.set(this._customData1, x, y);
        };
        _proto.setCustomData2 = function setCustomData2(x, y) {
          Vec2.set(this._customData2, x, y);
        };
        _proto.onDestroy = function onDestroy() {
          var _this$processor$getMo;
          this.stop();
          if ((_this$processor$getMo = this.processor.getModel()) !== null && _this$processor$getMo !== void 0 && _this$processor$getMo.scene) {
            this.processor.detachFromScene();
            if (this._trailModule && this._trailModule.enable) {
              this._trailModule._detachFromScene();
            }
          }
          legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this);
          this.processor.onDestroy();
          if (this._trailModule) this._trailModule.destroy();
          if (this._culler) {
            this._culler.clear();
            this._culler.destroy();
            this._culler = null;
          }
        };
        _proto.onEnable = function onEnable() {
          _ModelRenderer.prototype.onEnable.call(this);
          legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this);
          if (this.playOnAwake && !EDITOR_NOT_IN_PREVIEW) {
            this.play();
          }
          this.processor.onEnable();
          if (this._trailModule) this._trailModule.onEnable();
        };
        _proto.onDisable = function onDisable() {
          legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this);
          this.processor.onDisable();
          if (this._trailModule) this._trailModule.onDisable();
          if (this._boundingBox) {
            this._boundingBox = null;
          }
          if (this._culler) {
            this._culler.clear();
            this._culler.destroy();
            this._culler = null;
          }
        };
        _proto._calculateBounding = function _calculateBounding(forceRefresh) {
          if (this._boundingBox) {
            if (!this._culler) {
              this._culler = new ParticleCuller(this);
            }
            this._culler.calculatePositions();
            AABB.fromPoints(this._boundingBox, this._culler.minPos, this._culler.maxPos);
            if (forceRefresh) {
              this.aabbHalfX = this._boundingBox.halfExtents.x;
              this.aabbHalfY = this._boundingBox.halfExtents.y;
              this.aabbHalfZ = this._boundingBox.halfExtents.z;
            } else {
              if (this.aabbHalfX) {
                this.setBoundingX(this.aabbHalfX);
              } else {
                this.aabbHalfX = this._boundingBox.halfExtents.x;
              }
              if (this.aabbHalfY) {
                this.setBoundingY(this.aabbHalfY);
              } else {
                this.aabbHalfY = this._boundingBox.halfExtents.y;
              }
              if (this.aabbHalfZ) {
                this.setBoundingZ(this.aabbHalfZ);
              } else {
                this.aabbHalfZ = this._boundingBox.halfExtents.z;
              }
            }
            this._culler.clear();
          }
        };
        _proto.update = function update(dt) {
          var scaledDeltaTime = dt * this.simulationSpeed;
          if (!this.renderCulling) {
            if (this._boundingBox) {
              this._boundingBox = null;
            }
            if (this._culler) {
              this._culler.clear();
              this._culler.destroy();
              this._culler = null;
            }
            this._isSimulating = true;
          } else {
            var _this$node$scene$rend;
            if (!this._boundingBox) {
              this._boundingBox = new AABB();
              this._calculateBounding(false);
            }
            if (!this._curPos) {
              this._curPos = new Vec3();
            }
            this.node.getWorldPosition(this._curPos);
            if (!this._oldPos) {
              this._oldPos = new Vec3();
              this._oldPos.set(this._curPos);
            }
            if (!this._curPos.equals(this._oldPos) && this._boundingBox && this._culler) {
              var dx = this._curPos.x - this._oldPos.x;
              var dy = this._curPos.y - this._oldPos.y;
              var dz = this._curPos.z - this._oldPos.z;
              var center = this._boundingBox.center;
              center.x += dx;
              center.y += dy;
              center.z += dz;
              this._culler.setBoundingBoxCenter(center.x, center.y, center.z);
              this._oldPos.set(this._curPos);
            }
            var cameraLst = (_this$node$scene$rend = this.node.scene.renderScene) === null || _this$node$scene$rend === void 0 ? void 0 : _this$node$scene$rend.cameras;
            var culled = true;
            if (cameraLst !== undefined && this._boundingBox) {
              for (var i = 0; i < cameraLst.length; ++i) {
                var camera = cameraLst[i];
                var visibility = camera.visibility;
                if ((visibility & this.node.layer) === this.node.layer) {
                  if (intersect.aabbFrustum(this._boundingBox, camera.frustum)) {
                    culled = false;
                    break;
                  }
                }
              }
            }
            if (culled) {
              if (this._cullingMode !== CullingMode.AlwaysSimulate) {
                this._isSimulating = false;
              }
              if (!this._isCulled) {
                this.processor.detachFromScene();
                this._isCulled = true;
              }
              if (this._trailModule && this._trailModule.enable) {
                this._trailModule._detachFromScene();
              }
              if (this._cullingMode === CullingMode.PauseAndCatchup) {
                this._time += scaledDeltaTime;
              }
              if (this._cullingMode !== CullingMode.AlwaysSimulate) {
                return;
              }
            } else {
              if (this._isCulled) {
                this._attachToScene();
                this._isCulled = false;
              }
              if (!this._isSimulating) {
                this._isSimulating = true;
              }
            }
            if (!this._isSimulating) {
              return;
            }
          }
          if (this._isPlaying) {
            this._time += scaledDeltaTime;
            this._emit(scaledDeltaTime);
            if (this.processor.updateParticles(scaledDeltaTime) === 0 && !this._isEmitting) {
              this.stop();
            }
          } else {
            var mat = this.getMaterialInstance(0) || this.processor.getDefaultMaterial();
            var pass = mat.passes[0];
            this.processor.updateRotation(pass);
            this.processor.updateScale(pass);
          }
          if (this._needAttach) {
            if (this.getParticleCount() > 0) {
              if (!this._isCulled) {
                var _this$processor$getMo2;
                if (!((_this$processor$getMo2 = this.processor.getModel()) !== null && _this$processor$getMo2 !== void 0 && _this$processor$getMo2.scene)) {
                  this.processor.attachToScene();
                }
                if (this._trailModule && this._trailModule.enable) {
                  var _this$_trailModule$ge;
                  if (!((_this$_trailModule$ge = this._trailModule.getModel()) !== null && _this$_trailModule$ge !== void 0 && _this$_trailModule$ge.scene)) {
                    this._trailModule._attachToScene();
                  }
                }
                this._needAttach = false;
              }
            }
          }
          if (!this.renderer.useGPU && this._trailModule && this._trailModule.enable) {
            if (!this._trailModule.inited) {
              this._trailModule.clear();
              this._trailModule.destroy();
              this._trailModule.onInit(this);
              this._trailModule.enable = false;
              this._trailModule.enable = true;
            }
          }
        };
        _proto.beforeRender = function beforeRender() {
          var _this$processor$getMo4;
          if (this.getParticleCount() <= 0) {
            var _this$processor$getMo3;
            if ((_this$processor$getMo3 = this.processor.getModel()) !== null && _this$processor$getMo3 !== void 0 && _this$processor$getMo3.scene) {
              this.processor.detachFromScene();
              if (this._trailModule && this._trailModule.enable) {
                this._trailModule._detachFromScene();
              }
              this._needAttach = false;
            }
          } else if (!((_this$processor$getMo4 = this.processor.getModel()) !== null && _this$processor$getMo4 !== void 0 && _this$processor$getMo4.scene)) {
            this._needAttach = true;
          }
          if (!this._isPlaying) return;
          this.processor.updateRenderData();
          this.processor.beforeRender();
          if (this._trailModule && this._trailModule.enable) {
            this._trailModule.updateRenderData();
            this._trailModule.beforeRender();
          }
        };
        _proto._onVisibilityChange = function _onVisibilityChange(val) {
          if (this.processor.model) {
            this.processor.model.visFlags = val;
          }
        };
        _proto.emit = function emit(count, dt) {
          var loopDelta = this._time % this.duration / this.duration;
          if (this._needRefresh) {
            this.node.invalidateChildren(TransformBit.POSITION);
            this._needRefresh = false;
          }
          if (this._simulationSpace === Space.World) {
            this.node.getWorldMatrix(_world_mat);
            this.node.getWorldRotation(_world_rol);
          }
          for (var i = 0; i < count; ++i) {
            var particle = this.processor.getFreeParticle();
            if (particle === null) {
              return;
            }
            particle.particleSystem = this;
            particle.reset();
            var rand = pseudoRandom(randomRangeInt(0, INT_MAX));
            if (this._shapeModule && this._shapeModule.enable) {
              this._shapeModule.emit(particle);
            } else {
              Vec3.set(particle.position, 0, 0, 0);
              Vec3.copy(particle.velocity, particleEmitZAxis);
            }
            if (this._textureAnimationModule && this._textureAnimationModule.enable) {
              this._textureAnimationModule.init(particle);
            }
            var curveStartSpeed = this.startSpeed.evaluate(loopDelta, rand);
            Vec3.multiplyScalar(particle.velocity, particle.velocity, curveStartSpeed);
            if (this._simulationSpace === Space.World) {
              Vec3.transformMat4(particle.position, particle.position, _world_mat);
              Vec3.transformQuat(particle.velocity, particle.velocity, _world_rol);
            }
            Vec3.copy(particle.ultimateVelocity, particle.velocity);
            if (this.startRotation3D) {
              particle.startEuler.set(this.startRotationX.evaluate(loopDelta, rand), this.startRotationY.evaluate(loopDelta, rand), this.startRotationZ.evaluate(loopDelta, rand));
            } else {
              particle.startEuler.set(0, 0, this.startRotationZ.evaluate(loopDelta, rand));
            }
            particle.rotation.set(particle.startEuler);
            if (this.startSize3D) {
              Vec3.set(particle.startSize, this.startSizeX.evaluate(loopDelta, rand), this.startSizeY.evaluate(loopDelta, rand), this.startSizeZ.evaluate(loopDelta, rand));
            } else {
              Vec3.set(particle.startSize, this.startSizeX.evaluate(loopDelta, rand), 1, 1);
              particle.startSize.y = particle.startSize.x;
            }
            Vec3.copy(particle.size, particle.startSize);
            particle.startColor.set(this.startColor.evaluate(loopDelta, rand));
            particle.color.set(particle.startColor);
            particle.startLifetime = this.startLifetime.evaluate(loopDelta, rand) + dt;
            particle.remainingLifetime = particle.startLifetime;
            particle.randomSeed = randomRangeInt(0, 233280);
            particle.loopCount++;
            this.processor.setNewParticle(particle);
          }
        };
        _proto._prewarmSystem = function _prewarmSystem() {
          this.startDelay.mode = Mode$3.Constant;
          this.startDelay.constant = 0;
          var dt = 1.0;
          var cnt = this.duration / dt;
          for (var i = 0; i < cnt; ++i) {
            this._time += dt;
            this._emit(dt);
            this.processor.updateParticles(dt);
          }
        };
        _proto._emit = function _emit(dt) {
          var startDelay = this.startDelay.evaluate(0, 1);
          if (this._time > startDelay) {
            if (this._time > this.duration + startDelay) {
              if (!this.loop) {
                this._isEmitting = false;
              }
            }
            if (!this._isEmitting) return;
            this._emitRateTimeCounter += this.rateOverTime.evaluate(this._time / this.duration, 1) * dt;
            if (this._emitRateTimeCounter > 1) {
              var emitNum = Math.floor(this._emitRateTimeCounter);
              this._emitRateTimeCounter -= emitNum;
              this.emit(emitNum, dt);
            }
            var rateOverDistance = this.rateOverDistance.evaluate(this._time / this.duration, 1);
            if (rateOverDistance > 0) {
              Vec3.copy(this._oldWPos, this._curWPos);
              this.node.getWorldPosition(this._curWPos);
              var distance = Vec3.distance(this._curWPos, this._oldWPos);
              this._emitRateDistanceCounter += distance * rateOverDistance;
            }
            if (this._emitRateDistanceCounter > 1) {
              var _emitNum = Math.floor(this._emitRateDistanceCounter);
              this._emitRateDistanceCounter -= _emitNum;
              this.emit(_emitNum, dt);
            }
            for (var _iterator2 = _createForOfIteratorHelperLoose(this.bursts), _step2; !(_step2 = _iterator2()).done;) {
              var burst = _step2.value;
              burst.update(this, dt);
            }
          }
        };
        _proto._resetPosition = function _resetPosition() {
          this.node.getWorldPosition(this._oldWPos);
          Vec3.copy(this._curWPos, this._oldWPos);
        };
        _proto.addSubEmitter = function addSubEmitter(subEmitter) {
          this._subEmitters.push(subEmitter);
        };
        _proto.removeSubEmitter = function removeSubEmitter(idx) {
          this._subEmitters.splice(this._subEmitters.indexOf(idx), 1);
        };
        _proto.addBurst = function addBurst(burst) {
          this.bursts.push(burst);
        };
        _proto.removeBurst = function removeBurst(idx) {
          this.bursts.splice(this.bursts.indexOf(idx), 1);
        };
        _proto.getBoundingX = function getBoundingX() {
          return this._aabbHalfX;
        };
        _proto.getBoundingY = function getBoundingY() {
          return this._aabbHalfY;
        };
        _proto.getBoundingZ = function getBoundingZ() {
          return this._aabbHalfZ;
        };
        _proto.setBoundingX = function setBoundingX(value) {
          if (this._boundingBox && this._culler) {
            this._boundingBox.halfExtents.x = value;
            this._culler.setBoundingBoxSize(this._boundingBox.halfExtents);
            this._aabbHalfX = value;
          }
        };
        _proto.setBoundingY = function setBoundingY(value) {
          if (this._boundingBox && this._culler) {
            this._boundingBox.halfExtents.y = value;
            this._culler.setBoundingBoxSize(this._boundingBox.halfExtents);
            this._aabbHalfY = value;
          }
        };
        _proto.setBoundingZ = function setBoundingZ(value) {
          if (this._boundingBox && this._culler) {
            this._boundingBox.halfExtents.z = value;
            this._culler.setBoundingBoxSize(this._boundingBox.halfExtents);
            this._aabbHalfZ = value;
          }
        };
        _proto._onBeforeSerialize = function _onBeforeSerialize(props) {
          var _this2 = this;
          return this.dataCulling ? props.filter(function (p) {
            return !PARTICLE_MODULE_PROPERTY.includes(p) || _this2[p] && _this2[p].enable;
          }) : props;
        };
        _proto.getNoisePreview = function getNoisePreview(width, height) {
          var out = [];
          if (this.processor) {
            this.processor.getNoisePreview(out, width, height);
          }
          return out;
        };
        _createClass(ParticleSystem, [{
          key: "capacity",
          get: function get() {
            return this._capacity;
          },
          set: function set(val) {
            this._capacity = Math.floor(val > 0 ? val : 0);
            if (this.processor && this.processor.model) {
              this.processor.model.setCapacity(this._capacity);
            }
          }
        }, {
          key: "prewarm",
          get: function get() {
            return this._prewarm;
          },
          set: function set(val) {
            if (val === true && this.loop === false) ;
            this._prewarm = val;
          }
        }, {
          key: "simulationSpace",
          get: function get() {
            return this._simulationSpace;
          },
          set: function set(val) {
            if (val !== this._simulationSpace) {
              this._simulationSpace = val;
              if (this.processor) {
                this.processor.updateMaterialParams();
                this.processor.updateTrailMaterial();
              }
            }
          }
        }, {
          key: "renderCulling",
          get: function get() {
            return this._renderCulling;
          },
          set: function set(value) {
            this._renderCulling = value;
            if (value) {
              if (!this._boundingBox) {
                this._boundingBox = new AABB();
                this._calculateBounding(false);
              }
            }
          }
        }, {
          key: "cullingMode",
          get: function get() {
            return this._cullingMode;
          },
          set: function set(value) {
            this._cullingMode = value;
          }
        }, {
          key: "aabbHalfX",
          get: function get() {
            var res = this.getBoundingX();
            if (res) {
              return res;
            } else {
              return 0;
            }
          },
          set: function set(value) {
            this.setBoundingX(value);
          }
        }, {
          key: "aabbHalfY",
          get: function get() {
            var res = this.getBoundingY();
            if (res) {
              return res;
            } else {
              return 0;
            }
          },
          set: function set(value) {
            this.setBoundingY(value);
          }
        }, {
          key: "aabbHalfZ",
          get: function get() {
            var res = this.getBoundingZ();
            if (res) {
              return res;
            } else {
              return 0;
            }
          },
          set: function set(value) {
            this.setBoundingZ(value);
          }
        }, {
          key: "dataCulling",
          get: function get() {
            return this._dataCulling;
          },
          set: function set(value) {
            this._dataCulling = value;
          }
        }, {
          key: "sharedMaterials",
          get: function get() {
            return superMaterials.get.call(this);
          },
          set: function set(val) {
            superMaterials.set.call(this, val);
          }
        }, {
          key: "colorOverLifetimeModule",
          get: function get() {
            return this._colorOverLifetimeModule;
          },
          set: function set(val) {
            if (!val) return;
            this._colorOverLifetimeModule = val;
          }
        }, {
          key: "shapeModule",
          get: function get() {
            return this._shapeModule;
          },
          set: function set(val) {
            if (!val) return;
            this._shapeModule = val;
          }
        }, {
          key: "sizeOvertimeModule",
          get: function get() {
            return this._sizeOvertimeModule;
          },
          set: function set(val) {
            if (!val) return;
            this._sizeOvertimeModule = val;
          }
        }, {
          key: "velocityOvertimeModule",
          get: function get() {
            return this._velocityOvertimeModule;
          },
          set: function set(val) {
            if (!val) return;
            this._velocityOvertimeModule = val;
          }
        }, {
          key: "forceOvertimeModule",
          get: function get() {
            return this._forceOvertimeModule;
          },
          set: function set(val) {
            if (!val) return;
            this._forceOvertimeModule = val;
          }
        }, {
          key: "limitVelocityOvertimeModule",
          get: function get() {
            return this._limitVelocityOvertimeModule;
          },
          set: function set(val) {
            if (!val) return;
            this._limitVelocityOvertimeModule = val;
          }
        }, {
          key: "rotationOvertimeModule",
          get: function get() {
            return this._rotationOvertimeModule;
          },
          set: function set(val) {
            if (!val) return;
            this._rotationOvertimeModule = val;
          }
        }, {
          key: "textureAnimationModule",
          get: function get() {
            return this._textureAnimationModule;
          },
          set: function set(val) {
            if (!val) return;
            this._textureAnimationModule = val;
          }
        }, {
          key: "noiseModule",
          get: function get() {
            return this._noiseModule;
          },
          set: function set(val) {
            if (!val) return;
            this._noiseModule = val;
          }
        }, {
          key: "trailModule",
          get: function get() {
            return this._trailModule;
          },
          set: function set(val) {
            if (!val) return;
            this._trailModule = val;
          }
        }, {
          key: "isPlaying",
          get: function get() {
            return this._isPlaying;
          }
        }, {
          key: "isPaused",
          get: function get() {
            return this._isPaused;
          }
        }, {
          key: "isStopped",
          get: function get() {
            return this._isStopped;
          }
        }, {
          key: "isEmitting",
          get: function get() {
            return this._isEmitting;
          }
        }, {
          key: "time",
          get: function get() {
            return this._time;
          }
        }]);
        return ParticleSystem;
      }(ModelRenderer), _class3$o.CullingMode = CullingMode, _class3$o), (_initializer$10 = applyDecoratedInitializer(_class2$12.prototype, "startColor", [_dec3$N, serializable$p], function () {
        return new GradientRange();
      }), _initializer2$V = applyDecoratedInitializer(_class2$12.prototype, "scaleSpace", [_dec4$B, serializable$p], function () {
        return Space.Local;
      }), _initializer3$G = applyDecoratedInitializer(_class2$12.prototype, "startSize3D", [serializable$p], function () {
        return false;
      }), _initializer4$y = applyDecoratedInitializer(_class2$12.prototype, "startSizeX", [_dec5$y, _dec6$m], function () {
        return new CurveRange();
      }), _initializer5$r = applyDecoratedInitializer(_class2$12.prototype, "startSizeY", [_dec7$i, serializable$p], function () {
        return new CurveRange();
      }), _initializer6$n = applyDecoratedInitializer(_class2$12.prototype, "startSizeZ", [_dec8$c, serializable$p], function () {
        return new CurveRange();
      }), _initializer7$i = applyDecoratedInitializer(_class2$12.prototype, "startSpeed", [_dec9$a, serializable$p], function () {
        return new CurveRange();
      }), _initializer8$g = applyDecoratedInitializer(_class2$12.prototype, "startRotation3D", [serializable$p], function () {
        return false;
      }), _initializer9$e = applyDecoratedInitializer(_class2$12.prototype, "startRotationX", [_dec10$6, serializable$p], function () {
        return new CurveRange();
      }), _initializer10$d = applyDecoratedInitializer(_class2$12.prototype, "startRotationY", [_dec11$4, serializable$p], function () {
        return new CurveRange();
      }), _initializer11$d = applyDecoratedInitializer(_class2$12.prototype, "startRotationZ", [_dec12$3, _dec13$3], function () {
        return new CurveRange();
      }), _initializer12$b = applyDecoratedInitializer(_class2$12.prototype, "startDelay", [_dec14$2, serializable$p], function () {
        return new CurveRange();
      }), _initializer13$8 = applyDecoratedInitializer(_class2$12.prototype, "startLifetime", [_dec15$2, serializable$p], function () {
        return new CurveRange();
      }), _initializer14$7 = applyDecoratedInitializer(_class2$12.prototype, "duration", [serializable$p], function () {
        return 5.0;
      }), _initializer15$6 = applyDecoratedInitializer(_class2$12.prototype, "loop", [serializable$p], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "simulationSpace", [_dec16$2, serializable$p], Object.getOwnPropertyDescriptor(_class2$12.prototype, "simulationSpace"), _class2$12.prototype), _initializer16$6 = applyDecoratedInitializer(_class2$12.prototype, "simulationSpeed", [serializable$p], function () {
        return 1.0;
      }), _initializer17$4 = applyDecoratedInitializer(_class2$12.prototype, "playOnAwake", [serializable$p], function () {
        return true;
      }), _initializer18$4 = applyDecoratedInitializer(_class2$12.prototype, "gravityModifier", [_dec17$2, serializable$p], function () {
        return new CurveRange();
      }), _initializer19$3 = applyDecoratedInitializer(_class2$12.prototype, "rateOverTime", [_dec18$2, serializable$p], function () {
        return new CurveRange();
      }), _initializer20$3 = applyDecoratedInitializer(_class2$12.prototype, "rateOverDistance", [_dec19$2, serializable$p], function () {
        return new CurveRange();
      }), _initializer21$3 = applyDecoratedInitializer(_class2$12.prototype, "bursts", [_dec20$2, serializable$p], function () {
        return [];
      }), _applyDecoratedDescriptor(_class2$12.prototype, "renderCulling", [_dec21$2], Object.getOwnPropertyDescriptor(_class2$12.prototype, "renderCulling"), _class2$12.prototype), _initializer22$3 = applyDecoratedInitializer(_class2$12.prototype, "_renderCulling", [serializable$p], function () {
        return false;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "cullingMode", [_dec22$2], Object.getOwnPropertyDescriptor(_class2$12.prototype, "cullingMode"), _class2$12.prototype), _initializer23$2 = applyDecoratedInitializer(_class2$12.prototype, "_cullingMode", [serializable$p], function () {
        return CullingMode.Pause;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "aabbHalfX", [_dec23$2], Object.getOwnPropertyDescriptor(_class2$12.prototype, "aabbHalfX"), _class2$12.prototype), _initializer24$2 = applyDecoratedInitializer(_class2$12.prototype, "_aabbHalfX", [serializable$p], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "aabbHalfY", [_dec24$2], Object.getOwnPropertyDescriptor(_class2$12.prototype, "aabbHalfY"), _class2$12.prototype), _initializer25$2 = applyDecoratedInitializer(_class2$12.prototype, "_aabbHalfY", [serializable$p], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "aabbHalfZ", [_dec25$2], Object.getOwnPropertyDescriptor(_class2$12.prototype, "aabbHalfZ"), _class2$12.prototype), _initializer26$2 = applyDecoratedInitializer(_class2$12.prototype, "_aabbHalfZ", [serializable$p], function () {
        return 0;
      }), _initializer27$2 = applyDecoratedInitializer(_class2$12.prototype, "_dataCulling", [serializable$p, _dec26$2], function () {
        return false;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "sharedMaterials", [override$1, serializable$p], Object.getOwnPropertyDescriptor(_class2$12.prototype, "sharedMaterials"), _class2$12.prototype), _initializer28$2 = applyDecoratedInitializer(_class2$12.prototype, "_colorOverLifetimeModule", [_dec27$2], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "colorOverLifetimeModule", [_dec28$2], Object.getOwnPropertyDescriptor(_class2$12.prototype, "colorOverLifetimeModule"), _class2$12.prototype), _initializer29$2 = applyDecoratedInitializer(_class2$12.prototype, "_shapeModule", [_dec29$2], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "shapeModule", [_dec30$1], Object.getOwnPropertyDescriptor(_class2$12.prototype, "shapeModule"), _class2$12.prototype), _initializer30$2 = applyDecoratedInitializer(_class2$12.prototype, "_sizeOvertimeModule", [_dec31$1], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "sizeOvertimeModule", [_dec32$1], Object.getOwnPropertyDescriptor(_class2$12.prototype, "sizeOvertimeModule"), _class2$12.prototype), _initializer31$2 = applyDecoratedInitializer(_class2$12.prototype, "_velocityOvertimeModule", [_dec33$1], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "velocityOvertimeModule", [_dec34$1], Object.getOwnPropertyDescriptor(_class2$12.prototype, "velocityOvertimeModule"), _class2$12.prototype), _initializer32$2 = applyDecoratedInitializer(_class2$12.prototype, "_forceOvertimeModule", [_dec35$1], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "forceOvertimeModule", [_dec36$1], Object.getOwnPropertyDescriptor(_class2$12.prototype, "forceOvertimeModule"), _class2$12.prototype), _initializer33$2 = applyDecoratedInitializer(_class2$12.prototype, "_limitVelocityOvertimeModule", [_dec37$1], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "limitVelocityOvertimeModule", [_dec38$1], Object.getOwnPropertyDescriptor(_class2$12.prototype, "limitVelocityOvertimeModule"), _class2$12.prototype), _initializer34$2 = applyDecoratedInitializer(_class2$12.prototype, "_rotationOvertimeModule", [_dec39$1], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "rotationOvertimeModule", [_dec40$1], Object.getOwnPropertyDescriptor(_class2$12.prototype, "rotationOvertimeModule"), _class2$12.prototype), _initializer35$2 = applyDecoratedInitializer(_class2$12.prototype, "_textureAnimationModule", [_dec41$1], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "textureAnimationModule", [_dec42$1], Object.getOwnPropertyDescriptor(_class2$12.prototype, "textureAnimationModule"), _class2$12.prototype), _initializer36$2 = applyDecoratedInitializer(_class2$12.prototype, "_noiseModule", [_dec43$1], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "noiseModule", [_dec44$1], Object.getOwnPropertyDescriptor(_class2$12.prototype, "noiseModule"), _class2$12.prototype), _initializer37$2 = applyDecoratedInitializer(_class2$12.prototype, "_trailModule", [_dec45$1], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$12.prototype, "trailModule", [_dec46$1], Object.getOwnPropertyDescriptor(_class2$12.prototype, "trailModule"), _class2$12.prototype), _initializer38$2 = applyDecoratedInitializer(_class2$12.prototype, "renderer", [_dec47$1, serializable$p], function () {
        return new ParticleSystemRenderer();
      }), _initializer39$2 = applyDecoratedInitializer(_class2$12.prototype, "_prewarm", [serializable$p], function () {
        return false;
      }), _initializer40$2 = applyDecoratedInitializer(_class2$12.prototype, "_capacity", [serializable$p], function () {
        return 100;
      }), _initializer41$2 = applyDecoratedInitializer(_class2$12.prototype, "_simulationSpace", [serializable$p], function () {
        return Space.Local;
      })), _class2$12)) || _class$15) || _class$15));

      var ParticleUtils = exports('f7', function () {
        function ParticleUtils() {}
        ParticleUtils.instantiate = function instantiate$1(prefab) {
          if (!this.registeredSceneEvent) {
            director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, this.onSceneUnload, this);
            this.registeredSceneEvent = true;
          }
          if (!this.particleSystemPool.has(prefab._uuid)) {
            this.particleSystemPool.set(prefab._uuid, new Pool(function () {
              return instantiate(prefab) || new Node$1();
            }, 1, function (prefab) {
              return prefab.destroy();
            }));
          }
          return this.particleSystemPool.get(prefab._uuid).alloc();
        };
        ParticleUtils.destroy = function destroy(prefab) {
          if (this.particleSystemPool.has(prefab._prefab.asset._uuid)) {
            this.stop(prefab);
            this.particleSystemPool.get(prefab._prefab.asset._uuid).free(prefab);
          }
        };
        ParticleUtils.play = function play(rootNode) {
          for (var _iterator = _createForOfIteratorHelperLoose(rootNode.getComponentsInChildren(ParticleSystem)), _step; !(_step = _iterator()).done;) {
            var ps = _step.value;
            ps.play();
          }
        };
        ParticleUtils.stop = function stop(rootNode) {
          for (var _iterator2 = _createForOfIteratorHelperLoose(rootNode.getComponentsInChildren(ParticleSystem)), _step2; !(_step2 = _iterator2()).done;) {
            var ps = _step2.value;
            ps.stop();
          }
        };
        ParticleUtils.onSceneUnload = function onSceneUnload() {
          this.particleSystemPool.forEach(function (value) {
            return value.destroy();
          });
          this.particleSystemPool.clear();
        };
        return ParticleUtils;
      }());
      ParticleUtils.particleSystemPool = new Map();
      ParticleUtils.registeredSceneEvent = false;

      removeProperty(Burst.prototype, 'Burst.prototype', [{
        name: 'minCount'
      }, {
        name: 'maxCount'
      }]);
      replaceProperty(ParticleSystem.prototype, 'ParticleSystem.prototype', [{
        name: 'enableCulling',
        newName: 'dataCulling'
      }]);
      legacyCC.ParticleSystemComponent = ParticleSystem;
      setClassAlias(ParticleSystem, 'cc.ParticleSystemComponent');
      legacyCC.BillboardComponent = Billboard;
      setClassAlias(Billboard, 'cc.BillboardComponent');
      legacyCC.LineComponent = Line;
      setClassAlias(Line, 'cc.LineComponent');

      legacyCC.ParticleUtils = ParticleUtils;

      var DURATION_INFINITY = -1;
      var START_SIZE_EQUAL_TO_END_SIZE = -1;
      var START_RADIUS_EQUAL_TO_END_RADIUS = -1;
      var EmitterMode = Enum({
        GRAVITY: 0,
        RADIUS: 1
      });
      var PositionType = Enum({
        FREE: 0,
        RELATIVE: 1,
        GROUPED: 2
      });

      var ZERO_VEC2 = new Vec2(0, 0);
      var _pos = new Vec2();
      var _tpa = new Vec2();
      var _tpb = new Vec2();
      var _tpc = new Vec2();
      var formatBytes = getComponentPerVertex(vfmtPosUvColor);
      function getWorldRotation(node) {
        var rotation = 0;
        var tempNode = node;
        while (tempNode) {
          rotation += tempNode.eulerAngles.z;
          tempNode = tempNode.parent;
        }
        return rotation;
      }
      var Particle = function Particle() {
        this.pos = new Vec2(0, 0);
        this.startPos = new Vec2(0, 0);
        this.color = new Color$1(0, 0, 0, 255);
        this.deltaColor = {
          r: 0,
          g: 0,
          b: 0,
          a: 255
        };
        this.size = 0;
        this.deltaSize = 0;
        this.rotation = 0;
        this.deltaRotation = 0;
        this.timeToLive = 0;
        this.drawPos = new Vec2(0, 0);
        this.aspectRatio = 1;
        this.dir = new Vec2(0, 0);
        this.radialAccel = 0;
        this.tangentialAccel = 0;
        this.angle = 0;
        this.degreesPerSecond = 0;
        this.radius = 0;
        this.deltaRadius = 0;
      };
      var ParticlePool = function (_js$Pool) {
        _inheritsLoose(ParticlePool, _js$Pool);
        function ParticlePool() {
          return _js$Pool.apply(this, arguments) || this;
        }
        var _proto = ParticlePool.prototype;
        _proto.get = function get() {
          return this._get() || new Particle();
        };
        return ParticlePool;
      }(Pool$1);
      var pool = new ParticlePool(function (par) {
        par.pos.set(ZERO_VEC2);
        par.startPos.set(ZERO_VEC2);
        par.color._val = 0xFF000000;
        par.deltaColor.r = par.deltaColor.g = par.deltaColor.b = 0;
        par.deltaColor.a = 255;
        par.size = 0;
        par.deltaSize = 0;
        par.rotation = 0;
        par.deltaRotation = 0;
        par.timeToLive = 0;
        par.drawPos.set(ZERO_VEC2);
        par.aspectRatio = 1;
        par.dir.set(ZERO_VEC2);
        par.radialAccel = 0;
        par.tangentialAccel = 0;
        par.angle = 0;
        par.degreesPerSecond = 0;
        par.radius = 0;
        par.deltaRadius = 0;
      }, 1024);
      var Simulator = function () {
        function Simulator(system) {
          this.particles = [];
          this.active = false;
          this.uvFilled = 0;
          this.finished = false;
          this.readyToPlay = true;
          this.elapsed = 0;
          this.emitCounter = 0;
          this._worldRotation = 0;
          this.sys = system;
          this.particles = [];
          this.active = false;
          this.readyToPlay = true;
          this.finished = false;
          this.elapsed = 0;
          this.emitCounter = 0;
          this.uvFilled = 0;
          this._worldRotation = 0;
        }
        var _proto2 = Simulator.prototype;
        _proto2.stop = function stop() {
          this.active = false;
          this.readyToPlay = false;
          this.elapsed = this.sys.duration;
          this.emitCounter = 0;
        };
        _proto2.reset = function reset() {
          this.active = true;
          this.readyToPlay = true;
          this.elapsed = 0;
          this.emitCounter = 0;
          this.finished = false;
          var particles = this.particles;
          for (var id = 0; id < particles.length; ++id) pool.put(particles[id]);
          particles.length = 0;
          this.renderData.resize(0, 0);
        };
        _proto2.emitParticle = function emitParticle(pos) {
          var psys = this.sys;
          var particle = pool.get();
          this.particles.push(particle);
          particle.timeToLive = psys.life + psys.lifeVar * (random() - 0.5) * 2;
          var timeToLive = particle.timeToLive = Math.max(0, particle.timeToLive);
          particle.pos.x = psys.sourcePos.x + psys.posVar.x * (random() - 0.5) * 2;
          particle.pos.y = psys.sourcePos.y + psys.posVar.y * (random() - 0.5) * 2;
          var sr = 0;
          var sg = 0;
          var sb = 0;
          var sa = 0;
          var startColor = psys.startColor;
          var startColorVar = psys.startColorVar;
          var endColor = psys.endColor;
          var endColorVar = psys.endColorVar;
          particle.color.r = sr = clampf(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255);
          particle.color.g = sg = clampf(startColor.g + startColorVar.g * (random() - 0.5) * 2, 0, 255);
          particle.color.b = sb = clampf(startColor.b + startColorVar.b * (random() - 0.5) * 2, 0, 255);
          particle.color.a = sa = clampf(startColor.a + startColorVar.a * (random() - 0.5) * 2, 0, 255);
          particle.deltaColor.r = (clampf(endColor.r + endColorVar.r * (random() - 0.5) * 2, 0, 255) - sr) / timeToLive;
          particle.deltaColor.g = (clampf(endColor.g + endColorVar.g * (random() - 0.5) * 2, 0, 255) - sg) / timeToLive;
          particle.deltaColor.b = (clampf(endColor.b + endColorVar.b * (random() - 0.5) * 2, 0, 255) - sb) / timeToLive;
          particle.deltaColor.a = (clampf(endColor.a + endColorVar.a * (random() - 0.5) * 2, 0, 255) - sa) / timeToLive;
          var startS = psys.startSize + psys.startSizeVar * (random() - 0.5) * 2;
          startS = Math.max(0, startS);
          particle.size = startS;
          if (psys.endSize === START_SIZE_EQUAL_TO_END_SIZE) {
            particle.deltaSize = 0;
          } else {
            var endS = psys.endSize + psys.endSizeVar * (random() - 0.5) * 2;
            endS = Math.max(0, endS);
            particle.deltaSize = (endS - startS) / timeToLive;
          }
          var startA = psys.startSpin + psys.startSpinVar * (random() - 0.5) * 2;
          var endA = psys.endSpin + psys.endSpinVar * (random() - 0.5) * 2;
          particle.rotation = startA;
          particle.deltaRotation = (endA - startA) / timeToLive;
          particle.startPos.x = pos.x;
          particle.startPos.y = pos.y;
          particle.aspectRatio = psys.aspectRatio || 1;
          var a = degreesToRadians(psys.angle + this._worldRotation + psys.angleVar * (random() - 0.5) * 2);
          if (psys.emitterMode === EmitterMode.GRAVITY) {
            var s = psys.speed + psys.speedVar * (random() - 0.5) * 2;
            particle.dir.x = Math.cos(a);
            particle.dir.y = Math.sin(a);
            particle.dir.multiplyScalar(s);
            particle.radialAccel = psys.radialAccel + psys.radialAccelVar * (random() - 0.5) * 2;
            particle.tangentialAccel = psys.tangentialAccel + psys.tangentialAccelVar * (random() - 0.5) * 2;
            if (psys.rotationIsDir) {
              particle.rotation = -radiansToDegrees(Math.atan2(particle.dir.y, particle.dir.x));
            }
          } else {
            var startRadius = psys.startRadius + psys.startRadiusVar * (random() - 0.5) * 2;
            var endRadius = psys.endRadius + psys.endRadiusVar * (random() - 0.5) * 2;
            particle.radius = startRadius;
            particle.deltaRadius = psys.endRadius === START_RADIUS_EQUAL_TO_END_RADIUS ? 0 : (endRadius - startRadius) / timeToLive;
            particle.angle = a;
            particle.degreesPerSecond = degreesToRadians(psys.rotatePerS + psys.rotatePerSVar * (random() - 0.5) * 2);
          }
        };
        _proto2.updateUVs = function updateUVs(force) {
          var renderData = this.renderData;
          if (renderData && this.sys._renderSpriteFrame) {
            var vbuf = renderData.vData;
            var uv = this.sys._renderSpriteFrame.uv;
            var start = force ? 0 : this.uvFilled;
            var particleCount = this.particles.length;
            for (var i = start; i < particleCount; i++) {
              var offset = i * formatBytes * 4;
              vbuf[offset + 3] = uv[0];
              vbuf[offset + 4] = uv[1];
              vbuf[offset + 12] = uv[2];
              vbuf[offset + 13] = uv[3];
              vbuf[offset + 21] = uv[4];
              vbuf[offset + 22] = uv[5];
              vbuf[offset + 30] = uv[6];
              vbuf[offset + 31] = uv[7];
            }
            this.uvFilled = particleCount;
          }
        };
        _proto2.updateParticleBuffer = function updateParticleBuffer(particle, pos, buffer, offset) {
          var vbuf = buffer.vData;
          var x = pos.x;
          var y = pos.y;
          var width = particle.size;
          var height = width;
          var aspectRatio = particle.aspectRatio;
          if (aspectRatio > 1) {
            height = width / aspectRatio;
          } else {
            width = height * aspectRatio;
          }
          var halfWidth = width / 2;
          var halfHeight = height / 2;
          if (particle.rotation) {
            var x1 = -halfWidth;
            var y1 = -halfHeight;
            var x2 = halfWidth;
            var y2 = halfHeight;
            var rad = -degreesToRadians(particle.rotation);
            var cr = Math.cos(rad);
            var sr = Math.sin(rad);
            vbuf[offset] = x1 * cr - y1 * sr + x;
            vbuf[offset + 1] = x1 * sr + y1 * cr + y;
            vbuf[offset + 2] = 0;
            vbuf[offset + 9] = x2 * cr - y1 * sr + x;
            vbuf[offset + 10] = x2 * sr + y1 * cr + y;
            vbuf[offset + 11] = 0;
            vbuf[offset + 18] = x1 * cr - y2 * sr + x;
            vbuf[offset + 19] = x1 * sr + y2 * cr + y;
            vbuf[offset + 20] = 0;
            vbuf[offset + 27] = x2 * cr - y2 * sr + x;
            vbuf[offset + 28] = x2 * sr + y2 * cr + y;
            vbuf[offset + 29] = 0;
          } else {
            vbuf[offset] = x - halfWidth;
            vbuf[offset + 1] = y - halfHeight;
            vbuf[offset + 2] = 0;
            vbuf[offset + 9] = x + halfWidth;
            vbuf[offset + 10] = y - halfHeight;
            vbuf[offset + 11] = 0;
            vbuf[offset + 18] = x - halfWidth;
            vbuf[offset + 19] = y + halfHeight;
            vbuf[offset + 20] = 0;
            vbuf[offset + 27] = x + halfWidth;
            vbuf[offset + 28] = y + halfHeight;
            vbuf[offset + 29] = 0;
          }
          Color$1.toArray(vbuf, particle.color, offset + 5);
          Color$1.toArray(vbuf, particle.color, offset + 14);
          Color$1.toArray(vbuf, particle.color, offset + 23);
          Color$1.toArray(vbuf, particle.color, offset + 32);
        };
        _proto2.step = function step(dt) {
          var assembler = this.sys.assembler;
          var psys = this.sys;
          var node = psys.node;
          var particles = this.particles;
          dt = dt > assembler.maxParticleDeltaTime ? assembler.maxParticleDeltaTime : dt;
          node.updateWorldTransform();
          if (psys.positionType === PositionType.FREE) {
            this._worldRotation = getWorldRotation(node);
            var m = node.worldMatrix;
            _pos.x = m.m12;
            _pos.y = m.m13;
          } else if (psys.positionType === PositionType.RELATIVE) {
            this._worldRotation = node.eulerAngles.z;
            _pos.x = node.position.x;
            _pos.y = node.position.y;
          } else {
            this._worldRotation = 0;
          }
          if (this.active && psys.emissionRate) {
            var rate = 1.0 / psys.emissionRate;
            if (particles.length < psys.totalParticles) this.emitCounter += dt;
            while (particles.length < psys.totalParticles && this.emitCounter > rate) {
              this.emitParticle(_pos);
              this.emitCounter -= rate;
            }
            this.elapsed += dt;
            if (psys.duration !== -1 && psys.duration < this.elapsed) {
              psys.stopSystem();
            }
          }
          var renderData = this.renderData;
          var particleCount = particles.length;
          renderData.reset();
          this.requestData(particleCount * 4, particleCount * 6);
          if (particleCount > this.uvFilled) {
            this.updateUVs();
          }
          var particleIdx = 0;
          while (particleIdx < particles.length) {
            _tpa.x = _tpa.y = _tpb.x = _tpb.y = _tpc.x = _tpc.y = 0;
            var particle = particles[particleIdx];
            particle.timeToLive -= dt;
            if (particle.timeToLive > 0) {
              if (psys.emitterMode === EmitterMode.GRAVITY) {
                var tmp = _tpc;
                var radial = _tpa;
                var tangential = _tpb;
                if (particle.pos.x || particle.pos.y) {
                  radial.set(particle.pos);
                  radial.normalize();
                }
                tangential.set(radial);
                radial.multiplyScalar(particle.radialAccel);
                var newy = tangential.x;
                tangential.x = -tangential.y;
                tangential.y = newy;
                tangential.multiplyScalar(particle.tangentialAccel);
                tmp.set(radial);
                tmp.add(tangential);
                tmp.add(psys.gravity);
                tmp.multiplyScalar(dt);
                particle.dir.add(tmp);
                tmp.set(particle.dir);
                tmp.multiplyScalar(dt);
                particle.pos.add(tmp);
              } else {
                particle.angle += particle.degreesPerSecond * dt;
                particle.radius += particle.deltaRadius * dt;
                particle.pos.x = -Math.cos(particle.angle) * particle.radius;
                particle.pos.y = -Math.sin(particle.angle) * particle.radius;
              }
              particle.color.r += particle.deltaColor.r * dt;
              particle.color.g += particle.deltaColor.g * dt;
              particle.color.b += particle.deltaColor.b * dt;
              particle.color.a += particle.deltaColor.a * dt;
              particle.size += particle.deltaSize * dt;
              if (particle.size < 0) {
                particle.size = 0;
              }
              particle.rotation += particle.deltaRotation * dt;
              var newPos = _tpa;
              newPos.set(particle.pos);
              if (psys.positionType !== PositionType.GROUPED) {
                newPos.add(particle.startPos);
              }
              var offset = formatBytes * particleIdx * 4;
              this.updateParticleBuffer(particle, newPos, renderData, offset);
              ++particleIdx;
            } else {
              var deadParticle = particles[particleIdx];
              if (particleIdx !== particles.length - 1) {
                particles[particleIdx] = particles[particles.length - 1];
              }
              pool.put(deadParticle);
              particles.length--;
              renderData.resize(renderData.vertexCount - 4, renderData.indexCount - 6);
            }
          }
          this.renderData.material = this.sys.getRenderMaterial(0);
          this.renderData.frame = this.sys._renderSpriteFrame;
          renderData.setRenderDrawInfoAttributes();
          if (particles.length === 0 && !this.active && !this.readyToPlay) {
            this.finished = true;
            psys._finishedSimulation();
          }
        };
        _proto2.requestData = function requestData(vertexCount, indexCount) {
          var offset = this.renderData.indexCount;
          this.renderData.request(vertexCount, indexCount);
          var count = this.renderData.indexCount / 6;
          var buffer = this.renderData.iData;
          for (var i = offset; i < count; i++) {
            var vId = i * 4;
            buffer[offset++] = vId;
            buffer[offset++] = vId + 1;
            buffer[offset++] = vId + 2;
            buffer[offset++] = vId + 1;
            buffer[offset++] = vId + 3;
            buffer[offset++] = vId + 2;
          }
        };
        _proto2.initDrawInfo = function initDrawInfo() {
          var renderData = this.renderData;
          renderData.setRenderDrawInfoAttributes();
        };
        return Simulator;
      }();

      var _dec$16, _class$14, _class2$11, _initializer$$;
      var ccclass$e = ccclass$M,
        serializable = serializable$p;
      var ParticleAsset = exports('ff', (_dec$16 = ccclass$e('cc.ParticleAsset'), _dec$16(_class$14 = (_class2$11 = function (_Asset) {
        _inheritsLoose(ParticleAsset, _Asset);
        function ParticleAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.spriteFrame = _initializer$$ && _initializer$$();
          return _this;
        }
        return ParticleAsset;
      }(Asset), (_initializer$$ = applyDecoratedInitializer(_class2$11.prototype, "spriteFrame", [serializable], function () {
        return null;
      })), _class2$11)) || _class$14));
      legacyCC.ParticleAsset = ParticleAsset;

      var PNGReader = function () {
        function PNGReader(data) {
          var _this = this;
          this.pos = 8;
          this.palette = [];
          this.imgData = [];
          this.text = {};
          this.width = 0;
          this.height = 0;
          this.bits = 0;
          this.colorType = 0;
          this.compressionMethod = 0;
          this.filterMethod = 0;
          this.interlaceMethod = 0;
          this.colors = 0;
          this.hasAlphaChannel = false;
          this.pixelBitlength = 0;
          this.data = data;
          this.transparency = {
            indexed: [],
            rgb: 0,
            grayscale: 0
          };
          var frame;
          var _i = 0;
          var _j = 0;
          var chunkSize = 0;
          while (true) {
            chunkSize = this.readUInt32();
            var section = function () {
              var _results = [];
              for (_i = 0; _i < 4; ++_i) {
                _results.push(String.fromCharCode(_this.data[_this.pos++]));
              }
              return _results;
            }.call(this).join('');
            switch (section) {
              case 'IHDR':
                this.width = this.readUInt32();
                this.height = this.readUInt32();
                this.bits = this.data[this.pos++];
                this.colorType = this.data[this.pos++];
                this.compressionMethod = this.data[this.pos++];
                this.filterMethod = this.data[this.pos++];
                this.interlaceMethod = this.data[this.pos++];
                break;
              case 'acTL':
                this.animation = {
                  numFrames: this.readUInt32(),
                  numPlays: this.readUInt32() || Infinity,
                  frames: []
                };
                break;
              case 'PLTE':
                this.palette = this.read(chunkSize);
                break;
              case 'fcTL':
                if (frame) {
                  this.animation.frames.push(frame);
                }
                this.pos += 4;
                frame = {
                  width: this.readUInt32(),
                  height: this.readUInt32(),
                  xOffset: this.readUInt32(),
                  yOffset: this.readUInt32()
                };
                var delayNum = this.readUInt16();
                var delayDen = this.readUInt16() || 100;
                frame.delay = 1000 * delayNum / delayDen;
                frame.disposeOp = this.data[this.pos++];
                frame.blendOp = this.data[this.pos++];
                frame.data = [];
                break;
              case 'IDAT':
              case 'fdAT':
                if (section === 'fdAT') {
                  this.pos += 4;
                  chunkSize -= 4;
                }
                data = (frame != null ? frame.data : void 0) || this.imgData;
                for (_i = 0; chunkSize >= 0 ? _i < chunkSize : _i > chunkSize; chunkSize >= 0 ? ++_i : --_i) {
                  data.push(this.data[this.pos++]);
                }
                break;
              case 'tRNS':
                this.transparency = {};
                switch (this.colorType) {
                  case 3:
                    this.transparency.indexed = this.read(chunkSize);
                    var ccshort = 255 - this.transparency.indexed.length;
                    if (ccshort > 0) {
                      for (_j = 0; ccshort >= 0 ? _j < ccshort : _j > ccshort; ccshort >= 0 ? ++_j : --_j) {
                        this.transparency.indexed.push(255);
                      }
                    }
                    break;
                  case 0:
                    this.transparency.grayscale = this.read(chunkSize)[0];
                    break;
                  case 2:
                    this.transparency.rgb = this.read(chunkSize);
                }
                break;
              case 'tEXt':
                var text = this.read(chunkSize);
                var index = text.indexOf(0);
                var key = String.fromCharCode.apply(String, text.slice(0, index));
                this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
                break;
              case 'IEND':
                if (frame) {
                  this.animation.frames.push(frame);
                }
                this.colors = function () {
                  switch (_this.colorType) {
                    case 0:
                    case 3:
                    case 4:
                      return 1;
                    case 2:
                    case 6:
                      return 3;
                  }
                }.call(this);
                var _ref = this.colorType;
                this.hasAlphaChannel = _ref === 4 || _ref === 6;
                var colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
                this.pixelBitlength = this.bits * colors;
                this.colorSpace = function () {
                  switch (_this.colors) {
                    case 1:
                      return 'DeviceGray';
                    case 3:
                      return 'DeviceRGB';
                  }
                }.call(this);
                if (!(this.imgData instanceof Uint8Array)) {
                  this.imgData = new Uint8Array(this.imgData);
                }
                return;
              default:
                this.pos += chunkSize;
            }
            this.pos += 4;
            if (this.pos > this.data.length) {
              throw new Error(getError(6017));
            }
          }
        }
        var _proto = PNGReader.prototype;
        _proto.read = function read(bytes) {
          var _i = 0;
          var _results = [];
          for (_i = 0; bytes >= 0 ? _i < bytes : _i > bytes; bytes >= 0 ? ++_i : --_i) {
            _results.push(this.data[this.pos++]);
          }
          return _results;
        };
        _proto.readUInt32 = function readUInt32() {
          var b1 = this.data[this.pos++] << 24;
          var b2 = this.data[this.pos++] << 16;
          var b3 = this.data[this.pos++] << 8;
          var b4 = this.data[this.pos++];
          return b1 | b2 | b3 | b4;
        };
        _proto.readUInt16 = function readUInt16() {
          var b1 = this.data[this.pos++] << 8;
          var b2 = this.data[this.pos++];
          return b1 | b2;
        };
        _proto.decodePixels = function decodePixels(data) {
          if (data == null) {
            data = this.imgData;
          }
          if (data.length === 0) {
            return new Uint8Array(0);
          }
          var inflate = new _p.Inflate(data, {
            index: 0,
            verify: false
          });
          data = inflate.decompress();
          var pixelBytes = this.pixelBitlength / 8;
          var scanlineLength = pixelBytes * this.width;
          var pixels = new Uint8Array(scanlineLength * this.height);
          var length = data.length;
          var row = 0;
          var pos = 0;
          var c = 0;
          var ccbyte = 0;
          var col = 0;
          var i = 0;
          var _i = 0;
          var _j = 0;
          var _k = 0;
          var _l = 0;
          var _m = 0;
          var left = 0;
          var p = 0;
          var pa = 0;
          var paeth = 0;
          var pb = 0;
          var pc = 0;
          var upper = 0;
          var upperLeft = 0;
          while (pos < length) {
            switch (data[pos++]) {
              case 0:
                for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
                  pixels[c++] = data[pos++];
                }
                break;
              case 1:
                for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
                  ccbyte = data[pos++];
                  left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
                  pixels[c++] = (ccbyte + left) % 256;
                }
                break;
              case 2:
                for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
                  ccbyte = data[pos++];
                  col = (i - i % pixelBytes) / pixelBytes;
                  upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
                  pixels[c++] = (upper + ccbyte) % 256;
                }
                break;
              case 3:
                for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
                  ccbyte = data[pos++];
                  col = (i - i % pixelBytes) / pixelBytes;
                  left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
                  upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
                  pixels[c++] = (ccbyte + Math.floor((left + upper) / 2)) % 256;
                }
                break;
              case 4:
                for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
                  ccbyte = data[pos++];
                  col = (i - i % pixelBytes) / pixelBytes;
                  left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
                  if (row === 0) {
                    upper = upperLeft = 0;
                  } else {
                    upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
                    upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + i % pixelBytes];
                  }
                  p = left + upper - upperLeft;
                  pa = Math.abs(p - left);
                  pb = Math.abs(p - upper);
                  pc = Math.abs(p - upperLeft);
                  if (pa <= pb && pa <= pc) {
                    paeth = left;
                  } else if (pb <= pc) {
                    paeth = upper;
                  } else {
                    paeth = upperLeft;
                  }
                  pixels[c++] = (ccbyte + paeth) % 256;
                }
                break;
              default:
                throw new Error(getError(6018, data[pos - 1]));
            }
            row++;
          }
          return pixels;
        };
        _proto.copyToImageData = function copyToImageData(imageData, pixels) {
          var alpha = this.hasAlphaChannel;
          var palette;
          var colors = this.colors;
          if (this.palette.length) {
            palette = this._decodedPalette != null ? this._decodedPalette : this._decodedPalette = this.decodePalette();
            colors = 4;
            alpha = true;
          }
          var data = imageData.data || imageData;
          var length = data.length;
          var input = palette || pixels;
          var i = 0;
          var j = 0;
          var k = 0;
          var v = 0;
          if (colors === 1) {
            while (i < length) {
              k = palette ? pixels[i / 4] * 4 : j;
              v = input[k++];
              data[i++] = v;
              data[i++] = v;
              data[i++] = v;
              data[i++] = alpha ? input[k++] : 255;
              j = k;
            }
          } else {
            while (i < length) {
              k = palette ? pixels[i / 4] * 4 : j;
              data[i++] = input[k++];
              data[i++] = input[k++];
              data[i++] = input[k++];
              data[i++] = alpha ? input[k++] : 255;
              j = k;
            }
          }
        };
        _proto.decodePalette = function decodePalette() {
          var palette = this.palette;
          var transparency = this.transparency.indexed || [];
          var ret = new Uint8Array((transparency.length || 0) + palette.length);
          var pos = 0;
          var c = 0;
          var _ref1 = 0;
          for (var i = 0, _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
            ret[pos++] = palette[i];
            ret[pos++] = palette[i + 1];
            ret[pos++] = palette[i + 2];
            _ref1 = transparency[c++];
            ret[pos++] = _ref1 != null ? _ref1 : 255;
          }
          return ret;
        };
        _proto.render = function render(canvas) {
          canvas.width = this.width;
          canvas.height = this.height;
          var ctx = canvas.getContext('2d');
          var data = ctx.createImageData(this.width, this.height);
          this.copyToImageData(data, this.decodePixels(null));
          return ctx.putImageData(data, 0, 0);
        };
        return PNGReader;
      }();

      var TiffReader = function () {
        function TiffReader() {
          this._littleEndian = false;
          this._tiffData = [];
          this._fileDirectories = [];
        }
        var _proto = TiffReader.prototype;
        _proto.getUint8 = function getUint8(offset) {
          return this._tiffData[offset];
        };
        _proto.getUint16 = function getUint16(offset) {
          if (this._littleEndian) return this._tiffData[offset + 1] << 8 | this._tiffData[offset];else return this._tiffData[offset] << 8 | this._tiffData[offset + 1];
        };
        _proto.getUint32 = function getUint32(offset) {
          var a = this._tiffData;
          if (this._littleEndian) return a[offset + 3] << 24 | a[offset + 2] << 16 | a[offset + 1] << 8 | a[offset];else return a[offset] << 24 | a[offset + 1] << 16 | a[offset + 2] << 8 | a[offset + 3];
        };
        _proto.checkLittleEndian = function checkLittleEndian() {
          var BOM = this.getUint16(0);
          if (BOM === 0x4949) {
            this._littleEndian = true;
          } else if (BOM === 0x4D4D) {
            this._littleEndian = false;
          } else {
            console.log(BOM);
            throw TypeError(getError(6019));
          }
          return this._littleEndian;
        };
        _proto.hasTowel = function hasTowel() {
          if (this.getUint16(2) !== 42) {
            throw RangeError(getError(6020));
          }
          return true;
        };
        _proto.getFieldTypeName = function getFieldTypeName(fieldType) {
          var typeNames = fieldTypeNames;
          if (fieldType in typeNames) {
            return typeNames[fieldType];
          }
          return null;
        };
        _proto.getFieldTagName = function getFieldTagName(fieldTag) {
          var tagNames = fieldTagNames;
          if (fieldTag in tagNames) {
            return tagNames[fieldTag];
          } else {
            logID(6021, fieldTag);
            return "Tag" + fieldTag;
          }
        };
        _proto.getFieldTypeLength = function getFieldTypeLength(fieldTypeName) {
          if (['BYTE', 'ASCII', 'SBYTE', 'UNDEFINED'].indexOf(fieldTypeName) !== -1) {
            return 1;
          } else if (['SHORT', 'SSHORT'].indexOf(fieldTypeName) !== -1) {
            return 2;
          } else if (['LONG', 'SLONG', 'FLOAT'].indexOf(fieldTypeName) !== -1) {
            return 4;
          } else if (['RATIONAL', 'SRATIONAL', 'DOUBLE'].indexOf(fieldTypeName) !== -1) {
            return 8;
          }
          return 0;
        };
        _proto.getFieldValues = function getFieldValues(fieldTagName, fieldTypeName, typeCount, valueOffset) {
          var fieldValues = [];
          var fieldTypeLength = this.getFieldTypeLength(fieldTypeName);
          var fieldValueSize = fieldTypeLength * typeCount;
          if (fieldValueSize <= 4) {
            if (this._littleEndian === false) fieldValues.push(valueOffset >>> (4 - fieldTypeLength) * 8);else fieldValues.push(valueOffset);
          } else {
            for (var i = 0; i < typeCount; i++) {
              var indexOffset = fieldTypeLength * i;
              if (fieldTypeLength >= 8) {
                if (['RATIONAL', 'SRATIONAL'].indexOf(fieldTypeName) !== -1) {
                  fieldValues.push(this.getUint32(valueOffset + indexOffset));
                  fieldValues.push(this.getUint32(valueOffset + indexOffset + 4));
                } else {
                  logID(8000);
                }
              } else {
                fieldValues.push(this.getBytes(fieldTypeLength, valueOffset + indexOffset));
              }
            }
          }
          if (fieldTypeName === 'ASCII') {
            fieldValues.forEach(function (e, i, a) {
              a[i] = String.fromCharCode(e);
            });
          }
          return fieldValues;
        };
        _proto.getBytes = function getBytes(numBytes, offset) {
          if (numBytes <= 0) {
            logID(8001);
          } else if (numBytes <= 1) {
            return this.getUint8(offset);
          } else if (numBytes <= 2) {
            return this.getUint16(offset);
          } else if (numBytes <= 3) {
            return this.getUint32(offset) >>> 8;
          } else if (numBytes <= 4) {
            return this.getUint32(offset);
          } else {
            logID(8002);
          }
          return 0;
        };
        _proto.getBits = function getBits(numBits, byteOffset, bitOffset) {
          bitOffset = bitOffset || 0;
          var extraBytes = Math.floor(bitOffset / 8);
          var newByteOffset = byteOffset + extraBytes;
          var totalBits = bitOffset + numBits;
          var shiftRight = 32 - numBits;
          var shiftLeft = 0;
          var rawBits = 0;
          if (totalBits <= 0) {
            logID(6023);
          } else if (totalBits <= 8) {
            shiftLeft = 24 + bitOffset;
            rawBits = this.getUint8(newByteOffset);
          } else if (totalBits <= 16) {
            shiftLeft = 16 + bitOffset;
            rawBits = this.getUint16(newByteOffset);
          } else if (totalBits <= 32) {
            shiftLeft = bitOffset;
            rawBits = this.getUint32(newByteOffset);
          } else {
            logID(6022);
          }
          return {
            bits: rawBits << shiftLeft >>> shiftRight,
            byteOffset: newByteOffset + Math.floor(totalBits / 8),
            bitOffset: totalBits % 8
          };
        };
        _proto.parseFileDirectory = function parseFileDirectory(offset) {
          var numDirEntries = this.getUint16(offset);
          var tiffFields = [];
          var i = 0;
          var entryCount = 0;
          for (i = offset + 2, entryCount = 0; entryCount < numDirEntries; i += 12, entryCount++) {
            var fieldTag = this.getUint16(i);
            var fieldType = this.getUint16(i + 2);
            var typeCount = this.getUint32(i + 4);
            var valueOffset = this.getUint32(i + 8);
            var fieldTagName = this.getFieldTagName(fieldTag);
            var fieldTypeName = this.getFieldTypeName(fieldType);
            var fieldValues = this.getFieldValues(fieldTagName, fieldTypeName, typeCount, valueOffset);
            tiffFields[fieldTagName] = {
              type: fieldTypeName,
              values: fieldValues
            };
          }
          this._fileDirectories.push(tiffFields);
          var nextIFDByteOffset = this.getUint32(i);
          if (nextIFDByteOffset !== 0x00000000) {
            this.parseFileDirectory(nextIFDByteOffset);
          }
        };
        _proto.clampColorSample = function clampColorSample(colorSample, bitsPerSample) {
          var multiplier = Math.pow(2, 8 - bitsPerSample);
          return Math.floor(colorSample * multiplier + (multiplier - 1));
        };
        _proto.parseTIFF = function parseTIFF(tiffData, canvas) {
          var _this = this;
          canvas = canvas || ccwindow.document.createElement('canvas');
          this._tiffData = tiffData;
          this._canvas = canvas;
          this.checkLittleEndian();
          if (!this.hasTowel()) {
            return;
          }
          var firstIFDByteOffset = this.getUint32(4);
          this._fileDirectories.length = 0;
          this.parseFileDirectory(firstIFDByteOffset);
          var fileDirectory = this._fileDirectories[0];
          var imageWidth = fileDirectory.ImageWidth.values[0];
          var imageLength = fileDirectory.ImageLength.values[0];
          this._canvas.width = imageWidth;
          this._canvas.height = imageLength;
          var strips = [];
          var compression = fileDirectory.Compression ? fileDirectory.Compression.values[0] : 1;
          var samplesPerPixel = fileDirectory.SamplesPerPixel.values[0];
          var sampleProperties = [];
          var bitsPerPixel = 0;
          var hasBytesPerPixel = false;
          fileDirectory.BitsPerSample.values.forEach(function (bitsPerSample, i, bitsPerSampleValues) {
            sampleProperties[i] = {
              bitsPerSample: bitsPerSample,
              hasBytesPerSample: false,
              bytesPerSample: undefined
            };
            if (bitsPerSample % 8 === 0) {
              sampleProperties[i].hasBytesPerSample = true;
              sampleProperties[i].bytesPerSample = bitsPerSample / 8;
            }
            bitsPerPixel += bitsPerSample;
          }, this);
          var bytesPerPixel = 0;
          if (bitsPerPixel % 8 === 0) {
            hasBytesPerPixel = true;
            bytesPerPixel = bitsPerPixel / 8;
          }
          var stripOffsetValues = fileDirectory.StripOffsets.values;
          var numStripOffsetValues = stripOffsetValues.length;
          var stripByteCountValues;
          if (fileDirectory.StripByteCounts) {
            stripByteCountValues = fileDirectory.StripByteCounts.values;
          } else {
            logID(8003);
            if (numStripOffsetValues === 1) {
              stripByteCountValues = [Math.ceil(imageWidth * imageLength * bitsPerPixel / 8)];
            } else {
              throw Error(getError(6024));
            }
          }
          var blockLength = 1;
          var iterations = 1;
          for (var i = 0; i < numStripOffsetValues; i++) {
            var stripOffset = stripOffsetValues[i];
            strips[i] = [];
            var stripByteCount = stripByteCountValues[i];
            for (var byteOffset = 0, bitOffset = 0, jIncrement = 1, getHeader = true, pixel = [], numBytes = 0, sample = 0, currentSample = 0; byteOffset < stripByteCount; byteOffset += jIncrement) {
              switch (compression) {
                case 1:
                  pixel = [];
                  for (var m = 0; m < samplesPerPixel; m++) {
                    var s = sampleProperties[m];
                    if (s.hasBytesPerSample) {
                      var sampleOffset = s.bytesPerSample * m;
                      pixel.push(this.getBytes(s.bytesPerSample, stripOffset + byteOffset + sampleOffset));
                    } else {
                      var sampleInfo = this.getBits(s.bitsPerSample, stripOffset + byteOffset, bitOffset);
                      pixel.push(sampleInfo.bits);
                      byteOffset = sampleInfo.byteOffset - stripOffset;
                      bitOffset = sampleInfo.bitOffset;
                      throw RangeError(getError(6025));
                    }
                  }
                  strips[i].push(pixel);
                  if (hasBytesPerPixel) {
                    jIncrement = bytesPerPixel;
                  } else {
                    jIncrement = 0;
                    throw RangeError(getError(6026));
                  }
                  break;
                case 2:
                  break;
                case 3:
                  break;
                case 4:
                  break;
                case 5:
                  break;
                case 6:
                  break;
                case 7:
                  break;
                case 32773:
                  if (getHeader) {
                    getHeader = false;
                    var header = this.getUint8(stripOffset + byteOffset);
                    if (header >= 0 && header <= 127) {
                      blockLength = header + 1;
                    } else if (header >= -127 && header <= -1) {
                      iterations = -header + 1;
                    } else {
                        getHeader = true;
                      }
                  } else {
                    var currentByte = this.getUint8(stripOffset + byteOffset);
                    for (var _m = 0; _m < iterations; _m++) {
                      var _s = sampleProperties[sample];
                      if (_s.hasBytesPerSample) {
                        currentSample = currentSample << 8 * numBytes | currentByte;
                        numBytes++;
                        if (numBytes === _s.bytesPerSample) {
                          pixel.push(currentSample);
                          currentSample = numBytes = 0;
                          sample++;
                        }
                      } else {
                        throw RangeError(getError(6025));
                      }
                      if (sample === samplesPerPixel) {
                        strips[i].push(pixel);
                        pixel = [];
                        sample = 0;
                      }
                    }
                    blockLength--;
                    if (blockLength === 0) {
                      getHeader = true;
                    }
                  }
                  jIncrement = 1;
                  break;
              }
            }
          }
          if (canvas.getContext) {
            var ctx = this._canvas.getContext('2d');
            ctx.fillStyle = 'rgba(255, 255, 255, 0)';
            var rowsPerStrip = fileDirectory.RowsPerStrip ? fileDirectory.RowsPerStrip.values[0] : imageLength;
            var numStrips = strips.length;
            var imageLengthModRowsPerStrip = imageLength % rowsPerStrip;
            var rowsInLastStrip = imageLengthModRowsPerStrip === 0 ? rowsPerStrip : imageLengthModRowsPerStrip;
            var numRowsInStrip = rowsPerStrip;
            var numRowsInPreviousStrip = 0;
            var photometricInterpretation = fileDirectory.PhotometricInterpretation.values[0];
            var extraSamplesValues = [];
            var numExtraSamples = 0;
            if (fileDirectory.ExtraSamples) {
              extraSamplesValues = fileDirectory.ExtraSamples.values;
              numExtraSamples = extraSamplesValues.length;
            }
            var colorMapValues = [];
            var colorMapSampleSize = 0;
            if (fileDirectory.ColorMap) {
              colorMapValues = fileDirectory.ColorMap.values;
              colorMapSampleSize = Math.pow(2, sampleProperties[0].bitsPerSample);
            }
            for (var _i = 0; _i < numStrips; _i++) {
              if (_i + 1 === numStrips) {
                numRowsInStrip = rowsInLastStrip;
              }
              var numPixels = strips[_i].length;
              var yPadding = numRowsInPreviousStrip * _i;
              for (var y = 0, j = 0; y < numRowsInStrip && j < numPixels; y++) {
                var _loop = function _loop() {
                  var pixelSamples = strips[_i][j];
                  var red = 0;
                  var green = 0;
                  var blue = 0;
                  var opacity = 1.0;
                  if (numExtraSamples > 0) {
                    for (var k = 0; k < numExtraSamples; k++) {
                      if (extraSamplesValues[k] === 1 || extraSamplesValues[k] === 2) {
                        opacity = pixelSamples[3 + k] / 256;
                        break;
                      }
                    }
                  }
                  switch (photometricInterpretation) {
                    case 0:
                      var invertValue = 0;
                      if (sampleProperties[0].hasBytesPerSample) {
                        invertValue = Math.pow(0x10, sampleProperties[0].bytesPerSample * 2);
                      }
                      pixelSamples.forEach(function (sample, index, samples) {
                        samples[index] = invertValue - sample;
                      });
                    case 1:
                      red = green = blue = _this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample);
                      break;
                    case 2:
                      red = _this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample);
                      green = _this.clampColorSample(pixelSamples[1], sampleProperties[1].bitsPerSample);
                      blue = _this.clampColorSample(pixelSamples[2], sampleProperties[2].bitsPerSample);
                      break;
                    case 3:
                      if (colorMapValues === undefined) {
                        throw Error(getError(6027));
                      }
                      var colorMapIndex = pixelSamples[0];
                      red = _this.clampColorSample(colorMapValues[colorMapIndex], 16);
                      green = _this.clampColorSample(colorMapValues[colorMapSampleSize + colorMapIndex], 16);
                      blue = _this.clampColorSample(colorMapValues[2 * colorMapSampleSize + colorMapIndex], 16);
                      break;
                    default:
                      throw RangeError(getError(6028, photometricInterpretation));
                  }
                  ctx.fillStyle = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity + ")";
                  ctx.fillRect(x, yPadding + y, 1, 1);
                };
                for (var x = 0; x < imageWidth; x++, j++) {
                  _loop();
                }
              }
              numRowsInPreviousStrip = numRowsInStrip;
            }
          }
          return this._canvas;
        };
        return TiffReader;
      }();
      var fieldTagNames = {
        0x013B: 'Artist',
        0x0102: 'BitsPerSample',
        0x0109: 'CellLength',
        0x0108: 'CellWidth',
        0x0140: 'ColorMap',
        0x0103: 'Compression',
        0x8298: 'Copyright',
        0x0132: 'DateTime',
        0x0152: 'ExtraSamples',
        0x010A: 'FillOrder',
        0x0121: 'FreeByteCounts',
        0x0120: 'FreeOffsets',
        0x0123: 'GrayResponseCurve',
        0x0122: 'GrayResponseUnit',
        0x013C: 'HostComputer',
        0x010E: 'ImageDescription',
        0x0101: 'ImageLength',
        0x0100: 'ImageWidth',
        0x010F: 'Make',
        0x0119: 'MaxSampleValue',
        0x0118: 'MinSampleValue',
        0x0110: 'Model',
        0x00FE: 'NewSubfileType',
        0x0112: 'Orientation',
        0x0106: 'PhotometricInterpretation',
        0x011C: 'PlanarConfiguration',
        0x0128: 'ResolutionUnit',
        0x0116: 'RowsPerStrip',
        0x0115: 'SamplesPerPixel',
        0x0131: 'Software',
        0x0117: 'StripByteCounts',
        0x0111: 'StripOffsets',
        0x00FF: 'SubfileType',
        0x0107: 'Threshholding',
        0x011A: 'XResolution',
        0x011B: 'YResolution',
        0x0146: 'BadFaxLines',
        0x0147: 'CleanFaxData',
        0x0157: 'ClipPath',
        0x0148: 'ConsecutiveBadFaxLines',
        0x01B1: 'Decode',
        0x01B2: 'DefaultImageColor',
        0x010D: 'DocumentName',
        0x0150: 'DotRange',
        0x0141: 'HalftoneHints',
        0x015A: 'Indexed',
        0x015B: 'JPEGTables',
        0x011D: 'PageName',
        0x0129: 'PageNumber',
        0x013D: 'Predictor',
        0x013F: 'PrimaryChromaticities',
        0x0214: 'ReferenceBlackWhite',
        0x0153: 'SampleFormat',
        0x022F: 'StripRowCounts',
        0x014A: 'SubIFDs',
        0x0124: 'T4Options',
        0x0125: 'T6Options',
        0x0145: 'TileByteCounts',
        0x0143: 'TileLength',
        0x0144: 'TileOffsets',
        0x0142: 'TileWidth',
        0x012D: 'TransferFunction',
        0x013E: 'WhitePoint',
        0x0158: 'XClipPathUnits',
        0x011E: 'XPosition',
        0x0211: 'YCbCrCoefficients',
        0x0213: 'YCbCrPositioning',
        0x0212: 'YCbCrSubSampling',
        0x0159: 'YClipPathUnits',
        0x011F: 'YPosition',
        0x9202: 'ApertureValue',
        0xA001: 'ColorSpace',
        0x9004: 'DateTimeDigitized',
        0x9003: 'DateTimeOriginal',
        0x8769: 'Exif IFD',
        0x9000: 'ExifVersion',
        0x829A: 'ExposureTime',
        0xA300: 'FileSource',
        0x9209: 'Flash',
        0xA000: 'FlashpixVersion',
        0x829D: 'FNumber',
        0xA420: 'ImageUniqueID',
        0x9208: 'LightSource',
        0x927C: 'MakerNote',
        0x9201: 'ShutterSpeedValue',
        0x9286: 'UserComment',
        0x83BB: 'IPTC',
        0x8773: 'ICC Profile',
        0x02BC: 'XMP',
        0xA480: 'GDAL_METADATA',
        0xA481: 'GDAL_NODATA',
        0x8649: 'Photoshop'
      };
      var fieldTypeNames = {
        0x0001: 'BYTE',
        0x0002: 'ASCII',
        0x0003: 'SHORT',
        0x0004: 'LONG',
        0x0005: 'RATIONAL',
        0x0006: 'SBYTE',
        0x0007: 'UNDEFINED',
        0x0008: 'SSHORT',
        0x0009: 'SLONG',
        0x000A: 'SRATIONAL',
        0x000B: 'FLOAT',
        0x000C: 'DOUBLE'
      };

      var BASE64_KEYS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
      var BASE64_VALUES = new Array(123);
      for (var i$1 = 0; i$1 < 123; ++i$1) {
        BASE64_VALUES[i$1] = 64;
      }
      for (var _i = 0; _i < 64; ++_i) {
        BASE64_VALUES[BASE64_KEYS.charCodeAt(_i)] = _i;
      }

      var Base64 = {
        name: 'Jacob__Codec__Base64'
      };
      Base64.decode = function Jacob__Codec__Base64__decode(input) {
        var output = [],
          chr1,
          chr2,
          chr3,
          enc1,
          enc2,
          enc3,
          enc4,
          i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
          enc1 = BASE64_VALUES[input.charCodeAt(i++)];
          enc2 = BASE64_VALUES[input.charCodeAt(i++)];
          enc3 = BASE64_VALUES[input.charCodeAt(i++)];
          enc4 = BASE64_VALUES[input.charCodeAt(i++)];
          chr1 = enc1 << 2 | enc2 >> 4;
          chr2 = (enc2 & 15) << 4 | enc3 >> 2;
          chr3 = (enc3 & 3) << 6 | enc4;
          output.push(String.fromCharCode(chr1));
          if (enc3 !== 64) {
            output.push(String.fromCharCode(chr2));
          }
          if (enc4 !== 64) {
            output.push(String.fromCharCode(chr3));
          }
        }
        output = output.join('');
        return output;
      };
      Base64.decodeAsArray = function Jacob__Codec__Base64___decodeAsArray(input, bytes) {
        var dec = this.decode(input),
          ar = [],
          i,
          j,
          len;
        for (i = 0, len = dec.length / bytes; i < len; i++) {
          ar[i] = 0;
          for (j = bytes - 1; j >= 0; --j) {
            ar[i] += dec.charCodeAt(i * bytes + j) << j * 8;
          }
        }
        return ar;
      };

      var GZip = function Jacob__GZip(data) {
        this.data = data;
        this.debug = false;
        this.gpflags = undefined;
        this.files = 0;
        this.unzipped = [];
        this.buf32k = new Array(32768);
        this.bIdx = 0;
        this.modeZIP = false;
        this.bytepos = 0;
        this.bb = 1;
        this.bits = 0;
        this.nameBuf = [];
        this.fileout = undefined;
        this.literalTree = new Array(GZip.LITERALS);
        this.distanceTree = new Array(32);
        this.treepos = 0;
        this.Places = null;
        this.len = 0;
        this.fpos = new Array(17);
        this.fpos[0] = 0;
        this.flens = undefined;
        this.fmax = undefined;
      };
      GZip.gunzip = function (string) {
        if (string.constructor === Array) ; else if (string.constructor === String) ;
        var gzip = new GZip(string);
        return gzip.gunzip()[0][0];
      };
      GZip.HufNode = function () {
        this.b0 = 0;
        this.b1 = 0;
        this.jump = null;
        this.jumppos = -1;
      };
      GZip.LITERALS = 288;
      GZip.NAMEMAX = 256;
      GZip.bitReverse = [0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff];
      GZip.cplens = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0];
      GZip.cplext = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99];
      GZip.cpdist = [0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0007, 0x0009, 0x000d, 0x0011, 0x0019, 0x0021, 0x0031, 0x0041, 0x0061, 0x0081, 0x00c1, 0x0101, 0x0181, 0x0201, 0x0301, 0x0401, 0x0601, 0x0801, 0x0c01, 0x1001, 0x1801, 0x2001, 0x3001, 0x4001, 0x6001];
      GZip.cpdext = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
      GZip.border = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
      GZip.prototype.gunzip = function () {
        this.outputArr = [];
        this.nextFile();
        return this.unzipped;
      };
      GZip.prototype.readByte = function () {
        this.bits += 8;
        if (this.bytepos < this.data.length) {
          return this.data.charCodeAt(this.bytepos++);
        } else {
          return -1;
        }
      };
      GZip.prototype.byteAlign = function () {
        this.bb = 1;
      };
      GZip.prototype.readBit = function () {
        var carry;
        this.bits++;
        carry = this.bb & 1;
        this.bb >>= 1;
        if (this.bb === 0) {
          this.bb = this.readByte();
          carry = this.bb & 1;
          this.bb = this.bb >> 1 | 0x80;
        }
        return carry;
      };
      GZip.prototype.readBits = function (a) {
        var res = 0,
          i = a;
        while (i--) res = res << 1 | this.readBit();
        if (a) res = GZip.bitReverse[res] >> 8 - a;
        return res;
      };
      GZip.prototype.flushBuffer = function () {
        this.bIdx = 0;
      };
      GZip.prototype.addBuffer = function (a) {
        this.buf32k[this.bIdx++] = a;
        this.outputArr.push(String.fromCharCode(a));
        if (this.bIdx === 0x8000) this.bIdx = 0;
      };
      GZip.prototype.IsPat = function () {
        while (1) {
          if (this.fpos[this.len] >= this.fmax) return -1;
          if (this.flens[this.fpos[this.len]] === this.len) return this.fpos[this.len]++;
          this.fpos[this.len]++;
        }
      };
      GZip.prototype.Rec = function () {
        var curplace = this.Places[this.treepos];
        var tmp;
        if (this.len === 17) {
          return -1;
        }
        this.treepos++;
        this.len++;
        tmp = this.IsPat();
        if (tmp >= 0) {
          curplace.b0 = tmp;
        } else {
          curplace.b0 = 0x8000;
          if (this.Rec()) return -1;
        }
        tmp = this.IsPat();
        if (tmp >= 0) {
          curplace.b1 = tmp;
          curplace.jump = null;
        } else {
          curplace.b1 = 0x8000;
          curplace.jump = this.Places[this.treepos];
          curplace.jumppos = this.treepos;
          if (this.Rec()) return -1;
        }
        this.len--;
        return 0;
      };
      GZip.prototype.CreateTree = function (currentTree, numval, lengths, show) {
        var i;
        this.Places = currentTree;
        this.treepos = 0;
        this.flens = lengths;
        this.fmax = numval;
        for (i = 0; i < 17; i++) this.fpos[i] = 0;
        this.len = 0;
        if (this.Rec()) {
          return -1;
        }
        return 0;
      };
      GZip.prototype.DecodeValue = function (currentTree) {
        var len,
          i,
          xtreepos = 0,
          X = currentTree[xtreepos],
          b;
        while (1) {
          b = this.readBit();
          if (b) {
            if (!(X.b1 & 0x8000)) {
              return X.b1;
            }
            X = X.jump;
            len = currentTree.length;
            for (i = 0; i < len; i++) {
              if (currentTree[i] === X) {
                xtreepos = i;
                break;
              }
            }
          } else {
            if (!(X.b0 & 0x8000)) {
              return X.b0;
            }
            xtreepos++;
            X = currentTree[xtreepos];
          }
        }
        return -1;
      };
      GZip.prototype.DeflateLoop = function () {
        var last, c, type, i, len;
        do {
          last = this.readBit();
          type = this.readBits(2);
          if (type === 0) {
            var blockLen, cSum;
            this.byteAlign();
            blockLen = this.readByte();
            blockLen |= this.readByte() << 8;
            cSum = this.readByte();
            cSum |= this.readByte() << 8;
            if ((blockLen ^ ~cSum) & 0xffff) {
              document.write("BlockLen checksum mismatch\n");
            }
            while (blockLen--) {
              c = this.readByte();
              this.addBuffer(c);
            }
          } else if (type === 1) {
            var j;
            while (1) {
              j = GZip.bitReverse[this.readBits(7)] >> 1;
              if (j > 23) {
                j = j << 1 | this.readBit();
                if (j > 199) {
                  j -= 128;
                  j = j << 1 | this.readBit();
                } else {
                  j -= 48;
                  if (j > 143) {
                    j = j + 136;
                  }
                }
              } else {
                j += 256;
              }
              if (j < 256) {
                this.addBuffer(j);
              } else if (j === 256) {
                break;
              } else {
                var len, dist;
                j -= 256 + 1;
                len = this.readBits(GZip.cplext[j]) + GZip.cplens[j];
                j = GZip.bitReverse[this.readBits(5)] >> 3;
                if (GZip.cpdext[j] > 8) {
                  dist = this.readBits(8);
                  dist |= this.readBits(GZip.cpdext[j] - 8) << 8;
                } else {
                  dist = this.readBits(GZip.cpdext[j]);
                }
                dist += GZip.cpdist[j];
                for (j = 0; j < len; j++) {
                  var c = this.buf32k[this.bIdx - dist & 0x7fff];
                  this.addBuffer(c);
                }
              }
            }
          } else if (type === 2) {
            var j, n, literalCodes, distCodes, lenCodes;
            var ll = new Array(288 + 32);
            literalCodes = 257 + this.readBits(5);
            distCodes = 1 + this.readBits(5);
            lenCodes = 4 + this.readBits(4);
            for (j = 0; j < 19; j++) {
              ll[j] = 0;
            }
            for (j = 0; j < lenCodes; j++) {
              ll[GZip.border[j]] = this.readBits(3);
            }
            len = this.distanceTree.length;
            for (i = 0; i < len; i++) this.distanceTree[i] = new GZip.HufNode();
            if (this.CreateTree(this.distanceTree, 19, ll, 0)) {
              this.flushBuffer();
              return 1;
            }
            n = literalCodes + distCodes;
            i = 0;
            while (i < n) {
              j = this.DecodeValue(this.distanceTree);
              if (j < 16) {
                ll[i++] = j;
              } else if (j === 16) {
                var l;
                j = 3 + this.readBits(2);
                if (i + j > n) {
                  this.flushBuffer();
                  return 1;
                }
                l = i ? ll[i - 1] : 0;
                while (j--) {
                  ll[i++] = l;
                }
              } else {
                if (j === 17) {
                  j = 3 + this.readBits(3);
                } else {
                  j = 11 + this.readBits(7);
                }
                if (i + j > n) {
                  this.flushBuffer();
                  return 1;
                }
                while (j--) {
                  ll[i++] = 0;
                }
              }
            }
            len = this.literalTree.length;
            for (i = 0; i < len; i++) this.literalTree[i] = new GZip.HufNode();
            if (this.CreateTree(this.literalTree, literalCodes, ll, 0)) {
              this.flushBuffer();
              return 1;
            }
            len = this.literalTree.length;
            for (i = 0; i < len; i++) this.distanceTree[i] = new GZip.HufNode();
            var ll2 = new Array();
            for (i = literalCodes; i < ll.length; i++) ll2[i - literalCodes] = ll[i];
            if (this.CreateTree(this.distanceTree, distCodes, ll2, 0)) {
              this.flushBuffer();
              return 1;
            }
            while (1) {
              j = this.DecodeValue(this.literalTree);
              if (j >= 256) {
                var len, dist;
                j -= 256;
                if (j === 0) {
                  break;
                }
                j--;
                len = this.readBits(GZip.cplext[j]) + GZip.cplens[j];
                j = this.DecodeValue(this.distanceTree);
                if (GZip.cpdext[j] > 8) {
                  dist = this.readBits(8);
                  dist |= this.readBits(GZip.cpdext[j] - 8) << 8;
                } else {
                  dist = this.readBits(GZip.cpdext[j]);
                }
                dist += GZip.cpdist[j];
                while (len--) {
                  var c = this.buf32k[this.bIdx - dist & 0x7fff];
                  this.addBuffer(c);
                }
              } else {
                this.addBuffer(j);
              }
            }
          }
        } while (!last);
        this.flushBuffer();
        this.byteAlign();
        return 0;
      };
      GZip.prototype.unzipFile = function (name) {
        var i;
        this.gunzip();
        for (i = 0; i < this.unzipped.length; i++) {
          if (this.unzipped[i][1] === name) {
            return this.unzipped[i][0];
          }
        }
      };
      GZip.prototype.nextFile = function () {
        this.outputArr = [];
        this.modeZIP = false;
        var tmp = [];
        tmp[0] = this.readByte();
        tmp[1] = this.readByte();
        if (tmp[0] === 0x78 && tmp[1] === 0xda) {
          this.DeflateLoop();
          this.unzipped[this.files] = [this.outputArr.join(''), "geonext.gxt"];
          this.files++;
        }
        if (tmp[0] === 0x1f && tmp[1] === 0x8b) {
          this.skipdir();
          this.unzipped[this.files] = [this.outputArr.join(''), "file"];
          this.files++;
        }
        if (tmp[0] === 0x50 && tmp[1] === 0x4b) {
          this.modeZIP = true;
          tmp[2] = this.readByte();
          tmp[3] = this.readByte();
          if (tmp[2] === 0x03 && tmp[3] === 0x04) {
            tmp[0] = this.readByte();
            tmp[1] = this.readByte();
            this.gpflags = this.readByte();
            this.gpflags |= this.readByte() << 8;
            var method = this.readByte();
            method |= this.readByte() << 8;
            this.readByte();
            this.readByte();
            this.readByte();
            this.readByte();
            var compSize = this.readByte();
            compSize |= this.readByte() << 8;
            compSize |= this.readByte() << 16;
            compSize |= this.readByte() << 24;
            var size = this.readByte();
            size |= this.readByte() << 8;
            size |= this.readByte() << 16;
            size |= this.readByte() << 24;
            var filelen = this.readByte();
            filelen |= this.readByte() << 8;
            var extralen = this.readByte();
            extralen |= this.readByte() << 8;
            i = 0;
            this.nameBuf = [];
            while (filelen--) {
              var c = this.readByte();
              if (c === "/" | c === ":") {
                i = 0;
              } else if (i < GZip.NAMEMAX - 1) {
                this.nameBuf[i++] = String.fromCharCode(c);
              }
            }
            if (!this.fileout) this.fileout = this.nameBuf;
            var i = 0;
            while (i < extralen) {
              c = this.readByte();
              i++;
            }
            if (method === 8) {
              this.DeflateLoop();
              this.unzipped[this.files] = [this.outputArr.join(''), this.nameBuf.join('')];
              this.files++;
            }
            this.skipdir();
          }
        }
      };
      GZip.prototype.skipdir = function () {
        var tmp = [];
        var compSize, size, i, c;
        if (this.gpflags & 8) {
          tmp[0] = this.readByte();
          tmp[1] = this.readByte();
          tmp[2] = this.readByte();
          tmp[3] = this.readByte();
          compSize = this.readByte();
          compSize |= this.readByte() << 8;
          compSize |= this.readByte() << 16;
          compSize |= this.readByte() << 24;
          size = this.readByte();
          size |= this.readByte() << 8;
          size |= this.readByte() << 16;
          size |= this.readByte() << 24;
        }
        if (this.modeZIP) this.nextFile();
        tmp[0] = this.readByte();
        if (tmp[0] !== 8) {
          return 0;
        }
        this.gpflags = this.readByte();
        this.readByte();
        this.readByte();
        this.readByte();
        this.readByte();
        this.readByte();
        this.readByte();
        if (this.gpflags & 4) {
          tmp[0] = this.readByte();
          tmp[2] = this.readByte();
          this.len = tmp[0] + 256 * tmp[1];
          for (i = 0; i < this.len; i++) this.readByte();
        }
        if (this.gpflags & 8) {
          i = 0;
          this.nameBuf = [];
          while (c = this.readByte()) {
            if (c === "7" || c === ":") i = 0;
            if (i < GZip.NAMEMAX - 1) this.nameBuf[i++] = c;
          }
        }
        if (this.gpflags & 16) {
          while (c = this.readByte()) {}
        }
        if (this.gpflags & 2) {
          this.readByte();
          this.readByte();
        }
        this.DeflateLoop();
        size = this.readByte();
        size |= this.readByte() << 8;
        size |= this.readByte() << 16;
        size |= this.readByte() << 24;
        if (this.modeZIP) this.nextFile();
      };

      var codec = {
        name: 'Jacob__Codec'
      };
      codec.Base64 = Base64;
      codec.GZip = GZip;
      codec.unzip = function () {
        return codec.GZip.gunzip.apply(codec.GZip, arguments);
      };
      codec.unzipBase64 = function () {
        var buffer = codec.Base64.decode.apply(codec.Base64, arguments);
        try {
          return codec.GZip.gunzip.call(codec.GZip, buffer);
        } catch (e) {
          return buffer.slice(7);
        }
      };
      codec.unzipBase64AsArray = function (input, bytes) {
        bytes = bytes || 1;
        var dec = this.unzipBase64(input),
          ar = [],
          i,
          j,
          len;
        for (i = 0, len = dec.length / bytes; i < len; i++) {
          ar[i] = 0;
          for (j = bytes - 1; j >= 0; --j) {
            ar[i] += dec.charCodeAt(i * bytes + j) << j * 8;
          }
        }
        return ar;
      };
      codec.unzipAsArray = function (input, bytes) {
        bytes = bytes || 1;
        var dec = this.unzip(input),
          ar = [],
          i,
          j,
          len;
        for (i = 0, len = dec.length / bytes; i < len; i++) {
          ar[i] = 0;
          for (j = bytes - 1; j >= 0; --j) {
            ar[i] += dec.charCodeAt(i * bytes + j) << j * 8;
          }
        }
        return ar;
      };

      var _dec$15, _dec2$10, _dec3$M, _dec4$A, _dec5$x, _dec6$l, _class$13, _class2$10, _initializer$_, _initializer2$U, _initializer3$F, _initializer4$x, _initializer5$q, _initializer6$m, _initializer7$h, _initializer8$f, _initializer9$d, _initializer10$c, _initializer11$c, _initializer12$a, _initializer13$7, _initializer14$6, _initializer15$5, _initializer16$5, _initializer17$3, _initializer18$3, _initializer19$2, _initializer20$2, _initializer21$2, _initializer22$2, _initializer23$1, _initializer24$1, _initializer25$1, _initializer26$1, _initializer27$1, _initializer28$1, _initializer29$1, _initializer30$1, _initializer31$1, _initializer32$1, _initializer33$1, _initializer34$1, _initializer35$1, _initializer36$1, _initializer37$1, _initializer38$1, _initializer39$1, _initializer40$1, _initializer41$1, _initializer42$1, _initializer43$1, _class3$n;
      var ImageFormat;
      (function (ImageFormat) {
        ImageFormat[ImageFormat["JPG"] = 0] = "JPG";
        ImageFormat[ImageFormat["PNG"] = 1] = "PNG";
        ImageFormat[ImageFormat["TIFF"] = 2] = "TIFF";
        ImageFormat[ImageFormat["WEBP"] = 3] = "WEBP";
        ImageFormat[ImageFormat["PVR"] = 4] = "PVR";
        ImageFormat[ImageFormat["ETC"] = 5] = "ETC";
        ImageFormat[ImageFormat["S3TC"] = 6] = "S3TC";
        ImageFormat[ImageFormat["ATITC"] = 7] = "ATITC";
        ImageFormat[ImageFormat["TGA"] = 8] = "TGA";
        ImageFormat[ImageFormat["RAWDATA"] = 9] = "RAWDATA";
        ImageFormat[ImageFormat["UNKNOWN"] = 10] = "UNKNOWN";
      })(ImageFormat || (ImageFormat = {}));
      function getImageFormatByData(imgData) {
        if (imgData.length > 8 && imgData[0] === 0x89 && imgData[1] === 0x50 && imgData[2] === 0x4E && imgData[3] === 0x47 && imgData[4] === 0x0D && imgData[5] === 0x0A && imgData[6] === 0x1A && imgData[7] === 0x0A) {
          return ImageFormat.PNG;
        }
        if (imgData.length > 2 && (imgData[0] === 0x49 && imgData[1] === 0x49 || imgData[0] === 0x4d && imgData[1] === 0x4d || imgData[0] === 0xff && imgData[1] === 0xd8)) {
          return ImageFormat.TIFF;
        }
        return ImageFormat.UNKNOWN;
      }
      function getParticleComponents(node) {
        var parent = node.parent;
        var comp = node.getComponent(ParticleSystem2D);
        if (!parent || !comp) {
          return node.getComponentsInChildren(ParticleSystem2D);
        }
        return getParticleComponents(parent);
      }
      var ParticleSystem2D = exports('fb', (_dec$15 = ccclass$M('cc.ParticleSystem2D'), _dec2$10 = type$d(ParticleAsset), _dec3$M = type$d(SpriteFrame), _dec4$A = type$d(PositionType), _dec5$x = type$d(EmitterMode), _dec6$l = formerlySerializedAs$4('preview'), _dec$15(_class$13 = (_class2$10 = (_class3$n = function (_UIRenderer) {
        _inheritsLoose(ParticleSystem2D, _UIRenderer);
        function ParticleSystem2D() {
          var _this;
          _this = _UIRenderer.call(this) || this;
          _this.duration = _initializer$_ && _initializer$_();
          _this.emissionRate = _initializer2$U && _initializer2$U();
          _this.life = _initializer3$F && _initializer3$F();
          _this.lifeVar = _initializer4$x && _initializer4$x();
          _this.angle = _initializer5$q && _initializer5$q();
          _this.angleVar = _initializer6$m && _initializer6$m();
          _this.startSize = _initializer7$h && _initializer7$h();
          _this.startSizeVar = _initializer8$f && _initializer8$f();
          _this.endSize = _initializer9$d && _initializer9$d();
          _this.endSizeVar = _initializer10$c && _initializer10$c();
          _this.startSpin = _initializer11$c && _initializer11$c();
          _this.startSpinVar = _initializer12$a && _initializer12$a();
          _this.endSpin = _initializer13$7 && _initializer13$7();
          _this.endSpinVar = _initializer14$6 && _initializer14$6();
          _this.sourcePos = _initializer15$5 && _initializer15$5();
          _this.posVar = _initializer16$5 && _initializer16$5();
          _this.emitterMode = _initializer17$3 && _initializer17$3();
          _this.gravity = _initializer18$3 && _initializer18$3();
          _this.speed = _initializer19$2 && _initializer19$2();
          _this.speedVar = _initializer20$2 && _initializer20$2();
          _this.tangentialAccel = _initializer21$2 && _initializer21$2();
          _this.tangentialAccelVar = _initializer22$2 && _initializer22$2();
          _this.radialAccel = _initializer23$1 && _initializer23$1();
          _this.radialAccelVar = _initializer24$1 && _initializer24$1();
          _this.rotationIsDir = _initializer25$1 && _initializer25$1();
          _this.startRadius = _initializer26$1 && _initializer26$1();
          _this.startRadiusVar = _initializer27$1 && _initializer27$1();
          _this.endRadius = _initializer28$1 && _initializer28$1();
          _this.endRadiusVar = _initializer29$1 && _initializer29$1();
          _this.rotatePerS = _initializer30$1 && _initializer30$1();
          _this.rotatePerSVar = _initializer31$1 && _initializer31$1();
          _this.aspectRatio = 1;
          _this.playOnLoad = _initializer32$1 && _initializer32$1();
          _this.autoRemoveOnFinish = _initializer33$1 && _initializer33$1();
          _this._preview = _initializer34$1 && _initializer34$1();
          _this._custom = _initializer35$1 && _initializer35$1();
          _this._file = _initializer36$1 && _initializer36$1();
          _this._spriteFrame = _initializer37$1 && _initializer37$1();
          _this._totalParticles = _initializer38$1 && _initializer38$1();
          _this._startColor = _initializer39$1 && _initializer39$1();
          _this._startColorVar = _initializer40$1 && _initializer40$1();
          _this._endColor = _initializer41$1 && _initializer41$1();
          _this._endColorVar = _initializer42$1 && _initializer42$1();
          _this._positionType = _initializer43$1 && _initializer43$1();
          _this._stopped = true;
          _this._useFile = void 0;
          _this.initProperties();
          _this._useFile = false;
          return _this;
        }
        var _proto = ParticleSystem2D.prototype;
        _proto.onEnable = function onEnable() {
          _UIRenderer.prototype.onEnable.call(this);
          this._updateMaterial();
          this._updatePositionType();
        };
        _proto.onDestroy = function onDestroy() {
          _UIRenderer.prototype.onDestroy.call(this);
          if (this.autoRemoveOnFinish) {
            this.autoRemoveOnFinish = false;
          }
          this._simulator.uvFilled = 0;
          if (this._simulator.renderData && this._assembler) {
            this._assembler.removeData(this._simulator.renderData);
          }
        };
        _proto.initProperties = function initProperties() {
          this._previewTimer = null;
          this._focused = false;
          this.aspectRatio = 1;
          this._simulator = new Simulator(this);
        };
        _proto.onFocusInEditor = function onFocusInEditor() {
          this._focused = true;
          var components = getParticleComponents(this.node);
          for (var i = 0; i < components.length; ++i) {
            components[i]._startPreview();
          }
        };
        _proto.onLostFocusInEditor = function onLostFocusInEditor() {
          this._focused = false;
          var components = getParticleComponents(this.node);
          for (var i = 0; i < components.length; ++i) {
            components[i]._stopPreview();
          }
        };
        _proto._startPreview = function _startPreview() {
          if (this._preview) {
            this.resetSystem();
          }
        };
        _proto._stopPreview = function _stopPreview() {
          if (this._preview) {
            this.resetSystem();
            this.stopSystem();
          }
          if (this._previewTimer) {
            clearInterval(this._previewTimer);
          }
        };
        _proto.__preload = function __preload() {
          _UIRenderer.prototype.__preload.call(this);
          if (this._custom && this.spriteFrame && !this._renderSpriteFrame) {
            this._applySpriteFrame();
          } else if (this._file) {
            if (this._custom) {
              var missCustomTexture = !this._getTexture();
              if (missCustomTexture) {
                this._applyFile();
              }
            } else {
              this._applyFile();
            }
          }
          {
            if (this.playOnLoad) {
              this.resetSystem();
            }
          }
        };
        _proto._flushAssembler = function _flushAssembler() {
          var assembler = ParticleSystem2D.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
          }
          if (this._assembler && this._assembler.createData) {
            this._simulator.renderData = this._assembler.createData(this);
            this._simulator.renderData.particleInitRenderDrawInfo(this.renderEntity);
            this._simulator.initDrawInfo();
          }
        };
        _proto.lateUpdate = function lateUpdate(dt) {
          if (!this._simulator.finished) {
            this._simulator.step(dt);
          }
        };
        _proto.addParticle = function addParticle() {};
        _proto.stopSystem = function stopSystem() {
          this._stopped = true;
          this._simulator.stop();
        };
        _proto.resetSystem = function resetSystem() {
          this._stopped = false;
          this._simulator.reset();
          this.markForUpdateRenderData();
        };
        _proto.isFull = function isFull() {
          return this.particleCount >= this.totalParticles;
        };
        _proto._applyFile = function _applyFile() {
          var file = this._file;
          if (file) {
            if (!file) {
              errorID(6029);
              return;
            }
            if (!this.isValid) {
              return;
            }
            this._plistFile = file.nativeUrl;
            if (!this._custom) {
              var isDiffFrame = this._spriteFrame !== file.spriteFrame;
              if (isDiffFrame) this.spriteFrame = file.spriteFrame;
              this._initWithDictionary(file._nativeAsset);
            }
            if (!this._spriteFrame) {
              if (file.spriteFrame) {
                this.spriteFrame = file.spriteFrame;
              } else if (this._custom) {
                this._initTextureWithDictionary(file._nativeAsset);
              }
            } else if (!this._renderSpriteFrame && this._spriteFrame) {
              this._applySpriteFrame();
            }
          }
        };
        _proto._initTextureWithDictionary = function _initTextureWithDictionary(dict) {
          var _this2 = this;
          if (dict.spriteFrameUuid) {
            var spriteFrameUuid = dict.spriteFrameUuid;
            assetManager.loadAny(spriteFrameUuid, function (err, spriteFrame) {
              if (err) {
                dict.spriteFrameUuid = undefined;
                _this2._initTextureWithDictionary(dict);
                error(err);
              } else {
                _this2.spriteFrame = spriteFrame;
              }
            });
          } else {
            var imgPath = changeBasename(this._plistFile, dict.textureFileName || '');
            if (dict.textureFileName) {
              assetManager.loadRemote(imgPath, function (err, imageAsset) {
                if (err) {
                  dict.textureFileName = undefined;
                  _this2._initTextureWithDictionary(dict);
                  error(err);
                } else {
                  if (imageAsset) {
                    _this2.spriteFrame = SpriteFrame.createWithImage(imageAsset);
                  } else {
                    _this2.spriteFrame = SpriteFrame.createWithImage(builtinResMgr.get('white-texture'));
                  }
                }
              });
            } else if (dict.textureImageData) {
              var textureData = dict.textureImageData;
              if (textureData && textureData.length > 0) {
                var imgPathName = imgPath;
                if (this.file) {
                  imgPathName += "-" + this.file.uuid;
                }
                var imageAsset = assetManager.assets.get(imgPathName);
                if (!imageAsset) {
                  var buffer = codec.unzipBase64AsArray(textureData, 1);
                  if (!buffer) {
                    warnID(6030, this._file.name);
                    return false;
                  }
                  var imageFormat = getImageFormatByData(buffer);
                  if (imageFormat !== ImageFormat.TIFF && imageFormat !== ImageFormat.PNG) {
                    warnID(6031, this._file.name);
                    return false;
                  }
                  var canvasObj = ccwindow.document.createElement('canvas');
                  if (imageFormat === ImageFormat.PNG) {
                    var myPngObj = new PNGReader(buffer);
                    myPngObj.render(canvasObj);
                  } else {
                    if (!this._tiffReader) {
                      this._tiffReader = new TiffReader();
                    }
                    this._tiffReader.parseTIFF(buffer, canvasObj);
                  }
                  imageAsset = new ImageAsset(canvasObj);
                  assetManager.assets.add(imgPathName, imageAsset);
                }
                if (!imageAsset) {
                  warnID(6032, this._file.name);
                }
                if (imageAsset) {
                  this.spriteFrame = SpriteFrame.createWithImage(imageAsset);
                } else {
                  this.spriteFrame = SpriteFrame.createWithImage(builtinResMgr.get('white-texture'));
                }
              } else {
                return false;
              }
            }
          }
          return true;
        };
        _proto._initWithDictionary = function _initWithDictionary(dict) {
          this._useFile = true;
          this.totalParticles = parseInt(dict.maxParticles || 0);
          this.life = parseFloat(dict.particleLifespan || 0);
          this.lifeVar = parseFloat(dict.particleLifespanVariance || 0);
          var _tempEmissionRate = dict.emissionRate;
          if (_tempEmissionRate) {
            this.emissionRate = _tempEmissionRate;
          } else {
            this.emissionRate = Math.min(this.totalParticles / this.life, Number.MAX_VALUE);
          }
          this.duration = parseFloat(dict.duration || 0);
          this._srcBlendFactor = parseInt(dict.blendFuncSource || BlendFactor.SRC_ALPHA);
          this._dstBlendFactor = parseInt(dict.blendFuncDestination || BlendFactor.ONE_MINUS_SRC_ALPHA);
          var locStartColor = this._startColor;
          locStartColor.r = parseFloat(dict.startColorRed || 0) * 255;
          locStartColor.g = parseFloat(dict.startColorGreen || 0) * 255;
          locStartColor.b = parseFloat(dict.startColorBlue || 0) * 255;
          locStartColor.a = parseFloat(dict.startColorAlpha || 0) * 255;
          var locStartColorVar = this._startColorVar;
          locStartColorVar.r = parseFloat(dict.startColorVarianceRed || 0) * 255;
          locStartColorVar.g = parseFloat(dict.startColorVarianceGreen || 0) * 255;
          locStartColorVar.b = parseFloat(dict.startColorVarianceBlue || 0) * 255;
          locStartColorVar.a = parseFloat(dict.startColorVarianceAlpha || 0) * 255;
          var locEndColor = this._endColor;
          locEndColor.r = parseFloat(dict.finishColorRed || 0) * 255;
          locEndColor.g = parseFloat(dict.finishColorGreen || 0) * 255;
          locEndColor.b = parseFloat(dict.finishColorBlue || 0) * 255;
          locEndColor.a = parseFloat(dict.finishColorAlpha || 0) * 255;
          var locEndColorVar = this._endColorVar;
          locEndColorVar.r = parseFloat(dict.finishColorVarianceRed || 0) * 255;
          locEndColorVar.g = parseFloat(dict.finishColorVarianceGreen || 0) * 255;
          locEndColorVar.b = parseFloat(dict.finishColorVarianceBlue || 0) * 255;
          locEndColorVar.a = parseFloat(dict.finishColorVarianceAlpha || 0) * 255;
          this.startSize = parseFloat(dict.startParticleSize || 0);
          this.startSizeVar = parseFloat(dict.startParticleSizeVariance || 0);
          this.endSize = parseFloat(dict.finishParticleSize || 0);
          this.endSizeVar = parseFloat(dict.finishParticleSizeVariance || 0);
          this.positionType = parseFloat(dict.positionType !== undefined ? dict.positionType : PositionType.FREE);
          this.sourcePos.set(0, 0);
          this.posVar.set(parseFloat(dict.sourcePositionVariancex || 0), parseFloat(dict.sourcePositionVariancey || 0));
          this.angle = parseFloat(dict.angle || 0);
          this.angleVar = parseFloat(dict.angleVariance || 0);
          this.startSpin = parseFloat(dict.rotationStart || 0);
          this.startSpinVar = parseFloat(dict.rotationStartVariance || 0);
          this.endSpin = parseFloat(dict.rotationEnd || 0);
          this.endSpinVar = parseFloat(dict.rotationEndVariance || 0);
          this.emitterMode = parseInt(dict.emitterType || EmitterMode.GRAVITY);
          if (this.emitterMode === EmitterMode.GRAVITY) {
            this.gravity.set(parseFloat(dict.gravityx || 0), parseFloat(dict.gravityy || 0));
            this.speed = parseFloat(dict.speed || 0);
            this.speedVar = parseFloat(dict.speedVariance || 0);
            this.radialAccel = parseFloat(dict.radialAcceleration || 0);
            this.radialAccelVar = parseFloat(dict.radialAccelVariance || 0);
            this.tangentialAccel = parseFloat(dict.tangentialAcceleration || 0);
            this.tangentialAccelVar = parseFloat(dict.tangentialAccelVariance || 0);
            var locRotationIsDir = dict.rotationIsDir || '';
            if (locRotationIsDir !== null) {
              locRotationIsDir = locRotationIsDir.toString().toLowerCase();
              this.rotationIsDir = locRotationIsDir === 'true' || locRotationIsDir === '1';
            } else {
              this.rotationIsDir = false;
            }
          } else if (this.emitterMode === EmitterMode.RADIUS) {
            this.startRadius = parseFloat(dict.maxRadius || 0);
            this.startRadiusVar = parseFloat(dict.maxRadiusVariance || 0);
            this.endRadius = parseFloat(dict.minRadius || 0);
            this.endRadiusVar = parseFloat(dict.minRadiusVariance || 0);
            this.rotatePerS = parseFloat(dict.rotatePerSecond || 0);
            this.rotatePerSVar = parseFloat(dict.rotatePerSecondVariance || 0);
          } else {
            warnID(6009);
            return false;
          }
          this._initTextureWithDictionary(dict);
          return true;
        };
        _proto._syncAspect = function _syncAspect() {
          if (this._renderSpriteFrame) {
            var frameRect = this._renderSpriteFrame.rect;
            this.aspectRatio = frameRect.width / frameRect.height;
          }
        };
        _proto._applySpriteFrame = function _applySpriteFrame() {
          this._renderSpriteFrame = this._renderSpriteFrame || this._spriteFrame;
          if (this._renderSpriteFrame) {
            if (this._renderSpriteFrame.texture) {
              if (this._simulator) {
                this._simulator.updateUVs(true);
              }
              this._syncAspect();
              this._updateMaterial();
              this._stopped = false;
              this.markForUpdateRenderData();
            }
          } else {
            this.resetSystem();
          }
        };
        _proto._getTexture = function _getTexture() {
          return this._renderSpriteFrame && this._renderSpriteFrame.texture;
        };
        _proto._updateMaterial = function _updateMaterial() {
          if (this._customMaterial) {
            this.setSharedMaterial(this._customMaterial, 0);
            var target = this.getRenderMaterial(0).passes[0].blendState.targets[0];
            this._dstBlendFactor = target.blendDst;
            this._srcBlendFactor = target.blendSrc;
          }
          var mat = this.getMaterialInstance(0);
          if (mat) mat.recompileShaders({
            USE_LOCAL: this._positionType !== PositionType.FREE
          });
          if (mat && mat.passes.length > 0) {
            this._updateBlendFunc();
          }
        };
        _proto._finishedSimulation = function _finishedSimulation() {
          this.resetSystem();
          this.stopSystem();
          this.markForUpdateRenderData();
          if (this.autoRemoveOnFinish && this._stopped) {
            this.node.destroy();
          }
        };
        _proto._canRender = function _canRender() {
          return _UIRenderer.prototype._canRender.call(this) && !this._stopped && this._renderSpriteFrame !== null && this._renderSpriteFrame !== undefined;
        };
        _proto._render = function _render(render) {
          if (this._positionType === PositionType.RELATIVE) {
            render.commitComp(this, this._simulator.renderData, this._renderSpriteFrame, this._assembler, this.node.parent);
          } else if (this.positionType === PositionType.GROUPED) {
            render.commitComp(this, this._simulator.renderData, this._renderSpriteFrame, this._assembler, this.node);
          } else {
            render.commitComp(this, this._simulator.renderData, this._renderSpriteFrame, this._assembler, null);
          }
        };
        _proto._updatePositionType = function _updatePositionType() {
          if (this._positionType === PositionType.RELATIVE) {
            this._renderEntity.setRenderTransform(this.node.parent);
            this._renderEntity.setUseLocal(true);
          } else if (this.positionType === PositionType.GROUPED) {
            this._renderEntity.setRenderTransform(this.node);
            this._renderEntity.setUseLocal(true);
          } else {
            this._renderEntity.setRenderTransform(null);
            this._renderEntity.setUseLocal(false);
          }
        };
        _createClass(ParticleSystem2D, [{
          key: "custom",
          get: function get() {
            return this._custom;
          },
          set: function set(value) {
            if (this._custom !== value) {
              this._custom = value;
              this._applyFile();
              this._updateMaterial();
            }
          }
        }, {
          key: "file",
          get: function get() {
            return this._file;
          },
          set: function set(value) {
            if (this._file !== value) {
              this._file = value;
              if (value) {
                this._applyFile();
              } else {
                this.custom = true;
              }
            }
          }
        }, {
          key: "spriteFrame",
          get: function get() {
            return this._spriteFrame;
          },
          set: function set(value) {
            var lastSprite = this._renderSpriteFrame;
            if (lastSprite === value) {
              return;
            }
            this._renderSpriteFrame = value;
            if (!value || value._uuid) {
              this._spriteFrame = value;
            }
            this._applySpriteFrame();
          }
        }, {
          key: "particleCount",
          get: function get() {
            return this._simulator.particles.length;
          }
        }, {
          key: "totalParticles",
          get: function get() {
            return this._totalParticles;
          },
          set: function set(value) {
            if (this._totalParticles === value) return;
            this._totalParticles = value;
          }
        }, {
          key: "startColor",
          get: function get() {
            return this._startColor;
          },
          set: function set(val) {
            this._startColor.r = val.r;
            this._startColor.g = val.g;
            this._startColor.b = val.b;
            this._startColor.a = val.a;
          }
        }, {
          key: "startColorVar",
          get: function get() {
            return this._startColorVar;
          },
          set: function set(val) {
            this._startColorVar.r = val.r;
            this._startColorVar.g = val.g;
            this._startColorVar.b = val.b;
            this._startColorVar.a = val.a;
          }
        }, {
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(value) {}
        }, {
          key: "endColor",
          get: function get() {
            return this._endColor;
          },
          set: function set(val) {
            this._endColor.r = val.r;
            this._endColor.g = val.g;
            this._endColor.b = val.b;
            this._endColor.a = val.a;
          }
        }, {
          key: "endColorVar",
          get: function get() {
            return this._endColorVar;
          },
          set: function set(val) {
            this._endColorVar.r = val.r;
            this._endColorVar.g = val.g;
            this._endColorVar.b = val.b;
            this._endColorVar.a = val.a;
          }
        }, {
          key: "positionType",
          get: function get() {
            return this._positionType;
          },
          set: function set(val) {
            this._positionType = val;
            this._updateMaterial();
            this._updatePositionType();
          }
        }, {
          key: "preview",
          get: function get() {
            return this._preview;
          },
          set: function set(val) {
            if (val) {
              this._startPreview();
            } else {
              this._stopPreview();
            }
            this._preview = val;
          }
        }, {
          key: "stopped",
          get: function get() {
            return this._stopped;
          }
        }, {
          key: "active",
          get: function get() {
            return this._simulator.active;
          }
        }, {
          key: "assembler",
          get: function get() {
            return this._assembler;
          }
        }]);
        return ParticleSystem2D;
      }(UIRenderer), _class3$n.EmitterMode = EmitterMode, _class3$n.PositionType = PositionType, _class3$n.DURATION_INFINITY = DURATION_INFINITY, _class3$n.START_SIZE_EQUAL_TO_END_SIZE = START_SIZE_EQUAL_TO_END_SIZE, _class3$n.START_RADIUS_EQUAL_TO_END_RADIUS = START_RADIUS_EQUAL_TO_END_RADIUS, _class3$n), (_applyDecoratedDescriptor(_class2$10.prototype, "file", [_dec2$10], Object.getOwnPropertyDescriptor(_class2$10.prototype, "file"), _class2$10.prototype), _applyDecoratedDescriptor(_class2$10.prototype, "spriteFrame", [_dec3$M], Object.getOwnPropertyDescriptor(_class2$10.prototype, "spriteFrame"), _class2$10.prototype), _initializer$_ = applyDecoratedInitializer(_class2$10.prototype, "duration", [serializable$p], function () {
        return -1;
      }), _initializer2$U = applyDecoratedInitializer(_class2$10.prototype, "emissionRate", [serializable$p], function () {
        return 10;
      }), _initializer3$F = applyDecoratedInitializer(_class2$10.prototype, "life", [serializable$p], function () {
        return 1;
      }), _initializer4$x = applyDecoratedInitializer(_class2$10.prototype, "lifeVar", [serializable$p], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$10.prototype, "color", [override$1], Object.getOwnPropertyDescriptor(_class2$10.prototype, "color"), _class2$10.prototype), _initializer5$q = applyDecoratedInitializer(_class2$10.prototype, "angle", [serializable$p], function () {
        return 90;
      }), _initializer6$m = applyDecoratedInitializer(_class2$10.prototype, "angleVar", [serializable$p], function () {
        return 20;
      }), _initializer7$h = applyDecoratedInitializer(_class2$10.prototype, "startSize", [serializable$p], function () {
        return 50;
      }), _initializer8$f = applyDecoratedInitializer(_class2$10.prototype, "startSizeVar", [serializable$p], function () {
        return 0;
      }), _initializer9$d = applyDecoratedInitializer(_class2$10.prototype, "endSize", [serializable$p], function () {
        return 0;
      }), _initializer10$c = applyDecoratedInitializer(_class2$10.prototype, "endSizeVar", [serializable$p], function () {
        return 0;
      }), _initializer11$c = applyDecoratedInitializer(_class2$10.prototype, "startSpin", [serializable$p], function () {
        return 0;
      }), _initializer12$a = applyDecoratedInitializer(_class2$10.prototype, "startSpinVar", [serializable$p], function () {
        return 0;
      }), _initializer13$7 = applyDecoratedInitializer(_class2$10.prototype, "endSpin", [serializable$p], function () {
        return 0;
      }), _initializer14$6 = applyDecoratedInitializer(_class2$10.prototype, "endSpinVar", [serializable$p], function () {
        return 0;
      }), _initializer15$5 = applyDecoratedInitializer(_class2$10.prototype, "sourcePos", [serializable$p], function () {
        return Vec2.ZERO.clone();
      }), _initializer16$5 = applyDecoratedInitializer(_class2$10.prototype, "posVar", [serializable$p], function () {
        return Vec2.ZERO.clone();
      }), _applyDecoratedDescriptor(_class2$10.prototype, "positionType", [_dec4$A], Object.getOwnPropertyDescriptor(_class2$10.prototype, "positionType"), _class2$10.prototype), _initializer17$3 = applyDecoratedInitializer(_class2$10.prototype, "emitterMode", [serializable$p, _dec5$x], function () {
        return EmitterMode.GRAVITY;
      }), _initializer18$3 = applyDecoratedInitializer(_class2$10.prototype, "gravity", [serializable$p], function () {
        return Vec2.ZERO.clone();
      }), _initializer19$2 = applyDecoratedInitializer(_class2$10.prototype, "speed", [serializable$p], function () {
        return 180;
      }), _initializer20$2 = applyDecoratedInitializer(_class2$10.prototype, "speedVar", [serializable$p], function () {
        return 50;
      }), _initializer21$2 = applyDecoratedInitializer(_class2$10.prototype, "tangentialAccel", [serializable$p], function () {
        return 80;
      }), _initializer22$2 = applyDecoratedInitializer(_class2$10.prototype, "tangentialAccelVar", [serializable$p], function () {
        return 0;
      }), _initializer23$1 = applyDecoratedInitializer(_class2$10.prototype, "radialAccel", [serializable$p], function () {
        return 0;
      }), _initializer24$1 = applyDecoratedInitializer(_class2$10.prototype, "radialAccelVar", [serializable$p], function () {
        return 0;
      }), _initializer25$1 = applyDecoratedInitializer(_class2$10.prototype, "rotationIsDir", [serializable$p], function () {
        return false;
      }), _initializer26$1 = applyDecoratedInitializer(_class2$10.prototype, "startRadius", [serializable$p], function () {
        return 0;
      }), _initializer27$1 = applyDecoratedInitializer(_class2$10.prototype, "startRadiusVar", [serializable$p], function () {
        return 0;
      }), _initializer28$1 = applyDecoratedInitializer(_class2$10.prototype, "endRadius", [serializable$p], function () {
        return 0;
      }), _initializer29$1 = applyDecoratedInitializer(_class2$10.prototype, "endRadiusVar", [serializable$p], function () {
        return 0;
      }), _initializer30$1 = applyDecoratedInitializer(_class2$10.prototype, "rotatePerS", [serializable$p], function () {
        return 0;
      }), _initializer31$1 = applyDecoratedInitializer(_class2$10.prototype, "rotatePerSVar", [serializable$p], function () {
        return 0;
      }), _initializer32$1 = applyDecoratedInitializer(_class2$10.prototype, "playOnLoad", [serializable$p], function () {
        return true;
      }), _initializer33$1 = applyDecoratedInitializer(_class2$10.prototype, "autoRemoveOnFinish", [serializable$p], function () {
        return false;
      }), _initializer34$1 = applyDecoratedInitializer(_class2$10.prototype, "_preview", [_dec6$l], function () {
        return true;
      }), _initializer35$1 = applyDecoratedInitializer(_class2$10.prototype, "_custom", [serializable$p], function () {
        return false;
      }), _initializer36$1 = applyDecoratedInitializer(_class2$10.prototype, "_file", [serializable$p], function () {
        return null;
      }), _initializer37$1 = applyDecoratedInitializer(_class2$10.prototype, "_spriteFrame", [serializable$p], function () {
        return null;
      }), _initializer38$1 = applyDecoratedInitializer(_class2$10.prototype, "_totalParticles", [serializable$p], function () {
        return 150;
      }), _initializer39$1 = applyDecoratedInitializer(_class2$10.prototype, "_startColor", [serializable$p], function () {
        return new Color$1(255, 255, 255, 255);
      }), _initializer40$1 = applyDecoratedInitializer(_class2$10.prototype, "_startColorVar", [serializable$p], function () {
        return new Color$1(0, 0, 0, 0);
      }), _initializer41$1 = applyDecoratedInitializer(_class2$10.prototype, "_endColor", [serializable$p], function () {
        return new Color$1(255, 255, 255, 0);
      }), _initializer42$1 = applyDecoratedInitializer(_class2$10.prototype, "_endColorVar", [serializable$p], function () {
        return new Color$1(0, 0, 0, 0);
      }), _initializer43$1 = applyDecoratedInitializer(_class2$10.prototype, "_positionType", [serializable$p], function () {
        return PositionType.FREE;
      })), _class2$10)) || _class$13));

      var _dec$14, _dec2$$, _class2$$, _class3$m, _initializer$Z, _initializer2$T, _initializer3$E, _initializer4$w, _initializer5$p, _initializer6$l, _class4$5;
      var Point = function () {
        function Point(point, dir) {
          this.point = new Vec2();
          this.dir = new Vec2();
          this.distance = 0;
          this.time = 0;
          if (point) this.point.set(point);
          if (dir) this.dir.set(dir);
        }
        var _proto = Point.prototype;
        _proto.setPoint = function setPoint(x, y) {
          this.point.x = x;
          this.point.y = y;
        };
        _proto.setDir = function setDir(x, y) {
          this.dir.x = x;
          this.dir.y = y;
        };
        return Point;
      }();
      var MotionStreak = exports('fc', (_dec$14 = ccclass$M('cc.MotionStreak'), _dec2$$ = type$d(Texture2D), _dec$14(_class2$$ = (_class3$m = (_class4$5 = function (_UIRenderer) {
        _inheritsLoose(MotionStreak, _UIRenderer);
        function MotionStreak() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _UIRenderer.call.apply(_UIRenderer, [this].concat(args)) || this;
          _this._preview = _initializer$Z && _initializer$Z();
          _this._fadeTime = _initializer2$T && _initializer2$T();
          _this._minSeg = _initializer3$E && _initializer3$E();
          _this._stroke = _initializer4$w && _initializer4$w();
          _this._texture = _initializer5$p && _initializer5$p();
          _this._fastMode = _initializer6$l && _initializer6$l();
          _this._points = [];
          return _this;
        }
        var _proto2 = MotionStreak.prototype;
        _proto2.onEnable = function onEnable() {
          _UIRenderer.prototype.onEnable.call(this);
          this.reset();
        };
        _proto2._flushAssembler = function _flushAssembler() {
          var assembler = MotionStreak.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
          }
          if (!this._renderData) {
            if (this._assembler && this._assembler.createData) {
              this._renderData = this._assembler.createData(this);
              this._renderData.material = this.material;
              this._updateColor();
            }
          }
        };
        _proto2.onFocusInEditor = function onFocusInEditor() {
          if (this._preview) {
            this.reset();
          }
        };
        _proto2.onLostFocusInEditor = function onLostFocusInEditor() {
          if (this._preview) {
            this.reset();
          }
        };
        _proto2.reset = function reset() {
          this._points.length = 0;
          if (this._renderData) this._renderData.clear();
        };
        _proto2.lateUpdate = function lateUpdate(dt) {
          if (this._assembler) this._assembler.update(this, dt);
        };
        _proto2._render = function _render(render) {
          render.commitComp(this, this._renderData, this._texture, this._assembler, null);
        };
        _createClass(MotionStreak, [{
          key: "preview",
          get: function get() {
            return this._preview;
          },
          set: function set(val) {
            this._preview = val;
            this.reset();
          }
        }, {
          key: "fadeTime",
          get: function get() {
            return this._fadeTime;
          },
          set: function set(val) {
            this._fadeTime = val;
            this.reset();
          }
        }, {
          key: "minSeg",
          get: function get() {
            return this._minSeg;
          },
          set: function set(val) {
            this._minSeg = val;
          }
        }, {
          key: "stroke",
          get: function get() {
            return this._stroke;
          },
          set: function set(val) {
            this._stroke = val;
          }
        }, {
          key: "texture",
          get: function get() {
            return this._texture;
          },
          set: function set(val) {
            if (this._texture === val) return;
            this._texture = val;
          }
        }, {
          key: "fastMode",
          get: function get() {
            return this._fastMode;
          },
          set: function set(val) {
            this._fastMode = val;
          }
        }, {
          key: "points",
          get: function get() {
            return this._points;
          }
        }]);
        return MotionStreak;
      }(UIRenderer), _class4$5.Point = Point, _class4$5), (_applyDecoratedDescriptor(_class3$m.prototype, "texture", [_dec2$$], Object.getOwnPropertyDescriptor(_class3$m.prototype, "texture"), _class3$m.prototype), _initializer$Z = applyDecoratedInitializer(_class3$m.prototype, "_preview", [serializable$p], function () {
        return false;
      }), _initializer2$T = applyDecoratedInitializer(_class3$m.prototype, "_fadeTime", [serializable$p], function () {
        return 1;
      }), _initializer3$E = applyDecoratedInitializer(_class3$m.prototype, "_minSeg", [serializable$p], function () {
        return 1;
      }), _initializer4$w = applyDecoratedInitializer(_class3$m.prototype, "_stroke", [serializable$p], function () {
        return 64;
      }), _initializer5$p = applyDecoratedInitializer(_class3$m.prototype, "_texture", [serializable$p], function () {
        return null;
      }), _initializer6$l = applyDecoratedInitializer(_class3$m.prototype, "_fastMode", [serializable$p], function () {
        return false;
      })), _class3$m)) || _class2$$));

      new Vec2();
      var _normal = new Vec2();
      var _vec2 = new Vec2();
      var QUAD_INDICES;
      function normal(out, dir) {
        out.x = -dir.y;
        out.y = dir.x;
        return out;
      }
      var MotionStreakAssembler = {
        createData: function createData(comp) {
          var renderData = comp.requestRenderData();
          renderData.dataLength = 4;
          renderData.resize(16, (16 - 2) * 3);
          return renderData;
        },
        update: function update(comp, dt) {
          var stroke = comp.stroke / 2;
          var node = comp.node;
          var matrix = node.worldMatrix;
          var tx = matrix.m12;
          var ty = matrix.m13;
          var points = comp.points;
          var cur;
          if (points.length > 1) {
            var point = points[0];
            var difx = point.point.x - tx;
            var dify = point.point.y - ty;
            if (difx * difx + dify * dify < comp.minSeg) {
              cur = point;
            }
          }
          if (!cur) {
            cur = new MotionStreak.Point();
            points.unshift(cur);
          }
          cur.setPoint(tx, ty);
          cur.time = comp.fadeTime + dt;
          var vertexCount = 0;
          var indexCount = 0;
          if (points.length < 2) {
            return;
          }
          var renderData = comp.renderData;
          this.updateRenderDataCache(comp, renderData);
          var color = comp.color;
          var cr = color.r;
          var cg = color.g;
          var cb = color.b;
          var ca = color.a;
          var prev = points[1];
          prev.distance = Vec2.subtract(_vec2, cur.point, prev.point).length();
          _vec2.normalize();
          prev.setDir(_vec2.x, _vec2.y);
          cur.setDir(_vec2.x, _vec2.y);
          renderData.dataLength = points.length * 2;
          var data = renderData.data;
          var fadeTime = comp.fadeTime;
          var findLast = false;
          for (var i = points.length - 1; i >= 0; i--) {
            var p = points[i];
            var _point = p.point;
            var dir = p.dir;
            p.time -= dt;
            if (p.time < 0) {
              points.splice(i, 1);
              continue;
            }
            var progress = p.time / fadeTime;
            var next = points[i - 1];
            if (!findLast) {
              if (!next) {
                points.splice(i, 1);
                continue;
              }
              _point.x = next.point.x - dir.x * progress;
              _point.y = next.point.y - dir.y * progress;
            }
            findLast = true;
            normal(_normal, dir);
            var da = progress * ca;
            var c = (da << 24 >>> 0) + (cb << 16) + (cg << 8) + cr;
            var offset = vertexCount;
            data[offset].x = _point.x + _normal.x * stroke;
            data[offset].y = _point.y + _normal.y * stroke;
            data[offset].u = 1;
            data[offset].v = progress;
            data[offset].color._val = c;
            offset += 1;
            data[offset].x = _point.x - _normal.x * stroke;
            data[offset].y = _point.y - _normal.y * stroke;
            data[offset].u = 0;
            data[offset].v = progress;
            data[offset].color._val = c;
            vertexCount += 2;
          }
          indexCount = vertexCount <= 2 ? 0 : (vertexCount - 2) * 3;
          renderData.resize(vertexCount, indexCount);
        },
        updateWorldVertexAllData: function updateWorldVertexAllData(comp) {
          var renderData = comp.renderData;
          var stride = renderData.floatStride;
          var dataList = renderData.data;
          var vData = renderData.chunk.vb;
          for (var i = 0; i < dataList.length; i++) {
            var offset = i * stride;
            vData[offset + 0] = dataList[i].x;
            vData[offset + 1] = dataList[i].y;
            vData[offset + 2] = dataList[i].z;
            vData[offset + 3] = dataList[i].u;
            vData[offset + 4] = dataList[i].v;
            Color$1.toArray(vData, dataList[i].color, offset + 5);
          }
        },
        createQuadIndices: function createQuadIndices(comp, indexCount) {
          var renderData = comp.renderData;
          var chunk = renderData.chunk;
          var vid = 0;
          var meshBuffer = chunk.meshBuffer;
          var indexOffset = meshBuffer.indexOffset;
          QUAD_INDICES = null;
          QUAD_INDICES = new Uint16Array(indexCount);
          for (var i = 0, l = indexCount; i < l; i += 2) {
            var start = vid + i;
            QUAD_INDICES[indexOffset++] = start;
            QUAD_INDICES[indexOffset++] = start + 2;
            QUAD_INDICES[indexOffset++] = start + 1;
            QUAD_INDICES[indexOffset++] = start + 1;
            QUAD_INDICES[indexOffset++] = start + 2;
            QUAD_INDICES[indexOffset++] = start + 3;
          }
        },
        updateRenderDataCache: function updateRenderDataCache(comp, renderData) {
          if (renderData.passDirty) {
            renderData.updatePass(comp);
          }
          if (renderData.nodeDirty) {
            renderData.updateNode(comp);
          }
          if (renderData.textureDirty && comp.texture) {
            renderData.updateTexture(comp.texture);
            renderData.material = comp.getRenderMaterial(0);
          }
          if (renderData.hashDirty) {
            renderData.updateHash();
          }
        },
        updateRenderData: function updateRenderData(comp) {
        },
        updateColor: function updateColor(comp) {},
        fillBuffers: function fillBuffers(comp, renderer) {
          var renderData = comp.renderData;
          var chunk = renderData.chunk;
          var dataList = renderData.data;
          var vertexCount = renderData.vertexCount;
          var indexCount = renderData.indexCount;
          var vData = chunk.vb;
          var vertexOffset = 0;
          for (var i = 0; i < vertexCount; i++) {
            var vert = dataList[i];
            vData[vertexOffset++] = vert.x;
            vData[vertexOffset++] = vert.y;
            vData[vertexOffset++] = vert.z;
            vData[vertexOffset++] = vert.u;
            vData[vertexOffset++] = vert.v;
            Color$1.toArray(vData, vert.color, vertexOffset);
            vertexOffset += 4;
          }
          chunk.bufferId;
          var vid = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          for (var _i = 0, l = indexCount; _i < l; _i += 2) {
            var start = vid + _i;
            ib[indexOffset++] = start;
            ib[indexOffset++] = start + 2;
            ib[indexOffset++] = start + 1;
            ib[indexOffset++] = start + 1;
            ib[indexOffset++] = start + 2;
            ib[indexOffset++] = start + 3;
          }
          meshBuffer.indexOffset += renderData.indexCount;
          meshBuffer.setDirty();
        }
      };
      var MotionStreakAssemblerManager = exports('fd', {
        getAssembler: function getAssembler(comp) {
          return MotionStreakAssembler;
        }
      });
      MotionStreak.Assembler = MotionStreakAssemblerManager;

      var ParticleAssembler = {
        maxParticleDeltaTime: 0,
        createData: function createData(comp) {
          return MeshRenderData.add();
        },
        removeData: function removeData(data) {
          MeshRenderData.remove(data);
        },
        updateRenderData: function updateRenderData() {},
        fillBuffers: function fillBuffers(comp, renderer) {}
      };
      var ParticleSystem2DAssembler = exports('fe', {
        getAssembler: function getAssembler(comp) {
          if (!ParticleAssembler.maxParticleDeltaTime) {
            ParticleAssembler.maxParticleDeltaTime = legacyCC.game.frameTime / 1000 * 2;
          }
          return ParticleAssembler;
        }
      });
      ParticleSystem2D.Assembler = ParticleSystem2DAssembler;

      var ERigidBody2DType; exports('fi', ERigidBody2DType);
      (function (ERigidBody2DType) {
        ERigidBody2DType[ERigidBody2DType["Static"] = 0] = "Static";
        ERigidBody2DType[ERigidBody2DType["Kinematic"] = 1] = "Kinematic";
        ERigidBody2DType[ERigidBody2DType["Dynamic"] = 2] = "Dynamic";
        ERigidBody2DType[ERigidBody2DType["Animated"] = 3] = "Animated";
      })(ERigidBody2DType || (exports('fi', ERigidBody2DType = {})));
      Enum(ERigidBody2DType);
      var ECollider2DType; exports('fj', ECollider2DType);
      (function (ECollider2DType) {
        ECollider2DType[ECollider2DType["None"] = 0] = "None";
        ECollider2DType[ECollider2DType["BOX"] = 1] = "BOX";
        ECollider2DType[ECollider2DType["CIRCLE"] = 2] = "CIRCLE";
        ECollider2DType[ECollider2DType["POLYGON"] = 3] = "POLYGON";
      })(ECollider2DType || (exports('fj', ECollider2DType = {})));
      Enum(ECollider2DType);
      var EJoint2DType; exports('fk', EJoint2DType);
      (function (EJoint2DType) {
        EJoint2DType[EJoint2DType["None"] = 0] = "None";
        EJoint2DType[EJoint2DType["DISTANCE"] = 1] = "DISTANCE";
        EJoint2DType[EJoint2DType["SPRING"] = 2] = "SPRING";
        EJoint2DType[EJoint2DType["WHEEL"] = 3] = "WHEEL";
        EJoint2DType[EJoint2DType["MOUSE"] = 4] = "MOUSE";
        EJoint2DType[EJoint2DType["FIXED"] = 5] = "FIXED";
        EJoint2DType[EJoint2DType["SLIDER"] = 6] = "SLIDER";
        EJoint2DType[EJoint2DType["RELATIVE"] = 7] = "RELATIVE";
        EJoint2DType[EJoint2DType["HINGE"] = 8] = "HINGE";
      })(EJoint2DType || (exports('fk', EJoint2DType = {})));
      Enum(EJoint2DType);
      var PhysicsGroup$1; exports('fl', PhysicsGroup$1);
      (function (PhysicsGroup) {
        PhysicsGroup[PhysicsGroup["DEFAULT"] = 1] = "DEFAULT";
      })(PhysicsGroup$1 || (exports('fl', PhysicsGroup$1 = {})));
      Enum(PhysicsGroup$1);
      var ERaycast2DType; exports('fm', ERaycast2DType);
      (function (ERaycast2DType) {
        ERaycast2DType[ERaycast2DType["Closest"] = 0] = "Closest";
        ERaycast2DType[ERaycast2DType["Any"] = 1] = "Any";
        ERaycast2DType[ERaycast2DType["AllClosest"] = 2] = "AllClosest";
        ERaycast2DType[ERaycast2DType["All"] = 3] = "All";
      })(ERaycast2DType || (exports('fm', ERaycast2DType = {})));
      var Contact2DType = exports('fn', {
        None: 'none-contact',
        BEGIN_CONTACT: 'begin-contact',
        END_CONTACT: 'end-contact',
        PRE_SOLVE: 'pre-solve',
        POST_SOLVE: 'post-solve'
      });
      var EPhysics2DDrawFlags; exports('fo', EPhysics2DDrawFlags);
      (function (EPhysics2DDrawFlags) {
        EPhysics2DDrawFlags[EPhysics2DDrawFlags["None"] = 0] = "None";
        EPhysics2DDrawFlags[EPhysics2DDrawFlags["Shape"] = 1] = "Shape";
        EPhysics2DDrawFlags[EPhysics2DDrawFlags["Joint"] = 2] = "Joint";
        EPhysics2DDrawFlags[EPhysics2DDrawFlags["Aabb"] = 4] = "Aabb";
        EPhysics2DDrawFlags[EPhysics2DDrawFlags["Pair"] = 8] = "Pair";
        EPhysics2DDrawFlags[EPhysics2DDrawFlags["CenterOfMass"] = 16] = "CenterOfMass";
        EPhysics2DDrawFlags[EPhysics2DDrawFlags["Particle"] = 32] = "Particle";
        EPhysics2DDrawFlags[EPhysics2DDrawFlags["Controller"] = 64] = "Controller";
        EPhysics2DDrawFlags[EPhysics2DDrawFlags["All"] = 63] = "All";
      })(EPhysics2DDrawFlags || (exports('fo', EPhysics2DDrawFlags = {})));
      var PHYSICS_2D_PTM_RATIO = exports('fp', 32);

      function register$1(id, wrapper) {
        log("[PHYSICS2D]: register " + id + ".");
        selector$1.backend[id] = wrapper;
        if (!selector$1.physicsWorld || selector$1.id === id) {
          var mutableSelector = selector$1;
          mutableSelector.id = id;
          mutableSelector.wrapper = wrapper;
        }
      }
      function switchTo$1(id) {
        var mutableSelector = selector$1;
        if (selector$1.physicsWorld && id !== selector$1.id && selector$1.backend[id] != null) {
          log("[PHYSICS2D]: switch from " + selector$1.id + " to " + id + ".");
          mutableSelector.id = id;
          mutableSelector.wrapper = selector$1.backend[id];
          mutableSelector.physicsWorld = createPhysicsWorld$1();
        } else {
          log("[PHYSICS2D]: using " + mutableSelector.id + ".");
          mutableSelector.physicsWorld = createPhysicsWorld$1();
        }
      }
      var selector$1 = exports('fh', {
        id: '',
        switchTo: switchTo$1,
        register: register$1,
        wrapper: {},
        backend: {},
        physicsWorld: null,
        runInEditor: !EDITOR
      });
      var FUNC$1 = function FUNC() {
        return 0;
      };
      var ENTIRE_WORLD$1 = {
        impl: null,
        debugDrawFlags: 0,
        setGravity: FUNC$1,
        setAllowSleep: FUNC$1,
        step: FUNC$1,
        syncPhysicsToScene: FUNC$1,
        syncSceneToPhysics: FUNC$1,
        raycast: FUNC$1,
        testPoint: FUNC$1,
        testAABB: FUNC$1,
        drawDebug: FUNC$1
      };
      function checkPhysicsModule(obj) {
        if (obj == null) {
          errorID(9600);
          return true;
        }
        return false;
      }
      function createPhysicsWorld$1() {
        if (checkPhysicsModule(selector$1.wrapper.PhysicsWorld)) {
          return ENTIRE_WORLD$1;
        }
        return new selector$1.wrapper.PhysicsWorld();
      }
      var EntireBody = {
        impl: null,
        rigidBody: null,
        isAwake: false,
        isSleeping: false,
        initialize: FUNC$1,
        setType: FUNC$1,
        setLinearDamping: FUNC$1,
        setAngularDamping: FUNC$1,
        setGravityScale: FUNC$1,
        setFixedRotation: FUNC$1,
        setAllowSleep: FUNC$1,
        isActive: FUNC$1,
        setActive: FUNC$1,
        wakeUp: FUNC$1,
        sleep: FUNC$1,
        getMass: FUNC$1,
        getInertia: FUNC$1,
        getLinearVelocity: FUNC$1,
        setLinearVelocity: FUNC$1,
        getLinearVelocityFromWorldPoint: FUNC$1,
        getAngularVelocity: FUNC$1,
        setAngularVelocity: FUNC$1,
        getLocalVector: FUNC$1,
        getWorldVector: FUNC$1,
        getLocalPoint: FUNC$1,
        getWorldPoint: FUNC$1,
        getLocalCenter: FUNC$1,
        getWorldCenter: FUNC$1,
        applyForce: FUNC$1,
        applyForceToCenter: FUNC$1,
        applyTorque: FUNC$1,
        applyLinearImpulse: FUNC$1,
        applyLinearImpulseToCenter: FUNC$1,
        applyAngularImpulse: FUNC$1,
        onEnable: FUNC$1,
        onDisable: FUNC$1,
        onDestroy: FUNC$1
      };
      function createRigidBody$1() {
        var PHYSICS_2D_BUILTIN = selector$1.id === 'builtin';
        if (PHYSICS_2D_BUILTIN) {
          return EntireBody;
        } else {
          if (checkPhysicsModule(selector$1.wrapper.RigidBody)) {
            return EntireBody;
          }
          return new selector$1.wrapper.RigidBody();
        }
      }
      var CREATE_COLLIDER_PROXY$1 = {
        INITED: false
      };
      var ENTIRE_SHAPE$1 = {
        impl: null,
        collider: null,
        worldAABB: null,
        worldPoints: null,
        worldPosition: null,
        worldRadius: null,
        initialize: FUNC$1,
        apply: FUNC$1,
        onLoad: FUNC$1,
        onEnable: FUNC$1,
        onDisable: FUNC$1,
        onDestroy: FUNC$1,
        onGroupChanged: FUNC$1
      };
      function createShape$1(type) {
        initColliderProxy$1();
        return CREATE_COLLIDER_PROXY$1[type]();
      }
      function initColliderProxy$1() {
        if (CREATE_COLLIDER_PROXY$1.INITED) return;
        CREATE_COLLIDER_PROXY$1.INITED = true;
        CREATE_COLLIDER_PROXY$1[ECollider2DType.BOX] = function createBoxShape() {
          if (checkPhysicsModule(selector$1.wrapper.BoxShape)) {
            return ENTIRE_SHAPE$1;
          }
          return new selector$1.wrapper.BoxShape();
        };
        CREATE_COLLIDER_PROXY$1[ECollider2DType.CIRCLE] = function createCircleShape() {
          if (checkPhysicsModule(selector$1.wrapper.CircleShape)) {
            return ENTIRE_SHAPE$1;
          }
          return new selector$1.wrapper.CircleShape();
        };
        CREATE_COLLIDER_PROXY$1[ECollider2DType.POLYGON] = function createPolygonShape() {
          if (checkPhysicsModule(selector$1.wrapper.PolygonShape)) {
            return ENTIRE_SHAPE$1;
          }
          return new selector$1.wrapper.PolygonShape();
        };
      }
      var CREATE_JOINT_PROXY = {
        INITED: false
      };
      var ENTIRE_JOINT = {
        impl: null,
        initialize: FUNC$1,
        apply: FUNC$1,
        setDampingRatio: FUNC$1,
        setFrequency: FUNC$1,
        setMaxForce: FUNC$1,
        setTarget: FUNC$1,
        setDistance: FUNC$1,
        setAngularOffset: FUNC$1,
        setCorrectionFactor: FUNC$1,
        setLinearOffset: FUNC$1,
        setMaxLength: FUNC$1,
        setMaxTorque: FUNC$1,
        setLowerLimit: FUNC$1,
        setUpperLimit: FUNC$1,
        setMaxMotorForce: FUNC$1,
        setMaxMotorTorque: FUNC$1,
        setMotorSpeed: FUNC$1,
        enableLimit: FUNC$1,
        enableMotor: FUNC$1,
        setLowerAngle: FUNC$1,
        setUpperAngle: FUNC$1
      };
      function createJoint(type) {
        initJointProxy();
        return CREATE_JOINT_PROXY[type]();
      }
      function initJointProxy() {
        if (CREATE_JOINT_PROXY.INITED) return;
        CREATE_JOINT_PROXY.INITED = true;
        var PHYSICS_2D_BUILTIN = selector$1.id === 'builtin';
        CREATE_JOINT_PROXY[EJoint2DType.SPRING] = function createSpringJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector$1.wrapper.SpringJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector$1.wrapper.SpringJoint();
          }
        };
        CREATE_JOINT_PROXY[EJoint2DType.DISTANCE] = function createDistanceJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector$1.wrapper.DistanceJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector$1.wrapper.DistanceJoint();
          }
        };
        CREATE_JOINT_PROXY[EJoint2DType.FIXED] = function createFixedJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector$1.wrapper.FixedJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector$1.wrapper.FixedJoint();
          }
        };
        CREATE_JOINT_PROXY[EJoint2DType.MOUSE] = function createMouseJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector$1.wrapper.MouseJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector$1.wrapper.MouseJoint();
          }
        };
        CREATE_JOINT_PROXY[EJoint2DType.RELATIVE] = function createRelativeJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector$1.wrapper.RelativeJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector$1.wrapper.RelativeJoint();
          }
        };
        CREATE_JOINT_PROXY[EJoint2DType.SLIDER] = function createSliderJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector$1.wrapper.SliderJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector$1.wrapper.SliderJoint();
          }
        };
        CREATE_JOINT_PROXY[EJoint2DType.WHEEL] = function createWheelJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector$1.wrapper.WheelJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector$1.wrapper.WheelJoint();
          }
        };
        CREATE_JOINT_PROXY[EJoint2DType.HINGE] = function createHingeJoint() {
          if (PHYSICS_2D_BUILTIN) {
            return ENTIRE_JOINT;
          } else {
            if (checkPhysicsModule(selector$1.wrapper.HingeJoint)) {
              return ENTIRE_JOINT;
            }
            return new selector$1.wrapper.HingeJoint();
          }
        };
      }

      var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

      function unwrapExports (x) {
      	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
      }

      function createCommonjsModule(fn, module) {
      	return module = { exports: {} }, fn(module, module.exports), module.exports;
      }

      var box2d_umd=createCommonjsModule(function(module,exports$1){(function(global,factory){factory(exports$1);})(commonjsGlobal,function(exports$1){function b2Assert(condition){if(!condition){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}throw _construct(Error,args);}}function b2Maybe(value,def){return value!==undefined?value:def;}var b2_maxFloat=1E+37;var b2_epsilon=1E-5;var b2_epsilon_sq=b2_epsilon*b2_epsilon;var b2_pi=3.14159265359;var b2_maxManifoldPoints=2;var b2_maxPolygonVertices=8;var b2_aabbExtension=0.1;var b2_aabbMultiplier=2;var b2_linearSlop=0.008;var b2_angularSlop=2/180*b2_pi;var b2_polygonRadius=2*b2_linearSlop;var b2_maxSubSteps=8;var b2_maxTOIContacts=32;var b2_velocityThreshold=1;var b2_maxLinearCorrection=0.2;var b2_maxAngularCorrection=8/180*b2_pi;var b2_maxTranslation=2;var b2_maxTranslationSquared=b2_maxTranslation*b2_maxTranslation;var b2_maxRotation=0.5*b2_pi;var b2_maxRotationSquared=b2_maxRotation*b2_maxRotation;var b2_baumgarte=0.2;var b2_toiBaumgarte=0.75;var b2_invalidParticleIndex=-1;var b2_maxParticleIndex=0x7FFFFFFF;var b2_particleStride=0.75;var b2_minParticleWeight=1.0;var b2_maxParticlePressure=0.25;var b2_maxParticleForce=0.5;var b2_maxTriadDistance=2.0;var b2_maxTriadDistanceSquared=b2_maxTriadDistance*b2_maxTriadDistance;var b2_minParticleSystemBufferCapacity=256;var b2_barrierCollisionTime=2.5;var b2_timeToSleep=0.5;var b2_linearSleepTolerance=0.01;var b2_angularSleepTolerance=2/180*b2_pi;function b2Alloc(size){return null;}function b2Free(mem){}function b2Log(message){}var b2Version=function(){function b2Version(major,minor,revision){if(major===void 0){major=0;}if(minor===void 0){minor=0;}if(revision===void 0){revision=0;}this.major=0;this.minor=0;this.revision=0;this.major=major;this.minor=minor;this.revision=revision;}var _proto=b2Version.prototype;_proto.toString=function toString(){return this.major+"."+this.minor+"."+this.revision;};return b2Version;}();var b2_version=new b2Version(2,3,2);var b2_branch="master";var b2_commit="fbf51801d80fc389d43dc46524520e89043b6faf";function b2ParseInt(v){return parseInt(v,10);}function b2ParseUInt(v){return Math.abs(parseInt(v,10));}function b2MakeArray(length,init){var a=new Array(length);for(var i=0;i<length;++i){a[i]=init(i);}return a;}function b2MakeNullArray(length){var a=new Array(length);for(var i=0;i<length;++i){a[i]=null;}return a;}function b2MakeNumberArray(length,init){if(init===void 0){init=0;}var a=new Array(length);for(var i=0;i<length;++i){a[i]=init;}return a;}var b2_pi_over_180=b2_pi/180;var b2_180_over_pi=180/b2_pi;var b2_two_pi=2*b2_pi;var b2Abs=Math.abs;function b2Min(a,b){return a<b?a:b;}function b2Max(a,b){return a>b?a:b;}function b2Clamp(a,lo,hi){return a<lo?lo:a>hi?hi:a;}function b2Swap(a,b){var tmp=a[0];a[0]=b[0];b[0]=tmp;}var b2IsValid=isFinite;function b2Sq(n){return n*n;}function b2InvSqrt(n){return 1/Math.sqrt(n);}var b2Sqrt=Math.sqrt;var b2Pow=Math.pow;function b2DegToRad(degrees){return degrees*b2_pi_over_180;}function b2RadToDeg(radians){return radians*b2_180_over_pi;}var b2Cos=Math.cos;var b2Sin=Math.sin;var b2Acos=Math.acos;var b2Asin=Math.asin;var b2Atan2=Math.atan2;function b2NextPowerOfTwo(x){x|=x>>1&0x7FFFFFFF;x|=x>>2&0x3FFFFFFF;x|=x>>4&0x0FFFFFFF;x|=x>>8&0x00FFFFFF;x|=x>>16&0x0000FFFF;return x+1;}function b2IsPowerOfTwo(x){return x>0&&(x&x-1)===0;}function b2Random(){return Math.random()*2-1;}function b2RandomRange(lo,hi){return (hi-lo)*Math.random()+lo;}var b2Vec2=function(){function b2Vec2(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2];}if(args[0]instanceof Float32Array){if(args[0].length!==2){throw new Error();}this.data=args[0];}else {var x=typeof args[0]==="number"?args[0]:0;var y=typeof args[1]==="number"?args[1]:0;this.data=new Float32Array([x,y]);}}var _proto2=b2Vec2.prototype;_proto2.Clone=function Clone(){return new b2Vec2(this.x,this.y);};_proto2.SetZero=function SetZero(){this.x=0;this.y=0;return this;};_proto2.Set=function Set(x,y){this.x=x;this.y=y;return this;};_proto2.Copy=function Copy(other){this.x=other.x;this.y=other.y;return this;};_proto2.SelfAdd=function SelfAdd(v){this.x+=v.x;this.y+=v.y;return this;};_proto2.SelfAddXY=function SelfAddXY(x,y){this.x+=x;this.y+=y;return this;};_proto2.SelfSub=function SelfSub(v){this.x-=v.x;this.y-=v.y;return this;};_proto2.SelfSubXY=function SelfSubXY(x,y){this.x-=x;this.y-=y;return this;};_proto2.SelfMul=function SelfMul(s){this.x*=s;this.y*=s;return this;};_proto2.SelfMulAdd=function SelfMulAdd(s,v){this.x+=s*v.x;this.y+=s*v.y;return this;};_proto2.SelfMulSub=function SelfMulSub(s,v){this.x-=s*v.x;this.y-=s*v.y;return this;};_proto2.Dot=function Dot(v){return this.x*v.x+this.y*v.y;};_proto2.Cross=function Cross(v){return this.x*v.y-this.y*v.x;};_proto2.Length=function Length(){var x=this.x,y=this.y;return Math.sqrt(x*x+y*y);};_proto2.LengthSquared=function LengthSquared(){var x=this.x,y=this.y;return x*x+y*y;};_proto2.Normalize=function Normalize(){var length=this.Length();if(length>=b2_epsilon){var inv_length=1/length;this.x*=inv_length;this.y*=inv_length;}return length;};_proto2.SelfNormalize=function SelfNormalize(){var length=this.Length();if(length>=b2_epsilon){var inv_length=1/length;this.x*=inv_length;this.y*=inv_length;}return this;};_proto2.SelfRotate=function SelfRotate(radians){var c=Math.cos(radians);var s=Math.sin(radians);var x=this.x;this.x=c*x-s*this.y;this.y=s*x+c*this.y;return this;};_proto2.SelfRotateCosSin=function SelfRotateCosSin(c,s){var x=this.x;this.x=c*x-s*this.y;this.y=s*x+c*this.y;return this;};_proto2.IsValid=function IsValid(){return isFinite(this.x)&&isFinite(this.y);};_proto2.SelfCrossVS=function SelfCrossVS(s){var x=this.x;this.x=s*this.y;this.y=-s*x;return this;};_proto2.SelfCrossSV=function SelfCrossSV(s){var x=this.x;this.x=-s*this.y;this.y=s*x;return this;};_proto2.SelfMinV=function SelfMinV(v){this.x=b2Min(this.x,v.x);this.y=b2Min(this.y,v.y);return this;};_proto2.SelfMaxV=function SelfMaxV(v){this.x=b2Max(this.x,v.x);this.y=b2Max(this.y,v.y);return this;};_proto2.SelfAbs=function SelfAbs(){this.x=b2Abs(this.x);this.y=b2Abs(this.y);return this;};_proto2.SelfNeg=function SelfNeg(){this.x=-this.x;this.y=-this.y;return this;};_proto2.SelfSkew=function SelfSkew(){var x=this.x;this.x=-this.y;this.y=x;return this;};b2Vec2.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2Vec2();});};b2Vec2.AbsV=function AbsV(v,out){out.x=b2Abs(v.x);out.y=b2Abs(v.y);return out;};b2Vec2.MinV=function MinV(a,b,out){out.x=b2Min(a.x,b.x);out.y=b2Min(a.y,b.y);return out;};b2Vec2.MaxV=function MaxV(a,b,out){out.x=b2Max(a.x,b.x);out.y=b2Max(a.y,b.y);return out;};b2Vec2.ClampV=function ClampV(v,lo,hi,out){out.x=b2Clamp(v.x,lo.x,hi.x);out.y=b2Clamp(v.y,lo.y,hi.y);return out;};b2Vec2.RotateV=function RotateV(v,radians,out){var v_x=v.x,v_y=v.y;var c=Math.cos(radians);var s=Math.sin(radians);out.x=c*v_x-s*v_y;out.y=s*v_x+c*v_y;return out;};b2Vec2.DotVV=function DotVV(a,b){return a.x*b.x+a.y*b.y;};b2Vec2.CrossVV=function CrossVV(a,b){return a.x*b.y-a.y*b.x;};b2Vec2.CrossVS=function CrossVS(v,s,out){var v_x=v.x;out.x=s*v.y;out.y=-s*v_x;return out;};b2Vec2.CrossVOne=function CrossVOne(v,out){var v_x=v.x;out.x=v.y;out.y=-v_x;return out;};b2Vec2.CrossSV=function CrossSV(s,v,out){var v_x=v.x;out.x=-s*v.y;out.y=s*v_x;return out;};b2Vec2.CrossOneV=function CrossOneV(v,out){var v_x=v.x;out.x=-v.y;out.y=v_x;return out;};b2Vec2.AddVV=function AddVV(a,b,out){out.x=a.x+b.x;out.y=a.y+b.y;return out;};b2Vec2.SubVV=function SubVV(a,b,out){out.x=a.x-b.x;out.y=a.y-b.y;return out;};b2Vec2.MulSV=function MulSV(s,v,out){out.x=v.x*s;out.y=v.y*s;return out;};b2Vec2.MulVS=function MulVS(v,s,out){out.x=v.x*s;out.y=v.y*s;return out;};b2Vec2.AddVMulSV=function AddVMulSV(a,s,b,out){out.x=a.x+s*b.x;out.y=a.y+s*b.y;return out;};b2Vec2.SubVMulSV=function SubVMulSV(a,s,b,out){out.x=a.x-s*b.x;out.y=a.y-s*b.y;return out;};b2Vec2.AddVCrossSV=function AddVCrossSV(a,s,v,out){var v_x=v.x;out.x=a.x-s*v.y;out.y=a.y+s*v_x;return out;};b2Vec2.MidVV=function MidVV(a,b,out){out.x=(a.x+b.x)*0.5;out.y=(a.y+b.y)*0.5;return out;};b2Vec2.ExtVV=function ExtVV(a,b,out){out.x=(b.x-a.x)*0.5;out.y=(b.y-a.y)*0.5;return out;};b2Vec2.IsEqualToV=function IsEqualToV(a,b){return a.x===b.x&&a.y===b.y;};b2Vec2.DistanceVV=function DistanceVV(a,b){var c_x=a.x-b.x;var c_y=a.y-b.y;return Math.sqrt(c_x*c_x+c_y*c_y);};b2Vec2.DistanceSquaredVV=function DistanceSquaredVV(a,b){var c_x=a.x-b.x;var c_y=a.y-b.y;return c_x*c_x+c_y*c_y;};b2Vec2.NegV=function NegV(v,out){out.x=-v.x;out.y=-v.y;return out;};_createClass(b2Vec2,[{key:"x",get:function get(){return this.data[0];},set:function set(value){this.data[0]=value;}},{key:"y",get:function get(){return this.data[1];},set:function set(value){this.data[1]=value;}}]);return b2Vec2;}();b2Vec2.ZERO=new b2Vec2(0,0);b2Vec2.UNITX=new b2Vec2(1,0);b2Vec2.UNITY=new b2Vec2(0,1);b2Vec2.s_t0=new b2Vec2();b2Vec2.s_t1=new b2Vec2();b2Vec2.s_t2=new b2Vec2();b2Vec2.s_t3=new b2Vec2();var b2Vec2_zero=new b2Vec2(0,0);var b2Vec3=function(){function b2Vec3(){for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3];}if(args[0]instanceof Float32Array){if(args[0].length!==3){throw new Error();}this.data=args[0];}else {var x=typeof args[0]==="number"?args[0]:0;var y=typeof args[1]==="number"?args[1]:0;var z=typeof args[2]==="number"?args[2]:0;this.data=new Float32Array([x,y,z]);}}var _proto3=b2Vec3.prototype;_proto3.Clone=function Clone(){return new b2Vec3(this.x,this.y,this.z);};_proto3.SetZero=function SetZero(){this.x=0;this.y=0;this.z=0;return this;};_proto3.SetXYZ=function SetXYZ(x,y,z){this.x=x;this.y=y;this.z=z;return this;};_proto3.Copy=function Copy(other){this.x=other.x;this.y=other.y;this.z=other.z;return this;};_proto3.SelfNeg=function SelfNeg(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this;};_proto3.SelfAdd=function SelfAdd(v){this.x+=v.x;this.y+=v.y;this.z+=v.z;return this;};_proto3.SelfAddXYZ=function SelfAddXYZ(x,y,z){this.x+=x;this.y+=y;this.z+=z;return this;};_proto3.SelfSub=function SelfSub(v){this.x-=v.x;this.y-=v.y;this.z-=v.z;return this;};_proto3.SelfSubXYZ=function SelfSubXYZ(x,y,z){this.x-=x;this.y-=y;this.z-=z;return this;};_proto3.SelfMul=function SelfMul(s){this.x*=s;this.y*=s;this.z*=s;return this;};b2Vec3.DotV3V3=function DotV3V3(a,b){return a.x*b.x+a.y*b.y+a.z*b.z;};b2Vec3.CrossV3V3=function CrossV3V3(a,b,out){var a_x=a.x,a_y=a.y,a_z=a.z;var b_x=b.x,b_y=b.y,b_z=b.z;out.x=a_y*b_z-a_z*b_y;out.y=a_z*b_x-a_x*b_z;out.z=a_x*b_y-a_y*b_x;return out;};_createClass(b2Vec3,[{key:"x",get:function get(){return this.data[0];},set:function set(value){this.data[0]=value;}},{key:"y",get:function get(){return this.data[1];},set:function set(value){this.data[1]=value;}},{key:"z",get:function get(){return this.data[2];},set:function set(value){this.data[2]=value;}}]);return b2Vec3;}();b2Vec3.ZERO=new b2Vec3(0,0,0);b2Vec3.s_t0=new b2Vec3();var b2Mat22=function(){function b2Mat22(){this.data=new Float32Array([1,0,0,1]);this.ex=new b2Vec2(this.data.subarray(0,2));this.ey=new b2Vec2(this.data.subarray(2,4));}var _proto4=b2Mat22.prototype;_proto4.Clone=function Clone(){return new b2Mat22().Copy(this);};b2Mat22.FromVV=function FromVV(c1,c2){return new b2Mat22().SetVV(c1,c2);};b2Mat22.FromSSSS=function FromSSSS(r1c1,r1c2,r2c1,r2c2){return new b2Mat22().SetSSSS(r1c1,r1c2,r2c1,r2c2);};b2Mat22.FromAngle=function FromAngle(radians){return new b2Mat22().SetAngle(radians);};_proto4.SetSSSS=function SetSSSS(r1c1,r1c2,r2c1,r2c2){this.ex.Set(r1c1,r2c1);this.ey.Set(r1c2,r2c2);return this;};_proto4.SetVV=function SetVV(c1,c2){this.ex.Copy(c1);this.ey.Copy(c2);return this;};_proto4.SetAngle=function SetAngle(radians){var c=Math.cos(radians);var s=Math.sin(radians);this.ex.Set(c,s);this.ey.Set(-s,c);return this;};_proto4.Copy=function Copy(other){this.ex.Copy(other.ex);this.ey.Copy(other.ey);return this;};_proto4.SetIdentity=function SetIdentity(){this.ex.Set(1,0);this.ey.Set(0,1);return this;};_proto4.SetZero=function SetZero(){this.ex.SetZero();this.ey.SetZero();return this;};_proto4.GetAngle=function GetAngle(){return Math.atan2(this.ex.y,this.ex.x);};_proto4.GetInverse=function GetInverse(out){var a=this.ex.x;var b=this.ey.x;var c=this.ex.y;var d=this.ey.y;var det=a*d-b*c;if(det!==0){det=1/det;}out.ex.x=det*d;out.ey.x=-det*b;out.ex.y=-det*c;out.ey.y=det*a;return out;};_proto4.Solve=function Solve(b_x,b_y,out){var a11=this.ex.x,a12=this.ey.x;var a21=this.ex.y,a22=this.ey.y;var det=a11*a22-a12*a21;if(det!==0){det=1/det;}out.x=det*(a22*b_x-a12*b_y);out.y=det*(a11*b_y-a21*b_x);return out;};_proto4.SelfAbs=function SelfAbs(){this.ex.SelfAbs();this.ey.SelfAbs();return this;};_proto4.SelfInv=function SelfInv(){this.GetInverse(this);return this;};_proto4.SelfAddM=function SelfAddM(M){this.ex.SelfAdd(M.ex);this.ey.SelfAdd(M.ey);return this;};_proto4.SelfSubM=function SelfSubM(M){this.ex.SelfSub(M.ex);this.ey.SelfSub(M.ey);return this;};b2Mat22.AbsM=function AbsM(M,out){var M_ex=M.ex,M_ey=M.ey;out.ex.x=b2Abs(M_ex.x);out.ex.y=b2Abs(M_ex.y);out.ey.x=b2Abs(M_ey.x);out.ey.y=b2Abs(M_ey.y);return out;};b2Mat22.MulMV=function MulMV(M,v,out){var M_ex=M.ex,M_ey=M.ey;var v_x=v.x,v_y=v.y;out.x=M_ex.x*v_x+M_ey.x*v_y;out.y=M_ex.y*v_x+M_ey.y*v_y;return out;};b2Mat22.MulTMV=function MulTMV(M,v,out){var M_ex=M.ex,M_ey=M.ey;var v_x=v.x,v_y=v.y;out.x=M_ex.x*v_x+M_ex.y*v_y;out.y=M_ey.x*v_x+M_ey.y*v_y;return out;};b2Mat22.AddMM=function AddMM(A,B,out){var A_ex=A.ex,A_ey=A.ey;var B_ex=B.ex,B_ey=B.ey;out.ex.x=A_ex.x+B_ex.x;out.ex.y=A_ex.y+B_ex.y;out.ey.x=A_ey.x+B_ey.x;out.ey.y=A_ey.y+B_ey.y;return out;};b2Mat22.MulMM=function MulMM(A,B,out){var A_ex_x=A.ex.x,A_ex_y=A.ex.y;var A_ey_x=A.ey.x,A_ey_y=A.ey.y;var B_ex_x=B.ex.x,B_ex_y=B.ex.y;var B_ey_x=B.ey.x,B_ey_y=B.ey.y;out.ex.x=A_ex_x*B_ex_x+A_ey_x*B_ex_y;out.ex.y=A_ex_y*B_ex_x+A_ey_y*B_ex_y;out.ey.x=A_ex_x*B_ey_x+A_ey_x*B_ey_y;out.ey.y=A_ex_y*B_ey_x+A_ey_y*B_ey_y;return out;};b2Mat22.MulTMM=function MulTMM(A,B,out){var A_ex_x=A.ex.x,A_ex_y=A.ex.y;var A_ey_x=A.ey.x,A_ey_y=A.ey.y;var B_ex_x=B.ex.x,B_ex_y=B.ex.y;var B_ey_x=B.ey.x,B_ey_y=B.ey.y;out.ex.x=A_ex_x*B_ex_x+A_ex_y*B_ex_y;out.ex.y=A_ey_x*B_ex_x+A_ey_y*B_ex_y;out.ey.x=A_ex_x*B_ey_x+A_ex_y*B_ey_y;out.ey.y=A_ey_x*B_ey_x+A_ey_y*B_ey_y;return out;};return b2Mat22;}();b2Mat22.IDENTITY=new b2Mat22();var b2Mat33=function(){function b2Mat33(){this.data=new Float32Array([1,0,0,0,1,0,0,0,1]);this.ex=new b2Vec3(this.data.subarray(0,3));this.ey=new b2Vec3(this.data.subarray(3,6));this.ez=new b2Vec3(this.data.subarray(6,9));}var _proto5=b2Mat33.prototype;_proto5.Clone=function Clone(){return new b2Mat33().Copy(this);};_proto5.SetVVV=function SetVVV(c1,c2,c3){this.ex.Copy(c1);this.ey.Copy(c2);this.ez.Copy(c3);return this;};_proto5.Copy=function Copy(other){this.ex.Copy(other.ex);this.ey.Copy(other.ey);this.ez.Copy(other.ez);return this;};_proto5.SetIdentity=function SetIdentity(){this.ex.SetXYZ(1,0,0);this.ey.SetXYZ(0,1,0);this.ez.SetXYZ(0,0,1);return this;};_proto5.SetZero=function SetZero(){this.ex.SetZero();this.ey.SetZero();this.ez.SetZero();return this;};_proto5.SelfAddM=function SelfAddM(M){this.ex.SelfAdd(M.ex);this.ey.SelfAdd(M.ey);this.ez.SelfAdd(M.ez);return this;};_proto5.Solve33=function Solve33(b_x,b_y,b_z,out){var a11=this.ex.x,a21=this.ex.y,a31=this.ex.z;var a12=this.ey.x,a22=this.ey.y,a32=this.ey.z;var a13=this.ez.x,a23=this.ez.y,a33=this.ez.z;var det=a11*(a22*a33-a32*a23)+a21*(a32*a13-a12*a33)+a31*(a12*a23-a22*a13);if(det!==0){det=1/det;}out.x=det*(b_x*(a22*a33-a32*a23)+b_y*(a32*a13-a12*a33)+b_z*(a12*a23-a22*a13));out.y=det*(a11*(b_y*a33-b_z*a23)+a21*(b_z*a13-b_x*a33)+a31*(b_x*a23-b_y*a13));out.z=det*(a11*(a22*b_z-a32*b_y)+a21*(a32*b_x-a12*b_z)+a31*(a12*b_y-a22*b_x));return out;};_proto5.Solve22=function Solve22(b_x,b_y,out){var a11=this.ex.x,a12=this.ey.x;var a21=this.ex.y,a22=this.ey.y;var det=a11*a22-a12*a21;if(det!==0){det=1/det;}out.x=det*(a22*b_x-a12*b_y);out.y=det*(a11*b_y-a21*b_x);return out;};_proto5.GetInverse22=function GetInverse22(M){var a=this.ex.x,b=this.ey.x,c=this.ex.y,d=this.ey.y;var det=a*d-b*c;if(det!==0){det=1/det;}M.ex.x=det*d;M.ey.x=-det*b;M.ex.z=0;M.ex.y=-det*c;M.ey.y=det*a;M.ey.z=0;M.ez.x=0;M.ez.y=0;M.ez.z=0;};_proto5.GetSymInverse33=function GetSymInverse33(M){var det=b2Vec3.DotV3V3(this.ex,b2Vec3.CrossV3V3(this.ey,this.ez,b2Vec3.s_t0));if(det!==0){det=1/det;}var a11=this.ex.x,a12=this.ey.x,a13=this.ez.x;var a22=this.ey.y,a23=this.ez.y;var a33=this.ez.z;M.ex.x=det*(a22*a33-a23*a23);M.ex.y=det*(a13*a23-a12*a33);M.ex.z=det*(a12*a23-a13*a22);M.ey.x=M.ex.y;M.ey.y=det*(a11*a33-a13*a13);M.ey.z=det*(a13*a12-a11*a23);M.ez.x=M.ex.z;M.ez.y=M.ey.z;M.ez.z=det*(a11*a22-a12*a12);};b2Mat33.MulM33V3=function MulM33V3(A,v,out){var v_x=v.x,v_y=v.y,v_z=v.z;out.x=A.ex.x*v_x+A.ey.x*v_y+A.ez.x*v_z;out.y=A.ex.y*v_x+A.ey.y*v_y+A.ez.y*v_z;out.z=A.ex.z*v_x+A.ey.z*v_y+A.ez.z*v_z;return out;};b2Mat33.MulM33XYZ=function MulM33XYZ(A,x,y,z,out){out.x=A.ex.x*x+A.ey.x*y+A.ez.x*z;out.y=A.ex.y*x+A.ey.y*y+A.ez.y*z;out.z=A.ex.z*x+A.ey.z*y+A.ez.z*z;return out;};b2Mat33.MulM33V2=function MulM33V2(A,v,out){var v_x=v.x,v_y=v.y;out.x=A.ex.x*v_x+A.ey.x*v_y;out.y=A.ex.y*v_x+A.ey.y*v_y;return out;};b2Mat33.MulM33XY=function MulM33XY(A,x,y,out){out.x=A.ex.x*x+A.ey.x*y;out.y=A.ex.y*x+A.ey.y*y;return out;};return b2Mat33;}();b2Mat33.IDENTITY=new b2Mat33();var b2Rot=function(){function b2Rot(angle){if(angle===void 0){angle=0;}this.s=0;this.c=1;if(angle){this.s=Math.sin(angle);this.c=Math.cos(angle);}}var _proto6=b2Rot.prototype;_proto6.Clone=function Clone(){return new b2Rot().Copy(this);};_proto6.Copy=function Copy(other){this.s=other.s;this.c=other.c;return this;};_proto6.SetAngle=function SetAngle(angle){this.s=Math.sin(angle);this.c=Math.cos(angle);return this;};_proto6.SetIdentity=function SetIdentity(){this.s=0;this.c=1;return this;};_proto6.GetAngle=function GetAngle(){return Math.atan2(this.s,this.c);};_proto6.GetXAxis=function GetXAxis(out){out.x=this.c;out.y=this.s;return out;};_proto6.GetYAxis=function GetYAxis(out){out.x=-this.s;out.y=this.c;return out;};b2Rot.MulRR=function MulRR(q,r,out){var q_c=q.c,q_s=q.s;var r_c=r.c,r_s=r.s;out.s=q_s*r_c+q_c*r_s;out.c=q_c*r_c-q_s*r_s;return out;};b2Rot.MulTRR=function MulTRR(q,r,out){var q_c=q.c,q_s=q.s;var r_c=r.c,r_s=r.s;out.s=q_c*r_s-q_s*r_c;out.c=q_c*r_c+q_s*r_s;return out;};b2Rot.MulRV=function MulRV(q,v,out){var q_c=q.c,q_s=q.s;var v_x=v.x,v_y=v.y;out.x=q_c*v_x-q_s*v_y;out.y=q_s*v_x+q_c*v_y;return out;};b2Rot.MulTRV=function MulTRV(q,v,out){var q_c=q.c,q_s=q.s;var v_x=v.x,v_y=v.y;out.x=q_c*v_x+q_s*v_y;out.y=-q_s*v_x+q_c*v_y;return out;};return b2Rot;}();b2Rot.IDENTITY=new b2Rot();var b2Transform=function(){function b2Transform(){this.p=new b2Vec2();this.q=new b2Rot();}var _proto7=b2Transform.prototype;_proto7.Clone=function Clone(){return new b2Transform().Copy(this);};_proto7.Copy=function Copy(other){this.p.Copy(other.p);this.q.Copy(other.q);return this;};_proto7.SetIdentity=function SetIdentity(){this.p.SetZero();this.q.SetIdentity();return this;};_proto7.SetPositionRotation=function SetPositionRotation(position,q){this.p.Copy(position);this.q.Copy(q);return this;};_proto7.SetPositionAngle=function SetPositionAngle(pos,a){this.p.Copy(pos);this.q.SetAngle(a);return this;};_proto7.SetPosition=function SetPosition(position){this.p.Copy(position);return this;};_proto7.SetPositionXY=function SetPositionXY(x,y){this.p.Set(x,y);return this;};_proto7.SetRotation=function SetRotation(rotation){this.q.Copy(rotation);return this;};_proto7.SetRotationAngle=function SetRotationAngle(radians){this.q.SetAngle(radians);return this;};_proto7.GetPosition=function GetPosition(){return this.p;};_proto7.GetRotation=function GetRotation(){return this.q;};_proto7.GetRotationAngle=function GetRotationAngle(){return this.q.GetAngle();};_proto7.GetAngle=function GetAngle(){return this.q.GetAngle();};b2Transform.MulXV=function MulXV(T,v,out){var T_q_c=T.q.c,T_q_s=T.q.s;var v_x=v.x,v_y=v.y;out.x=T_q_c*v_x-T_q_s*v_y+T.p.x;out.y=T_q_s*v_x+T_q_c*v_y+T.p.y;return out;};b2Transform.MulTXV=function MulTXV(T,v,out){var T_q_c=T.q.c,T_q_s=T.q.s;var p_x=v.x-T.p.x;var p_y=v.y-T.p.y;out.x=T_q_c*p_x+T_q_s*p_y;out.y=-T_q_s*p_x+T_q_c*p_y;return out;};b2Transform.MulXX=function MulXX(A,B,out){b2Rot.MulRR(A.q,B.q,out.q);b2Vec2.AddVV(b2Rot.MulRV(A.q,B.p,out.p),A.p,out.p);return out;};b2Transform.MulTXX=function MulTXX(A,B,out){b2Rot.MulTRR(A.q,B.q,out.q);b2Rot.MulTRV(A.q,b2Vec2.SubVV(B.p,A.p,out.p),out.p);return out;};return b2Transform;}();b2Transform.IDENTITY=new b2Transform();var b2Sweep=function(){function b2Sweep(){this.localCenter=new b2Vec2();this.c0=new b2Vec2();this.c=new b2Vec2();this.a0=0;this.a=0;this.alpha0=0;}var _proto8=b2Sweep.prototype;_proto8.Clone=function Clone(){return new b2Sweep().Copy(this);};_proto8.Copy=function Copy(other){this.localCenter.Copy(other.localCenter);this.c0.Copy(other.c0);this.c.Copy(other.c);this.a0=other.a0;this.a=other.a;this.alpha0=other.alpha0;return this;};_proto8.GetTransform=function GetTransform(xf,beta){var one_minus_beta=1-beta;xf.p.x=one_minus_beta*this.c0.x+beta*this.c.x;xf.p.y=one_minus_beta*this.c0.y+beta*this.c.y;var angle=one_minus_beta*this.a0+beta*this.a;xf.q.SetAngle(angle);xf.p.SelfSub(b2Rot.MulRV(xf.q,this.localCenter,b2Vec2.s_t0));return xf;};_proto8.Advance=function Advance(alpha){var beta=(alpha-this.alpha0)/(1-this.alpha0);var one_minus_beta=1-beta;this.c0.x=one_minus_beta*this.c0.x+beta*this.c.x;this.c0.y=one_minus_beta*this.c0.y+beta*this.c.y;this.a0=one_minus_beta*this.a0+beta*this.a;this.alpha0=alpha;};_proto8.Normalize=function Normalize(){var d=b2_two_pi*Math.floor(this.a0/b2_two_pi);this.a0-=d;this.a-=d;};return b2Sweep;}();var b2Color=function(){function b2Color(){for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4];}if(args[0]instanceof Float32Array){if(args[0].length!==4){throw new Error();}this.data=args[0];}else {var rr=typeof args[0]==="number"?args[0]:0.5;var gg=typeof args[1]==="number"?args[1]:0.5;var bb=typeof args[2]==="number"?args[2]:0.5;var aa=typeof args[3]==="number"?args[3]:1.0;this.data=new Float32Array([rr,gg,bb,aa]);}}var _proto9=b2Color.prototype;_proto9.Clone=function Clone(){return new b2Color().Copy(this);};_proto9.Copy=function Copy(other){this.r=other.r;this.g=other.g;this.b=other.b;this.a=other.a;return this;};_proto9.IsEqual=function IsEqual(color){return this.r===color.r&&this.g===color.g&&this.b===color.b&&this.a===color.a;};_proto9.IsZero=function IsZero(){return this.r===0&&this.g===0&&this.b===0&&this.a===0;};_proto9.Set=function Set(r,g,b,a){if(a===void 0){a=this.a;}this.SetRGBA(r,g,b,a);};_proto9.SetByteRGB=function SetByteRGB(r,g,b){this.r=r/0xff;this.g=g/0xff;this.b=b/0xff;return this;};_proto9.SetByteRGBA=function SetByteRGBA(r,g,b,a){this.r=r/0xff;this.g=g/0xff;this.b=b/0xff;this.a=a/0xff;return this;};_proto9.SetRGB=function SetRGB(rr,gg,bb){this.r=rr;this.g=gg;this.b=bb;return this;};_proto9.SetRGBA=function SetRGBA(rr,gg,bb,aa){this.r=rr;this.g=gg;this.b=bb;this.a=aa;return this;};_proto9.SelfAdd=function SelfAdd(color){this.r+=color.r;this.g+=color.g;this.b+=color.b;this.a+=color.a;return this;};_proto9.Add=function Add(color,out){out.r=this.r+color.r;out.g=this.g+color.g;out.b=this.b+color.b;out.a=this.a+color.a;return out;};_proto9.SelfSub=function SelfSub(color){this.r-=color.r;this.g-=color.g;this.b-=color.b;this.a-=color.a;return this;};_proto9.Sub=function Sub(color,out){out.r=this.r-color.r;out.g=this.g-color.g;out.b=this.b-color.b;out.a=this.a-color.a;return out;};_proto9.SelfMul=function SelfMul(s){this.r*=s;this.g*=s;this.b*=s;this.a*=s;return this;};_proto9.Mul=function Mul(s,out){out.r=this.r*s;out.g=this.g*s;out.b=this.b*s;out.a=this.a*s;return out;};_proto9.Mix=function Mix(mixColor,strength){b2Color.MixColors(this,mixColor,strength);};b2Color.MixColors=function MixColors(colorA,colorB,strength){var dr=strength*(colorB.r-colorA.r);var dg=strength*(colorB.g-colorA.g);var db=strength*(colorB.b-colorA.b);var da=strength*(colorB.a-colorA.a);colorA.r+=dr;colorA.g+=dg;colorA.b+=db;colorA.a+=da;colorB.r-=dr;colorB.g-=dg;colorB.b-=db;colorB.a-=da;};_proto9.MakeStyleString=function MakeStyleString(alpha){if(alpha===void 0){alpha=this.a;}return b2Color.MakeStyleString(this.r,this.g,this.b,alpha);};b2Color.MakeStyleString=function MakeStyleString(r,g,b,a){if(a===void 0){a=1.0;}r*=255;g*=255;b*=255;if(a<1){return "rgba("+r+","+g+","+b+","+a+")";}else {return "rgb("+r+","+g+","+b+")";}};_createClass(b2Color,[{key:"r",get:function get(){return this.data[0];},set:function set(value){this.data[0]=value;}},{key:"g",get:function get(){return this.data[1];},set:function set(value){this.data[1]=value;}},{key:"b",get:function get(){return this.data[2];},set:function set(value){this.data[2]=value;}},{key:"a",get:function get(){return this.data[3];},set:function set(value){this.data[3]=value;}}]);return b2Color;}();b2Color.ZERO=new b2Color(0,0,0,0);b2Color.RED=new b2Color(1,0,0);b2Color.GREEN=new b2Color(0,1,0);b2Color.BLUE=new b2Color(0,0,1);(function(b2DrawFlags){b2DrawFlags[b2DrawFlags["e_none"]=0]="e_none";b2DrawFlags[b2DrawFlags["e_shapeBit"]=1]="e_shapeBit";b2DrawFlags[b2DrawFlags["e_jointBit"]=2]="e_jointBit";b2DrawFlags[b2DrawFlags["e_aabbBit"]=4]="e_aabbBit";b2DrawFlags[b2DrawFlags["e_pairBit"]=8]="e_pairBit";b2DrawFlags[b2DrawFlags["e_centerOfMassBit"]=16]="e_centerOfMassBit";b2DrawFlags[b2DrawFlags["e_particleBit"]=32]="e_particleBit";b2DrawFlags[b2DrawFlags["e_controllerBit"]=64]="e_controllerBit";b2DrawFlags[b2DrawFlags["e_all"]=63]="e_all";})(exports$1.b2DrawFlags||(exports$1.b2DrawFlags={}));var b2Draw=function(){function b2Draw(){this.m_drawFlags=0;}var _proto10=b2Draw.prototype;_proto10.SetFlags=function SetFlags(flags){this.m_drawFlags=flags;};_proto10.GetFlags=function GetFlags(){return this.m_drawFlags;};_proto10.AppendFlags=function AppendFlags(flags){this.m_drawFlags|=flags;};_proto10.ClearFlags=function ClearFlags(flags){this.m_drawFlags&=~flags;};return b2Draw;}();var b2Timer=function(){function b2Timer(){this.m_start=Date.now();}var _proto11=b2Timer.prototype;_proto11.Reset=function Reset(){this.m_start=Date.now();return this;};_proto11.GetMilliseconds=function GetMilliseconds(){return Date.now()-this.m_start;};return b2Timer;}();var b2Counter=function(){function b2Counter(){this.m_count=0;this.m_min_count=0;this.m_max_count=0;}var _proto12=b2Counter.prototype;_proto12.GetCount=function GetCount(){return this.m_count;};_proto12.GetMinCount=function GetMinCount(){return this.m_min_count;};_proto12.GetMaxCount=function GetMaxCount(){return this.m_max_count;};_proto12.ResetCount=function ResetCount(){var count=this.m_count;this.m_count=0;return count;};_proto12.ResetMinCount=function ResetMinCount(){this.m_min_count=0;};_proto12.ResetMaxCount=function ResetMaxCount(){this.m_max_count=0;};_proto12.Increment=function Increment(){this.m_count++;if(this.m_max_count<this.m_count){this.m_max_count=this.m_count;}};_proto12.Decrement=function Decrement(){this.m_count--;if(this.m_min_count>this.m_count){this.m_min_count=this.m_count;}};return b2Counter;}();var b2GrowableStack=function(){function b2GrowableStack(N){this.m_stack=[];this.m_count=0;this.m_stack=b2MakeArray(N,function(index){return null;});this.m_count=0;}var _proto13=b2GrowableStack.prototype;_proto13.Reset=function Reset(){this.m_count=0;return this;};_proto13.Push=function Push(element){this.m_stack[this.m_count]=element;this.m_count++;};_proto13.Pop=function Pop(){this.m_count--;var element=this.m_stack[this.m_count];this.m_stack[this.m_count]=null;if(element===null){throw new Error();}return element;};_proto13.GetCount=function GetCount(){return this.m_count;};return b2GrowableStack;}();var b2BlockAllocator=function b2BlockAllocator(){};var b2StackAllocator=function b2StackAllocator(){};var b2DistanceProxy=function(){function b2DistanceProxy(){this.m_buffer=b2Vec2.MakeArray(2);this.m_vertices=this.m_buffer;this.m_count=0;this.m_radius=0;}var _proto14=b2DistanceProxy.prototype;_proto14.Copy=function Copy(other){if(other.m_vertices===other.m_buffer){this.m_vertices=this.m_buffer;this.m_buffer[0].Copy(other.m_buffer[0]);this.m_buffer[1].Copy(other.m_buffer[1]);}else {this.m_vertices=other.m_vertices;}this.m_count=other.m_count;this.m_radius=other.m_radius;return this;};_proto14.Reset=function Reset(){this.m_vertices=this.m_buffer;this.m_count=0;this.m_radius=0;return this;};_proto14.SetShape=function SetShape(shape,index){shape.SetupDistanceProxy(this,index);};_proto14.SetVerticesRadius=function SetVerticesRadius(vertices,count,radius){this.m_vertices=vertices;this.m_count=count;this.m_radius=radius;};_proto14.GetSupport=function GetSupport(d){var bestIndex=0;var bestValue=b2Vec2.DotVV(this.m_vertices[0],d);for(var i=1;i<this.m_count;++i){var value=b2Vec2.DotVV(this.m_vertices[i],d);if(value>bestValue){bestIndex=i;bestValue=value;}}return bestIndex;};_proto14.GetSupportVertex=function GetSupportVertex(d){var bestIndex=0;var bestValue=b2Vec2.DotVV(this.m_vertices[0],d);for(var i=1;i<this.m_count;++i){var value=b2Vec2.DotVV(this.m_vertices[i],d);if(value>bestValue){bestIndex=i;bestValue=value;}}return this.m_vertices[bestIndex];};_proto14.GetVertexCount=function GetVertexCount(){return this.m_count;};_proto14.GetVertex=function GetVertex(index){return this.m_vertices[index];};return b2DistanceProxy;}();var b2SimplexCache=function(){function b2SimplexCache(){this.metric=0;this.count=0;this.indexA=[0,0,0];this.indexB=[0,0,0];}var _proto15=b2SimplexCache.prototype;_proto15.Reset=function Reset(){this.metric=0;this.count=0;return this;};return b2SimplexCache;}();var b2DistanceInput=function(){function b2DistanceInput(){this.proxyA=new b2DistanceProxy();this.proxyB=new b2DistanceProxy();this.transformA=new b2Transform();this.transformB=new b2Transform();this.useRadii=false;}var _proto16=b2DistanceInput.prototype;_proto16.Reset=function Reset(){this.proxyA.Reset();this.proxyB.Reset();this.transformA.SetIdentity();this.transformB.SetIdentity();this.useRadii=false;return this;};return b2DistanceInput;}();var b2DistanceOutput=function(){function b2DistanceOutput(){this.pointA=new b2Vec2();this.pointB=new b2Vec2();this.distance=0;this.iterations=0;}var _proto17=b2DistanceOutput.prototype;_proto17.Reset=function Reset(){this.pointA.SetZero();this.pointB.SetZero();this.distance=0;this.iterations=0;return this;};return b2DistanceOutput;}();var b2ShapeCastInput=function b2ShapeCastInput(){this.proxyA=new b2DistanceProxy();this.proxyB=new b2DistanceProxy();this.transformA=new b2Transform();this.transformB=new b2Transform();this.translationB=new b2Vec2();};var b2ShapeCastOutput=function b2ShapeCastOutput(){this.point=new b2Vec2();this.normal=new b2Vec2();this.lambda=0.0;this.iterations=0;};exports$1.b2_gjkCalls=0;exports$1.b2_gjkIters=0;exports$1.b2_gjkMaxIters=0;function b2_gjk_reset(){exports$1.b2_gjkCalls=0;exports$1.b2_gjkIters=0;exports$1.b2_gjkMaxIters=0;}var b2SimplexVertex=function(){function b2SimplexVertex(){this.wA=new b2Vec2();this.wB=new b2Vec2();this.w=new b2Vec2();this.a=0;this.indexA=0;this.indexB=0;}var _proto18=b2SimplexVertex.prototype;_proto18.Copy=function Copy(other){this.wA.Copy(other.wA);this.wB.Copy(other.wB);this.w.Copy(other.w);this.a=other.a;this.indexA=other.indexA;this.indexB=other.indexB;return this;};return b2SimplexVertex;}();var b2Simplex=function(){function b2Simplex(){this.m_v1=new b2SimplexVertex();this.m_v2=new b2SimplexVertex();this.m_v3=new b2SimplexVertex();this.m_vertices=[];this.m_count=0;this.m_vertices[0]=this.m_v1;this.m_vertices[1]=this.m_v2;this.m_vertices[2]=this.m_v3;}var _proto19=b2Simplex.prototype;_proto19.ReadCache=function ReadCache(cache,proxyA,transformA,proxyB,transformB){this.m_count=cache.count;var vertices=this.m_vertices;for(var i=0;i<this.m_count;++i){var v=vertices[i];v.indexA=cache.indexA[i];v.indexB=cache.indexB[i];var wALocal=proxyA.GetVertex(v.indexA);var wBLocal=proxyB.GetVertex(v.indexB);b2Transform.MulXV(transformA,wALocal,v.wA);b2Transform.MulXV(transformB,wBLocal,v.wB);b2Vec2.SubVV(v.wB,v.wA,v.w);v.a=0;}if(this.m_count>1){var metric1=cache.metric;var metric2=this.GetMetric();if(metric2<0.5*metric1||2*metric1<metric2||metric2<b2_epsilon){this.m_count=0;}}if(this.m_count===0){var _v=vertices[0];_v.indexA=0;_v.indexB=0;var _wALocal=proxyA.GetVertex(0);var _wBLocal=proxyB.GetVertex(0);b2Transform.MulXV(transformA,_wALocal,_v.wA);b2Transform.MulXV(transformB,_wBLocal,_v.wB);b2Vec2.SubVV(_v.wB,_v.wA,_v.w);_v.a=1;this.m_count=1;}};_proto19.WriteCache=function WriteCache(cache){cache.metric=this.GetMetric();cache.count=this.m_count;var vertices=this.m_vertices;for(var i=0;i<this.m_count;++i){cache.indexA[i]=vertices[i].indexA;cache.indexB[i]=vertices[i].indexB;}};_proto19.GetSearchDirection=function GetSearchDirection(out){switch(this.m_count){case 1:return b2Vec2.NegV(this.m_v1.w,out);case 2:{var e12=b2Vec2.SubVV(this.m_v2.w,this.m_v1.w,out);var sgn=b2Vec2.CrossVV(e12,b2Vec2.NegV(this.m_v1.w,b2Vec2.s_t0));if(sgn>0){return b2Vec2.CrossOneV(e12,out);}else {return b2Vec2.CrossVOne(e12,out);}}default:return out.SetZero();}};_proto19.GetClosestPoint=function GetClosestPoint(out){switch(this.m_count){case 0:return out.SetZero();case 1:return out.Copy(this.m_v1.w);case 2:return out.Set(this.m_v1.a*this.m_v1.w.x+this.m_v2.a*this.m_v2.w.x,this.m_v1.a*this.m_v1.w.y+this.m_v2.a*this.m_v2.w.y);case 3:return out.SetZero();default:return out.SetZero();}};_proto19.GetWitnessPoints=function GetWitnessPoints(pA,pB){switch(this.m_count){case 0:break;case 1:pA.Copy(this.m_v1.wA);pB.Copy(this.m_v1.wB);break;case 2:pA.x=this.m_v1.a*this.m_v1.wA.x+this.m_v2.a*this.m_v2.wA.x;pA.y=this.m_v1.a*this.m_v1.wA.y+this.m_v2.a*this.m_v2.wA.y;pB.x=this.m_v1.a*this.m_v1.wB.x+this.m_v2.a*this.m_v2.wB.x;pB.y=this.m_v1.a*this.m_v1.wB.y+this.m_v2.a*this.m_v2.wB.y;break;case 3:pB.x=pA.x=this.m_v1.a*this.m_v1.wA.x+this.m_v2.a*this.m_v2.wA.x+this.m_v3.a*this.m_v3.wA.x;pB.y=pA.y=this.m_v1.a*this.m_v1.wA.y+this.m_v2.a*this.m_v2.wA.y+this.m_v3.a*this.m_v3.wA.y;break;}};_proto19.GetMetric=function GetMetric(){switch(this.m_count){case 0:return 0;case 1:return 0;case 2:return b2Vec2.DistanceVV(this.m_v1.w,this.m_v2.w);case 3:return b2Vec2.CrossVV(b2Vec2.SubVV(this.m_v2.w,this.m_v1.w,b2Vec2.s_t0),b2Vec2.SubVV(this.m_v3.w,this.m_v1.w,b2Vec2.s_t1));default:return 0;}};_proto19.Solve2=function Solve2(){var w1=this.m_v1.w;var w2=this.m_v2.w;var e12=b2Vec2.SubVV(w2,w1,b2Simplex.s_e12);var d12_2=-b2Vec2.DotVV(w1,e12);if(d12_2<=0){this.m_v1.a=1;this.m_count=1;return;}var d12_1=b2Vec2.DotVV(w2,e12);if(d12_1<=0){this.m_v2.a=1;this.m_count=1;this.m_v1.Copy(this.m_v2);return;}var inv_d12=1/(d12_1+d12_2);this.m_v1.a=d12_1*inv_d12;this.m_v2.a=d12_2*inv_d12;this.m_count=2;};_proto19.Solve3=function Solve3(){var w1=this.m_v1.w;var w2=this.m_v2.w;var w3=this.m_v3.w;var e12=b2Vec2.SubVV(w2,w1,b2Simplex.s_e12);var w1e12=b2Vec2.DotVV(w1,e12);var w2e12=b2Vec2.DotVV(w2,e12);var d12_1=w2e12;var d12_2=-w1e12;var e13=b2Vec2.SubVV(w3,w1,b2Simplex.s_e13);var w1e13=b2Vec2.DotVV(w1,e13);var w3e13=b2Vec2.DotVV(w3,e13);var d13_1=w3e13;var d13_2=-w1e13;var e23=b2Vec2.SubVV(w3,w2,b2Simplex.s_e23);var w2e23=b2Vec2.DotVV(w2,e23);var w3e23=b2Vec2.DotVV(w3,e23);var d23_1=w3e23;var d23_2=-w2e23;var n123=b2Vec2.CrossVV(e12,e13);var d123_1=n123*b2Vec2.CrossVV(w2,w3);var d123_2=n123*b2Vec2.CrossVV(w3,w1);var d123_3=n123*b2Vec2.CrossVV(w1,w2);if(d12_2<=0&&d13_2<=0){this.m_v1.a=1;this.m_count=1;return;}if(d12_1>0&&d12_2>0&&d123_3<=0){var inv_d12=1/(d12_1+d12_2);this.m_v1.a=d12_1*inv_d12;this.m_v2.a=d12_2*inv_d12;this.m_count=2;return;}if(d13_1>0&&d13_2>0&&d123_2<=0){var inv_d13=1/(d13_1+d13_2);this.m_v1.a=d13_1*inv_d13;this.m_v3.a=d13_2*inv_d13;this.m_count=2;this.m_v2.Copy(this.m_v3);return;}if(d12_1<=0&&d23_2<=0){this.m_v2.a=1;this.m_count=1;this.m_v1.Copy(this.m_v2);return;}if(d13_1<=0&&d23_1<=0){this.m_v3.a=1;this.m_count=1;this.m_v1.Copy(this.m_v3);return;}if(d23_1>0&&d23_2>0&&d123_1<=0){var inv_d23=1/(d23_1+d23_2);this.m_v2.a=d23_1*inv_d23;this.m_v3.a=d23_2*inv_d23;this.m_count=2;this.m_v1.Copy(this.m_v3);return;}var inv_d123=1/(d123_1+d123_2+d123_3);this.m_v1.a=d123_1*inv_d123;this.m_v2.a=d123_2*inv_d123;this.m_v3.a=d123_3*inv_d123;this.m_count=3;};return b2Simplex;}();b2Simplex.s_e12=new b2Vec2();b2Simplex.s_e13=new b2Vec2();b2Simplex.s_e23=new b2Vec2();var b2Distance_s_simplex=new b2Simplex();var b2Distance_s_saveA=[0,0,0];var b2Distance_s_saveB=[0,0,0];var b2Distance_s_p=new b2Vec2();var b2Distance_s_d=new b2Vec2();var b2Distance_s_normal=new b2Vec2();var b2Distance_s_supportA=new b2Vec2();var b2Distance_s_supportB=new b2Vec2();function b2Distance(output,cache,input){++exports$1.b2_gjkCalls;var proxyA=input.proxyA;var proxyB=input.proxyB;var transformA=input.transformA;var transformB=input.transformB;var simplex=b2Distance_s_simplex;simplex.ReadCache(cache,proxyA,transformA,proxyB,transformB);var vertices=simplex.m_vertices;var k_maxIters=20;var saveA=b2Distance_s_saveA;var saveB=b2Distance_s_saveB;var saveCount=0;var iter=0;while(iter<k_maxIters){saveCount=simplex.m_count;for(var i=0;i<saveCount;++i){saveA[i]=vertices[i].indexA;saveB[i]=vertices[i].indexB;}switch(simplex.m_count){case 1:break;case 2:simplex.Solve2();break;case 3:simplex.Solve3();break;}if(simplex.m_count===3){break;}var d=simplex.GetSearchDirection(b2Distance_s_d);if(d.LengthSquared()<b2_epsilon_sq){break;}var vertex=vertices[simplex.m_count];vertex.indexA=proxyA.GetSupport(b2Rot.MulTRV(transformA.q,b2Vec2.NegV(d,b2Vec2.s_t0),b2Distance_s_supportA));b2Transform.MulXV(transformA,proxyA.GetVertex(vertex.indexA),vertex.wA);vertex.indexB=proxyB.GetSupport(b2Rot.MulTRV(transformB.q,d,b2Distance_s_supportB));b2Transform.MulXV(transformB,proxyB.GetVertex(vertex.indexB),vertex.wB);b2Vec2.SubVV(vertex.wB,vertex.wA,vertex.w);++iter;++exports$1.b2_gjkIters;var duplicate=false;for(var _i=0;_i<saveCount;++_i){if(vertex.indexA===saveA[_i]&&vertex.indexB===saveB[_i]){duplicate=true;break;}}if(duplicate){break;}++simplex.m_count;}exports$1.b2_gjkMaxIters=b2Max(exports$1.b2_gjkMaxIters,iter);simplex.GetWitnessPoints(output.pointA,output.pointB);output.distance=b2Vec2.DistanceVV(output.pointA,output.pointB);output.iterations=iter;simplex.WriteCache(cache);if(input.useRadii){var rA=proxyA.m_radius;var rB=proxyB.m_radius;if(output.distance>rA+rB&&output.distance>b2_epsilon){output.distance-=rA+rB;var normal=b2Vec2.SubVV(output.pointB,output.pointA,b2Distance_s_normal);normal.Normalize();output.pointA.SelfMulAdd(rA,normal);output.pointB.SelfMulSub(rB,normal);}else {var p=b2Vec2.MidVV(output.pointA,output.pointB,b2Distance_s_p);output.pointA.Copy(p);output.pointB.Copy(p);output.distance=0;}}}var b2ShapeCast_s_n=new b2Vec2();var b2ShapeCast_s_simplex=new b2Simplex();var b2ShapeCast_s_wA=new b2Vec2();var b2ShapeCast_s_wB=new b2Vec2();var b2ShapeCast_s_v=new b2Vec2();var b2ShapeCast_s_p=new b2Vec2();var b2ShapeCast_s_pointA=new b2Vec2();var b2ShapeCast_s_pointB=new b2Vec2();function b2ShapeCast(output,input){output.iterations=0;output.lambda=1.0;output.normal.SetZero();output.point.SetZero();var proxyA=input.proxyA;var proxyB=input.proxyB;var radiusA=b2Max(proxyA.m_radius,b2_polygonRadius);var radiusB=b2Max(proxyB.m_radius,b2_polygonRadius);var radius=radiusA+radiusB;var xfA=input.transformA;var xfB=input.transformB;var r=input.translationB;var n=b2ShapeCast_s_n.Set(0.0,0.0);var lambda=0.0;var simplex=b2ShapeCast_s_simplex;simplex.m_count=0;var vertices=simplex.m_vertices;var indexA=proxyA.GetSupport(b2Rot.MulTRV(xfA.q,b2Vec2.NegV(r,b2Vec2.s_t1),b2Vec2.s_t0));var wA=b2Transform.MulXV(xfA,proxyA.GetVertex(indexA),b2ShapeCast_s_wA);var indexB=proxyB.GetSupport(b2Rot.MulTRV(xfB.q,r,b2Vec2.s_t0));var wB=b2Transform.MulXV(xfB,proxyB.GetVertex(indexB),b2ShapeCast_s_wB);var v=b2Vec2.SubVV(wA,wB,b2ShapeCast_s_v);var sigma=b2Max(b2_polygonRadius,radius-b2_polygonRadius);var tolerance=0.5*b2_linearSlop;var k_maxIters=20;var iter=0;while(iter<k_maxIters&&b2Abs(v.Length()-sigma)>tolerance){output.iterations+=1;indexA=proxyA.GetSupport(b2Rot.MulTRV(xfA.q,b2Vec2.NegV(v,b2Vec2.s_t1),b2Vec2.s_t0));wA=b2Transform.MulXV(xfA,proxyA.GetVertex(indexA),b2ShapeCast_s_wA);indexB=proxyB.GetSupport(b2Rot.MulTRV(xfB.q,v,b2Vec2.s_t0));wB=b2Transform.MulXV(xfB,proxyB.GetVertex(indexB),b2ShapeCast_s_wB);var p=b2Vec2.SubVV(wA,wB,b2ShapeCast_s_p);v.Normalize();var vp=b2Vec2.DotVV(v,p);var vr=b2Vec2.DotVV(v,r);if(vp-sigma>lambda*vr){if(vr<=0.0){return false;}lambda=(vp-sigma)/vr;if(lambda>1.0){return false;}n.Copy(v).SelfNeg();simplex.m_count=0;}var vertex=vertices[simplex.m_count];vertex.indexA=indexB;vertex.wA.Copy(wB).SelfMulAdd(lambda,r);vertex.indexB=indexA;vertex.wB.Copy(wA);vertex.w.Copy(vertex.wB).SelfSub(vertex.wA);vertex.a=1.0;simplex.m_count+=1;switch(simplex.m_count){case 1:break;case 2:simplex.Solve2();break;case 3:simplex.Solve3();break;}if(simplex.m_count===3){return false;}simplex.GetClosestPoint(v);++iter;}var pointA=b2ShapeCast_s_pointA;var pointB=b2ShapeCast_s_pointB;simplex.GetWitnessPoints(pointA,pointB);if(v.LengthSquared()>0.0){n.Copy(v).SelfNeg();n.Normalize();}output.normal.Copy(n);output.lambda=lambda;output.iterations=iter;return true;}(function(b2ContactFeatureType){b2ContactFeatureType[b2ContactFeatureType["e_vertex"]=0]="e_vertex";b2ContactFeatureType[b2ContactFeatureType["e_face"]=1]="e_face";})(exports$1.b2ContactFeatureType||(exports$1.b2ContactFeatureType={}));var b2ContactFeature=function(){function b2ContactFeature(){this._key=0;this._key_invalid=false;this._indexA=0;this._indexB=0;this._typeA=0;this._typeB=0;}_createClass(b2ContactFeature,[{key:"key",get:function get(){if(this._key_invalid){this._key_invalid=false;this._key=this._indexA|this._indexB<<8|this._typeA<<16|this._typeB<<24;}return this._key;},set:function set(value){this._key=value;this._key_invalid=false;this._indexA=this._key&0xff;this._indexB=this._key>>8&0xff;this._typeA=this._key>>16&0xff;this._typeB=this._key>>24&0xff;}},{key:"indexA",get:function get(){return this._indexA;},set:function set(value){this._indexA=value;this._key_invalid=true;}},{key:"indexB",get:function get(){return this._indexB;},set:function set(value){this._indexB=value;this._key_invalid=true;}},{key:"typeA",get:function get(){return this._typeA;},set:function set(value){this._typeA=value;this._key_invalid=true;}},{key:"typeB",get:function get(){return this._typeB;},set:function set(value){this._typeB=value;this._key_invalid=true;}}]);return b2ContactFeature;}();var b2ContactID=function(){function b2ContactID(){this.cf=new b2ContactFeature();}var _proto20=b2ContactID.prototype;_proto20.Copy=function Copy(o){this.key=o.key;return this;};_proto20.Clone=function Clone(){return new b2ContactID().Copy(this);};_createClass(b2ContactID,[{key:"key",get:function get(){return this.cf.key;},set:function set(value){this.cf.key=value;}}]);return b2ContactID;}();var b2ManifoldPoint=function(){function b2ManifoldPoint(){this.localPoint=new b2Vec2();this.normalImpulse=0;this.tangentImpulse=0;this.id=new b2ContactID();}b2ManifoldPoint.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2ManifoldPoint();});};var _proto21=b2ManifoldPoint.prototype;_proto21.Reset=function Reset(){this.localPoint.SetZero();this.normalImpulse=0;this.tangentImpulse=0;this.id.key=0;};_proto21.Copy=function Copy(o){this.localPoint.Copy(o.localPoint);this.normalImpulse=o.normalImpulse;this.tangentImpulse=o.tangentImpulse;this.id.Copy(o.id);return this;};return b2ManifoldPoint;}();(function(b2ManifoldType){b2ManifoldType[b2ManifoldType["e_unknown"]=-1]="e_unknown";b2ManifoldType[b2ManifoldType["e_circles"]=0]="e_circles";b2ManifoldType[b2ManifoldType["e_faceA"]=1]="e_faceA";b2ManifoldType[b2ManifoldType["e_faceB"]=2]="e_faceB";})(exports$1.b2ManifoldType||(exports$1.b2ManifoldType={}));var b2Manifold=function(){function b2Manifold(){this.points=b2ManifoldPoint.MakeArray(b2_maxManifoldPoints);this.localNormal=new b2Vec2();this.localPoint=new b2Vec2();this.type=exports$1.b2ManifoldType.e_unknown;this.pointCount=0;}var _proto22=b2Manifold.prototype;_proto22.Reset=function Reset(){for(var i=0;i<b2_maxManifoldPoints;++i){this.points[i].Reset();}this.localNormal.SetZero();this.localPoint.SetZero();this.type=exports$1.b2ManifoldType.e_unknown;this.pointCount=0;};_proto22.Copy=function Copy(o){this.pointCount=o.pointCount;for(var i=0;i<b2_maxManifoldPoints;++i){this.points[i].Copy(o.points[i]);}this.localNormal.Copy(o.localNormal);this.localPoint.Copy(o.localPoint);this.type=o.type;return this;};_proto22.Clone=function Clone(){return new b2Manifold().Copy(this);};return b2Manifold;}();var b2WorldManifold=function(){function b2WorldManifold(){this.normal=new b2Vec2();this.points=b2Vec2.MakeArray(b2_maxManifoldPoints);this.separations=b2MakeNumberArray(b2_maxManifoldPoints);}var _proto23=b2WorldManifold.prototype;_proto23.Initialize=function Initialize(manifold,xfA,radiusA,xfB,radiusB){if(manifold.pointCount===0){return;}switch(manifold.type){case exports$1.b2ManifoldType.e_circles:{this.normal.Set(1,0);var pointA=b2Transform.MulXV(xfA,manifold.localPoint,b2WorldManifold.Initialize_s_pointA);var pointB=b2Transform.MulXV(xfB,manifold.points[0].localPoint,b2WorldManifold.Initialize_s_pointB);if(b2Vec2.DistanceSquaredVV(pointA,pointB)>b2_epsilon_sq){b2Vec2.SubVV(pointB,pointA,this.normal).SelfNormalize();}var cA=b2Vec2.AddVMulSV(pointA,radiusA,this.normal,b2WorldManifold.Initialize_s_cA);var cB=b2Vec2.SubVMulSV(pointB,radiusB,this.normal,b2WorldManifold.Initialize_s_cB);b2Vec2.MidVV(cA,cB,this.points[0]);this.separations[0]=b2Vec2.DotVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),this.normal);break;}case exports$1.b2ManifoldType.e_faceA:{b2Rot.MulRV(xfA.q,manifold.localNormal,this.normal);var planePoint=b2Transform.MulXV(xfA,manifold.localPoint,b2WorldManifold.Initialize_s_planePoint);for(var i=0;i<manifold.pointCount;++i){var clipPoint=b2Transform.MulXV(xfB,manifold.points[i].localPoint,b2WorldManifold.Initialize_s_clipPoint);var s=radiusA-b2Vec2.DotVV(b2Vec2.SubVV(clipPoint,planePoint,b2Vec2.s_t0),this.normal);var _cA=b2Vec2.AddVMulSV(clipPoint,s,this.normal,b2WorldManifold.Initialize_s_cA);var _cB=b2Vec2.SubVMulSV(clipPoint,radiusB,this.normal,b2WorldManifold.Initialize_s_cB);b2Vec2.MidVV(_cA,_cB,this.points[i]);this.separations[i]=b2Vec2.DotVV(b2Vec2.SubVV(_cB,_cA,b2Vec2.s_t0),this.normal);}break;}case exports$1.b2ManifoldType.e_faceB:{b2Rot.MulRV(xfB.q,manifold.localNormal,this.normal);var _planePoint=b2Transform.MulXV(xfB,manifold.localPoint,b2WorldManifold.Initialize_s_planePoint);for(var _i2=0;_i2<manifold.pointCount;++_i2){var _clipPoint=b2Transform.MulXV(xfA,manifold.points[_i2].localPoint,b2WorldManifold.Initialize_s_clipPoint);var _s=radiusB-b2Vec2.DotVV(b2Vec2.SubVV(_clipPoint,_planePoint,b2Vec2.s_t0),this.normal);var _cB2=b2Vec2.AddVMulSV(_clipPoint,_s,this.normal,b2WorldManifold.Initialize_s_cB);var _cA2=b2Vec2.SubVMulSV(_clipPoint,radiusA,this.normal,b2WorldManifold.Initialize_s_cA);b2Vec2.MidVV(_cA2,_cB2,this.points[_i2]);this.separations[_i2]=b2Vec2.DotVV(b2Vec2.SubVV(_cA2,_cB2,b2Vec2.s_t0),this.normal);}this.normal.SelfNeg();break;}}};return b2WorldManifold;}();b2WorldManifold.Initialize_s_pointA=new b2Vec2();b2WorldManifold.Initialize_s_pointB=new b2Vec2();b2WorldManifold.Initialize_s_cA=new b2Vec2();b2WorldManifold.Initialize_s_cB=new b2Vec2();b2WorldManifold.Initialize_s_planePoint=new b2Vec2();b2WorldManifold.Initialize_s_clipPoint=new b2Vec2();(function(b2PointState){b2PointState[b2PointState["b2_nullState"]=0]="b2_nullState";b2PointState[b2PointState["b2_addState"]=1]="b2_addState";b2PointState[b2PointState["b2_persistState"]=2]="b2_persistState";b2PointState[b2PointState["b2_removeState"]=3]="b2_removeState";})(exports$1.b2PointState||(exports$1.b2PointState={}));function b2GetPointStates(state1,state2,manifold1,manifold2){var i;for(i=0;i<manifold1.pointCount;++i){var id=manifold1.points[i].id;var key=id.key;state1[i]=exports$1.b2PointState.b2_removeState;for(var j=0,jct=manifold2.pointCount;j<jct;++j){if(manifold2.points[j].id.key===key){state1[i]=exports$1.b2PointState.b2_persistState;break;}}}for(;i<b2_maxManifoldPoints;++i){state1[i]=exports$1.b2PointState.b2_nullState;}for(i=0;i<manifold2.pointCount;++i){var _id=manifold2.points[i].id;var _key5=_id.key;state2[i]=exports$1.b2PointState.b2_addState;for(var _j=0,_jct=manifold1.pointCount;_j<_jct;++_j){if(manifold1.points[_j].id.key===_key5){state2[i]=exports$1.b2PointState.b2_persistState;break;}}}for(;i<b2_maxManifoldPoints;++i){state2[i]=exports$1.b2PointState.b2_nullState;}}var b2ClipVertex=function(){function b2ClipVertex(){this.v=new b2Vec2();this.id=new b2ContactID();}b2ClipVertex.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2ClipVertex();});};var _proto24=b2ClipVertex.prototype;_proto24.Copy=function Copy(other){this.v.Copy(other.v);this.id.Copy(other.id);return this;};return b2ClipVertex;}();var b2RayCastInput=function(){function b2RayCastInput(){this.p1=new b2Vec2();this.p2=new b2Vec2();this.maxFraction=1;}var _proto25=b2RayCastInput.prototype;_proto25.Copy=function Copy(o){this.p1.Copy(o.p1);this.p2.Copy(o.p2);this.maxFraction=o.maxFraction;return this;};return b2RayCastInput;}();var b2RayCastOutput=function(){function b2RayCastOutput(){this.normal=new b2Vec2();this.fraction=0;}var _proto26=b2RayCastOutput.prototype;_proto26.Copy=function Copy(o){this.normal.Copy(o.normal);this.fraction=o.fraction;return this;};return b2RayCastOutput;}();var b2AABB=function(){function b2AABB(){this.lowerBound=new b2Vec2();this.upperBound=new b2Vec2();this.m_cache_center=new b2Vec2();this.m_cache_extent=new b2Vec2();}var _proto27=b2AABB.prototype;_proto27.Copy=function Copy(o){this.lowerBound.Copy(o.lowerBound);this.upperBound.Copy(o.upperBound);return this;};_proto27.IsValid=function IsValid(){if(!this.lowerBound.IsValid()){return false;}if(!this.upperBound.IsValid()){return false;}if(this.upperBound.x<this.lowerBound.x){return false;}if(this.upperBound.y<this.lowerBound.y){return false;}return true;};_proto27.GetCenter=function GetCenter(){return b2Vec2.MidVV(this.lowerBound,this.upperBound,this.m_cache_center);};_proto27.GetExtents=function GetExtents(){return b2Vec2.ExtVV(this.lowerBound,this.upperBound,this.m_cache_extent);};_proto27.GetPerimeter=function GetPerimeter(){var wx=this.upperBound.x-this.lowerBound.x;var wy=this.upperBound.y-this.lowerBound.y;return 2*(wx+wy);};_proto27.Combine1=function Combine1(aabb){this.lowerBound.x=b2Min(this.lowerBound.x,aabb.lowerBound.x);this.lowerBound.y=b2Min(this.lowerBound.y,aabb.lowerBound.y);this.upperBound.x=b2Max(this.upperBound.x,aabb.upperBound.x);this.upperBound.y=b2Max(this.upperBound.y,aabb.upperBound.y);return this;};_proto27.Combine2=function Combine2(aabb1,aabb2){this.lowerBound.x=b2Min(aabb1.lowerBound.x,aabb2.lowerBound.x);this.lowerBound.y=b2Min(aabb1.lowerBound.y,aabb2.lowerBound.y);this.upperBound.x=b2Max(aabb1.upperBound.x,aabb2.upperBound.x);this.upperBound.y=b2Max(aabb1.upperBound.y,aabb2.upperBound.y);return this;};b2AABB.Combine=function Combine(aabb1,aabb2,out){out.Combine2(aabb1,aabb2);return out;};_proto27.Contains=function Contains(aabb){if(this.lowerBound.x<=aabb.lowerBound.x){return false;}if(this.lowerBound.y<=aabb.lowerBound.y){return false;}if(aabb.upperBound.x<=this.upperBound.x){return false;}if(aabb.upperBound.y<=this.upperBound.y){return false;}return true;};_proto27.RayCast=function RayCast(output,input){var tmin=-b2_maxFloat;var tmax=b2_maxFloat;var p_x=input.p1.x;var p_y=input.p1.y;var d_x=input.p2.x-input.p1.x;var d_y=input.p2.y-input.p1.y;var absD_x=b2Abs(d_x);var absD_y=b2Abs(d_y);var normal=output.normal;if(absD_x<b2_epsilon){if(p_x<this.lowerBound.x||this.upperBound.x<p_x){return false;}}else {var inv_d=1/d_x;var t1=(this.lowerBound.x-p_x)*inv_d;var t2=(this.upperBound.x-p_x)*inv_d;var s=-1;if(t1>t2){var t3=t1;t1=t2;t2=t3;s=1;}if(t1>tmin){normal.x=s;normal.y=0;tmin=t1;}tmax=b2Min(tmax,t2);if(tmin>tmax){return false;}}if(absD_y<b2_epsilon){if(p_y<this.lowerBound.y||this.upperBound.y<p_y){return false;}}else {var _inv_d=1/d_y;var _t=(this.lowerBound.y-p_y)*_inv_d;var _t2=(this.upperBound.y-p_y)*_inv_d;var _s2=-1;if(_t>_t2){var _t3=_t;_t=_t2;_t2=_t3;_s2=1;}if(_t>tmin){normal.x=0;normal.y=_s2;tmin=_t;}tmax=b2Min(tmax,_t2);if(tmin>tmax){return false;}}if(tmin<0||input.maxFraction<tmin){return false;}output.fraction=tmin;return true;};_proto27.TestContain=function TestContain(point){if(point.x<this.lowerBound.x||this.upperBound.x<point.x){return false;}if(point.y<this.lowerBound.y||this.upperBound.y<point.y){return false;}return true;};_proto27.TestOverlap=function TestOverlap(other){if(this.upperBound.x<other.lowerBound.x){return false;}if(this.upperBound.y<other.lowerBound.y){return false;}if(other.upperBound.x<this.lowerBound.x){return false;}if(other.upperBound.y<this.lowerBound.y){return false;}return true;};return b2AABB;}();function b2TestOverlapAABB(a,b){if(a.upperBound.x<b.lowerBound.x){return false;}if(a.upperBound.y<b.lowerBound.y){return false;}if(b.upperBound.x<a.lowerBound.x){return false;}if(b.upperBound.y<a.lowerBound.y){return false;}return true;}function b2ClipSegmentToLine(vOut,vIn,normal,offset,vertexIndexA){var numOut=0;var vIn0=vIn[0];var vIn1=vIn[1];var distance0=b2Vec2.DotVV(normal,vIn0.v)-offset;var distance1=b2Vec2.DotVV(normal,vIn1.v)-offset;if(distance0<=0){vOut[numOut++].Copy(vIn0);}if(distance1<=0){vOut[numOut++].Copy(vIn1);}if(distance0*distance1<0){var interp=distance0/(distance0-distance1);var v=vOut[numOut].v;v.x=vIn0.v.x+interp*(vIn1.v.x-vIn0.v.x);v.y=vIn0.v.y+interp*(vIn1.v.y-vIn0.v.y);var id=vOut[numOut].id;id.cf.indexA=vertexIndexA;id.cf.indexB=vIn0.id.cf.indexB;id.cf.typeA=exports$1.b2ContactFeatureType.e_vertex;id.cf.typeB=exports$1.b2ContactFeatureType.e_face;++numOut;}return numOut;}var b2TestOverlapShape_s_input=new b2DistanceInput();var b2TestOverlapShape_s_simplexCache=new b2SimplexCache();var b2TestOverlapShape_s_output=new b2DistanceOutput();function b2TestOverlapShape(shapeA,indexA,shapeB,indexB,xfA,xfB){var input=b2TestOverlapShape_s_input.Reset();input.proxyA.SetShape(shapeA,indexA);input.proxyB.SetShape(shapeB,indexB);input.transformA.Copy(xfA);input.transformB.Copy(xfB);input.useRadii=true;var simplexCache=b2TestOverlapShape_s_simplexCache.Reset();simplexCache.count=0;var output=b2TestOverlapShape_s_output.Reset();b2Distance(output,simplexCache,input);return output.distance<10*b2_epsilon;}function verify(value){if(value===null){throw new Error();}return value;}var b2TreeNode=function(){function b2TreeNode(id){if(id===void 0){id=0;}this.m_id=0;this.aabb=new b2AABB();this._userData=null;this.parent=null;this.child1=null;this.child2=null;this.height=0;this.m_id=id;}var _proto28=b2TreeNode.prototype;_proto28.Reset=function Reset(){this._userData=null;};_proto28.IsLeaf=function IsLeaf(){return this.child1===null;};_createClass(b2TreeNode,[{key:"userData",get:function get(){if(this._userData===null){throw new Error();}return this._userData;},set:function set(value){if(this._userData!==null){throw new Error();}this._userData=value;}}]);return b2TreeNode;}();var b2DynamicTree=function(){function b2DynamicTree(){this.m_root=null;this.m_freeList=null;this.m_path=0;this.m_insertionCount=0;this.m_stack=new b2GrowableStack(256);}var _proto29=b2DynamicTree.prototype;_proto29.Query=function Query(aabb,callback){var stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){var node=stack.Pop();if(node===null){continue;}if(node.aabb.TestOverlap(aabb)){if(node.IsLeaf()){var proceed=callback(node);if(!proceed){return;}}else {stack.Push(node.child1);stack.Push(node.child2);}}}};_proto29.QueryPoint=function QueryPoint(point,callback){var stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){var node=stack.Pop();if(node===null){continue;}if(node.aabb.TestContain(point)){if(node.IsLeaf()){var proceed=callback(node);if(!proceed){return;}}else {stack.Push(node.child1);stack.Push(node.child2);}}}};_proto29.RayCast=function RayCast(input,callback){var p1=input.p1;var p2=input.p2;var r=b2Vec2.SubVV(p2,p1,b2DynamicTree.s_r);r.Normalize();var v=b2Vec2.CrossOneV(r,b2DynamicTree.s_v);var abs_v=b2Vec2.AbsV(v,b2DynamicTree.s_abs_v);var maxFraction=input.maxFraction;var segmentAABB=b2DynamicTree.s_segmentAABB;var t_x=p1.x+maxFraction*(p2.x-p1.x);var t_y=p1.y+maxFraction*(p2.y-p1.y);segmentAABB.lowerBound.x=b2Min(p1.x,t_x);segmentAABB.lowerBound.y=b2Min(p1.y,t_y);segmentAABB.upperBound.x=b2Max(p1.x,t_x);segmentAABB.upperBound.y=b2Max(p1.y,t_y);var stack=this.m_stack.Reset();stack.Push(this.m_root);while(stack.GetCount()>0){var node=stack.Pop();if(node===null){continue;}if(!b2TestOverlapAABB(node.aabb,segmentAABB)){continue;}var c=node.aabb.GetCenter();var h=node.aabb.GetExtents();var separation=b2Abs(b2Vec2.DotVV(v,b2Vec2.SubVV(p1,c,b2Vec2.s_t0)))-b2Vec2.DotVV(abs_v,h);if(separation>0){continue;}if(node.IsLeaf()){var subInput=b2DynamicTree.s_subInput;subInput.p1.Copy(input.p1);subInput.p2.Copy(input.p2);subInput.maxFraction=maxFraction;var value=callback(subInput,node);if(value===0){return;}if(value>0){maxFraction=value;t_x=p1.x+maxFraction*(p2.x-p1.x);t_y=p1.y+maxFraction*(p2.y-p1.y);segmentAABB.lowerBound.x=b2Min(p1.x,t_x);segmentAABB.lowerBound.y=b2Min(p1.y,t_y);segmentAABB.upperBound.x=b2Max(p1.x,t_x);segmentAABB.upperBound.y=b2Max(p1.y,t_y);}}else {stack.Push(node.child1);stack.Push(node.child2);}}};_proto29.AllocateNode=function AllocateNode(){if(this.m_freeList!==null){var node=this.m_freeList;this.m_freeList=node.parent;node.parent=null;node.child1=null;node.child2=null;node.height=0;return node;}return new b2TreeNode(b2DynamicTree.s_node_id++);};_proto29.FreeNode=function FreeNode(node){node.parent=this.m_freeList;node.child1=null;node.child2=null;node.height=-1;node.Reset();this.m_freeList=node;};_proto29.CreateProxy=function CreateProxy(aabb,userData){var node=this.AllocateNode();var r_x=b2_aabbExtension;var r_y=b2_aabbExtension;node.aabb.lowerBound.x=aabb.lowerBound.x-r_x;node.aabb.lowerBound.y=aabb.lowerBound.y-r_y;node.aabb.upperBound.x=aabb.upperBound.x+r_x;node.aabb.upperBound.y=aabb.upperBound.y+r_y;node.userData=userData;node.height=0;this.InsertLeaf(node);return node;};_proto29.DestroyProxy=function DestroyProxy(node){this.RemoveLeaf(node);this.FreeNode(node);};_proto29.MoveProxy=function MoveProxy(node,aabb,displacement){if(node.aabb.Contains(aabb)){return false;}this.RemoveLeaf(node);var r_x=b2_aabbExtension;var r_y=b2_aabbExtension;node.aabb.lowerBound.x=aabb.lowerBound.x-r_x;node.aabb.lowerBound.y=aabb.lowerBound.y-r_y;node.aabb.upperBound.x=aabb.upperBound.x+r_x;node.aabb.upperBound.y=aabb.upperBound.y+r_y;var d_x=b2_aabbMultiplier*displacement.x;var d_y=b2_aabbMultiplier*displacement.y;if(d_x<0.0){node.aabb.lowerBound.x+=d_x;}else {node.aabb.upperBound.x+=d_x;}if(d_y<0.0){node.aabb.lowerBound.y+=d_y;}else {node.aabb.upperBound.y+=d_y;}this.InsertLeaf(node);return true;};_proto29.InsertLeaf=function InsertLeaf(leaf){++this.m_insertionCount;if(this.m_root===null){this.m_root=leaf;this.m_root.parent=null;return;}var leafAABB=leaf.aabb;var sibling=this.m_root;while(!sibling.IsLeaf()){var child1=verify(sibling.child1);var child2=verify(sibling.child2);var area=sibling.aabb.GetPerimeter();var combinedAABB=b2DynamicTree.s_combinedAABB;combinedAABB.Combine2(sibling.aabb,leafAABB);var combinedArea=combinedAABB.GetPerimeter();var cost=2*combinedArea;var inheritanceCost=2*(combinedArea-area);var cost1=void 0;var aabb=b2DynamicTree.s_aabb;var oldArea=void 0;var newArea=void 0;if(child1.IsLeaf()){aabb.Combine2(leafAABB,child1.aabb);cost1=aabb.GetPerimeter()+inheritanceCost;}else {aabb.Combine2(leafAABB,child1.aabb);oldArea=child1.aabb.GetPerimeter();newArea=aabb.GetPerimeter();cost1=newArea-oldArea+inheritanceCost;}var cost2=void 0;if(child2.IsLeaf()){aabb.Combine2(leafAABB,child2.aabb);cost2=aabb.GetPerimeter()+inheritanceCost;}else {aabb.Combine2(leafAABB,child2.aabb);oldArea=child2.aabb.GetPerimeter();newArea=aabb.GetPerimeter();cost2=newArea-oldArea+inheritanceCost;}if(cost<cost1&&cost<cost2){break;}if(cost1<cost2){sibling=child1;}else {sibling=child2;}}var oldParent=sibling.parent;var newParent=this.AllocateNode();newParent.parent=oldParent;newParent.aabb.Combine2(leafAABB,sibling.aabb);newParent.height=sibling.height+1;if(oldParent!==null){if(oldParent.child1===sibling){oldParent.child1=newParent;}else {oldParent.child2=newParent;}newParent.child1=sibling;newParent.child2=leaf;sibling.parent=newParent;leaf.parent=newParent;}else {newParent.child1=sibling;newParent.child2=leaf;sibling.parent=newParent;leaf.parent=newParent;this.m_root=newParent;}var node=leaf.parent;while(node!==null){node=this.Balance(node);var _child=verify(node.child1);var _child2=verify(node.child2);node.height=1+b2Max(_child.height,_child2.height);node.aabb.Combine2(_child.aabb,_child2.aabb);node=node.parent;}};_proto29.RemoveLeaf=function RemoveLeaf(leaf){if(leaf===this.m_root){this.m_root=null;return;}var parent=verify(leaf.parent);var grandParent=parent&&parent.parent;var sibling=verify(parent.child1===leaf?parent.child2:parent.child1);if(grandParent!==null){if(grandParent.child1===parent){grandParent.child1=sibling;}else {grandParent.child2=sibling;}sibling.parent=grandParent;this.FreeNode(parent);var index=grandParent;while(index!==null){index=this.Balance(index);var child1=verify(index.child1);var child2=verify(index.child2);index.aabb.Combine2(child1.aabb,child2.aabb);index.height=1+b2Max(child1.height,child2.height);index=index.parent;}}else {this.m_root=sibling;sibling.parent=null;this.FreeNode(parent);}};_proto29.Balance=function Balance(A){if(A.IsLeaf()||A.height<2){return A;}var B=verify(A.child1);var C=verify(A.child2);var balance=C.height-B.height;if(balance>1){var F=verify(C.child1);var G=verify(C.child2);C.child1=A;C.parent=A.parent;A.parent=C;if(C.parent!==null){if(C.parent.child1===A){C.parent.child1=C;}else {C.parent.child2=C;}}else {this.m_root=C;}if(F.height>G.height){C.child2=F;A.child2=G;G.parent=A;A.aabb.Combine2(B.aabb,G.aabb);C.aabb.Combine2(A.aabb,F.aabb);A.height=1+b2Max(B.height,G.height);C.height=1+b2Max(A.height,F.height);}else {C.child2=G;A.child2=F;F.parent=A;A.aabb.Combine2(B.aabb,F.aabb);C.aabb.Combine2(A.aabb,G.aabb);A.height=1+b2Max(B.height,F.height);C.height=1+b2Max(A.height,G.height);}return C;}if(balance<-1){var D=verify(B.child1);var E=verify(B.child2);B.child1=A;B.parent=A.parent;A.parent=B;if(B.parent!==null){if(B.parent.child1===A){B.parent.child1=B;}else {B.parent.child2=B;}}else {this.m_root=B;}if(D.height>E.height){B.child2=D;A.child1=E;E.parent=A;A.aabb.Combine2(C.aabb,E.aabb);B.aabb.Combine2(A.aabb,D.aabb);A.height=1+b2Max(C.height,E.height);B.height=1+b2Max(A.height,D.height);}else {B.child2=E;A.child1=D;D.parent=A;A.aabb.Combine2(C.aabb,D.aabb);B.aabb.Combine2(A.aabb,E.aabb);A.height=1+b2Max(C.height,D.height);B.height=1+b2Max(A.height,E.height);}return B;}return A;};_proto29.GetHeight=function GetHeight(){if(this.m_root===null){return 0;}return this.m_root.height;};b2DynamicTree.GetAreaNode=function GetAreaNode(node){if(node===null){return 0;}if(node.IsLeaf()){return 0;}var area=node.aabb.GetPerimeter();area+=b2DynamicTree.GetAreaNode(node.child1);area+=b2DynamicTree.GetAreaNode(node.child2);return area;};_proto29.GetAreaRatio=function GetAreaRatio(){if(this.m_root===null){return 0;}var root=this.m_root;var rootArea=root.aabb.GetPerimeter();var totalArea=b2DynamicTree.GetAreaNode(this.m_root);return totalArea/rootArea;};b2DynamicTree.ComputeHeightNode=function ComputeHeightNode(node){if(node===null){return 0;}if(node.IsLeaf()){return 0;}var height1=b2DynamicTree.ComputeHeightNode(node.child1);var height2=b2DynamicTree.ComputeHeightNode(node.child2);return 1+b2Max(height1,height2);};_proto29.ComputeHeight=function ComputeHeight(){var height=b2DynamicTree.ComputeHeightNode(this.m_root);return height;};_proto29.ValidateStructure=function ValidateStructure(node){if(node===null){return;}if(node===this.m_root);if(node.IsLeaf()){return;}var child1=verify(node.child1);var child2=verify(node.child2);this.ValidateStructure(child1);this.ValidateStructure(child2);};_proto29.ValidateMetrics=function ValidateMetrics(node){if(node===null){return;}if(node.IsLeaf()){return;}var child1=verify(node.child1);var child2=verify(node.child2);var aabb=b2DynamicTree.s_aabb;aabb.Combine2(child1.aabb,child2.aabb);this.ValidateMetrics(child1);this.ValidateMetrics(child2);};_proto29.Validate=function Validate(){};b2DynamicTree.GetMaxBalanceNode=function GetMaxBalanceNode(node,maxBalance){if(node===null){return maxBalance;}if(node.height<=1){return maxBalance;}var child1=verify(node.child1);var child2=verify(node.child2);var balance=b2Abs(child2.height-child1.height);return b2Max(maxBalance,balance);};_proto29.GetMaxBalance=function GetMaxBalance(){var maxBalance=b2DynamicTree.GetMaxBalanceNode(this.m_root,0);return maxBalance;};_proto29.RebuildBottomUp=function RebuildBottomUp(){this.Validate();};b2DynamicTree.ShiftOriginNode=function ShiftOriginNode(node,newOrigin){if(node===null){return;}if(node.height<=1){return;}var child1=node.child1;var child2=node.child2;b2DynamicTree.ShiftOriginNode(child1,newOrigin);b2DynamicTree.ShiftOriginNode(child2,newOrigin);node.aabb.lowerBound.SelfSub(newOrigin);node.aabb.upperBound.SelfSub(newOrigin);};_proto29.ShiftOrigin=function ShiftOrigin(newOrigin){b2DynamicTree.ShiftOriginNode(this.m_root,newOrigin);};return b2DynamicTree;}();b2DynamicTree.s_r=new b2Vec2();b2DynamicTree.s_v=new b2Vec2();b2DynamicTree.s_abs_v=new b2Vec2();b2DynamicTree.s_segmentAABB=new b2AABB();b2DynamicTree.s_subInput=new b2RayCastInput();b2DynamicTree.s_combinedAABB=new b2AABB();b2DynamicTree.s_aabb=new b2AABB();b2DynamicTree.s_node_id=0;function std_iter_swap(array,a,b){var tmp=array[a];array[a]=array[b];array[b]=tmp;}function default_compare(a,b){return a<b;}function std_sort(array,first,len,cmp){if(first===void 0){first=0;}if(len===void 0){len=array.length-first;}if(cmp===void 0){cmp=default_compare;}var left=first;var stack=[];var pos=0;for(;;){for(;left+1<len;len++){var pivot=array[left+Math.floor(Math.random()*(len-left))];stack[pos++]=len;for(var right=left-1;;){while(cmp(array[++right],pivot)){}while(cmp(pivot,array[--len])){}if(right>=len){break;}std_iter_swap(array,right,len);}}if(pos===0){break;}left=len;len=stack[--pos];}return array;}var b2Pair=function b2Pair(proxyA,proxyB){this.proxyA=proxyA;this.proxyB=proxyB;};var b2BroadPhase=function(){function b2BroadPhase(){this.m_tree=new b2DynamicTree();this.m_proxyCount=0;this.m_moveCount=0;this.m_moveBuffer=[];this.m_pairCount=0;this.m_pairBuffer=[];}var _proto30=b2BroadPhase.prototype;_proto30.CreateProxy=function CreateProxy(aabb,userData){var proxy=this.m_tree.CreateProxy(aabb,userData);++this.m_proxyCount;this.BufferMove(proxy);return proxy;};_proto30.DestroyProxy=function DestroyProxy(proxy){this.UnBufferMove(proxy);--this.m_proxyCount;this.m_tree.DestroyProxy(proxy);};_proto30.MoveProxy=function MoveProxy(proxy,aabb,displacement){var buffer=this.m_tree.MoveProxy(proxy,aabb,displacement);if(buffer){this.BufferMove(proxy);}};_proto30.TouchProxy=function TouchProxy(proxy){this.BufferMove(proxy);};_proto30.GetProxyCount=function GetProxyCount(){return this.m_proxyCount;};_proto30.UpdatePairs=function UpdatePairs(callback){var _this=this;this.m_pairCount=0;var _loop=function _loop(){var queryProxy=_this.m_moveBuffer[_i3];if(queryProxy===null){return 1;}var fatAABB=queryProxy.aabb;_this.m_tree.Query(fatAABB,function(proxy){if(proxy.m_id===queryProxy.m_id){return true;}var proxyA;var proxyB;if(proxy.m_id<queryProxy.m_id){proxyA=proxy;proxyB=queryProxy;}else {proxyA=queryProxy;proxyB=proxy;}if(_this.m_pairCount===_this.m_pairBuffer.length){_this.m_pairBuffer[_this.m_pairCount]=new b2Pair(proxyA,proxyB);}else {var _pair=_this.m_pairBuffer[_this.m_pairCount];_pair.proxyA=proxyA;_pair.proxyB=proxyB;}++_this.m_pairCount;return true;});};for(var _i3=0;_i3<this.m_moveCount;++_i3){if(_loop())continue;}this.m_moveCount=0;std_sort(this.m_pairBuffer,0,this.m_pairCount,b2PairLessThan);var i=0;while(i<this.m_pairCount){var primaryPair=this.m_pairBuffer[i];var userDataA=primaryPair.proxyA.userData;var userDataB=primaryPair.proxyB.userData;callback(userDataA,userDataB);++i;while(i<this.m_pairCount){var pair=this.m_pairBuffer[i];if(pair.proxyA.m_id!==primaryPair.proxyA.m_id||pair.proxyB.m_id!==primaryPair.proxyB.m_id){break;}++i;}}};_proto30.Query=function Query(aabb,callback){this.m_tree.Query(aabb,callback);};_proto30.QueryPoint=function QueryPoint(point,callback){this.m_tree.QueryPoint(point,callback);};_proto30.RayCast=function RayCast(input,callback){this.m_tree.RayCast(input,callback);};_proto30.GetTreeHeight=function GetTreeHeight(){return this.m_tree.GetHeight();};_proto30.GetTreeBalance=function GetTreeBalance(){return this.m_tree.GetMaxBalance();};_proto30.GetTreeQuality=function GetTreeQuality(){return this.m_tree.GetAreaRatio();};_proto30.ShiftOrigin=function ShiftOrigin(newOrigin){this.m_tree.ShiftOrigin(newOrigin);};_proto30.BufferMove=function BufferMove(proxy){this.m_moveBuffer[this.m_moveCount]=proxy;++this.m_moveCount;};_proto30.UnBufferMove=function UnBufferMove(proxy){var i=this.m_moveBuffer.indexOf(proxy);this.m_moveBuffer[i]=null;};return b2BroadPhase;}();function b2PairLessThan(pair1,pair2){if(pair1.proxyA.m_id<pair2.proxyA.m_id){return true;}if(pair1.proxyA.m_id===pair2.proxyA.m_id){return pair1.proxyB.m_id<pair2.proxyB.m_id;}return false;}exports$1.b2_toiTime=0;exports$1.b2_toiMaxTime=0;exports$1.b2_toiCalls=0;exports$1.b2_toiIters=0;exports$1.b2_toiMaxIters=0;exports$1.b2_toiRootIters=0;exports$1.b2_toiMaxRootIters=0;function b2_toi_reset(){exports$1.b2_toiTime=0;exports$1.b2_toiMaxTime=0;exports$1.b2_toiCalls=0;exports$1.b2_toiIters=0;exports$1.b2_toiMaxIters=0;exports$1.b2_toiRootIters=0;exports$1.b2_toiMaxRootIters=0;}var b2TimeOfImpact_s_xfA=new b2Transform();var b2TimeOfImpact_s_xfB=new b2Transform();var b2TimeOfImpact_s_pointA=new b2Vec2();var b2TimeOfImpact_s_pointB=new b2Vec2();var b2TimeOfImpact_s_normal=new b2Vec2();var b2TimeOfImpact_s_axisA=new b2Vec2();var b2TimeOfImpact_s_axisB=new b2Vec2();var b2TOIInput=function b2TOIInput(){this.proxyA=new b2DistanceProxy();this.proxyB=new b2DistanceProxy();this.sweepA=new b2Sweep();this.sweepB=new b2Sweep();this.tMax=0;};(function(b2TOIOutputState){b2TOIOutputState[b2TOIOutputState["e_unknown"]=0]="e_unknown";b2TOIOutputState[b2TOIOutputState["e_failed"]=1]="e_failed";b2TOIOutputState[b2TOIOutputState["e_overlapped"]=2]="e_overlapped";b2TOIOutputState[b2TOIOutputState["e_touching"]=3]="e_touching";b2TOIOutputState[b2TOIOutputState["e_separated"]=4]="e_separated";})(exports$1.b2TOIOutputState||(exports$1.b2TOIOutputState={}));var b2TOIOutput=function b2TOIOutput(){this.state=exports$1.b2TOIOutputState.e_unknown;this.t=0;};(function(b2SeparationFunctionType){b2SeparationFunctionType[b2SeparationFunctionType["e_unknown"]=-1]="e_unknown";b2SeparationFunctionType[b2SeparationFunctionType["e_points"]=0]="e_points";b2SeparationFunctionType[b2SeparationFunctionType["e_faceA"]=1]="e_faceA";b2SeparationFunctionType[b2SeparationFunctionType["e_faceB"]=2]="e_faceB";})(exports$1.b2SeparationFunctionType||(exports$1.b2SeparationFunctionType={}));var b2SeparationFunction=function(){function b2SeparationFunction(){this.m_sweepA=new b2Sweep();this.m_sweepB=new b2Sweep();this.m_type=exports$1.b2SeparationFunctionType.e_unknown;this.m_localPoint=new b2Vec2();this.m_axis=new b2Vec2();}var _proto31=b2SeparationFunction.prototype;_proto31.Initialize=function Initialize(cache,proxyA,sweepA,proxyB,sweepB,t1){this.m_proxyA=proxyA;this.m_proxyB=proxyB;var count=cache.count;this.m_sweepA.Copy(sweepA);this.m_sweepB.Copy(sweepB);var xfA=b2TimeOfImpact_s_xfA;var xfB=b2TimeOfImpact_s_xfB;this.m_sweepA.GetTransform(xfA,t1);this.m_sweepB.GetTransform(xfB,t1);if(count===1){this.m_type=exports$1.b2SeparationFunctionType.e_points;var localPointA=this.m_proxyA.GetVertex(cache.indexA[0]);var localPointB=this.m_proxyB.GetVertex(cache.indexB[0]);var pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);var pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);b2Vec2.SubVV(pointB,pointA,this.m_axis);var s=this.m_axis.Normalize();this.m_localPoint.SetZero();return s;}else if(cache.indexA[0]===cache.indexA[1]){this.m_type=exports$1.b2SeparationFunctionType.e_faceB;var localPointB1=this.m_proxyB.GetVertex(cache.indexB[0]);var localPointB2=this.m_proxyB.GetVertex(cache.indexB[1]);b2Vec2.CrossVOne(b2Vec2.SubVV(localPointB2,localPointB1,b2Vec2.s_t0),this.m_axis).SelfNormalize();var normal=b2Rot.MulRV(xfB.q,this.m_axis,b2TimeOfImpact_s_normal);b2Vec2.MidVV(localPointB1,localPointB2,this.m_localPoint);var _pointB=b2Transform.MulXV(xfB,this.m_localPoint,b2TimeOfImpact_s_pointB);var _localPointA=this.m_proxyA.GetVertex(cache.indexA[0]);var _pointA=b2Transform.MulXV(xfA,_localPointA,b2TimeOfImpact_s_pointA);var _s3=b2Vec2.DotVV(b2Vec2.SubVV(_pointA,_pointB,b2Vec2.s_t0),normal);if(_s3<0){this.m_axis.SelfNeg();_s3=-_s3;}return _s3;}else {this.m_type=exports$1.b2SeparationFunctionType.e_faceA;var localPointA1=this.m_proxyA.GetVertex(cache.indexA[0]);var localPointA2=this.m_proxyA.GetVertex(cache.indexA[1]);b2Vec2.CrossVOne(b2Vec2.SubVV(localPointA2,localPointA1,b2Vec2.s_t0),this.m_axis).SelfNormalize();var _normal=b2Rot.MulRV(xfA.q,this.m_axis,b2TimeOfImpact_s_normal);b2Vec2.MidVV(localPointA1,localPointA2,this.m_localPoint);var _pointA2=b2Transform.MulXV(xfA,this.m_localPoint,b2TimeOfImpact_s_pointA);var _localPointB=this.m_proxyB.GetVertex(cache.indexB[0]);var _pointB2=b2Transform.MulXV(xfB,_localPointB,b2TimeOfImpact_s_pointB);var _s4=b2Vec2.DotVV(b2Vec2.SubVV(_pointB2,_pointA2,b2Vec2.s_t0),_normal);if(_s4<0){this.m_axis.SelfNeg();_s4=-_s4;}return _s4;}};_proto31.FindMinSeparation=function FindMinSeparation(indexA,indexB,t){var xfA=b2TimeOfImpact_s_xfA;var xfB=b2TimeOfImpact_s_xfB;this.m_sweepA.GetTransform(xfA,t);this.m_sweepB.GetTransform(xfB,t);switch(this.m_type){case exports$1.b2SeparationFunctionType.e_points:{var axisA=b2Rot.MulTRV(xfA.q,this.m_axis,b2TimeOfImpact_s_axisA);var axisB=b2Rot.MulTRV(xfB.q,b2Vec2.NegV(this.m_axis,b2Vec2.s_t0),b2TimeOfImpact_s_axisB);indexA[0]=this.m_proxyA.GetSupport(axisA);indexB[0]=this.m_proxyB.GetSupport(axisB);var localPointA=this.m_proxyA.GetVertex(indexA[0]);var localPointB=this.m_proxyB.GetVertex(indexB[0]);var pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);var pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);var separation=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),this.m_axis);return separation;}case exports$1.b2SeparationFunctionType.e_faceA:{var normal=b2Rot.MulRV(xfA.q,this.m_axis,b2TimeOfImpact_s_normal);var _pointA3=b2Transform.MulXV(xfA,this.m_localPoint,b2TimeOfImpact_s_pointA);var _axisB=b2Rot.MulTRV(xfB.q,b2Vec2.NegV(normal,b2Vec2.s_t0),b2TimeOfImpact_s_axisB);indexA[0]=-1;indexB[0]=this.m_proxyB.GetSupport(_axisB);var _localPointB2=this.m_proxyB.GetVertex(indexB[0]);var _pointB3=b2Transform.MulXV(xfB,_localPointB2,b2TimeOfImpact_s_pointB);var _separation=b2Vec2.DotVV(b2Vec2.SubVV(_pointB3,_pointA3,b2Vec2.s_t0),normal);return _separation;}case exports$1.b2SeparationFunctionType.e_faceB:{var _normal2=b2Rot.MulRV(xfB.q,this.m_axis,b2TimeOfImpact_s_normal);var _pointB4=b2Transform.MulXV(xfB,this.m_localPoint,b2TimeOfImpact_s_pointB);var _axisA=b2Rot.MulTRV(xfA.q,b2Vec2.NegV(_normal2,b2Vec2.s_t0),b2TimeOfImpact_s_axisA);indexB[0]=-1;indexA[0]=this.m_proxyA.GetSupport(_axisA);var _localPointA2=this.m_proxyA.GetVertex(indexA[0]);var _pointA4=b2Transform.MulXV(xfA,_localPointA2,b2TimeOfImpact_s_pointA);var _separation2=b2Vec2.DotVV(b2Vec2.SubVV(_pointA4,_pointB4,b2Vec2.s_t0),_normal2);return _separation2;}default:indexA[0]=-1;indexB[0]=-1;return 0;}};_proto31.Evaluate=function Evaluate(indexA,indexB,t){var xfA=b2TimeOfImpact_s_xfA;var xfB=b2TimeOfImpact_s_xfB;this.m_sweepA.GetTransform(xfA,t);this.m_sweepB.GetTransform(xfB,t);switch(this.m_type){case exports$1.b2SeparationFunctionType.e_points:{var localPointA=this.m_proxyA.GetVertex(indexA);var localPointB=this.m_proxyB.GetVertex(indexB);var pointA=b2Transform.MulXV(xfA,localPointA,b2TimeOfImpact_s_pointA);var pointB=b2Transform.MulXV(xfB,localPointB,b2TimeOfImpact_s_pointB);var separation=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),this.m_axis);return separation;}case exports$1.b2SeparationFunctionType.e_faceA:{var normal=b2Rot.MulRV(xfA.q,this.m_axis,b2TimeOfImpact_s_normal);var _pointA5=b2Transform.MulXV(xfA,this.m_localPoint,b2TimeOfImpact_s_pointA);var _localPointB3=this.m_proxyB.GetVertex(indexB);var _pointB5=b2Transform.MulXV(xfB,_localPointB3,b2TimeOfImpact_s_pointB);var _separation3=b2Vec2.DotVV(b2Vec2.SubVV(_pointB5,_pointA5,b2Vec2.s_t0),normal);return _separation3;}case exports$1.b2SeparationFunctionType.e_faceB:{var _normal3=b2Rot.MulRV(xfB.q,this.m_axis,b2TimeOfImpact_s_normal);var _pointB6=b2Transform.MulXV(xfB,this.m_localPoint,b2TimeOfImpact_s_pointB);var _localPointA3=this.m_proxyA.GetVertex(indexA);var _pointA6=b2Transform.MulXV(xfA,_localPointA3,b2TimeOfImpact_s_pointA);var _separation4=b2Vec2.DotVV(b2Vec2.SubVV(_pointA6,_pointB6,b2Vec2.s_t0),_normal3);return _separation4;}default:return 0;}};return b2SeparationFunction;}();var b2TimeOfImpact_s_timer=new b2Timer();var b2TimeOfImpact_s_cache=new b2SimplexCache();var b2TimeOfImpact_s_distanceInput=new b2DistanceInput();var b2TimeOfImpact_s_distanceOutput=new b2DistanceOutput();var b2TimeOfImpact_s_fcn=new b2SeparationFunction();var b2TimeOfImpact_s_indexA=[0];var b2TimeOfImpact_s_indexB=[0];var b2TimeOfImpact_s_sweepA=new b2Sweep();var b2TimeOfImpact_s_sweepB=new b2Sweep();function b2TimeOfImpact(output,input){var timer=b2TimeOfImpact_s_timer.Reset();++exports$1.b2_toiCalls;output.state=exports$1.b2TOIOutputState.e_unknown;output.t=input.tMax;var proxyA=input.proxyA;var proxyB=input.proxyB;var maxVertices=b2Max(b2_maxPolygonVertices,b2Max(proxyA.m_count,proxyB.m_count));var sweepA=b2TimeOfImpact_s_sweepA.Copy(input.sweepA);var sweepB=b2TimeOfImpact_s_sweepB.Copy(input.sweepB);sweepA.Normalize();sweepB.Normalize();var tMax=input.tMax;var totalRadius=proxyA.m_radius+proxyB.m_radius;var target=b2Max(b2_linearSlop,totalRadius-3*b2_linearSlop);var tolerance=0.25*b2_linearSlop;var t1=0;var k_maxIterations=20;var iter=0;var cache=b2TimeOfImpact_s_cache;cache.count=0;var distanceInput=b2TimeOfImpact_s_distanceInput;distanceInput.proxyA.Copy(input.proxyA);distanceInput.proxyB.Copy(input.proxyB);distanceInput.useRadii=false;for(;;){var xfA=b2TimeOfImpact_s_xfA;var xfB=b2TimeOfImpact_s_xfB;sweepA.GetTransform(xfA,t1);sweepB.GetTransform(xfB,t1);distanceInput.transformA.Copy(xfA);distanceInput.transformB.Copy(xfB);var distanceOutput=b2TimeOfImpact_s_distanceOutput;b2Distance(distanceOutput,cache,distanceInput);if(distanceOutput.distance<=0){output.state=exports$1.b2TOIOutputState.e_overlapped;output.t=0;break;}if(distanceOutput.distance<target+tolerance){output.state=exports$1.b2TOIOutputState.e_touching;output.t=t1;break;}var fcn=b2TimeOfImpact_s_fcn;fcn.Initialize(cache,proxyA,sweepA,proxyB,sweepB,t1);var done=false;var t2=tMax;var pushBackIter=0;for(;;){var indexA=b2TimeOfImpact_s_indexA;var indexB=b2TimeOfImpact_s_indexB;var s2=fcn.FindMinSeparation(indexA,indexB,t2);if(s2>target+tolerance){output.state=exports$1.b2TOIOutputState.e_separated;output.t=tMax;done=true;break;}if(s2>target-tolerance){t1=t2;break;}var s1=fcn.Evaluate(indexA[0],indexB[0],t1);if(s1<target-tolerance){output.state=exports$1.b2TOIOutputState.e_failed;output.t=t1;done=true;break;}if(s1<=target+tolerance){output.state=exports$1.b2TOIOutputState.e_touching;output.t=t1;done=true;break;}var rootIterCount=0;var a1=t1;var a2=t2;for(;;){var t=0;if(rootIterCount&1){t=a1+(target-s1)*(a2-a1)/(s2-s1);}else {t=0.5*(a1+a2);}++rootIterCount;++exports$1.b2_toiRootIters;var s=fcn.Evaluate(indexA[0],indexB[0],t);if(b2Abs(s-target)<tolerance){t2=t;break;}if(s>target){a1=t;s1=s;}else {a2=t;s2=s;}if(rootIterCount===50){break;}}exports$1.b2_toiMaxRootIters=b2Max(exports$1.b2_toiMaxRootIters,rootIterCount);++pushBackIter;if(pushBackIter===maxVertices){break;}}++iter;++exports$1.b2_toiIters;if(done){break;}if(iter===k_maxIterations){output.state=exports$1.b2TOIOutputState.e_failed;output.t=t1;break;}}exports$1.b2_toiMaxIters=b2Max(exports$1.b2_toiMaxIters,iter);var time=timer.GetMilliseconds();exports$1.b2_toiMaxTime=b2Max(exports$1.b2_toiMaxTime,time);exports$1.b2_toiTime+=time;}var b2CollideCircles_s_pA=new b2Vec2();var b2CollideCircles_s_pB=new b2Vec2();function b2CollideCircles(manifold,circleA,xfA,circleB,xfB){manifold.pointCount=0;var pA=b2Transform.MulXV(xfA,circleA.m_p,b2CollideCircles_s_pA);var pB=b2Transform.MulXV(xfB,circleB.m_p,b2CollideCircles_s_pB);var distSqr=b2Vec2.DistanceSquaredVV(pA,pB);var radius=circleA.m_radius+circleB.m_radius;if(distSqr>radius*radius){return;}manifold.type=exports$1.b2ManifoldType.e_circles;manifold.localPoint.Copy(circleA.m_p);manifold.localNormal.SetZero();manifold.pointCount=1;manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0;}var b2CollidePolygonAndCircle_s_c=new b2Vec2();var b2CollidePolygonAndCircle_s_cLocal=new b2Vec2();var b2CollidePolygonAndCircle_s_faceCenter=new b2Vec2();function b2CollidePolygonAndCircle(manifold,polygonA,xfA,circleB,xfB){manifold.pointCount=0;var c=b2Transform.MulXV(xfB,circleB.m_p,b2CollidePolygonAndCircle_s_c);var cLocal=b2Transform.MulTXV(xfA,c,b2CollidePolygonAndCircle_s_cLocal);var normalIndex=0;var separation=-b2_maxFloat;var radius=polygonA.m_radius+circleB.m_radius;var vertexCount=polygonA.m_count;var vertices=polygonA.m_vertices;var normals=polygonA.m_normals;for(var i=0;i<vertexCount;++i){var s=b2Vec2.DotVV(normals[i],b2Vec2.SubVV(cLocal,vertices[i],b2Vec2.s_t0));if(s>radius){return;}if(s>separation){separation=s;normalIndex=i;}}var vertIndex1=normalIndex;var vertIndex2=(vertIndex1+1)%vertexCount;var v1=vertices[vertIndex1];var v2=vertices[vertIndex2];if(separation<b2_epsilon){manifold.pointCount=1;manifold.type=exports$1.b2ManifoldType.e_faceA;manifold.localNormal.Copy(normals[normalIndex]);b2Vec2.MidVV(v1,v2,manifold.localPoint);manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0;return;}var u1=b2Vec2.DotVV(b2Vec2.SubVV(cLocal,v1,b2Vec2.s_t0),b2Vec2.SubVV(v2,v1,b2Vec2.s_t1));var u2=b2Vec2.DotVV(b2Vec2.SubVV(cLocal,v2,b2Vec2.s_t0),b2Vec2.SubVV(v1,v2,b2Vec2.s_t1));if(u1<=0){if(b2Vec2.DistanceSquaredVV(cLocal,v1)>radius*radius){return;}manifold.pointCount=1;manifold.type=exports$1.b2ManifoldType.e_faceA;b2Vec2.SubVV(cLocal,v1,manifold.localNormal).SelfNormalize();manifold.localPoint.Copy(v1);manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0;}else if(u2<=0){if(b2Vec2.DistanceSquaredVV(cLocal,v2)>radius*radius){return;}manifold.pointCount=1;manifold.type=exports$1.b2ManifoldType.e_faceA;b2Vec2.SubVV(cLocal,v2,manifold.localNormal).SelfNormalize();manifold.localPoint.Copy(v2);manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0;}else {var faceCenter=b2Vec2.MidVV(v1,v2,b2CollidePolygonAndCircle_s_faceCenter);var _separation5=b2Vec2.DotVV(b2Vec2.SubVV(cLocal,faceCenter,b2Vec2.s_t1),normals[vertIndex1]);if(_separation5>radius){return;}manifold.pointCount=1;manifold.type=exports$1.b2ManifoldType.e_faceA;manifold.localNormal.Copy(normals[vertIndex1]).SelfNormalize();manifold.localPoint.Copy(faceCenter);manifold.points[0].localPoint.Copy(circleB.m_p);manifold.points[0].id.key=0;}}var b2EdgeSeparation_s_normal1World=new b2Vec2();var b2EdgeSeparation_s_normal1=new b2Vec2();var b2EdgeSeparation_s_v1=new b2Vec2();var b2EdgeSeparation_s_v2=new b2Vec2();function b2EdgeSeparation(poly1,xf1,edge1,poly2,xf2){var vertices1=poly1.m_vertices;var normals1=poly1.m_normals;var count2=poly2.m_count;var vertices2=poly2.m_vertices;var normal1World=b2Rot.MulRV(xf1.q,normals1[edge1],b2EdgeSeparation_s_normal1World);var normal1=b2Rot.MulTRV(xf2.q,normal1World,b2EdgeSeparation_s_normal1);var index=0;var minDot=b2_maxFloat;for(var i=0;i<count2;++i){var dot=b2Vec2.DotVV(vertices2[i],normal1);if(dot<minDot){minDot=dot;index=i;}}var v1=b2Transform.MulXV(xf1,vertices1[edge1],b2EdgeSeparation_s_v1);var v2=b2Transform.MulXV(xf2,vertices2[index],b2EdgeSeparation_s_v2);var separation=b2Vec2.DotVV(b2Vec2.SubVV(v2,v1,b2Vec2.s_t0),normal1World);return separation;}var b2FindMaxSeparation_s_d=new b2Vec2();var b2FindMaxSeparation_s_dLocal1=new b2Vec2();function b2FindMaxSeparation(edgeIndex,poly1,xf1,poly2,xf2){var count1=poly1.m_count;var normals1=poly1.m_normals;var d=b2Vec2.SubVV(b2Transform.MulXV(xf2,poly2.m_centroid,b2Vec2.s_t0),b2Transform.MulXV(xf1,poly1.m_centroid,b2Vec2.s_t1),b2FindMaxSeparation_s_d);var dLocal1=b2Rot.MulTRV(xf1.q,d,b2FindMaxSeparation_s_dLocal1);var edge=0;var maxDot=-b2_maxFloat;for(var i=0;i<count1;++i){var dot=b2Vec2.DotVV(normals1[i],dLocal1);if(dot>maxDot){maxDot=dot;edge=i;}}var s=b2EdgeSeparation(poly1,xf1,edge,poly2,xf2);var prevEdge=(edge+count1-1)%count1;var sPrev=b2EdgeSeparation(poly1,xf1,prevEdge,poly2,xf2);var nextEdge=(edge+1)%count1;var sNext=b2EdgeSeparation(poly1,xf1,nextEdge,poly2,xf2);var bestEdge=0;var bestSeparation=0;var increment=0;if(sPrev>s&&sPrev>sNext){increment=-1;bestEdge=prevEdge;bestSeparation=sPrev;}else if(sNext>s){increment=1;bestEdge=nextEdge;bestSeparation=sNext;}else {edgeIndex[0]=edge;return s;}while(true){if(increment===-1){edge=(bestEdge+count1-1)%count1;}else {edge=(bestEdge+1)%count1;}s=b2EdgeSeparation(poly1,xf1,edge,poly2,xf2);if(s>bestSeparation){bestEdge=edge;bestSeparation=s;}else {break;}}edgeIndex[0]=bestEdge;return bestSeparation;}var b2FindIncidentEdge_s_normal1=new b2Vec2();function b2FindIncidentEdge(c,poly1,xf1,edge1,poly2,xf2){var normals1=poly1.m_normals;var count2=poly2.m_count;var vertices2=poly2.m_vertices;var normals2=poly2.m_normals;var normal1=b2Rot.MulTRV(xf2.q,b2Rot.MulRV(xf1.q,normals1[edge1],b2Vec2.s_t0),b2FindIncidentEdge_s_normal1);var index=0;var minDot=b2_maxFloat;for(var i=0;i<count2;++i){var dot=b2Vec2.DotVV(normal1,normals2[i]);if(dot<minDot){minDot=dot;index=i;}}var i1=index;var i2=(i1+1)%count2;var c0=c[0];b2Transform.MulXV(xf2,vertices2[i1],c0.v);var cf0=c0.id.cf;cf0.indexA=edge1;cf0.indexB=i1;cf0.typeA=exports$1.b2ContactFeatureType.e_face;cf0.typeB=exports$1.b2ContactFeatureType.e_vertex;var c1=c[1];b2Transform.MulXV(xf2,vertices2[i2],c1.v);var cf1=c1.id.cf;cf1.indexA=edge1;cf1.indexB=i2;cf1.typeA=exports$1.b2ContactFeatureType.e_face;cf1.typeB=exports$1.b2ContactFeatureType.e_vertex;}var b2CollidePolygons_s_incidentEdge=b2ClipVertex.MakeArray(2);var b2CollidePolygons_s_clipPoints1=b2ClipVertex.MakeArray(2);var b2CollidePolygons_s_clipPoints2=b2ClipVertex.MakeArray(2);var b2CollidePolygons_s_edgeA=[0];var b2CollidePolygons_s_edgeB=[0];var b2CollidePolygons_s_localTangent=new b2Vec2();var b2CollidePolygons_s_localNormal=new b2Vec2();var b2CollidePolygons_s_planePoint=new b2Vec2();var b2CollidePolygons_s_normal=new b2Vec2();var b2CollidePolygons_s_tangent=new b2Vec2();var b2CollidePolygons_s_ntangent=new b2Vec2();var b2CollidePolygons_s_v11=new b2Vec2();var b2CollidePolygons_s_v12=new b2Vec2();function b2CollidePolygons(manifold,polyA,xfA,polyB,xfB){manifold.pointCount=0;var totalRadius=polyA.m_radius+polyB.m_radius;var edgeA=b2CollidePolygons_s_edgeA;edgeA[0]=0;var separationA=b2FindMaxSeparation(edgeA,polyA,xfA,polyB,xfB);if(separationA>totalRadius){return;}var edgeB=b2CollidePolygons_s_edgeB;edgeB[0]=0;var separationB=b2FindMaxSeparation(edgeB,polyB,xfB,polyA,xfA);if(separationB>totalRadius){return;}var poly1;var poly2;var xf1,xf2;var edge1=0;var flip=0;var k_relativeTol=0.98;var k_absoluteTol=0.001;if(separationB>k_relativeTol*separationA+k_absoluteTol){poly1=polyB;poly2=polyA;xf1=xfB;xf2=xfA;edge1=edgeB[0];manifold.type=exports$1.b2ManifoldType.e_faceB;flip=1;}else {poly1=polyA;poly2=polyB;xf1=xfA;xf2=xfB;edge1=edgeA[0];manifold.type=exports$1.b2ManifoldType.e_faceA;flip=0;}var incidentEdge=b2CollidePolygons_s_incidentEdge;b2FindIncidentEdge(incidentEdge,poly1,xf1,edge1,poly2,xf2);var count1=poly1.m_count;var vertices1=poly1.m_vertices;var iv1=edge1;var iv2=(edge1+1)%count1;var local_v11=vertices1[iv1];var local_v12=vertices1[iv2];var localTangent=b2Vec2.SubVV(local_v12,local_v11,b2CollidePolygons_s_localTangent);localTangent.Normalize();var localNormal=b2Vec2.CrossVOne(localTangent,b2CollidePolygons_s_localNormal);var planePoint=b2Vec2.MidVV(local_v11,local_v12,b2CollidePolygons_s_planePoint);var tangent=b2Rot.MulRV(xf1.q,localTangent,b2CollidePolygons_s_tangent);var normal=b2Vec2.CrossVOne(tangent,b2CollidePolygons_s_normal);var v11=b2Transform.MulXV(xf1,local_v11,b2CollidePolygons_s_v11);var v12=b2Transform.MulXV(xf1,local_v12,b2CollidePolygons_s_v12);var frontOffset=b2Vec2.DotVV(normal,v11);var sideOffset1=-b2Vec2.DotVV(tangent,v11)+totalRadius;var sideOffset2=b2Vec2.DotVV(tangent,v12)+totalRadius;var clipPoints1=b2CollidePolygons_s_clipPoints1;var clipPoints2=b2CollidePolygons_s_clipPoints2;var np;var ntangent=b2Vec2.NegV(tangent,b2CollidePolygons_s_ntangent);np=b2ClipSegmentToLine(clipPoints1,incidentEdge,ntangent,sideOffset1,iv1);if(np<2){return;}np=b2ClipSegmentToLine(clipPoints2,clipPoints1,tangent,sideOffset2,iv2);if(np<2){return;}manifold.localNormal.Copy(localNormal);manifold.localPoint.Copy(planePoint);var pointCount=0;for(var i=0;i<b2_maxManifoldPoints;++i){var cv=clipPoints2[i];var separation=b2Vec2.DotVV(normal,cv.v)-frontOffset;if(separation<=totalRadius){var cp=manifold.points[pointCount];b2Transform.MulTXV(xf2,cv.v,cp.localPoint);cp.id.Copy(cv.id);if(flip){var cf=cp.id.cf;cp.id.cf.indexA=cf.indexB;cp.id.cf.indexB=cf.indexA;cp.id.cf.typeA=cf.typeB;cp.id.cf.typeB=cf.typeA;}++pointCount;}}manifold.pointCount=pointCount;}var b2CollideEdgeAndCircle_s_Q=new b2Vec2();var b2CollideEdgeAndCircle_s_e=new b2Vec2();var b2CollideEdgeAndCircle_s_d=new b2Vec2();var b2CollideEdgeAndCircle_s_e1=new b2Vec2();var b2CollideEdgeAndCircle_s_e2=new b2Vec2();var b2CollideEdgeAndCircle_s_P=new b2Vec2();var b2CollideEdgeAndCircle_s_n=new b2Vec2();var b2CollideEdgeAndCircle_s_id=new b2ContactID();function b2CollideEdgeAndCircle(manifold,edgeA,xfA,circleB,xfB){manifold.pointCount=0;var Q=b2Transform.MulTXV(xfA,b2Transform.MulXV(xfB,circleB.m_p,b2Vec2.s_t0),b2CollideEdgeAndCircle_s_Q);var A=edgeA.m_vertex1;var B=edgeA.m_vertex2;var e=b2Vec2.SubVV(B,A,b2CollideEdgeAndCircle_s_e);var u=b2Vec2.DotVV(e,b2Vec2.SubVV(B,Q,b2Vec2.s_t0));var v=b2Vec2.DotVV(e,b2Vec2.SubVV(Q,A,b2Vec2.s_t0));var radius=edgeA.m_radius+circleB.m_radius;var id=b2CollideEdgeAndCircle_s_id;id.cf.indexB=0;id.cf.typeB=exports$1.b2ContactFeatureType.e_vertex;if(v<=0){var _P=A;var _d=b2Vec2.SubVV(Q,_P,b2CollideEdgeAndCircle_s_d);var _dd=b2Vec2.DotVV(_d,_d);if(_dd>radius*radius){return;}if(edgeA.m_hasVertex0){var A1=edgeA.m_vertex0;var B1=A;var e1=b2Vec2.SubVV(B1,A1,b2CollideEdgeAndCircle_s_e1);var u1=b2Vec2.DotVV(e1,b2Vec2.SubVV(B1,Q,b2Vec2.s_t0));if(u1>0){return;}}id.cf.indexA=0;id.cf.typeA=exports$1.b2ContactFeatureType.e_vertex;manifold.pointCount=1;manifold.type=exports$1.b2ManifoldType.e_circles;manifold.localNormal.SetZero();manifold.localPoint.Copy(_P);manifold.points[0].id.Copy(id);manifold.points[0].localPoint.Copy(circleB.m_p);return;}if(u<=0){var _P2=B;var _d2=b2Vec2.SubVV(Q,_P2,b2CollideEdgeAndCircle_s_d);var _dd2=b2Vec2.DotVV(_d2,_d2);if(_dd2>radius*radius){return;}if(edgeA.m_hasVertex3){var B2=edgeA.m_vertex3;var A2=B;var e2=b2Vec2.SubVV(B2,A2,b2CollideEdgeAndCircle_s_e2);var v2=b2Vec2.DotVV(e2,b2Vec2.SubVV(Q,A2,b2Vec2.s_t0));if(v2>0){return;}}id.cf.indexA=1;id.cf.typeA=exports$1.b2ContactFeatureType.e_vertex;manifold.pointCount=1;manifold.type=exports$1.b2ManifoldType.e_circles;manifold.localNormal.SetZero();manifold.localPoint.Copy(_P2);manifold.points[0].id.Copy(id);manifold.points[0].localPoint.Copy(circleB.m_p);return;}var den=b2Vec2.DotVV(e,e);var P=b2CollideEdgeAndCircle_s_P;P.x=1/den*(u*A.x+v*B.x);P.y=1/den*(u*A.y+v*B.y);var d=b2Vec2.SubVV(Q,P,b2CollideEdgeAndCircle_s_d);var dd=b2Vec2.DotVV(d,d);if(dd>radius*radius){return;}var n=b2CollideEdgeAndCircle_s_n.Set(-e.y,e.x);if(b2Vec2.DotVV(n,b2Vec2.SubVV(Q,A,b2Vec2.s_t0))<0){n.Set(-n.x,-n.y);}n.Normalize();id.cf.indexA=0;id.cf.typeA=exports$1.b2ContactFeatureType.e_face;manifold.pointCount=1;manifold.type=exports$1.b2ManifoldType.e_faceA;manifold.localNormal.Copy(n);manifold.localPoint.Copy(A);manifold.points[0].id.Copy(id);manifold.points[0].localPoint.Copy(circleB.m_p);}var b2EPAxisType;(function(b2EPAxisType){b2EPAxisType[b2EPAxisType["e_unknown"]=0]="e_unknown";b2EPAxisType[b2EPAxisType["e_edgeA"]=1]="e_edgeA";b2EPAxisType[b2EPAxisType["e_edgeB"]=2]="e_edgeB";})(b2EPAxisType||(b2EPAxisType={}));var b2EPAxis=function b2EPAxis(){this.type=b2EPAxisType.e_unknown;this.index=0;this.separation=0;};var b2TempPolygon=function b2TempPolygon(){this.vertices=[];this.normals=[];this.count=0;};var b2ReferenceFace=function b2ReferenceFace(){this.i1=0;this.i2=0;this.v1=new b2Vec2();this.v2=new b2Vec2();this.normal=new b2Vec2();this.sideNormal1=new b2Vec2();this.sideOffset1=0;this.sideNormal2=new b2Vec2();this.sideOffset2=0;};var b2EPColliderVertexType;(function(b2EPColliderVertexType){b2EPColliderVertexType[b2EPColliderVertexType["e_isolated"]=0]="e_isolated";b2EPColliderVertexType[b2EPColliderVertexType["e_concave"]=1]="e_concave";b2EPColliderVertexType[b2EPColliderVertexType["e_convex"]=2]="e_convex";})(b2EPColliderVertexType||(b2EPColliderVertexType={}));var b2EPCollider=function(){function b2EPCollider(){this.m_polygonB=new b2TempPolygon();this.m_xf=new b2Transform();this.m_centroidB=new b2Vec2();this.m_v0=new b2Vec2();this.m_v1=new b2Vec2();this.m_v2=new b2Vec2();this.m_v3=new b2Vec2();this.m_normal0=new b2Vec2();this.m_normal1=new b2Vec2();this.m_normal2=new b2Vec2();this.m_normal=new b2Vec2();this.m_type1=b2EPColliderVertexType.e_isolated;this.m_type2=b2EPColliderVertexType.e_isolated;this.m_lowerLimit=new b2Vec2();this.m_upperLimit=new b2Vec2();this.m_radius=0;this.m_front=false;}var _proto32=b2EPCollider.prototype;_proto32.Collide=function Collide(manifold,edgeA,xfA,polygonB,xfB){b2Transform.MulTXX(xfA,xfB,this.m_xf);b2Transform.MulXV(this.m_xf,polygonB.m_centroid,this.m_centroidB);this.m_v0.Copy(edgeA.m_vertex0);this.m_v1.Copy(edgeA.m_vertex1);this.m_v2.Copy(edgeA.m_vertex2);this.m_v3.Copy(edgeA.m_vertex3);var hasVertex0=edgeA.m_hasVertex0;var hasVertex3=edgeA.m_hasVertex3;var edge1=b2Vec2.SubVV(this.m_v2,this.m_v1,b2EPCollider.s_edge1);edge1.Normalize();this.m_normal1.Set(edge1.y,-edge1.x);var offset1=b2Vec2.DotVV(this.m_normal1,b2Vec2.SubVV(this.m_centroidB,this.m_v1,b2Vec2.s_t0));var offset0=0;var offset2=0;var convex1=false;var convex2=false;if(hasVertex0){var edge0=b2Vec2.SubVV(this.m_v1,this.m_v0,b2EPCollider.s_edge0);edge0.Normalize();this.m_normal0.Set(edge0.y,-edge0.x);convex1=b2Vec2.CrossVV(edge0,edge1)>=0;offset0=b2Vec2.DotVV(this.m_normal0,b2Vec2.SubVV(this.m_centroidB,this.m_v0,b2Vec2.s_t0));}if(hasVertex3){var edge2=b2Vec2.SubVV(this.m_v3,this.m_v2,b2EPCollider.s_edge2);edge2.Normalize();this.m_normal2.Set(edge2.y,-edge2.x);convex2=b2Vec2.CrossVV(edge1,edge2)>0;offset2=b2Vec2.DotVV(this.m_normal2,b2Vec2.SubVV(this.m_centroidB,this.m_v2,b2Vec2.s_t0));}if(hasVertex0&&hasVertex3){if(convex1&&convex2){this.m_front=offset0>=0||offset1>=0||offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal0);this.m_upperLimit.Copy(this.m_normal2);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}}else if(convex1){this.m_front=offset0>=0||offset1>=0&&offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal0);this.m_upperLimit.Copy(this.m_normal1);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal2).SelfNeg();this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}}else if(convex2){this.m_front=offset2>=0||offset0>=0&&offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal2);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal0).SelfNeg();}}else {this.m_front=offset0>=0&&offset1>=0&&offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal2).SelfNeg();this.m_upperLimit.Copy(this.m_normal0).SelfNeg();}}}else if(hasVertex0){if(convex1){this.m_front=offset0>=0||offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal0);this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}}else {this.m_front=offset0>=0&&offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal0).SelfNeg();}}}else if(hasVertex3){if(convex2){this.m_front=offset1>=0||offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal2);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1);}}else {this.m_front=offset1>=0&&offset2>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1);}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal2).SelfNeg();this.m_upperLimit.Copy(this.m_normal1);}}}else {this.m_front=offset1>=0;if(this.m_front){this.m_normal.Copy(this.m_normal1);this.m_lowerLimit.Copy(this.m_normal1).SelfNeg();this.m_upperLimit.Copy(this.m_normal1).SelfNeg();}else {this.m_normal.Copy(this.m_normal1).SelfNeg();this.m_lowerLimit.Copy(this.m_normal1);this.m_upperLimit.Copy(this.m_normal1);}}this.m_polygonB.count=polygonB.m_count;for(var i=0;i<polygonB.m_count;++i){if(this.m_polygonB.vertices.length<=i){this.m_polygonB.vertices.push(new b2Vec2());}if(this.m_polygonB.normals.length<=i){this.m_polygonB.normals.push(new b2Vec2());}b2Transform.MulXV(this.m_xf,polygonB.m_vertices[i],this.m_polygonB.vertices[i]);b2Rot.MulRV(this.m_xf.q,polygonB.m_normals[i],this.m_polygonB.normals[i]);}this.m_radius=polygonB.m_radius+edgeA.m_radius;manifold.pointCount=0;var edgeAxis=this.ComputeEdgeSeparation(b2EPCollider.s_edgeAxis);if(edgeAxis.type===b2EPAxisType.e_unknown){return;}if(edgeAxis.separation>this.m_radius){return;}var polygonAxis=this.ComputePolygonSeparation(b2EPCollider.s_polygonAxis);if(polygonAxis.type!==b2EPAxisType.e_unknown&&polygonAxis.separation>this.m_radius){return;}var k_relativeTol=0.98;var k_absoluteTol=0.001;var primaryAxis;if(polygonAxis.type===b2EPAxisType.e_unknown){primaryAxis=edgeAxis;}else if(polygonAxis.separation>k_relativeTol*edgeAxis.separation+k_absoluteTol){primaryAxis=polygonAxis;}else {primaryAxis=edgeAxis;}var ie=b2EPCollider.s_ie;var rf=b2EPCollider.s_rf;if(primaryAxis.type===b2EPAxisType.e_edgeA){manifold.type=exports$1.b2ManifoldType.e_faceA;var bestIndex=0;var bestValue=b2Vec2.DotVV(this.m_normal,this.m_polygonB.normals[0]);for(var _i4=1;_i4<this.m_polygonB.count;++_i4){var value=b2Vec2.DotVV(this.m_normal,this.m_polygonB.normals[_i4]);if(value<bestValue){bestValue=value;bestIndex=_i4;}}var i1=bestIndex;var i2=(i1+1)%this.m_polygonB.count;var ie0=ie[0];ie0.v.Copy(this.m_polygonB.vertices[i1]);ie0.id.cf.indexA=0;ie0.id.cf.indexB=i1;ie0.id.cf.typeA=exports$1.b2ContactFeatureType.e_face;ie0.id.cf.typeB=exports$1.b2ContactFeatureType.e_vertex;var ie1=ie[1];ie1.v.Copy(this.m_polygonB.vertices[i2]);ie1.id.cf.indexA=0;ie1.id.cf.indexB=i2;ie1.id.cf.typeA=exports$1.b2ContactFeatureType.e_face;ie1.id.cf.typeB=exports$1.b2ContactFeatureType.e_vertex;if(this.m_front){rf.i1=0;rf.i2=1;rf.v1.Copy(this.m_v1);rf.v2.Copy(this.m_v2);rf.normal.Copy(this.m_normal1);}else {rf.i1=1;rf.i2=0;rf.v1.Copy(this.m_v2);rf.v2.Copy(this.m_v1);rf.normal.Copy(this.m_normal1).SelfNeg();}}else {manifold.type=exports$1.b2ManifoldType.e_faceB;var _ie=ie[0];_ie.v.Copy(this.m_v1);_ie.id.cf.indexA=0;_ie.id.cf.indexB=primaryAxis.index;_ie.id.cf.typeA=exports$1.b2ContactFeatureType.e_vertex;_ie.id.cf.typeB=exports$1.b2ContactFeatureType.e_face;var _ie2=ie[1];_ie2.v.Copy(this.m_v2);_ie2.id.cf.indexA=0;_ie2.id.cf.indexB=primaryAxis.index;_ie2.id.cf.typeA=exports$1.b2ContactFeatureType.e_vertex;_ie2.id.cf.typeB=exports$1.b2ContactFeatureType.e_face;rf.i1=primaryAxis.index;rf.i2=(rf.i1+1)%this.m_polygonB.count;rf.v1.Copy(this.m_polygonB.vertices[rf.i1]);rf.v2.Copy(this.m_polygonB.vertices[rf.i2]);rf.normal.Copy(this.m_polygonB.normals[rf.i1]);}rf.sideNormal1.Set(rf.normal.y,-rf.normal.x);rf.sideNormal2.Copy(rf.sideNormal1).SelfNeg();rf.sideOffset1=b2Vec2.DotVV(rf.sideNormal1,rf.v1);rf.sideOffset2=b2Vec2.DotVV(rf.sideNormal2,rf.v2);var clipPoints1=b2EPCollider.s_clipPoints1;var clipPoints2=b2EPCollider.s_clipPoints2;var np=0;np=b2ClipSegmentToLine(clipPoints1,ie,rf.sideNormal1,rf.sideOffset1,rf.i1);if(np<b2_maxManifoldPoints){return;}np=b2ClipSegmentToLine(clipPoints2,clipPoints1,rf.sideNormal2,rf.sideOffset2,rf.i2);if(np<b2_maxManifoldPoints){return;}if(primaryAxis.type===b2EPAxisType.e_edgeA){manifold.localNormal.Copy(rf.normal);manifold.localPoint.Copy(rf.v1);}else {manifold.localNormal.Copy(polygonB.m_normals[rf.i1]);manifold.localPoint.Copy(polygonB.m_vertices[rf.i1]);}var pointCount=0;for(var _i5=0;_i5<b2_maxManifoldPoints;++_i5){var separation=void 0;separation=b2Vec2.DotVV(rf.normal,b2Vec2.SubVV(clipPoints2[_i5].v,rf.v1,b2Vec2.s_t0));if(separation<=this.m_radius){var cp=manifold.points[pointCount];if(primaryAxis.type===b2EPAxisType.e_edgeA){b2Transform.MulTXV(this.m_xf,clipPoints2[_i5].v,cp.localPoint);cp.id.Copy(clipPoints2[_i5].id);}else {cp.localPoint.Copy(clipPoints2[_i5].v);cp.id.cf.typeA=clipPoints2[_i5].id.cf.typeB;cp.id.cf.typeB=clipPoints2[_i5].id.cf.typeA;cp.id.cf.indexA=clipPoints2[_i5].id.cf.indexB;cp.id.cf.indexB=clipPoints2[_i5].id.cf.indexA;}++pointCount;}}manifold.pointCount=pointCount;};_proto32.ComputeEdgeSeparation=function ComputeEdgeSeparation(out){var axis=out;axis.type=b2EPAxisType.e_edgeA;axis.index=this.m_front?0:1;axis.separation=b2_maxFloat;for(var i=0;i<this.m_polygonB.count;++i){var s=b2Vec2.DotVV(this.m_normal,b2Vec2.SubVV(this.m_polygonB.vertices[i],this.m_v1,b2Vec2.s_t0));if(s<axis.separation){axis.separation=s;}}return axis;};_proto32.ComputePolygonSeparation=function ComputePolygonSeparation(out){var axis=out;axis.type=b2EPAxisType.e_unknown;axis.index=-1;axis.separation=-b2_maxFloat;var perp=b2EPCollider.s_perp.Set(-this.m_normal.y,this.m_normal.x);for(var i=0;i<this.m_polygonB.count;++i){var n=b2Vec2.NegV(this.m_polygonB.normals[i],b2EPCollider.s_n);var s1=b2Vec2.DotVV(n,b2Vec2.SubVV(this.m_polygonB.vertices[i],this.m_v1,b2Vec2.s_t0));var s2=b2Vec2.DotVV(n,b2Vec2.SubVV(this.m_polygonB.vertices[i],this.m_v2,b2Vec2.s_t0));var s=b2Min(s1,s2);if(s>this.m_radius){axis.type=b2EPAxisType.e_edgeB;axis.index=i;axis.separation=s;return axis;}if(b2Vec2.DotVV(n,perp)>=0){if(b2Vec2.DotVV(b2Vec2.SubVV(n,this.m_upperLimit,b2Vec2.s_t0),this.m_normal)<-b2_angularSlop){continue;}}else {if(b2Vec2.DotVV(b2Vec2.SubVV(n,this.m_lowerLimit,b2Vec2.s_t0),this.m_normal)<-b2_angularSlop){continue;}}if(s>axis.separation){axis.type=b2EPAxisType.e_edgeB;axis.index=i;axis.separation=s;}}return axis;};return b2EPCollider;}();b2EPCollider.s_edge1=new b2Vec2();b2EPCollider.s_edge0=new b2Vec2();b2EPCollider.s_edge2=new b2Vec2();b2EPCollider.s_ie=b2ClipVertex.MakeArray(2);b2EPCollider.s_rf=new b2ReferenceFace();b2EPCollider.s_clipPoints1=b2ClipVertex.MakeArray(2);b2EPCollider.s_clipPoints2=b2ClipVertex.MakeArray(2);b2EPCollider.s_edgeAxis=new b2EPAxis();b2EPCollider.s_polygonAxis=new b2EPAxis();b2EPCollider.s_n=new b2Vec2();b2EPCollider.s_perp=new b2Vec2();var b2CollideEdgeAndPolygon_s_collider=new b2EPCollider();function b2CollideEdgeAndPolygon(manifold,edgeA,xfA,polygonB,xfB){var collider=b2CollideEdgeAndPolygon_s_collider;collider.Collide(manifold,edgeA,xfA,polygonB,xfB);}var b2MassData=function b2MassData(){this.mass=0;this.center=new b2Vec2(0,0);this.I=0;};(function(b2ShapeType){b2ShapeType[b2ShapeType["e_unknown"]=-1]="e_unknown";b2ShapeType[b2ShapeType["e_circleShape"]=0]="e_circleShape";b2ShapeType[b2ShapeType["e_edgeShape"]=1]="e_edgeShape";b2ShapeType[b2ShapeType["e_polygonShape"]=2]="e_polygonShape";b2ShapeType[b2ShapeType["e_chainShape"]=3]="e_chainShape";b2ShapeType[b2ShapeType["e_shapeTypeCount"]=4]="e_shapeTypeCount";})(exports$1.b2ShapeType||(exports$1.b2ShapeType={}));var b2Shape=function(){function b2Shape(type,radius){this.m_type=exports$1.b2ShapeType.e_unknown;this.m_radius=0;this.m_type=type;this.m_radius=radius;}var _proto33=b2Shape.prototype;_proto33.Copy=function Copy(other){this.m_radius=other.m_radius;return this;};_proto33.GetType=function GetType(){return this.m_type;};return b2Shape;}();var b2CircleShape=function(_b2Shape){_inheritsLoose(b2CircleShape,_b2Shape);function b2CircleShape(radius){var _this2;if(radius===void 0){radius=0;}_this2=_b2Shape.call(this,exports$1.b2ShapeType.e_circleShape,radius)||this;_this2.m_p=new b2Vec2();return _this2;}var _proto34=b2CircleShape.prototype;_proto34.Set=function Set(position,radius){if(radius===void 0){radius=this.m_radius;}this.m_p.Copy(position);this.m_radius=radius;return this;};_proto34.Clone=function Clone(){return new b2CircleShape().Copy(this);};_proto34.Copy=function Copy(other){_b2Shape.prototype.Copy.call(this,other);this.m_p.Copy(other.m_p);return this;};_proto34.GetChildCount=function GetChildCount(){return 1;};_proto34.TestPoint=function TestPoint(transform,p){var center=b2Transform.MulXV(transform,this.m_p,b2CircleShape.TestPoint_s_center);var d=b2Vec2.SubVV(p,center,b2CircleShape.TestPoint_s_d);return b2Vec2.DotVV(d,d)<=b2Sq(this.m_radius);};_proto34.ComputeDistance=function ComputeDistance(xf,p,normal,childIndex){var center=b2Transform.MulXV(xf,this.m_p,b2CircleShape.ComputeDistance_s_center);b2Vec2.SubVV(p,center,normal);return normal.Normalize()-this.m_radius;};_proto34.RayCast=function RayCast(output,input,transform,childIndex){var position=b2Transform.MulXV(transform,this.m_p,b2CircleShape.RayCast_s_position);var s=b2Vec2.SubVV(input.p1,position,b2CircleShape.RayCast_s_s);var b=b2Vec2.DotVV(s,s)-b2Sq(this.m_radius);var r=b2Vec2.SubVV(input.p2,input.p1,b2CircleShape.RayCast_s_r);var c=b2Vec2.DotVV(s,r);var rr=b2Vec2.DotVV(r,r);var sigma=c*c-rr*b;if(sigma<0||rr<b2_epsilon){return false;}var a=-(c+b2Sqrt(sigma));if(0<=a&&a<=input.maxFraction*rr){a/=rr;output.fraction=a;b2Vec2.AddVMulSV(s,a,r,output.normal).SelfNormalize();return true;}return false;};_proto34.ComputeAABB=function ComputeAABB(aabb,transform,childIndex){var p=b2Transform.MulXV(transform,this.m_p,b2CircleShape.ComputeAABB_s_p);aabb.lowerBound.Set(p.x-this.m_radius,p.y-this.m_radius);aabb.upperBound.Set(p.x+this.m_radius,p.y+this.m_radius);};_proto34.ComputeMass=function ComputeMass(massData,density){var radius_sq=b2Sq(this.m_radius);massData.mass=density*b2_pi*radius_sq;massData.center.Copy(this.m_p);massData.I=massData.mass*(0.5*radius_sq+b2Vec2.DotVV(this.m_p,this.m_p));};_proto34.SetupDistanceProxy=function SetupDistanceProxy(proxy,index){proxy.m_vertices=proxy.m_buffer;proxy.m_vertices[0].Copy(this.m_p);proxy.m_count=1;proxy.m_radius=this.m_radius;};_proto34.ComputeSubmergedArea=function ComputeSubmergedArea(normal,offset,xf,c){var p=b2Transform.MulXV(xf,this.m_p,new b2Vec2());var l=-(b2Vec2.DotVV(normal,p)-offset);if(l<-this.m_radius+b2_epsilon){return 0;}if(l>this.m_radius){c.Copy(p);return b2_pi*this.m_radius*this.m_radius;}var r2=this.m_radius*this.m_radius;var l2=l*l;var area=r2*(b2Asin(l/this.m_radius)+b2_pi/2)+l*b2Sqrt(r2-l2);var com=-2/3*b2Pow(r2-l2,1.5)/area;c.x=p.x+normal.x*com;c.y=p.y+normal.y*com;return area;};_proto34.Dump=function Dump(log){log("    const shape: b2CircleShape = new b2CircleShape();\n");log("    shape.m_radius = %.15f;\n",this.m_radius);log("    shape.m_p.Set(%.15f, %.15f);\n",this.m_p.x,this.m_p.y);};return b2CircleShape;}(b2Shape);b2CircleShape.TestPoint_s_center=new b2Vec2();b2CircleShape.TestPoint_s_d=new b2Vec2();b2CircleShape.ComputeDistance_s_center=new b2Vec2();b2CircleShape.RayCast_s_position=new b2Vec2();b2CircleShape.RayCast_s_s=new b2Vec2();b2CircleShape.RayCast_s_r=new b2Vec2();b2CircleShape.ComputeAABB_s_p=new b2Vec2();var b2PolygonShape=function(_b2Shape2){_inheritsLoose(b2PolygonShape,_b2Shape2);function b2PolygonShape(){var _this3;_this3=_b2Shape2.call(this,exports$1.b2ShapeType.e_polygonShape,b2_polygonRadius)||this;_this3.m_centroid=new b2Vec2(0,0);_this3.m_vertices=[];_this3.m_normals=[];_this3.m_count=0;return _this3;}var _proto35=b2PolygonShape.prototype;_proto35.Clone=function Clone(){return new b2PolygonShape().Copy(this);};_proto35.Copy=function Copy(other){_b2Shape2.prototype.Copy.call(this,other);this.m_centroid.Copy(other.m_centroid);this.m_count=other.m_count;this.m_vertices=b2Vec2.MakeArray(this.m_count);this.m_normals=b2Vec2.MakeArray(this.m_count);for(var i=0;i<this.m_count;++i){this.m_vertices[i].Copy(other.m_vertices[i]);this.m_normals[i].Copy(other.m_normals[i]);}return this;};_proto35.GetChildCount=function GetChildCount(){return 1;};_proto35.Set=function Set(){for(var _len5=arguments.length,args=new Array(_len5),_key6=0;_key6<_len5;_key6++){args[_key6]=arguments[_key6];}if(typeof args[0][0]==="number"){var vertices=args[0];if(vertices.length%2!==0){throw new Error();}return this._Set(function(index){return {x:vertices[index*2],y:vertices[index*2+1]};},vertices.length/2);}else {var _vertices=args[0];var count=args[1]||_vertices.length;return this._Set(function(index){return _vertices[index];},count);}};_proto35._Set=function _Set(vertices,count){if(count<3){return this.SetAsBox(1,1);}var n=count;var ps=[];for(var i=0;i<n;++i){var v=vertices(i);var unique=true;for(var j=0;j<ps.length;++j){if(b2Vec2.DistanceSquaredVV(v,ps[j])<0.5*b2_linearSlop*(0.5*b2_linearSlop)){unique=false;break;}}if(unique){ps.push(v);}}n=ps.length;if(n<3){return this.SetAsBox(1.0,1.0);}var i0=0;var x0=ps[0].x;for(var _i6=1;_i6<n;++_i6){var x=ps[_i6].x;if(x>x0||x===x0&&ps[_i6].y<ps[i0].y){i0=_i6;x0=x;}}var hull=[];var m=0;var ih=i0;for(;;){hull[m]=ih;var ie=0;for(var _j2=1;_j2<n;++_j2){if(ie===ih){ie=_j2;continue;}var r=b2Vec2.SubVV(ps[ie],ps[hull[m]],b2PolygonShape.Set_s_r);var _v2=b2Vec2.SubVV(ps[_j2],ps[hull[m]],b2PolygonShape.Set_s_v);var c=b2Vec2.CrossVV(r,_v2);if(c<0){ie=_j2;}if(c===0&&_v2.LengthSquared()>r.LengthSquared()){ie=_j2;}}++m;ih=ie;if(ie===i0){break;}}this.m_count=m;this.m_vertices=b2Vec2.MakeArray(this.m_count);this.m_normals=b2Vec2.MakeArray(this.m_count);for(var _i7=0;_i7<m;++_i7){this.m_vertices[_i7].Copy(ps[hull[_i7]]);}for(var _i8=0;_i8<m;++_i8){var vertexi1=this.m_vertices[_i8];var vertexi2=this.m_vertices[(_i8+1)%m];var edge=b2Vec2.SubVV(vertexi2,vertexi1,b2Vec2.s_t0);b2Vec2.CrossVOne(edge,this.m_normals[_i8]).SelfNormalize();}b2PolygonShape.ComputeCentroid(this.m_vertices,m,this.m_centroid);return this;};_proto35.SetAsBox=function SetAsBox(hx,hy,center,angle){if(angle===void 0){angle=0;}this.m_count=4;this.m_vertices=b2Vec2.MakeArray(this.m_count);this.m_normals=b2Vec2.MakeArray(this.m_count);this.m_vertices[0].Set(-hx,-hy);this.m_vertices[1].Set(hx,-hy);this.m_vertices[2].Set(hx,hy);this.m_vertices[3].Set(-hx,hy);this.m_normals[0].Set(0,-1);this.m_normals[1].Set(1,0);this.m_normals[2].Set(0,1);this.m_normals[3].Set(-1,0);this.m_centroid.SetZero();if(center){this.m_centroid.Copy(center);var xf=new b2Transform();xf.SetPosition(center);xf.SetRotationAngle(angle);for(var i=0;i<this.m_count;++i){b2Transform.MulXV(xf,this.m_vertices[i],this.m_vertices[i]);b2Rot.MulRV(xf.q,this.m_normals[i],this.m_normals[i]);}}return this;};_proto35.TestPoint=function TestPoint(xf,p){var pLocal=b2Transform.MulTXV(xf,p,b2PolygonShape.TestPoint_s_pLocal);for(var i=0;i<this.m_count;++i){var dot=b2Vec2.DotVV(this.m_normals[i],b2Vec2.SubVV(pLocal,this.m_vertices[i],b2Vec2.s_t0));if(dot>0){return false;}}return true;};_proto35.ComputeDistance=function ComputeDistance(xf,p,normal,childIndex){var pLocal=b2Transform.MulTXV(xf,p,b2PolygonShape.ComputeDistance_s_pLocal);var maxDistance=-b2_maxFloat;var normalForMaxDistance=b2PolygonShape.ComputeDistance_s_normalForMaxDistance.Copy(pLocal);for(var i=0;i<this.m_count;++i){var dot=b2Vec2.DotVV(this.m_normals[i],b2Vec2.SubVV(pLocal,this.m_vertices[i],b2Vec2.s_t0));if(dot>maxDistance){maxDistance=dot;normalForMaxDistance.Copy(this.m_normals[i]);}}if(maxDistance>0){var minDistance=b2PolygonShape.ComputeDistance_s_minDistance.Copy(normalForMaxDistance);var minDistance2=maxDistance*maxDistance;for(var _i9=0;_i9<this.m_count;++_i9){var distance=b2Vec2.SubVV(pLocal,this.m_vertices[_i9],b2PolygonShape.ComputeDistance_s_distance);var distance2=distance.LengthSquared();if(minDistance2>distance2){minDistance.Copy(distance);minDistance2=distance2;}}b2Rot.MulRV(xf.q,minDistance,normal);normal.Normalize();return Math.sqrt(minDistance2);}else {b2Rot.MulRV(xf.q,normalForMaxDistance,normal);return maxDistance;}};_proto35.RayCast=function RayCast(output,input,xf,childIndex){var p1=b2Transform.MulTXV(xf,input.p1,b2PolygonShape.RayCast_s_p1);var p2=b2Transform.MulTXV(xf,input.p2,b2PolygonShape.RayCast_s_p2);var d=b2Vec2.SubVV(p2,p1,b2PolygonShape.RayCast_s_d);var lower=0,upper=input.maxFraction;var index=-1;for(var i=0;i<this.m_count;++i){var numerator=b2Vec2.DotVV(this.m_normals[i],b2Vec2.SubVV(this.m_vertices[i],p1,b2Vec2.s_t0));var denominator=b2Vec2.DotVV(this.m_normals[i],d);if(denominator===0){if(numerator<0){return false;}}else {if(denominator<0&&numerator<lower*denominator){lower=numerator/denominator;index=i;}else if(denominator>0&&numerator<upper*denominator){upper=numerator/denominator;}}if(upper<lower){return false;}}if(index>=0){output.fraction=lower;b2Rot.MulRV(xf.q,this.m_normals[index],output.normal);return true;}return false;};_proto35.ComputeAABB=function ComputeAABB(aabb,xf,childIndex){var lower=b2Transform.MulXV(xf,this.m_vertices[0],aabb.lowerBound);var upper=aabb.upperBound.Copy(lower);for(var i=0;i<this.m_count;++i){var v=b2Transform.MulXV(xf,this.m_vertices[i],b2PolygonShape.ComputeAABB_s_v);b2Vec2.MinV(v,lower,lower);b2Vec2.MaxV(v,upper,upper);}var r=this.m_radius;lower.SelfSubXY(r,r);upper.SelfAddXY(r,r);};_proto35.ComputeMass=function ComputeMass(massData,density){var center=b2PolygonShape.ComputeMass_s_center.SetZero();var area=0;var I=0;var s=b2PolygonShape.ComputeMass_s_s.SetZero();for(var i=0;i<this.m_count;++i){s.SelfAdd(this.m_vertices[i]);}s.SelfMul(1/this.m_count);var k_inv3=1/3;for(var _i10=0;_i10<this.m_count;++_i10){var e1=b2Vec2.SubVV(this.m_vertices[_i10],s,b2PolygonShape.ComputeMass_s_e1);var e2=b2Vec2.SubVV(this.m_vertices[(_i10+1)%this.m_count],s,b2PolygonShape.ComputeMass_s_e2);var D=b2Vec2.CrossVV(e1,e2);var triangleArea=0.5*D;area+=triangleArea;center.SelfAdd(b2Vec2.MulSV(triangleArea*k_inv3,b2Vec2.AddVV(e1,e2,b2Vec2.s_t0),b2Vec2.s_t1));var ex1=e1.x;var ey1=e1.y;var ex2=e2.x;var ey2=e2.y;var intx2=ex1*ex1+ex2*ex1+ex2*ex2;var inty2=ey1*ey1+ey2*ey1+ey2*ey2;I+=0.25*k_inv3*D*(intx2+inty2);}massData.mass=density*area;center.SelfMul(1/area);b2Vec2.AddVV(center,s,massData.center);massData.I=density*I;massData.I+=massData.mass*(b2Vec2.DotVV(massData.center,massData.center)-b2Vec2.DotVV(center,center));};_proto35.Validate=function Validate(){for(var i=0;i<this.m_count;++i){var i1=i;var i2=(i+1)%this.m_count;var p=this.m_vertices[i1];var e=b2Vec2.SubVV(this.m_vertices[i2],p,b2PolygonShape.Validate_s_e);for(var j=0;j<this.m_count;++j){if(j===i1||j===i2){continue;}var v=b2Vec2.SubVV(this.m_vertices[j],p,b2PolygonShape.Validate_s_v);var c=b2Vec2.CrossVV(e,v);if(c<0){return false;}}}return true;};_proto35.SetupDistanceProxy=function SetupDistanceProxy(proxy,index){proxy.m_vertices=this.m_vertices;proxy.m_count=this.m_count;proxy.m_radius=this.m_radius;};_proto35.ComputeSubmergedArea=function ComputeSubmergedArea(normal,offset,xf,c){var normalL=b2Rot.MulTRV(xf.q,normal,b2PolygonShape.ComputeSubmergedArea_s_normalL);var offsetL=offset-b2Vec2.DotVV(normal,xf.p);var depths=[];var diveCount=0;var intoIndex=-1;var outoIndex=-1;var lastSubmerged=false;for(var _i11=0;_i11<this.m_count;++_i11){depths[_i11]=b2Vec2.DotVV(normalL,this.m_vertices[_i11])-offsetL;var isSubmerged=depths[_i11]<-b2_epsilon;if(_i11>0){if(isSubmerged){if(!lastSubmerged){intoIndex=_i11-1;diveCount++;}}else {if(lastSubmerged){outoIndex=_i11-1;diveCount++;}}}lastSubmerged=isSubmerged;}switch(diveCount){case 0:if(lastSubmerged){var md=b2PolygonShape.ComputeSubmergedArea_s_md;this.ComputeMass(md,1);b2Transform.MulXV(xf,md.center,c);return md.mass;}else {return 0;}case 1:if(intoIndex===-1){intoIndex=this.m_count-1;}else {outoIndex=this.m_count-1;}break;}var intoIndex2=(intoIndex+1)%this.m_count;var outoIndex2=(outoIndex+1)%this.m_count;var intoLamdda=(0-depths[intoIndex])/(depths[intoIndex2]-depths[intoIndex]);var outoLamdda=(0-depths[outoIndex])/(depths[outoIndex2]-depths[outoIndex]);var intoVec=b2PolygonShape.ComputeSubmergedArea_s_intoVec.Set(this.m_vertices[intoIndex].x*(1-intoLamdda)+this.m_vertices[intoIndex2].x*intoLamdda,this.m_vertices[intoIndex].y*(1-intoLamdda)+this.m_vertices[intoIndex2].y*intoLamdda);var outoVec=b2PolygonShape.ComputeSubmergedArea_s_outoVec.Set(this.m_vertices[outoIndex].x*(1-outoLamdda)+this.m_vertices[outoIndex2].x*outoLamdda,this.m_vertices[outoIndex].y*(1-outoLamdda)+this.m_vertices[outoIndex2].y*outoLamdda);var area=0;var center=b2PolygonShape.ComputeSubmergedArea_s_center.SetZero();var p2=this.m_vertices[intoIndex2];var p3;var i=intoIndex2;while(i!==outoIndex2){i=(i+1)%this.m_count;if(i===outoIndex2){p3=outoVec;}else {p3=this.m_vertices[i];}var triangleArea=0.5*((p2.x-intoVec.x)*(p3.y-intoVec.y)-(p2.y-intoVec.y)*(p3.x-intoVec.x));area+=triangleArea;center.x+=triangleArea*(intoVec.x+p2.x+p3.x)/3;center.y+=triangleArea*(intoVec.y+p2.y+p3.y)/3;p2=p3;}center.SelfMul(1/area);b2Transform.MulXV(xf,center,c);return area;};_proto35.Dump=function Dump(log){log("    const shape: b2PolygonShape = new b2PolygonShape();\n");log("    const vs: b2Vec2[] = [];\n");for(var i=0;i<this.m_count;++i){log("    vs[%d] = new b2Vec2(%.15f, %.15f);\n",i,this.m_vertices[i].x,this.m_vertices[i].y);}log("    shape.Set(vs, %d);\n",this.m_count);};b2PolygonShape.ComputeCentroid=function ComputeCentroid(vs,count,out){var c=out;c.SetZero();var area=0;var pRef=b2PolygonShape.ComputeCentroid_s_pRef.SetZero();var inv3=1/3;for(var i=0;i<count;++i){var p1=pRef;var p2=vs[i];var p3=vs[(i+1)%count];var e1=b2Vec2.SubVV(p2,p1,b2PolygonShape.ComputeCentroid_s_e1);var e2=b2Vec2.SubVV(p3,p1,b2PolygonShape.ComputeCentroid_s_e2);var D=b2Vec2.CrossVV(e1,e2);var triangleArea=0.5*D;area+=triangleArea;c.x+=triangleArea*inv3*(p1.x+p2.x+p3.x);c.y+=triangleArea*inv3*(p1.y+p2.y+p3.y);}c.SelfMul(1/area);return c;};return b2PolygonShape;}(b2Shape);b2PolygonShape.Set_s_r=new b2Vec2();b2PolygonShape.Set_s_v=new b2Vec2();b2PolygonShape.TestPoint_s_pLocal=new b2Vec2();b2PolygonShape.ComputeDistance_s_pLocal=new b2Vec2();b2PolygonShape.ComputeDistance_s_normalForMaxDistance=new b2Vec2();b2PolygonShape.ComputeDistance_s_minDistance=new b2Vec2();b2PolygonShape.ComputeDistance_s_distance=new b2Vec2();b2PolygonShape.RayCast_s_p1=new b2Vec2();b2PolygonShape.RayCast_s_p2=new b2Vec2();b2PolygonShape.RayCast_s_d=new b2Vec2();b2PolygonShape.ComputeAABB_s_v=new b2Vec2();b2PolygonShape.ComputeMass_s_center=new b2Vec2();b2PolygonShape.ComputeMass_s_s=new b2Vec2();b2PolygonShape.ComputeMass_s_e1=new b2Vec2();b2PolygonShape.ComputeMass_s_e2=new b2Vec2();b2PolygonShape.Validate_s_e=new b2Vec2();b2PolygonShape.Validate_s_v=new b2Vec2();b2PolygonShape.ComputeSubmergedArea_s_normalL=new b2Vec2();b2PolygonShape.ComputeSubmergedArea_s_md=new b2MassData();b2PolygonShape.ComputeSubmergedArea_s_intoVec=new b2Vec2();b2PolygonShape.ComputeSubmergedArea_s_outoVec=new b2Vec2();b2PolygonShape.ComputeSubmergedArea_s_center=new b2Vec2();b2PolygonShape.ComputeCentroid_s_pRef=new b2Vec2();b2PolygonShape.ComputeCentroid_s_e1=new b2Vec2();b2PolygonShape.ComputeCentroid_s_e2=new b2Vec2();var b2EdgeShape=function(_b2Shape3){_inheritsLoose(b2EdgeShape,_b2Shape3);function b2EdgeShape(){var _this4;_this4=_b2Shape3.call(this,exports$1.b2ShapeType.e_edgeShape,b2_polygonRadius)||this;_this4.m_vertex1=new b2Vec2();_this4.m_vertex2=new b2Vec2();_this4.m_vertex0=new b2Vec2();_this4.m_vertex3=new b2Vec2();_this4.m_hasVertex0=false;_this4.m_hasVertex3=false;return _this4;}var _proto36=b2EdgeShape.prototype;_proto36.Set=function Set(v1,v2){this.m_vertex1.Copy(v1);this.m_vertex2.Copy(v2);this.m_hasVertex0=false;this.m_hasVertex3=false;return this;};_proto36.Clone=function Clone(){return new b2EdgeShape().Copy(this);};_proto36.Copy=function Copy(other){_b2Shape3.prototype.Copy.call(this,other);this.m_vertex1.Copy(other.m_vertex1);this.m_vertex2.Copy(other.m_vertex2);this.m_vertex0.Copy(other.m_vertex0);this.m_vertex3.Copy(other.m_vertex3);this.m_hasVertex0=other.m_hasVertex0;this.m_hasVertex3=other.m_hasVertex3;return this;};_proto36.GetChildCount=function GetChildCount(){return 1;};_proto36.TestPoint=function TestPoint(xf,p){return false;};_proto36.ComputeDistance=function ComputeDistance(xf,p,normal,childIndex){var v1=b2Transform.MulXV(xf,this.m_vertex1,b2EdgeShape.ComputeDistance_s_v1);var v2=b2Transform.MulXV(xf,this.m_vertex2,b2EdgeShape.ComputeDistance_s_v2);var d=b2Vec2.SubVV(p,v1,b2EdgeShape.ComputeDistance_s_d);var s=b2Vec2.SubVV(v2,v1,b2EdgeShape.ComputeDistance_s_s);var ds=b2Vec2.DotVV(d,s);if(ds>0){var s2=b2Vec2.DotVV(s,s);if(ds>s2){b2Vec2.SubVV(p,v2,d);}else {d.SelfMulSub(ds/s2,s);}}normal.Copy(d);return normal.Normalize();};_proto36.RayCast=function RayCast(output,input,xf,childIndex){var p1=b2Transform.MulTXV(xf,input.p1,b2EdgeShape.RayCast_s_p1);var p2=b2Transform.MulTXV(xf,input.p2,b2EdgeShape.RayCast_s_p2);var d=b2Vec2.SubVV(p2,p1,b2EdgeShape.RayCast_s_d);var v1=this.m_vertex1;var v2=this.m_vertex2;var e=b2Vec2.SubVV(v2,v1,b2EdgeShape.RayCast_s_e);var normal=output.normal.Set(e.y,-e.x).SelfNormalize();var numerator=b2Vec2.DotVV(normal,b2Vec2.SubVV(v1,p1,b2Vec2.s_t0));var denominator=b2Vec2.DotVV(normal,d);if(denominator===0){return false;}var t=numerator/denominator;if(t<0||input.maxFraction<t){return false;}var q=b2Vec2.AddVMulSV(p1,t,d,b2EdgeShape.RayCast_s_q);var r=b2Vec2.SubVV(v2,v1,b2EdgeShape.RayCast_s_r);var rr=b2Vec2.DotVV(r,r);if(rr===0){return false;}var s=b2Vec2.DotVV(b2Vec2.SubVV(q,v1,b2Vec2.s_t0),r)/rr;if(s<0||1<s){return false;}output.fraction=t;b2Rot.MulRV(xf.q,output.normal,output.normal);if(numerator>0){output.normal.SelfNeg();}return true;};_proto36.ComputeAABB=function ComputeAABB(aabb,xf,childIndex){var v1=b2Transform.MulXV(xf,this.m_vertex1,b2EdgeShape.ComputeAABB_s_v1);var v2=b2Transform.MulXV(xf,this.m_vertex2,b2EdgeShape.ComputeAABB_s_v2);b2Vec2.MinV(v1,v2,aabb.lowerBound);b2Vec2.MaxV(v1,v2,aabb.upperBound);var r=this.m_radius;aabb.lowerBound.SelfSubXY(r,r);aabb.upperBound.SelfAddXY(r,r);};_proto36.ComputeMass=function ComputeMass(massData,density){massData.mass=0;b2Vec2.MidVV(this.m_vertex1,this.m_vertex2,massData.center);massData.I=0;};_proto36.SetupDistanceProxy=function SetupDistanceProxy(proxy,index){proxy.m_vertices=proxy.m_buffer;proxy.m_vertices[0].Copy(this.m_vertex1);proxy.m_vertices[1].Copy(this.m_vertex2);proxy.m_count=2;proxy.m_radius=this.m_radius;};_proto36.ComputeSubmergedArea=function ComputeSubmergedArea(normal,offset,xf,c){c.SetZero();return 0;};_proto36.Dump=function Dump(log){log("    const shape: b2EdgeShape = new b2EdgeShape();\n");log("    shape.m_radius = %.15f;\n",this.m_radius);log("    shape.m_vertex0.Set(%.15f, %.15f);\n",this.m_vertex0.x,this.m_vertex0.y);log("    shape.m_vertex1.Set(%.15f, %.15f);\n",this.m_vertex1.x,this.m_vertex1.y);log("    shape.m_vertex2.Set(%.15f, %.15f);\n",this.m_vertex2.x,this.m_vertex2.y);log("    shape.m_vertex3.Set(%.15f, %.15f);\n",this.m_vertex3.x,this.m_vertex3.y);log("    shape.m_hasVertex0 = %s;\n",this.m_hasVertex0);log("    shape.m_hasVertex3 = %s;\n",this.m_hasVertex3);};return b2EdgeShape;}(b2Shape);b2EdgeShape.ComputeDistance_s_v1=new b2Vec2();b2EdgeShape.ComputeDistance_s_v2=new b2Vec2();b2EdgeShape.ComputeDistance_s_d=new b2Vec2();b2EdgeShape.ComputeDistance_s_s=new b2Vec2();b2EdgeShape.RayCast_s_p1=new b2Vec2();b2EdgeShape.RayCast_s_p2=new b2Vec2();b2EdgeShape.RayCast_s_d=new b2Vec2();b2EdgeShape.RayCast_s_e=new b2Vec2();b2EdgeShape.RayCast_s_q=new b2Vec2();b2EdgeShape.RayCast_s_r=new b2Vec2();b2EdgeShape.ComputeAABB_s_v1=new b2Vec2();b2EdgeShape.ComputeAABB_s_v2=new b2Vec2();var b2ChainShape=function(_b2Shape4){_inheritsLoose(b2ChainShape,_b2Shape4);function b2ChainShape(){var _this5;_this5=_b2Shape4.call(this,exports$1.b2ShapeType.e_chainShape,b2_polygonRadius)||this;_this5.m_vertices=[];_this5.m_count=0;_this5.m_prevVertex=new b2Vec2();_this5.m_nextVertex=new b2Vec2();_this5.m_hasPrevVertex=false;_this5.m_hasNextVertex=false;return _this5;}var _proto37=b2ChainShape.prototype;_proto37.CreateLoop=function CreateLoop(){for(var _len6=arguments.length,args=new Array(_len6),_key7=0;_key7<_len6;_key7++){args[_key7]=arguments[_key7];}if(typeof args[0][0]==="number"){var vertices=args[0];if(vertices.length%2!==0){throw new Error();}return this._CreateLoop(function(index){return {x:vertices[index*2],y:vertices[index*2+1]};},vertices.length/2);}else {var _vertices2=args[0];var count=args[1]||_vertices2.length;return this._CreateLoop(function(index){return _vertices2[index];},count);}};_proto37._CreateLoop=function _CreateLoop(vertices,count){if(count<3){return this;}this.m_count=count+1;this.m_vertices=b2Vec2.MakeArray(this.m_count);for(var i=0;i<count;++i){this.m_vertices[i].Copy(vertices(i));}this.m_vertices[count].Copy(this.m_vertices[0]);this.m_prevVertex.Copy(this.m_vertices[this.m_count-2]);this.m_nextVertex.Copy(this.m_vertices[1]);this.m_hasPrevVertex=true;this.m_hasNextVertex=true;return this;};_proto37.CreateChain=function CreateChain(){for(var _len7=arguments.length,args=new Array(_len7),_key8=0;_key8<_len7;_key8++){args[_key8]=arguments[_key8];}if(typeof args[0][0]==="number"){var vertices=args[0];if(vertices.length%2!==0){throw new Error();}return this._CreateChain(function(index){return {x:vertices[index*2],y:vertices[index*2+1]};},vertices.length/2);}else {var _vertices3=args[0];var count=args[1]||_vertices3.length;return this._CreateChain(function(index){return _vertices3[index];},count);}};_proto37._CreateChain=function _CreateChain(vertices,count){this.m_count=count;this.m_vertices=b2Vec2.MakeArray(count);for(var i=0;i<count;++i){this.m_vertices[i].Copy(vertices(i));}this.m_hasPrevVertex=false;this.m_hasNextVertex=false;this.m_prevVertex.SetZero();this.m_nextVertex.SetZero();return this;};_proto37.SetPrevVertex=function SetPrevVertex(prevVertex){this.m_prevVertex.Copy(prevVertex);this.m_hasPrevVertex=true;return this;};_proto37.SetNextVertex=function SetNextVertex(nextVertex){this.m_nextVertex.Copy(nextVertex);this.m_hasNextVertex=true;return this;};_proto37.Clone=function Clone(){return new b2ChainShape().Copy(this);};_proto37.Copy=function Copy(other){_b2Shape4.prototype.Copy.call(this,other);this._CreateChain(function(index){return other.m_vertices[index];},other.m_count);this.m_prevVertex.Copy(other.m_prevVertex);this.m_nextVertex.Copy(other.m_nextVertex);this.m_hasPrevVertex=other.m_hasPrevVertex;this.m_hasNextVertex=other.m_hasNextVertex;return this;};_proto37.GetChildCount=function GetChildCount(){return this.m_count-1;};_proto37.GetChildEdge=function GetChildEdge(edge,index){edge.m_radius=this.m_radius;edge.m_vertex1.Copy(this.m_vertices[index]);edge.m_vertex2.Copy(this.m_vertices[index+1]);if(index>0){edge.m_vertex0.Copy(this.m_vertices[index-1]);edge.m_hasVertex0=true;}else {edge.m_vertex0.Copy(this.m_prevVertex);edge.m_hasVertex0=this.m_hasPrevVertex;}if(index<this.m_count-2){edge.m_vertex3.Copy(this.m_vertices[index+2]);edge.m_hasVertex3=true;}else {edge.m_vertex3.Copy(this.m_nextVertex);edge.m_hasVertex3=this.m_hasNextVertex;}};_proto37.TestPoint=function TestPoint(xf,p){return false;};_proto37.ComputeDistance=function ComputeDistance(xf,p,normal,childIndex){var edge=b2ChainShape.ComputeDistance_s_edgeShape;this.GetChildEdge(edge,childIndex);return edge.ComputeDistance(xf,p,normal,0);};_proto37.RayCast=function RayCast(output,input,xf,childIndex){var edgeShape=b2ChainShape.RayCast_s_edgeShape;edgeShape.m_vertex1.Copy(this.m_vertices[childIndex]);edgeShape.m_vertex2.Copy(this.m_vertices[(childIndex+1)%this.m_count]);return edgeShape.RayCast(output,input,xf,0);};_proto37.ComputeAABB=function ComputeAABB(aabb,xf,childIndex){var vertexi1=this.m_vertices[childIndex];var vertexi2=this.m_vertices[(childIndex+1)%this.m_count];var v1=b2Transform.MulXV(xf,vertexi1,b2ChainShape.ComputeAABB_s_v1);var v2=b2Transform.MulXV(xf,vertexi2,b2ChainShape.ComputeAABB_s_v2);b2Vec2.MinV(v1,v2,aabb.lowerBound);b2Vec2.MaxV(v1,v2,aabb.upperBound);};_proto37.ComputeMass=function ComputeMass(massData,density){massData.mass=0;massData.center.SetZero();massData.I=0;};_proto37.SetupDistanceProxy=function SetupDistanceProxy(proxy,index){proxy.m_vertices=proxy.m_buffer;proxy.m_vertices[0].Copy(this.m_vertices[index]);if(index+1<this.m_count){proxy.m_vertices[1].Copy(this.m_vertices[index+1]);}else {proxy.m_vertices[1].Copy(this.m_vertices[0]);}proxy.m_count=2;proxy.m_radius=this.m_radius;};_proto37.ComputeSubmergedArea=function ComputeSubmergedArea(normal,offset,xf,c){c.SetZero();return 0;};_proto37.Dump=function Dump(log){log("    const shape: b2ChainShape = new b2ChainShape();\n");log("    const vs: b2Vec2[] = [];\n");for(var i=0;i<this.m_count;++i){log("    vs[%d] = new bVec2(%.15f, %.15f);\n",i,this.m_vertices[i].x,this.m_vertices[i].y);}log("    shape.CreateChain(vs, %d);\n",this.m_count);log("    shape.m_prevVertex.Set(%.15f, %.15f);\n",this.m_prevVertex.x,this.m_prevVertex.y);log("    shape.m_nextVertex.Set(%.15f, %.15f);\n",this.m_nextVertex.x,this.m_nextVertex.y);log("    shape.m_hasPrevVertex = %s;\n",this.m_hasPrevVertex?"true":"false");log("    shape.m_hasNextVertex = %s;\n",this.m_hasNextVertex?"true":"false");};return b2ChainShape;}(b2Shape);b2ChainShape.ComputeDistance_s_edgeShape=new b2EdgeShape();b2ChainShape.RayCast_s_edgeShape=new b2EdgeShape();b2ChainShape.ComputeAABB_s_v1=new b2Vec2();b2ChainShape.ComputeAABB_s_v2=new b2Vec2();var b2Filter=function(){function b2Filter(){this.categoryBits=0x0001;this.maskBits=0xFFFF;this.groupIndex=0;}var _proto38=b2Filter.prototype;_proto38.Clone=function Clone(){return new b2Filter().Copy(this);};_proto38.Copy=function Copy(other){this.categoryBits=other.categoryBits;this.maskBits=other.maskBits;this.groupIndex=other.groupIndex||0;return this;};return b2Filter;}();b2Filter.DEFAULT=new b2Filter();var b2FixtureDef=function b2FixtureDef(){this.userData=null;this.friction=0.2;this.restitution=0;this.density=0;this.isSensor=false;this.filter=new b2Filter();};var b2FixtureProxy=function(){function b2FixtureProxy(fixture,childIndex){this.aabb=new b2AABB();this.childIndex=0;this.fixture=fixture;this.childIndex=childIndex;this.fixture.m_shape.ComputeAABB(this.aabb,this.fixture.m_body.GetTransform(),childIndex);this.treeNode=this.fixture.m_body.m_world.m_contactManager.m_broadPhase.CreateProxy(this.aabb,this);}var _proto39=b2FixtureProxy.prototype;_proto39.Reset=function Reset(){this.fixture.m_body.m_world.m_contactManager.m_broadPhase.DestroyProxy(this.treeNode);};_proto39.Touch=function Touch(){this.fixture.m_body.m_world.m_contactManager.m_broadPhase.TouchProxy(this.treeNode);};_proto39.Synchronize=function Synchronize(transform1,transform2,displacement){if(transform1===transform2){this.fixture.m_shape.ComputeAABB(this.aabb,transform1,this.childIndex);this.fixture.m_body.m_world.m_contactManager.m_broadPhase.MoveProxy(this.treeNode,this.aabb,displacement);}else {var aabb1=b2FixtureProxy.Synchronize_s_aabb1;var aabb2=b2FixtureProxy.Synchronize_s_aabb2;this.fixture.m_shape.ComputeAABB(aabb1,transform1,this.childIndex);this.fixture.m_shape.ComputeAABB(aabb2,transform2,this.childIndex);this.aabb.Combine2(aabb1,aabb2);this.fixture.m_body.m_world.m_contactManager.m_broadPhase.MoveProxy(this.treeNode,this.aabb,displacement);}};return b2FixtureProxy;}();b2FixtureProxy.Synchronize_s_aabb1=new b2AABB();b2FixtureProxy.Synchronize_s_aabb2=new b2AABB();var b2Fixture=function(){function b2Fixture(body,def){this.m_density=0;this.m_next=null;this.m_friction=0;this.m_restitution=0;this.m_proxies=[];this.m_filter=new b2Filter();this.m_isSensor=false;this.m_userData=null;this.m_body=body;this.m_shape=def.shape.Clone();this.m_userData=b2Maybe(def.userData,null);this.m_friction=b2Maybe(def.friction,0.2);this.m_restitution=b2Maybe(def.restitution,0);this.m_filter.Copy(b2Maybe(def.filter,b2Filter.DEFAULT));this.m_isSensor=b2Maybe(def.isSensor,false);this.m_density=b2Maybe(def.density,0);}var _proto40=b2Fixture.prototype;_proto40.Reset=function Reset(){};_proto40.GetType=function GetType(){return this.m_shape.GetType();};_proto40.GetShape=function GetShape(){return this.m_shape;};_proto40.SetSensor=function SetSensor(sensor){if(sensor!==this.m_isSensor){this.m_body.SetAwake(true);this.m_isSensor=sensor;}};_proto40.IsSensor=function IsSensor(){return this.m_isSensor;};_proto40.SetFilterData=function SetFilterData(filter){this.m_filter.Copy(filter);this.Refilter();};_proto40.GetFilterData=function GetFilterData(){return this.m_filter;};_proto40.Refilter=function Refilter(){var edge=this.m_body.GetContactList();while(edge){var contact=edge.contact;var fixtureA=contact.GetFixtureA();var fixtureB=contact.GetFixtureB();if(fixtureA===this||fixtureB===this){contact.FlagForFiltering();}edge=edge.next;}this.TouchProxies();};_proto40.GetBody=function GetBody(){return this.m_body;};_proto40.GetNext=function GetNext(){return this.m_next;};_proto40.GetUserData=function GetUserData(){return this.m_userData;};_proto40.SetUserData=function SetUserData(data){this.m_userData=data;};_proto40.TestPoint=function TestPoint(p){return this.m_shape.TestPoint(this.m_body.GetTransform(),p);};_proto40.ComputeDistance=function ComputeDistance(p,normal,childIndex){return this.m_shape.ComputeDistance(this.m_body.GetTransform(),p,normal,childIndex);};_proto40.RayCast=function RayCast(output,input,childIndex){return this.m_shape.RayCast(output,input,this.m_body.GetTransform(),childIndex);};_proto40.GetMassData=function GetMassData(massData){if(massData===void 0){massData=new b2MassData();}this.m_shape.ComputeMass(massData,this.m_density);return massData;};_proto40.SetDensity=function SetDensity(density){this.m_density=density;};_proto40.GetDensity=function GetDensity(){return this.m_density;};_proto40.GetFriction=function GetFriction(){return this.m_friction;};_proto40.SetFriction=function SetFriction(friction){this.m_friction=friction;};_proto40.GetRestitution=function GetRestitution(){return this.m_restitution;};_proto40.SetRestitution=function SetRestitution(restitution){this.m_restitution=restitution;};_proto40.GetAABB=function GetAABB(childIndex){return this.m_proxies[childIndex].aabb;};_proto40.Dump=function Dump(log,bodyIndex){log("    const fd: b2FixtureDef = new b2FixtureDef();\n");log("    fd.friction = %.15f;\n",this.m_friction);log("    fd.restitution = %.15f;\n",this.m_restitution);log("    fd.density = %.15f;\n",this.m_density);log("    fd.isSensor = %s;\n",this.m_isSensor?"true":"false");log("    fd.filter.categoryBits = %d;\n",this.m_filter.categoryBits);log("    fd.filter.maskBits = %d;\n",this.m_filter.maskBits);log("    fd.filter.groupIndex = %d;\n",this.m_filter.groupIndex);this.m_shape.Dump(log);log("\n");log("    fd.shape = shape;\n");log("\n");log("    bodies[%d].CreateFixture(fd);\n",bodyIndex);};_proto40.CreateProxies=function CreateProxies(){if(this.m_proxies.length!==0){throw new Error();}for(var i=0;i<this.m_shape.GetChildCount();++i){this.m_proxies[i]=new b2FixtureProxy(this,i);}};_proto40.DestroyProxies=function DestroyProxies(){for(var _iterator=_createForOfIteratorHelperLoose(this.m_proxies),_step;!(_step=_iterator()).done;){var proxy=_step.value;proxy.Reset();}this.m_proxies.length=0;};_proto40.TouchProxies=function TouchProxies(){for(var _iterator2=_createForOfIteratorHelperLoose(this.m_proxies),_step2;!(_step2=_iterator2()).done;){var proxy=_step2.value;proxy.Touch();}};_proto40.SynchronizeProxies=function SynchronizeProxies(transform1,transform2,displacement){for(var _iterator3=_createForOfIteratorHelperLoose(this.m_proxies),_step3;!(_step3=_iterator3()).done;){var proxy=_step3.value;proxy.Synchronize(transform1,transform2,displacement);}};_createClass(b2Fixture,[{key:"m_proxyCount",get:function get(){return this.m_proxies.length;}}]);return b2Fixture;}();(function(b2BodyType){b2BodyType[b2BodyType["b2_unknown"]=-1]="b2_unknown";b2BodyType[b2BodyType["b2_staticBody"]=0]="b2_staticBody";b2BodyType[b2BodyType["b2_kinematicBody"]=1]="b2_kinematicBody";b2BodyType[b2BodyType["b2_dynamicBody"]=2]="b2_dynamicBody";})(exports$1.b2BodyType||(exports$1.b2BodyType={}));var b2BodyDef=function b2BodyDef(){this.type=exports$1.b2BodyType.b2_staticBody;this.position=new b2Vec2(0,0);this.angle=0;this.linearVelocity=new b2Vec2(0,0);this.angularVelocity=0;this.linearDamping=0;this.angularDamping=0;this.allowSleep=true;this.awake=true;this.fixedRotation=false;this.bullet=false;this.active=true;this.userData=null;this.gravityScale=1;};var b2Body=function(){function b2Body(bd,world){this.m_type=exports$1.b2BodyType.b2_staticBody;this.m_islandFlag=false;this.m_awakeFlag=false;this.m_autoSleepFlag=false;this.m_bulletFlag=false;this.m_fixedRotationFlag=false;this.m_activeFlag=false;this.m_toiFlag=false;this.m_islandIndex=0;this.m_xf=new b2Transform();this.m_xf0=new b2Transform();this.m_sweep=new b2Sweep();this.m_linearVelocity=new b2Vec2();this.m_angularVelocity=0;this.m_force=new b2Vec2();this.m_torque=0;this.m_prev=null;this.m_next=null;this.m_fixtureList=null;this.m_fixtureCount=0;this.m_jointList=null;this.m_contactList=null;this.m_mass=1;this.m_invMass=1;this.m_I=0;this.m_invI=0;this.m_linearDamping=0;this.m_angularDamping=0;this.m_gravityScale=1;this.m_sleepTime=0;this.m_userData=null;this.m_controllerList=null;this.m_controllerCount=0;this.m_bulletFlag=b2Maybe(bd.bullet,false);this.m_fixedRotationFlag=b2Maybe(bd.fixedRotation,false);this.m_autoSleepFlag=b2Maybe(bd.allowSleep,true);this.m_awakeFlag=b2Maybe(bd.awake,true);this.m_activeFlag=b2Maybe(bd.active,true);this.m_world=world;this.m_xf.p.Copy(b2Maybe(bd.position,b2Vec2.ZERO));this.m_xf.q.SetAngle(b2Maybe(bd.angle,0));this.m_xf0.Copy(this.m_xf);this.m_sweep.localCenter.SetZero();this.m_sweep.c0.Copy(this.m_xf.p);this.m_sweep.c.Copy(this.m_xf.p);this.m_sweep.a0=this.m_sweep.a=this.m_xf.q.GetAngle();this.m_sweep.alpha0=0;this.m_linearVelocity.Copy(b2Maybe(bd.linearVelocity,b2Vec2.ZERO));this.m_angularVelocity=b2Maybe(bd.angularVelocity,0);this.m_linearDamping=b2Maybe(bd.linearDamping,0);this.m_angularDamping=b2Maybe(bd.angularDamping,0);this.m_gravityScale=b2Maybe(bd.gravityScale,1);this.m_force.SetZero();this.m_torque=0;this.m_sleepTime=0;this.m_type=b2Maybe(bd.type,exports$1.b2BodyType.b2_staticBody);if(bd.type===exports$1.b2BodyType.b2_dynamicBody){this.m_mass=1;this.m_invMass=1;}else {this.m_mass=0;this.m_invMass=0;}this.m_I=0;this.m_invI=0;this.m_userData=bd.userData;this.m_fixtureList=null;this.m_fixtureCount=0;this.m_controllerList=null;this.m_controllerCount=0;}var _proto41=b2Body.prototype;_proto41.CreateFixture=function CreateFixture(a,b){if(b===void 0){b=0;}if(a instanceof b2Shape){return this.CreateFixtureShapeDensity(a,b);}else {return this.CreateFixtureDef(a);}};_proto41.CreateFixtureDef=function CreateFixtureDef(def){if(this.m_world.IsLocked()){throw new Error();}var fixture=new b2Fixture(this,def);if(this.m_activeFlag){fixture.CreateProxies();}fixture.m_next=this.m_fixtureList;this.m_fixtureList=fixture;++this.m_fixtureCount;if(fixture.m_density>0){this.ResetMassData();}this.m_world.m_newFixture=true;return fixture;};_proto41.CreateFixtureShapeDensity=function CreateFixtureShapeDensity(shape,density){if(density===void 0){density=0;}var def=b2Body.CreateFixtureShapeDensity_s_def;def.shape=shape;def.density=density;return this.CreateFixtureDef(def);};_proto41.DestroyFixture=function DestroyFixture(fixture){if(this.m_world.IsLocked()){throw new Error();}var node=this.m_fixtureList;var ppF=null;while(node!==null){if(node===fixture){if(ppF){ppF.m_next=fixture.m_next;}else {this.m_fixtureList=fixture.m_next;}break;}ppF=node;node=node.m_next;}var edge=this.m_contactList;while(edge){var c=edge.contact;edge=edge.next;var fixtureA=c.GetFixtureA();var fixtureB=c.GetFixtureB();if(fixture===fixtureA||fixture===fixtureB){this.m_world.m_contactManager.Destroy(c);}}if(this.m_activeFlag){fixture.DestroyProxies();}fixture.m_next=null;fixture.Reset();--this.m_fixtureCount;this.ResetMassData();};_proto41.SetTransformVec=function SetTransformVec(position,angle){this.SetTransformXY(position.x,position.y,angle);};_proto41.SetTransformXY=function SetTransformXY(x,y,angle){if(this.m_world.IsLocked()){throw new Error();}this.m_xf.q.SetAngle(angle);this.m_xf.p.Set(x,y);this.m_xf0.Copy(this.m_xf);b2Transform.MulXV(this.m_xf,this.m_sweep.localCenter,this.m_sweep.c);this.m_sweep.a=angle;this.m_sweep.c0.Copy(this.m_sweep.c);this.m_sweep.a0=angle;for(var f=this.m_fixtureList;f;f=f.m_next){f.SynchronizeProxies(this.m_xf,this.m_xf,b2Vec2.ZERO);}this.m_world.m_contactManager.FindNewContacts();};_proto41.SetTransform=function SetTransform(xf){this.SetTransformVec(xf.p,xf.GetAngle());};_proto41.GetTransform=function GetTransform(){return this.m_xf;};_proto41.GetPosition=function GetPosition(){return this.m_xf.p;};_proto41.SetPosition=function SetPosition(position){this.SetTransformVec(position,this.GetAngle());};_proto41.SetPositionXY=function SetPositionXY(x,y){this.SetTransformXY(x,y,this.GetAngle());};_proto41.GetAngle=function GetAngle(){return this.m_sweep.a;};_proto41.SetAngle=function SetAngle(angle){this.SetTransformVec(this.GetPosition(),angle);};_proto41.GetWorldCenter=function GetWorldCenter(){return this.m_sweep.c;};_proto41.GetLocalCenter=function GetLocalCenter(){return this.m_sweep.localCenter;};_proto41.SetLinearVelocity=function SetLinearVelocity(v){if(this.m_type===exports$1.b2BodyType.b2_staticBody){return;}if(b2Vec2.DotVV(v,v)>0){this.SetAwake(true);}this.m_linearVelocity.Copy(v);};_proto41.GetLinearVelocity=function GetLinearVelocity(){return this.m_linearVelocity;};_proto41.SetAngularVelocity=function SetAngularVelocity(w){if(this.m_type===exports$1.b2BodyType.b2_staticBody){return;}if(w*w>0){this.SetAwake(true);}this.m_angularVelocity=w;};_proto41.GetAngularVelocity=function GetAngularVelocity(){return this.m_angularVelocity;};_proto41.GetDefinition=function GetDefinition(bd){bd.type=this.GetType();bd.allowSleep=this.m_autoSleepFlag;bd.angle=this.GetAngle();bd.angularDamping=this.m_angularDamping;bd.gravityScale=this.m_gravityScale;bd.angularVelocity=this.m_angularVelocity;bd.fixedRotation=this.m_fixedRotationFlag;bd.bullet=this.m_bulletFlag;bd.awake=this.m_awakeFlag;bd.linearDamping=this.m_linearDamping;bd.linearVelocity.Copy(this.GetLinearVelocity());bd.position.Copy(this.GetPosition());bd.userData=this.GetUserData();return bd;};_proto41.ApplyForce=function ApplyForce(force,point,wake){if(wake===void 0){wake=true;}if(this.m_type!==exports$1.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_force.x+=force.x;this.m_force.y+=force.y;this.m_torque+=(point.x-this.m_sweep.c.x)*force.y-(point.y-this.m_sweep.c.y)*force.x;}};_proto41.ApplyForceToCenter=function ApplyForceToCenter(force,wake){if(wake===void 0){wake=true;}if(this.m_type!==exports$1.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_force.x+=force.x;this.m_force.y+=force.y;}};_proto41.ApplyTorque=function ApplyTorque(torque,wake){if(wake===void 0){wake=true;}if(this.m_type!==exports$1.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_torque+=torque;}};_proto41.ApplyLinearImpulse=function ApplyLinearImpulse(impulse,point,wake){if(wake===void 0){wake=true;}if(this.m_type!==exports$1.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_linearVelocity.x+=this.m_invMass*impulse.x;this.m_linearVelocity.y+=this.m_invMass*impulse.y;this.m_angularVelocity+=this.m_invI*((point.x-this.m_sweep.c.x)*impulse.y-(point.y-this.m_sweep.c.y)*impulse.x);}};_proto41.ApplyLinearImpulseToCenter=function ApplyLinearImpulseToCenter(impulse,wake){if(wake===void 0){wake=true;}if(this.m_type!==exports$1.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_linearVelocity.x+=this.m_invMass*impulse.x;this.m_linearVelocity.y+=this.m_invMass*impulse.y;}};_proto41.ApplyAngularImpulse=function ApplyAngularImpulse(impulse,wake){if(wake===void 0){wake=true;}if(this.m_type!==exports$1.b2BodyType.b2_dynamicBody){return;}if(wake&&!this.m_awakeFlag){this.SetAwake(true);}if(this.m_awakeFlag){this.m_angularVelocity+=this.m_invI*impulse;}};_proto41.GetMass=function GetMass(){return this.m_mass;};_proto41.GetInertia=function GetInertia(){return this.m_I+this.m_mass*b2Vec2.DotVV(this.m_sweep.localCenter,this.m_sweep.localCenter);};_proto41.GetMassData=function GetMassData(data){data.mass=this.m_mass;data.I=this.m_I+this.m_mass*b2Vec2.DotVV(this.m_sweep.localCenter,this.m_sweep.localCenter);data.center.Copy(this.m_sweep.localCenter);return data;};_proto41.SetMassData=function SetMassData(massData){if(this.m_world.IsLocked()){throw new Error();}if(this.m_type!==exports$1.b2BodyType.b2_dynamicBody){return;}this.m_invMass=0;this.m_I=0;this.m_invI=0;this.m_mass=massData.mass;if(this.m_mass<=0){this.m_mass=1;}this.m_invMass=1/this.m_mass;if(massData.I>0&&!this.m_fixedRotationFlag){this.m_I=massData.I-this.m_mass*b2Vec2.DotVV(massData.center,massData.center);this.m_invI=1/this.m_I;}var oldCenter=b2Body.SetMassData_s_oldCenter.Copy(this.m_sweep.c);this.m_sweep.localCenter.Copy(massData.center);b2Transform.MulXV(this.m_xf,this.m_sweep.localCenter,this.m_sweep.c);this.m_sweep.c0.Copy(this.m_sweep.c);b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(this.m_sweep.c,oldCenter,b2Vec2.s_t0),this.m_linearVelocity);};_proto41.ResetMassData=function ResetMassData(){this.m_mass=0;this.m_invMass=0;this.m_I=0;this.m_invI=0;this.m_sweep.localCenter.SetZero();if(this.m_type===exports$1.b2BodyType.b2_staticBody||this.m_type===exports$1.b2BodyType.b2_kinematicBody){this.m_sweep.c0.Copy(this.m_xf.p);this.m_sweep.c.Copy(this.m_xf.p);this.m_sweep.a0=this.m_sweep.a;return;}var localCenter=b2Body.ResetMassData_s_localCenter.SetZero();for(var f=this.m_fixtureList;f;f=f.m_next){if(f.m_density===0){continue;}var massData=f.GetMassData(b2Body.ResetMassData_s_massData);this.m_mass+=massData.mass;localCenter.x+=massData.center.x*massData.mass;localCenter.y+=massData.center.y*massData.mass;this.m_I+=massData.I;}if(this.m_mass>0){this.m_invMass=1/this.m_mass;localCenter.x*=this.m_invMass;localCenter.y*=this.m_invMass;}else {this.m_mass=1;this.m_invMass=1;}if(this.m_I>0&&!this.m_fixedRotationFlag){this.m_I-=this.m_mass*b2Vec2.DotVV(localCenter,localCenter);this.m_invI=1/this.m_I;}else {this.m_I=0;this.m_invI=0;}var oldCenter=b2Body.ResetMassData_s_oldCenter.Copy(this.m_sweep.c);this.m_sweep.localCenter.Copy(localCenter);b2Transform.MulXV(this.m_xf,this.m_sweep.localCenter,this.m_sweep.c);this.m_sweep.c0.Copy(this.m_sweep.c);b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(this.m_sweep.c,oldCenter,b2Vec2.s_t0),this.m_linearVelocity);};_proto41.GetWorldPoint=function GetWorldPoint(localPoint,out){return b2Transform.MulXV(this.m_xf,localPoint,out);};_proto41.GetWorldVector=function GetWorldVector(localVector,out){return b2Rot.MulRV(this.m_xf.q,localVector,out);};_proto41.GetLocalPoint=function GetLocalPoint(worldPoint,out){return b2Transform.MulTXV(this.m_xf,worldPoint,out);};_proto41.GetLocalVector=function GetLocalVector(worldVector,out){return b2Rot.MulTRV(this.m_xf.q,worldVector,out);};_proto41.GetLinearVelocityFromWorldPoint=function GetLinearVelocityFromWorldPoint(worldPoint,out){return b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(worldPoint,this.m_sweep.c,b2Vec2.s_t0),out);};_proto41.GetLinearVelocityFromLocalPoint=function GetLinearVelocityFromLocalPoint(localPoint,out){return this.GetLinearVelocityFromWorldPoint(this.GetWorldPoint(localPoint,out),out);};_proto41.GetLinearDamping=function GetLinearDamping(){return this.m_linearDamping;};_proto41.SetLinearDamping=function SetLinearDamping(linearDamping){this.m_linearDamping=linearDamping;};_proto41.GetAngularDamping=function GetAngularDamping(){return this.m_angularDamping;};_proto41.SetAngularDamping=function SetAngularDamping(angularDamping){this.m_angularDamping=angularDamping;};_proto41.GetGravityScale=function GetGravityScale(){return this.m_gravityScale;};_proto41.SetGravityScale=function SetGravityScale(scale){this.m_gravityScale=scale;};_proto41.SetType=function SetType(type){if(this.m_world.IsLocked()){throw new Error();}if(this.m_type===type){return;}this.m_type=type;this.ResetMassData();if(this.m_type===exports$1.b2BodyType.b2_staticBody){this.m_linearVelocity.SetZero();this.m_angularVelocity=0;this.m_sweep.a0=this.m_sweep.a;this.m_sweep.c0.Copy(this.m_sweep.c);this.SynchronizeFixtures();}this.SetAwake(true);this.m_force.SetZero();this.m_torque=0;var ce=this.m_contactList;while(ce){var ce0=ce;ce=ce.next;this.m_world.m_contactManager.Destroy(ce0.contact);}this.m_contactList=null;for(var f=this.m_fixtureList;f;f=f.m_next){f.TouchProxies();}};_proto41.GetType=function GetType(){return this.m_type;};_proto41.SetBullet=function SetBullet(flag){this.m_bulletFlag=flag;};_proto41.IsBullet=function IsBullet(){return this.m_bulletFlag;};_proto41.SetSleepingAllowed=function SetSleepingAllowed(flag){this.m_autoSleepFlag=flag;if(!flag){this.SetAwake(true);}};_proto41.IsSleepingAllowed=function IsSleepingAllowed(){return this.m_autoSleepFlag;};_proto41.SetAwake=function SetAwake(flag){if(flag){this.m_awakeFlag=true;this.m_sleepTime=0;}else {this.m_awakeFlag=false;this.m_sleepTime=0;this.m_linearVelocity.SetZero();this.m_angularVelocity=0;this.m_force.SetZero();this.m_torque=0;}};_proto41.IsAwake=function IsAwake(){return this.m_awakeFlag;};_proto41.SetActive=function SetActive(flag){if(this.m_world.IsLocked()){throw new Error();}if(flag===this.IsActive()){return;}this.m_activeFlag=flag;if(flag){for(var f=this.m_fixtureList;f;f=f.m_next){f.CreateProxies();}}else {for(var _f=this.m_fixtureList;_f;_f=_f.m_next){_f.DestroyProxies();}var ce=this.m_contactList;while(ce){var ce0=ce;ce=ce.next;this.m_world.m_contactManager.Destroy(ce0.contact);}this.m_contactList=null;}};_proto41.IsActive=function IsActive(){return this.m_activeFlag;};_proto41.SetFixedRotation=function SetFixedRotation(flag){if(this.m_fixedRotationFlag===flag){return;}this.m_fixedRotationFlag=flag;this.m_angularVelocity=0;this.ResetMassData();};_proto41.IsFixedRotation=function IsFixedRotation(){return this.m_fixedRotationFlag;};_proto41.GetFixtureList=function GetFixtureList(){return this.m_fixtureList;};_proto41.GetJointList=function GetJointList(){return this.m_jointList;};_proto41.GetContactList=function GetContactList(){return this.m_contactList;};_proto41.GetNext=function GetNext(){return this.m_next;};_proto41.GetUserData=function GetUserData(){return this.m_userData;};_proto41.SetUserData=function SetUserData(data){this.m_userData=data;};_proto41.GetWorld=function GetWorld(){return this.m_world;};_proto41.Dump=function Dump(log){var bodyIndex=this.m_islandIndex;log("{\n");log("  const bd: b2BodyDef = new b2BodyDef();\n");var type_str="";switch(this.m_type){case exports$1.b2BodyType.b2_staticBody:type_str="b2BodyType.b2_staticBody";break;case exports$1.b2BodyType.b2_kinematicBody:type_str="b2BodyType.b2_kinematicBody";break;case exports$1.b2BodyType.b2_dynamicBody:type_str="b2BodyType.b2_dynamicBody";break;}log("  bd.type = %s;\n",type_str);log("  bd.position.Set(%.15f, %.15f);\n",this.m_xf.p.x,this.m_xf.p.y);log("  bd.angle = %.15f;\n",this.m_sweep.a);log("  bd.linearVelocity.Set(%.15f, %.15f);\n",this.m_linearVelocity.x,this.m_linearVelocity.y);log("  bd.angularVelocity = %.15f;\n",this.m_angularVelocity);log("  bd.linearDamping = %.15f;\n",this.m_linearDamping);log("  bd.angularDamping = %.15f;\n",this.m_angularDamping);log("  bd.allowSleep = %s;\n",this.m_autoSleepFlag?"true":"false");log("  bd.awake = %s;\n",this.m_awakeFlag?"true":"false");log("  bd.fixedRotation = %s;\n",this.m_fixedRotationFlag?"true":"false");log("  bd.bullet = %s;\n",this.m_bulletFlag?"true":"false");log("  bd.active = %s;\n",this.m_activeFlag?"true":"false");log("  bd.gravityScale = %.15f;\n",this.m_gravityScale);log("\n");log("  bodies[%d] = this.m_world.CreateBody(bd);\n",this.m_islandIndex);log("\n");for(var f=this.m_fixtureList;f;f=f.m_next){log("  {\n");f.Dump(log,bodyIndex);log("  }\n");}log("}\n");};_proto41.SynchronizeFixtures=function SynchronizeFixtures(){var xf1=b2Body.SynchronizeFixtures_s_xf1;xf1.q.SetAngle(this.m_sweep.a0);b2Rot.MulRV(xf1.q,this.m_sweep.localCenter,xf1.p);b2Vec2.SubVV(this.m_sweep.c0,xf1.p,xf1.p);var displacement=b2Vec2.SubVV(this.m_sweep.c,this.m_sweep.c0,b2Body.SynchronizeFixtures_s_displacement);for(var f=this.m_fixtureList;f;f=f.m_next){f.SynchronizeProxies(xf1,this.m_xf,displacement);}};_proto41.SynchronizeTransform=function SynchronizeTransform(){this.m_xf.q.SetAngle(this.m_sweep.a);b2Rot.MulRV(this.m_xf.q,this.m_sweep.localCenter,this.m_xf.p);b2Vec2.SubVV(this.m_sweep.c,this.m_xf.p,this.m_xf.p);};_proto41.ShouldCollide=function ShouldCollide(other){if(this.m_type===exports$1.b2BodyType.b2_staticBody&&other.m_type===exports$1.b2BodyType.b2_staticBody){return false;}return this.ShouldCollideConnected(other);};_proto41.ShouldCollideConnected=function ShouldCollideConnected(other){for(var jn=this.m_jointList;jn;jn=jn.next){if(jn.other===other){if(!jn.joint.m_collideConnected){return false;}}}return true;};_proto41.Advance=function Advance(alpha){this.m_sweep.Advance(alpha);this.m_sweep.c.Copy(this.m_sweep.c0);this.m_sweep.a=this.m_sweep.a0;this.m_xf.q.SetAngle(this.m_sweep.a);b2Rot.MulRV(this.m_xf.q,this.m_sweep.localCenter,this.m_xf.p);b2Vec2.SubVV(this.m_sweep.c,this.m_xf.p,this.m_xf.p);};_proto41.GetControllerList=function GetControllerList(){return this.m_controllerList;};_proto41.GetControllerCount=function GetControllerCount(){return this.m_controllerCount;};return b2Body;}();b2Body.CreateFixtureShapeDensity_s_def=new b2FixtureDef();b2Body.SetMassData_s_oldCenter=new b2Vec2();b2Body.ResetMassData_s_localCenter=new b2Vec2();b2Body.ResetMassData_s_oldCenter=new b2Vec2();b2Body.ResetMassData_s_massData=new b2MassData();b2Body.SynchronizeFixtures_s_xf1=new b2Transform();b2Body.SynchronizeFixtures_s_displacement=new b2Vec2();(function(b2JointType){b2JointType[b2JointType["e_unknownJoint"]=0]="e_unknownJoint";b2JointType[b2JointType["e_revoluteJoint"]=1]="e_revoluteJoint";b2JointType[b2JointType["e_prismaticJoint"]=2]="e_prismaticJoint";b2JointType[b2JointType["e_distanceJoint"]=3]="e_distanceJoint";b2JointType[b2JointType["e_pulleyJoint"]=4]="e_pulleyJoint";b2JointType[b2JointType["e_mouseJoint"]=5]="e_mouseJoint";b2JointType[b2JointType["e_gearJoint"]=6]="e_gearJoint";b2JointType[b2JointType["e_wheelJoint"]=7]="e_wheelJoint";b2JointType[b2JointType["e_weldJoint"]=8]="e_weldJoint";b2JointType[b2JointType["e_frictionJoint"]=9]="e_frictionJoint";b2JointType[b2JointType["e_ropeJoint"]=10]="e_ropeJoint";b2JointType[b2JointType["e_motorJoint"]=11]="e_motorJoint";b2JointType[b2JointType["e_areaJoint"]=12]="e_areaJoint";})(exports$1.b2JointType||(exports$1.b2JointType={}));(function(b2LimitState){b2LimitState[b2LimitState["e_inactiveLimit"]=0]="e_inactiveLimit";b2LimitState[b2LimitState["e_atLowerLimit"]=1]="e_atLowerLimit";b2LimitState[b2LimitState["e_atUpperLimit"]=2]="e_atUpperLimit";b2LimitState[b2LimitState["e_equalLimits"]=3]="e_equalLimits";})(exports$1.b2LimitState||(exports$1.b2LimitState={}));var b2Jacobian=function(){function b2Jacobian(){this.linear=new b2Vec2();this.angularA=0;this.angularB=0;}var _proto42=b2Jacobian.prototype;_proto42.SetZero=function SetZero(){this.linear.SetZero();this.angularA=0;this.angularB=0;return this;};_proto42.Set=function Set(x,a1,a2){this.linear.Copy(x);this.angularA=a1;this.angularB=a2;return this;};return b2Jacobian;}();var b2JointEdge=function(){function b2JointEdge(joint){this._other=null;this.prev=null;this.next=null;this.joint=joint;}var _proto43=b2JointEdge.prototype;_proto43.Reset=function Reset(){this._other=null;this.prev=null;this.next=null;};_createClass(b2JointEdge,[{key:"other",get:function get(){if(this._other===null){throw new Error();}return this._other;},set:function set(value){if(this._other!==null){throw new Error();}this._other=value;}}]);return b2JointEdge;}();var b2JointDef=function b2JointDef(type){this.type=exports$1.b2JointType.e_unknownJoint;this.userData=null;this.collideConnected=false;this.type=type;};var b2Joint=function(){function b2Joint(def){this.m_type=exports$1.b2JointType.e_unknownJoint;this.m_prev=null;this.m_next=null;this.m_edgeA=new b2JointEdge(this);this.m_edgeB=new b2JointEdge(this);this.m_index=0;this.m_islandFlag=false;this.m_collideConnected=false;this.m_userData=null;this.m_type=def.type;this.m_edgeA.other=def.bodyB;this.m_edgeB.other=def.bodyA;this.m_bodyA=def.bodyA;this.m_bodyB=def.bodyB;this.m_collideConnected=b2Maybe(def.collideConnected,false);this.m_userData=b2Maybe(def.userData,null);}var _proto44=b2Joint.prototype;_proto44.GetType=function GetType(){return this.m_type;};_proto44.GetBodyA=function GetBodyA(){return this.m_bodyA;};_proto44.GetBodyB=function GetBodyB(){return this.m_bodyB;};_proto44.GetNext=function GetNext(){return this.m_next;};_proto44.GetUserData=function GetUserData(){return this.m_userData;};_proto44.SetUserData=function SetUserData(data){this.m_userData=data;};_proto44.IsActive=function IsActive(){return this.m_bodyA.IsActive()&&this.m_bodyB.IsActive();};_proto44.GetCollideConnected=function GetCollideConnected(){return this.m_collideConnected;};_proto44.Dump=function Dump(log){log("// Dump is not supported for this joint type.\n");};_proto44.ShiftOrigin=function ShiftOrigin(newOrigin){};return b2Joint;}();var b2DistanceJointDef=function(_b2JointDef){_inheritsLoose(b2DistanceJointDef,_b2JointDef);function b2DistanceJointDef(){var _this6;_this6=_b2JointDef.call(this,exports$1.b2JointType.e_distanceJoint)||this;_this6.localAnchorA=new b2Vec2();_this6.localAnchorB=new b2Vec2();_this6.length=1;_this6.frequencyHz=0;_this6.dampingRatio=0;return _this6;}var _proto45=b2DistanceJointDef.prototype;_proto45.Initialize=function Initialize(b1,b2,anchor1,anchor2){this.bodyA=b1;this.bodyB=b2;this.bodyA.GetLocalPoint(anchor1,this.localAnchorA);this.bodyB.GetLocalPoint(anchor2,this.localAnchorB);this.length=b2Vec2.DistanceVV(anchor1,anchor2);this.frequencyHz=0;this.dampingRatio=0;};return b2DistanceJointDef;}(b2JointDef);var b2DistanceJoint=function(_b2Joint){_inheritsLoose(b2DistanceJoint,_b2Joint);function b2DistanceJoint(def){var _this7;_this7=_b2Joint.call(this,def)||this;_this7.m_frequencyHz=0;_this7.m_dampingRatio=0;_this7.m_bias=0;_this7.m_localAnchorA=new b2Vec2();_this7.m_localAnchorB=new b2Vec2();_this7.m_gamma=0;_this7.m_impulse=0;_this7.m_length=0;_this7.m_indexA=0;_this7.m_indexB=0;_this7.m_u=new b2Vec2();_this7.m_rA=new b2Vec2();_this7.m_rB=new b2Vec2();_this7.m_localCenterA=new b2Vec2();_this7.m_localCenterB=new b2Vec2();_this7.m_invMassA=0;_this7.m_invMassB=0;_this7.m_invIA=0;_this7.m_invIB=0;_this7.m_mass=0;_this7.m_qA=new b2Rot();_this7.m_qB=new b2Rot();_this7.m_lalcA=new b2Vec2();_this7.m_lalcB=new b2Vec2();_this7.m_frequencyHz=b2Maybe(def.frequencyHz,0);_this7.m_dampingRatio=b2Maybe(def.dampingRatio,0);_this7.m_localAnchorA.Copy(def.localAnchorA);_this7.m_localAnchorB.Copy(def.localAnchorB);_this7.m_length=def.length;return _this7;}var _proto46=b2DistanceJoint.prototype;_proto46.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto46.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto46.GetReactionForce=function GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse*this.m_u.x;out.y=inv_dt*this.m_impulse*this.m_u.y;return out;};_proto46.GetReactionTorque=function GetReactionTorque(inv_dt){return 0;};_proto46.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto46.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto46.SetLength=function SetLength(length){this.m_length=length;};_proto46.Length=function Length(){return this.m_length;};_proto46.SetFrequency=function SetFrequency(hz){this.m_frequencyHz=hz;};_proto46.GetFrequency=function GetFrequency(){return this.m_frequencyHz;};_proto46.SetDampingRatio=function SetDampingRatio(ratio){this.m_dampingRatio=ratio;};_proto46.GetDampingRatio=function GetDampingRatio(){return this.m_dampingRatio;};_proto46.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2DistanceJointDef = new b2DistanceJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.length = %.15f;\n",this.m_length);log("  jd.frequencyHz = %.15f;\n",this.m_frequencyHz);log("  jd.dampingRatio = %.15f;\n",this.m_dampingRatio);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);};_proto46.InitVelocityConstraints=function InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);this.m_u.x=cB.x+this.m_rB.x-cA.x-this.m_rA.x;this.m_u.y=cB.y+this.m_rB.y-cA.y-this.m_rA.y;var length=this.m_u.Length();if(length>b2_linearSlop){this.m_u.SelfMul(1/length);}else {this.m_u.SetZero();}var crAu=b2Vec2.CrossVV(this.m_rA,this.m_u);var crBu=b2Vec2.CrossVV(this.m_rB,this.m_u);var invMass=this.m_invMassA+this.m_invIA*crAu*crAu+this.m_invMassB+this.m_invIB*crBu*crBu;this.m_mass=invMass!==0?1/invMass:0;if(this.m_frequencyHz>0){var C=length-this.m_length;var omega=2*b2_pi*this.m_frequencyHz;var d=2*this.m_mass*this.m_dampingRatio*omega;var k=this.m_mass*omega*omega;var h=data.step.dt;this.m_gamma=h*(d+h*k);this.m_gamma=this.m_gamma!==0?1/this.m_gamma:0;this.m_bias=C*h*k*this.m_gamma;invMass+=this.m_gamma;this.m_mass=invMass!==0?1/invMass:0;}else {this.m_gamma=0;this.m_bias=0;}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;var P=b2Vec2.MulSV(this.m_impulse,this.m_u,b2DistanceJoint.InitVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P);}else {this.m_impulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto46.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2DistanceJoint.SolveVelocityConstraints_s_vpA);var vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2DistanceJoint.SolveVelocityConstraints_s_vpB);var Cdot=b2Vec2.DotVV(this.m_u,b2Vec2.SubVV(vpB,vpA,b2Vec2.s_t0));var impulse=-this.m_mass*(Cdot+this.m_bias+this.m_gamma*this.m_impulse);this.m_impulse+=impulse;var P=b2Vec2.MulSV(impulse,this.m_u,b2DistanceJoint.SolveVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P);data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto46.SolvePositionConstraints=function SolvePositionConstraints(data){if(this.m_frequencyHz>0){return true;}var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var u=this.m_u;u.x=cB.x+rB.x-cA.x-rA.x;u.y=cB.y+rB.y-cA.y-rA.y;var length=this.m_u.Normalize();var C=length-this.m_length;C=b2Clamp(C,-b2_maxLinearCorrection,b2_maxLinearCorrection);var impulse=-this.m_mass*C;var P=b2Vec2.MulSV(impulse,u,b2DistanceJoint.SolvePositionConstraints_s_P);cA.SelfMulSub(this.m_invMassA,P);aA-=this.m_invIA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(this.m_invMassB,P);aB+=this.m_invIB*b2Vec2.CrossVV(rB,P);data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return b2Abs(C)<b2_linearSlop;};return b2DistanceJoint;}(b2Joint);b2DistanceJoint.InitVelocityConstraints_s_P=new b2Vec2();b2DistanceJoint.SolveVelocityConstraints_s_vpA=new b2Vec2();b2DistanceJoint.SolveVelocityConstraints_s_vpB=new b2Vec2();b2DistanceJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2DistanceJoint.SolvePositionConstraints_s_P=new b2Vec2();var b2AreaJointDef=function(_b2JointDef2){_inheritsLoose(b2AreaJointDef,_b2JointDef2);function b2AreaJointDef(){var _this8;_this8=_b2JointDef2.call(this,exports$1.b2JointType.e_areaJoint)||this;_this8.bodies=[];_this8.frequencyHz=0;_this8.dampingRatio=0;return _this8;}var _proto47=b2AreaJointDef.prototype;_proto47.AddBody=function AddBody(body){this.bodies.push(body);if(this.bodies.length===1){this.bodyA=body;}else if(this.bodies.length===2){this.bodyB=body;}};return b2AreaJointDef;}(b2JointDef);var b2AreaJoint=function(_b2Joint2){_inheritsLoose(b2AreaJoint,_b2Joint2);function b2AreaJoint(def){var _this9;_this9=_b2Joint2.call(this,def)||this;_this9.m_frequencyHz=0;_this9.m_dampingRatio=0;_this9.m_impulse=0;_this9.m_targetArea=0;_this9.m_delta=new b2Vec2();_this9.m_bodies=def.bodies;_this9.m_frequencyHz=b2Maybe(def.frequencyHz,0);_this9.m_dampingRatio=b2Maybe(def.dampingRatio,0);_this9.m_targetLengths=b2MakeNumberArray(def.bodies.length);_this9.m_normals=b2Vec2.MakeArray(def.bodies.length);_this9.m_joints=[];_this9.m_deltas=b2Vec2.MakeArray(def.bodies.length);var djd=new b2DistanceJointDef();djd.frequencyHz=_this9.m_frequencyHz;djd.dampingRatio=_this9.m_dampingRatio;_this9.m_targetArea=0;for(var i=0;i<_this9.m_bodies.length;++i){var body=_this9.m_bodies[i];var next=_this9.m_bodies[(i+1)%_this9.m_bodies.length];var body_c=body.GetWorldCenter();var next_c=next.GetWorldCenter();_this9.m_targetLengths[i]=b2Vec2.DistanceVV(body_c,next_c);_this9.m_targetArea+=b2Vec2.CrossVV(body_c,next_c);djd.Initialize(body,next,body_c,next_c);_this9.m_joints[i]=body.GetWorld().CreateJoint(djd);}_this9.m_targetArea*=0.5;return _this9;}var _proto48=b2AreaJoint.prototype;_proto48.GetAnchorA=function GetAnchorA(out){return out;};_proto48.GetAnchorB=function GetAnchorB(out){return out;};_proto48.GetReactionForce=function GetReactionForce(inv_dt,out){return out;};_proto48.GetReactionTorque=function GetReactionTorque(inv_dt){return 0;};_proto48.SetFrequency=function SetFrequency(hz){this.m_frequencyHz=hz;for(var i=0;i<this.m_joints.length;++i){this.m_joints[i].SetFrequency(hz);}};_proto48.GetFrequency=function GetFrequency(){return this.m_frequencyHz;};_proto48.SetDampingRatio=function SetDampingRatio(ratio){this.m_dampingRatio=ratio;for(var i=0;i<this.m_joints.length;++i){this.m_joints[i].SetDampingRatio(ratio);}};_proto48.GetDampingRatio=function GetDampingRatio(){return this.m_dampingRatio;};_proto48.Dump=function Dump(log){log("Area joint dumping is not supported.\n");};_proto48.InitVelocityConstraints=function InitVelocityConstraints(data){for(var i=0;i<this.m_bodies.length;++i){var prev=this.m_bodies[(i+this.m_bodies.length-1)%this.m_bodies.length];var next=this.m_bodies[(i+1)%this.m_bodies.length];var prev_c=data.positions[prev.m_islandIndex].c;var next_c=data.positions[next.m_islandIndex].c;var delta=this.m_deltas[i];b2Vec2.SubVV(next_c,prev_c,delta);}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;for(var _i12=0;_i12<this.m_bodies.length;++_i12){var body=this.m_bodies[_i12];var body_v=data.velocities[body.m_islandIndex].v;var _delta=this.m_deltas[_i12];body_v.x+=body.m_invMass*_delta.y*0.5*this.m_impulse;body_v.y+=body.m_invMass*-_delta.x*0.5*this.m_impulse;}}else {this.m_impulse=0;}};_proto48.SolveVelocityConstraints=function SolveVelocityConstraints(data){var dotMassSum=0;var crossMassSum=0;for(var i=0;i<this.m_bodies.length;++i){var body=this.m_bodies[i];var body_v=data.velocities[body.m_islandIndex].v;var delta=this.m_deltas[i];dotMassSum+=delta.LengthSquared()/body.GetMass();crossMassSum+=b2Vec2.CrossVV(body_v,delta);}var lambda=-2*crossMassSum/dotMassSum;this.m_impulse+=lambda;for(var _i13=0;_i13<this.m_bodies.length;++_i13){var _body=this.m_bodies[_i13];var _body_v=data.velocities[_body.m_islandIndex].v;var _delta2=this.m_deltas[_i13];_body_v.x+=_body.m_invMass*_delta2.y*0.5*lambda;_body_v.y+=_body.m_invMass*-_delta2.x*0.5*lambda;}};_proto48.SolvePositionConstraints=function SolvePositionConstraints(data){var perimeter=0;var area=0;for(var i=0;i<this.m_bodies.length;++i){var body=this.m_bodies[i];var next=this.m_bodies[(i+1)%this.m_bodies.length];var body_c=data.positions[body.m_islandIndex].c;var next_c=data.positions[next.m_islandIndex].c;var delta=b2Vec2.SubVV(next_c,body_c,this.m_delta);var dist=delta.Length();if(dist<b2_epsilon){dist=1;}this.m_normals[i].x=delta.y/dist;this.m_normals[i].y=-delta.x/dist;perimeter+=dist;area+=b2Vec2.CrossVV(body_c,next_c);}area*=0.5;var deltaArea=this.m_targetArea-area;var toExtrude=0.5*deltaArea/perimeter;var done=true;for(var _i14=0;_i14<this.m_bodies.length;++_i14){var _body2=this.m_bodies[_i14];var _body_c=data.positions[_body2.m_islandIndex].c;var next_i=(_i14+1)%this.m_bodies.length;var _delta3=b2Vec2.AddVV(this.m_normals[_i14],this.m_normals[next_i],this.m_delta);_delta3.SelfMul(toExtrude);var norm_sq=_delta3.LengthSquared();if(norm_sq>b2Sq(b2_maxLinearCorrection)){_delta3.SelfMul(b2_maxLinearCorrection/b2Sqrt(norm_sq));}if(norm_sq>b2Sq(b2_linearSlop)){done=false;}_body_c.x+=_delta3.x;_body_c.y+=_delta3.y;}return done;};return b2AreaJoint;}(b2Joint);var b2FrictionJointDef=function(_b2JointDef3){_inheritsLoose(b2FrictionJointDef,_b2JointDef3);function b2FrictionJointDef(){var _this10;_this10=_b2JointDef3.call(this,exports$1.b2JointType.e_frictionJoint)||this;_this10.localAnchorA=new b2Vec2();_this10.localAnchorB=new b2Vec2();_this10.maxForce=0;_this10.maxTorque=0;return _this10;}var _proto49=b2FrictionJointDef.prototype;_proto49.Initialize=function Initialize(bA,bB,anchor){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);};return b2FrictionJointDef;}(b2JointDef);var b2FrictionJoint=function(_b2Joint3){_inheritsLoose(b2FrictionJoint,_b2Joint3);function b2FrictionJoint(def){var _this11;_this11=_b2Joint3.call(this,def)||this;_this11.m_localAnchorA=new b2Vec2();_this11.m_localAnchorB=new b2Vec2();_this11.m_linearImpulse=new b2Vec2();_this11.m_angularImpulse=0;_this11.m_maxForce=0;_this11.m_maxTorque=0;_this11.m_indexA=0;_this11.m_indexB=0;_this11.m_rA=new b2Vec2();_this11.m_rB=new b2Vec2();_this11.m_localCenterA=new b2Vec2();_this11.m_localCenterB=new b2Vec2();_this11.m_invMassA=0;_this11.m_invMassB=0;_this11.m_invIA=0;_this11.m_invIB=0;_this11.m_linearMass=new b2Mat22();_this11.m_angularMass=0;_this11.m_qA=new b2Rot();_this11.m_qB=new b2Rot();_this11.m_lalcA=new b2Vec2();_this11.m_lalcB=new b2Vec2();_this11.m_K=new b2Mat22();_this11.m_localAnchorA.Copy(def.localAnchorA);_this11.m_localAnchorB.Copy(def.localAnchorB);_this11.m_linearImpulse.SetZero();_this11.m_maxForce=b2Maybe(def.maxForce,0);_this11.m_maxTorque=b2Maybe(def.maxTorque,0);_this11.m_linearMass.SetZero();return _this11;}var _proto50=b2FrictionJoint.prototype;_proto50.InitVelocityConstraints=function InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var K=this.m_K;K.ex.x=mA+mB+iA*rA.y*rA.y+iB*rB.y*rB.y;K.ex.y=-iA*rA.x*rA.y-iB*rB.x*rB.y;K.ey.x=K.ex.y;K.ey.y=mA+mB+iA*rA.x*rA.x+iB*rB.x*rB.x;K.GetInverse(this.m_linearMass);this.m_angularMass=iA+iB;if(this.m_angularMass>0){this.m_angularMass=1/this.m_angularMass;}if(data.step.warmStarting){this.m_linearImpulse.SelfMul(data.step.dtRatio);this.m_angularImpulse*=data.step.dtRatio;var P=this.m_linearImpulse;vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+this.m_angularImpulse);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+this.m_angularImpulse);}else {this.m_linearImpulse.SetZero();this.m_angularImpulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto50.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var h=data.step.dt;{var Cdot=wB-wA;var impulse=-this.m_angularMass*Cdot;var oldImpulse=this.m_angularImpulse;var maxImpulse=h*this.m_maxTorque;this.m_angularImpulse=b2Clamp(this.m_angularImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_angularImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse;}{var Cdot_v2=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2FrictionJoint.SolveVelocityConstraints_s_Cdot_v2);var impulseV=b2Mat22.MulMV(this.m_linearMass,Cdot_v2,b2FrictionJoint.SolveVelocityConstraints_s_impulseV).SelfNeg();var oldImpulseV=b2FrictionJoint.SolveVelocityConstraints_s_oldImpulseV.Copy(this.m_linearImpulse);this.m_linearImpulse.SelfAdd(impulseV);var _maxImpulse=h*this.m_maxForce;if(this.m_linearImpulse.LengthSquared()>_maxImpulse*_maxImpulse){this.m_linearImpulse.Normalize();this.m_linearImpulse.SelfMul(_maxImpulse);}b2Vec2.SubVV(this.m_linearImpulse,oldImpulseV,impulseV);vA.SelfMulSub(mA,impulseV);wA-=iA*b2Vec2.CrossVV(this.m_rA,impulseV);vB.SelfMulAdd(mB,impulseV);wB+=iB*b2Vec2.CrossVV(this.m_rB,impulseV);}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto50.SolvePositionConstraints=function SolvePositionConstraints(data){return true;};_proto50.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto50.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto50.GetReactionForce=function GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_linearImpulse.x;out.y=inv_dt*this.m_linearImpulse.y;return out;};_proto50.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_angularImpulse;};_proto50.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto50.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto50.SetMaxForce=function SetMaxForce(force){this.m_maxForce=force;};_proto50.GetMaxForce=function GetMaxForce(){return this.m_maxForce;};_proto50.SetMaxTorque=function SetMaxTorque(torque){this.m_maxTorque=torque;};_proto50.GetMaxTorque=function GetMaxTorque(){return this.m_maxTorque;};_proto50.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2FrictionJointDef = new b2FrictionJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.maxForce = %.15f;\n",this.m_maxForce);log("  jd.maxTorque = %.15f;\n",this.m_maxTorque);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);};return b2FrictionJoint;}(b2Joint);b2FrictionJoint.SolveVelocityConstraints_s_Cdot_v2=new b2Vec2();b2FrictionJoint.SolveVelocityConstraints_s_impulseV=new b2Vec2();b2FrictionJoint.SolveVelocityConstraints_s_oldImpulseV=new b2Vec2();var b2GearJointDef=function(_b2JointDef4){_inheritsLoose(b2GearJointDef,_b2JointDef4);function b2GearJointDef(){var _this12;_this12=_b2JointDef4.call(this,exports$1.b2JointType.e_gearJoint)||this;_this12.ratio=1;return _this12;}return b2GearJointDef;}(b2JointDef);var b2GearJoint=function(_b2Joint4){_inheritsLoose(b2GearJoint,_b2Joint4);function b2GearJoint(def){var _this13;_this13=_b2Joint4.call(this,def)||this;_this13.m_typeA=exports$1.b2JointType.e_unknownJoint;_this13.m_typeB=exports$1.b2JointType.e_unknownJoint;_this13.m_localAnchorA=new b2Vec2();_this13.m_localAnchorB=new b2Vec2();_this13.m_localAnchorC=new b2Vec2();_this13.m_localAnchorD=new b2Vec2();_this13.m_localAxisC=new b2Vec2();_this13.m_localAxisD=new b2Vec2();_this13.m_referenceAngleA=0;_this13.m_referenceAngleB=0;_this13.m_constant=0;_this13.m_ratio=0;_this13.m_impulse=0;_this13.m_indexA=0;_this13.m_indexB=0;_this13.m_indexC=0;_this13.m_indexD=0;_this13.m_lcA=new b2Vec2();_this13.m_lcB=new b2Vec2();_this13.m_lcC=new b2Vec2();_this13.m_lcD=new b2Vec2();_this13.m_mA=0;_this13.m_mB=0;_this13.m_mC=0;_this13.m_mD=0;_this13.m_iA=0;_this13.m_iB=0;_this13.m_iC=0;_this13.m_iD=0;_this13.m_JvAC=new b2Vec2();_this13.m_JvBD=new b2Vec2();_this13.m_JwA=0;_this13.m_JwB=0;_this13.m_JwC=0;_this13.m_JwD=0;_this13.m_mass=0;_this13.m_qA=new b2Rot();_this13.m_qB=new b2Rot();_this13.m_qC=new b2Rot();_this13.m_qD=new b2Rot();_this13.m_lalcA=new b2Vec2();_this13.m_lalcB=new b2Vec2();_this13.m_lalcC=new b2Vec2();_this13.m_lalcD=new b2Vec2();_this13.m_joint1=def.joint1;_this13.m_joint2=def.joint2;_this13.m_typeA=_this13.m_joint1.GetType();_this13.m_typeB=_this13.m_joint2.GetType();var coordinateA,coordinateB;_this13.m_bodyC=_this13.m_joint1.GetBodyA();_this13.m_bodyA=_this13.m_joint1.GetBodyB();var xfA=_this13.m_bodyA.m_xf;var aA=_this13.m_bodyA.m_sweep.a;var xfC=_this13.m_bodyC.m_xf;var aC=_this13.m_bodyC.m_sweep.a;if(_this13.m_typeA===exports$1.b2JointType.e_revoluteJoint){var revolute=def.joint1;_this13.m_localAnchorC.Copy(revolute.m_localAnchorA);_this13.m_localAnchorA.Copy(revolute.m_localAnchorB);_this13.m_referenceAngleA=revolute.m_referenceAngle;_this13.m_localAxisC.SetZero();coordinateA=aA-aC-_this13.m_referenceAngleA;}else {var prismatic=def.joint1;_this13.m_localAnchorC.Copy(prismatic.m_localAnchorA);_this13.m_localAnchorA.Copy(prismatic.m_localAnchorB);_this13.m_referenceAngleA=prismatic.m_referenceAngle;_this13.m_localAxisC.Copy(prismatic.m_localXAxisA);var pC=_this13.m_localAnchorC;var pA=b2Rot.MulTRV(xfC.q,b2Vec2.AddVV(b2Rot.MulRV(xfA.q,_this13.m_localAnchorA,b2Vec2.s_t0),b2Vec2.SubVV(xfA.p,xfC.p,b2Vec2.s_t1),b2Vec2.s_t0),b2Vec2.s_t0);coordinateA=b2Vec2.DotVV(b2Vec2.SubVV(pA,pC,b2Vec2.s_t0),_this13.m_localAxisC);}_this13.m_bodyD=_this13.m_joint2.GetBodyA();_this13.m_bodyB=_this13.m_joint2.GetBodyB();var xfB=_this13.m_bodyB.m_xf;var aB=_this13.m_bodyB.m_sweep.a;var xfD=_this13.m_bodyD.m_xf;var aD=_this13.m_bodyD.m_sweep.a;if(_this13.m_typeB===exports$1.b2JointType.e_revoluteJoint){var _revolute=def.joint2;_this13.m_localAnchorD.Copy(_revolute.m_localAnchorA);_this13.m_localAnchorB.Copy(_revolute.m_localAnchorB);_this13.m_referenceAngleB=_revolute.m_referenceAngle;_this13.m_localAxisD.SetZero();coordinateB=aB-aD-_this13.m_referenceAngleB;}else {var _prismatic=def.joint2;_this13.m_localAnchorD.Copy(_prismatic.m_localAnchorA);_this13.m_localAnchorB.Copy(_prismatic.m_localAnchorB);_this13.m_referenceAngleB=_prismatic.m_referenceAngle;_this13.m_localAxisD.Copy(_prismatic.m_localXAxisA);var pD=_this13.m_localAnchorD;var pB=b2Rot.MulTRV(xfD.q,b2Vec2.AddVV(b2Rot.MulRV(xfB.q,_this13.m_localAnchorB,b2Vec2.s_t0),b2Vec2.SubVV(xfB.p,xfD.p,b2Vec2.s_t1),b2Vec2.s_t0),b2Vec2.s_t0);coordinateB=b2Vec2.DotVV(b2Vec2.SubVV(pB,pD,b2Vec2.s_t0),_this13.m_localAxisD);}_this13.m_ratio=b2Maybe(def.ratio,1);_this13.m_constant=coordinateA+_this13.m_ratio*coordinateB;_this13.m_impulse=0;return _this13;}var _proto51=b2GearJoint.prototype;_proto51.InitVelocityConstraints=function InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_indexC=this.m_bodyC.m_islandIndex;this.m_indexD=this.m_bodyD.m_islandIndex;this.m_lcA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_lcB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_lcC.Copy(this.m_bodyC.m_sweep.localCenter);this.m_lcD.Copy(this.m_bodyD.m_sweep.localCenter);this.m_mA=this.m_bodyA.m_invMass;this.m_mB=this.m_bodyB.m_invMass;this.m_mC=this.m_bodyC.m_invMass;this.m_mD=this.m_bodyD.m_invMass;this.m_iA=this.m_bodyA.m_invI;this.m_iB=this.m_bodyB.m_invI;this.m_iC=this.m_bodyC.m_invI;this.m_iD=this.m_bodyD.m_invI;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var aC=data.positions[this.m_indexC].a;var vC=data.velocities[this.m_indexC].v;var wC=data.velocities[this.m_indexC].w;var aD=data.positions[this.m_indexD].a;var vD=data.velocities[this.m_indexD].v;var wD=data.velocities[this.m_indexD].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB),qC=this.m_qC.SetAngle(aC),qD=this.m_qD.SetAngle(aD);this.m_mass=0;if(this.m_typeA===exports$1.b2JointType.e_revoluteJoint){this.m_JvAC.SetZero();this.m_JwA=1;this.m_JwC=1;this.m_mass+=this.m_iA+this.m_iC;}else {var u=b2Rot.MulRV(qC,this.m_localAxisC,b2GearJoint.InitVelocityConstraints_s_u);b2Vec2.SubVV(this.m_localAnchorC,this.m_lcC,this.m_lalcC);var rC=b2Rot.MulRV(qC,this.m_lalcC,b2GearJoint.InitVelocityConstraints_s_rC);b2Vec2.SubVV(this.m_localAnchorA,this.m_lcA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,b2GearJoint.InitVelocityConstraints_s_rA);this.m_JvAC.Copy(u);this.m_JwC=b2Vec2.CrossVV(rC,u);this.m_JwA=b2Vec2.CrossVV(rA,u);this.m_mass+=this.m_mC+this.m_mA+this.m_iC*this.m_JwC*this.m_JwC+this.m_iA*this.m_JwA*this.m_JwA;}if(this.m_typeB===exports$1.b2JointType.e_revoluteJoint){this.m_JvBD.SetZero();this.m_JwB=this.m_ratio;this.m_JwD=this.m_ratio;this.m_mass+=this.m_ratio*this.m_ratio*(this.m_iB+this.m_iD);}else {var _u=b2Rot.MulRV(qD,this.m_localAxisD,b2GearJoint.InitVelocityConstraints_s_u);b2Vec2.SubVV(this.m_localAnchorD,this.m_lcD,this.m_lalcD);var rD=b2Rot.MulRV(qD,this.m_lalcD,b2GearJoint.InitVelocityConstraints_s_rD);b2Vec2.SubVV(this.m_localAnchorB,this.m_lcB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,b2GearJoint.InitVelocityConstraints_s_rB);b2Vec2.MulSV(this.m_ratio,_u,this.m_JvBD);this.m_JwD=this.m_ratio*b2Vec2.CrossVV(rD,_u);this.m_JwB=this.m_ratio*b2Vec2.CrossVV(rB,_u);this.m_mass+=this.m_ratio*this.m_ratio*(this.m_mD+this.m_mB)+this.m_iD*this.m_JwD*this.m_JwD+this.m_iB*this.m_JwB*this.m_JwB;}this.m_mass=this.m_mass>0?1/this.m_mass:0;if(data.step.warmStarting){vA.SelfMulAdd(this.m_mA*this.m_impulse,this.m_JvAC);wA+=this.m_iA*this.m_impulse*this.m_JwA;vB.SelfMulAdd(this.m_mB*this.m_impulse,this.m_JvBD);wB+=this.m_iB*this.m_impulse*this.m_JwB;vC.SelfMulSub(this.m_mC*this.m_impulse,this.m_JvAC);wC-=this.m_iC*this.m_impulse*this.m_JwC;vD.SelfMulSub(this.m_mD*this.m_impulse,this.m_JvBD);wD-=this.m_iD*this.m_impulse*this.m_JwD;}else {this.m_impulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;data.velocities[this.m_indexC].w=wC;data.velocities[this.m_indexD].w=wD;};_proto51.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var vC=data.velocities[this.m_indexC].v;var wC=data.velocities[this.m_indexC].w;var vD=data.velocities[this.m_indexD].v;var wD=data.velocities[this.m_indexD].w;var Cdot=b2Vec2.DotVV(this.m_JvAC,b2Vec2.SubVV(vA,vC,b2Vec2.s_t0))+b2Vec2.DotVV(this.m_JvBD,b2Vec2.SubVV(vB,vD,b2Vec2.s_t0));Cdot+=this.m_JwA*wA-this.m_JwC*wC+(this.m_JwB*wB-this.m_JwD*wD);var impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;vA.SelfMulAdd(this.m_mA*impulse,this.m_JvAC);wA+=this.m_iA*impulse*this.m_JwA;vB.SelfMulAdd(this.m_mB*impulse,this.m_JvBD);wB+=this.m_iB*impulse*this.m_JwB;vC.SelfMulSub(this.m_mC*impulse,this.m_JvAC);wC-=this.m_iC*impulse*this.m_JwC;vD.SelfMulSub(this.m_mD*impulse,this.m_JvBD);wD-=this.m_iD*impulse*this.m_JwD;data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;data.velocities[this.m_indexC].w=wC;data.velocities[this.m_indexD].w=wD;};_proto51.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var cC=data.positions[this.m_indexC].c;var aC=data.positions[this.m_indexC].a;var cD=data.positions[this.m_indexD].c;var aD=data.positions[this.m_indexD].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB),qC=this.m_qC.SetAngle(aC),qD=this.m_qD.SetAngle(aD);var linearError=0;var coordinateA,coordinateB;var JvAC=this.m_JvAC,JvBD=this.m_JvBD;var JwA,JwB,JwC,JwD;var mass=0;if(this.m_typeA===exports$1.b2JointType.e_revoluteJoint){JvAC.SetZero();JwA=1;JwC=1;mass+=this.m_iA+this.m_iC;coordinateA=aA-aC-this.m_referenceAngleA;}else {var u=b2Rot.MulRV(qC,this.m_localAxisC,b2GearJoint.SolvePositionConstraints_s_u);var rC=b2Rot.MulRV(qC,this.m_lalcC,b2GearJoint.SolvePositionConstraints_s_rC);var rA=b2Rot.MulRV(qA,this.m_lalcA,b2GearJoint.SolvePositionConstraints_s_rA);JvAC.Copy(u);JwC=b2Vec2.CrossVV(rC,u);JwA=b2Vec2.CrossVV(rA,u);mass+=this.m_mC+this.m_mA+this.m_iC*JwC*JwC+this.m_iA*JwA*JwA;var pC=this.m_lalcC;var pA=b2Rot.MulTRV(qC,b2Vec2.AddVV(rA,b2Vec2.SubVV(cA,cC,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.s_t0);coordinateA=b2Vec2.DotVV(b2Vec2.SubVV(pA,pC,b2Vec2.s_t0),this.m_localAxisC);}if(this.m_typeB===exports$1.b2JointType.e_revoluteJoint){JvBD.SetZero();JwB=this.m_ratio;JwD=this.m_ratio;mass+=this.m_ratio*this.m_ratio*(this.m_iB+this.m_iD);coordinateB=aB-aD-this.m_referenceAngleB;}else {var _u2=b2Rot.MulRV(qD,this.m_localAxisD,b2GearJoint.SolvePositionConstraints_s_u);var rD=b2Rot.MulRV(qD,this.m_lalcD,b2GearJoint.SolvePositionConstraints_s_rD);var rB=b2Rot.MulRV(qB,this.m_lalcB,b2GearJoint.SolvePositionConstraints_s_rB);b2Vec2.MulSV(this.m_ratio,_u2,JvBD);JwD=this.m_ratio*b2Vec2.CrossVV(rD,_u2);JwB=this.m_ratio*b2Vec2.CrossVV(rB,_u2);mass+=this.m_ratio*this.m_ratio*(this.m_mD+this.m_mB)+this.m_iD*JwD*JwD+this.m_iB*JwB*JwB;var pD=this.m_lalcD;var pB=b2Rot.MulTRV(qD,b2Vec2.AddVV(rB,b2Vec2.SubVV(cB,cD,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.s_t0);coordinateB=b2Vec2.DotVV(b2Vec2.SubVV(pB,pD,b2Vec2.s_t0),this.m_localAxisD);}var C=coordinateA+this.m_ratio*coordinateB-this.m_constant;var impulse=0;if(mass>0){impulse=-C/mass;}cA.SelfMulAdd(this.m_mA*impulse,JvAC);aA+=this.m_iA*impulse*JwA;cB.SelfMulAdd(this.m_mB*impulse,JvBD);aB+=this.m_iB*impulse*JwB;cC.SelfMulSub(this.m_mC*impulse,JvAC);aC-=this.m_iC*impulse*JwC;cD.SelfMulSub(this.m_mD*impulse,JvBD);aD-=this.m_iD*impulse*JwD;data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;data.positions[this.m_indexC].a=aC;data.positions[this.m_indexD].a=aD;return linearError<b2_linearSlop;};_proto51.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto51.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto51.GetReactionForce=function GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt*this.m_impulse,this.m_JvAC,out);};_proto51.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_impulse*this.m_JwA;};_proto51.GetJoint1=function GetJoint1(){return this.m_joint1;};_proto51.GetJoint2=function GetJoint2(){return this.m_joint2;};_proto51.GetRatio=function GetRatio(){return this.m_ratio;};_proto51.SetRatio=function SetRatio(ratio){this.m_ratio=ratio;};_proto51.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var indexB=this.m_bodyB.m_islandIndex;var index1=this.m_joint1.m_index;var index2=this.m_joint2.m_index;log("  const jd: b2GearJointDef = new b2GearJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.joint1 = joints[%d];\n",index1);log("  jd.joint2 = joints[%d];\n",index2);log("  jd.ratio = %.15f;\n",this.m_ratio);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);};return b2GearJoint;}(b2Joint);b2GearJoint.InitVelocityConstraints_s_u=new b2Vec2();b2GearJoint.InitVelocityConstraints_s_rA=new b2Vec2();b2GearJoint.InitVelocityConstraints_s_rB=new b2Vec2();b2GearJoint.InitVelocityConstraints_s_rC=new b2Vec2();b2GearJoint.InitVelocityConstraints_s_rD=new b2Vec2();b2GearJoint.SolvePositionConstraints_s_u=new b2Vec2();b2GearJoint.SolvePositionConstraints_s_rA=new b2Vec2();b2GearJoint.SolvePositionConstraints_s_rB=new b2Vec2();b2GearJoint.SolvePositionConstraints_s_rC=new b2Vec2();b2GearJoint.SolvePositionConstraints_s_rD=new b2Vec2();var b2MotorJointDef=function(_b2JointDef5){_inheritsLoose(b2MotorJointDef,_b2JointDef5);function b2MotorJointDef(){var _this14;_this14=_b2JointDef5.call(this,exports$1.b2JointType.e_motorJoint)||this;_this14.linearOffset=new b2Vec2(0,0);_this14.angularOffset=0;_this14.maxForce=1;_this14.maxTorque=1;_this14.correctionFactor=0.3;return _this14;}var _proto52=b2MotorJointDef.prototype;_proto52.Initialize=function Initialize(bA,bB){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(this.bodyB.GetPosition(),this.linearOffset);var angleA=this.bodyA.GetAngle();var angleB=this.bodyB.GetAngle();this.angularOffset=angleB-angleA;};return b2MotorJointDef;}(b2JointDef);var b2MotorJoint=function(_b2Joint5){_inheritsLoose(b2MotorJoint,_b2Joint5);function b2MotorJoint(def){var _this15;_this15=_b2Joint5.call(this,def)||this;_this15.m_linearOffset=new b2Vec2();_this15.m_angularOffset=0;_this15.m_linearImpulse=new b2Vec2();_this15.m_angularImpulse=0;_this15.m_maxForce=0;_this15.m_maxTorque=0;_this15.m_correctionFactor=0.3;_this15.m_indexA=0;_this15.m_indexB=0;_this15.m_rA=new b2Vec2();_this15.m_rB=new b2Vec2();_this15.m_localCenterA=new b2Vec2();_this15.m_localCenterB=new b2Vec2();_this15.m_linearError=new b2Vec2();_this15.m_angularError=0;_this15.m_invMassA=0;_this15.m_invMassB=0;_this15.m_invIA=0;_this15.m_invIB=0;_this15.m_linearMass=new b2Mat22();_this15.m_angularMass=0;_this15.m_qA=new b2Rot();_this15.m_qB=new b2Rot();_this15.m_K=new b2Mat22();_this15.m_linearOffset.Copy(b2Maybe(def.linearOffset,b2Vec2.ZERO));_this15.m_linearImpulse.SetZero();_this15.m_maxForce=b2Maybe(def.maxForce,0);_this15.m_maxTorque=b2Maybe(def.maxTorque,0);_this15.m_correctionFactor=b2Maybe(def.correctionFactor,0.3);return _this15;}var _proto53=b2MotorJoint.prototype;_proto53.GetAnchorA=function GetAnchorA(out){var pos=this.m_bodyA.GetPosition();out.x=pos.x;out.y=pos.y;return out;};_proto53.GetAnchorB=function GetAnchorB(out){var pos=this.m_bodyB.GetPosition();out.x=pos.x;out.y=pos.y;return out;};_proto53.GetReactionForce=function GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt,this.m_linearImpulse,out);};_proto53.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_angularImpulse;};_proto53.SetLinearOffset=function SetLinearOffset(linearOffset){if(!b2Vec2.IsEqualToV(linearOffset,this.m_linearOffset)){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_linearOffset.Copy(linearOffset);}};_proto53.GetLinearOffset=function GetLinearOffset(){return this.m_linearOffset;};_proto53.SetAngularOffset=function SetAngularOffset(angularOffset){if(angularOffset!==this.m_angularOffset){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_angularOffset=angularOffset;}};_proto53.GetAngularOffset=function GetAngularOffset(){return this.m_angularOffset;};_proto53.SetMaxForce=function SetMaxForce(force){this.m_maxForce=force;};_proto53.GetMaxForce=function GetMaxForce(){return this.m_maxForce;};_proto53.SetMaxTorque=function SetMaxTorque(torque){this.m_maxTorque=torque;};_proto53.GetMaxTorque=function GetMaxTorque(){return this.m_maxTorque;};_proto53.InitVelocityConstraints=function InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);var rA=b2Rot.MulRV(qA,b2Vec2.SubVV(this.m_linearOffset,this.m_localCenterA,b2Vec2.s_t0),this.m_rA);var rB=b2Rot.MulRV(qB,b2Vec2.NegV(this.m_localCenterB,b2Vec2.s_t0),this.m_rB);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var K=this.m_K;K.ex.x=mA+mB+iA*rA.y*rA.y+iB*rB.y*rB.y;K.ex.y=-iA*rA.x*rA.y-iB*rB.x*rB.y;K.ey.x=K.ex.y;K.ey.y=mA+mB+iA*rA.x*rA.x+iB*rB.x*rB.x;K.GetInverse(this.m_linearMass);this.m_angularMass=iA+iB;if(this.m_angularMass>0){this.m_angularMass=1/this.m_angularMass;}b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),this.m_linearError);this.m_angularError=aB-aA-this.m_angularOffset;if(data.step.warmStarting){this.m_linearImpulse.SelfMul(data.step.dtRatio);this.m_angularImpulse*=data.step.dtRatio;var P=this.m_linearImpulse;vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(rA,P)+this.m_angularImpulse);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(rB,P)+this.m_angularImpulse);}else {this.m_linearImpulse.SetZero();this.m_angularImpulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto53.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var h=data.step.dt;var inv_h=data.step.inv_dt;{var Cdot=wB-wA+inv_h*this.m_correctionFactor*this.m_angularError;var impulse=-this.m_angularMass*Cdot;var oldImpulse=this.m_angularImpulse;var maxImpulse=h*this.m_maxTorque;this.m_angularImpulse=b2Clamp(this.m_angularImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_angularImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse;}{var rA=this.m_rA;var rB=this.m_rB;var Cdot_v2=b2Vec2.AddVV(b2Vec2.SubVV(b2Vec2.AddVV(vB,b2Vec2.CrossSV(wB,rB,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.AddVV(vA,b2Vec2.CrossSV(wA,rA,b2Vec2.s_t1),b2Vec2.s_t1),b2Vec2.s_t2),b2Vec2.MulSV(inv_h*this.m_correctionFactor,this.m_linearError,b2Vec2.s_t3),b2MotorJoint.SolveVelocityConstraints_s_Cdot_v2);var impulse_v2=b2Mat22.MulMV(this.m_linearMass,Cdot_v2,b2MotorJoint.SolveVelocityConstraints_s_impulse_v2).SelfNeg();var oldImpulse_v2=b2MotorJoint.SolveVelocityConstraints_s_oldImpulse_v2.Copy(this.m_linearImpulse);this.m_linearImpulse.SelfAdd(impulse_v2);var _maxImpulse2=h*this.m_maxForce;if(this.m_linearImpulse.LengthSquared()>_maxImpulse2*_maxImpulse2){this.m_linearImpulse.Normalize();this.m_linearImpulse.SelfMul(_maxImpulse2);}b2Vec2.SubVV(this.m_linearImpulse,oldImpulse_v2,impulse_v2);vA.SelfMulSub(mA,impulse_v2);wA-=iA*b2Vec2.CrossVV(rA,impulse_v2);vB.SelfMulAdd(mB,impulse_v2);wB+=iB*b2Vec2.CrossVV(rB,impulse_v2);}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto53.SolvePositionConstraints=function SolvePositionConstraints(data){return true;};_proto53.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2MotorJointDef = new b2MotorJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.linearOffset.Set(%.15f, %.15f);\n",this.m_linearOffset.x,this.m_linearOffset.y);log("  jd.angularOffset = %.15f;\n",this.m_angularOffset);log("  jd.maxForce = %.15f;\n",this.m_maxForce);log("  jd.maxTorque = %.15f;\n",this.m_maxTorque);log("  jd.correctionFactor = %.15f;\n",this.m_correctionFactor);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);};return b2MotorJoint;}(b2Joint);b2MotorJoint.SolveVelocityConstraints_s_Cdot_v2=new b2Vec2();b2MotorJoint.SolveVelocityConstraints_s_impulse_v2=new b2Vec2();b2MotorJoint.SolveVelocityConstraints_s_oldImpulse_v2=new b2Vec2();var b2MouseJointDef=function(_b2JointDef6){_inheritsLoose(b2MouseJointDef,_b2JointDef6);function b2MouseJointDef(){var _this16;_this16=_b2JointDef6.call(this,exports$1.b2JointType.e_mouseJoint)||this;_this16.target=new b2Vec2();_this16.maxForce=0;_this16.frequencyHz=5;_this16.dampingRatio=0.7;return _this16;}return b2MouseJointDef;}(b2JointDef);var b2MouseJoint=function(_b2Joint6){_inheritsLoose(b2MouseJoint,_b2Joint6);function b2MouseJoint(def){var _this17;_this17=_b2Joint6.call(this,def)||this;_this17.m_localAnchorB=new b2Vec2();_this17.m_targetA=new b2Vec2();_this17.m_frequencyHz=0;_this17.m_dampingRatio=0;_this17.m_beta=0;_this17.m_impulse=new b2Vec2();_this17.m_maxForce=0;_this17.m_gamma=0;_this17.m_indexA=0;_this17.m_indexB=0;_this17.m_rB=new b2Vec2();_this17.m_localCenterB=new b2Vec2();_this17.m_invMassB=0;_this17.m_invIB=0;_this17.m_mass=new b2Mat22();_this17.m_C=new b2Vec2();_this17.m_qB=new b2Rot();_this17.m_lalcB=new b2Vec2();_this17.m_K=new b2Mat22();_this17.m_targetA.Copy(b2Maybe(def.target,b2Vec2.ZERO));b2Transform.MulTXV(_this17.m_bodyB.GetTransform(),_this17.m_targetA,_this17.m_localAnchorB);_this17.m_maxForce=b2Maybe(def.maxForce,0);_this17.m_impulse.SetZero();_this17.m_frequencyHz=b2Maybe(def.frequencyHz,0);_this17.m_dampingRatio=b2Maybe(def.dampingRatio,0);_this17.m_beta=0;_this17.m_gamma=0;return _this17;}var _proto54=b2MouseJoint.prototype;_proto54.SetTarget=function SetTarget(target){if(!this.m_bodyB.IsAwake()){this.m_bodyB.SetAwake(true);}this.m_targetA.Copy(target);};_proto54.GetTarget=function GetTarget(){return this.m_targetA;};_proto54.SetMaxForce=function SetMaxForce(maxForce){this.m_maxForce=maxForce;};_proto54.GetMaxForce=function GetMaxForce(){return this.m_maxForce;};_proto54.SetFrequency=function SetFrequency(hz){this.m_frequencyHz=hz;};_proto54.GetFrequency=function GetFrequency(){return this.m_frequencyHz;};_proto54.SetDampingRatio=function SetDampingRatio(ratio){this.m_dampingRatio=ratio;};_proto54.GetDampingRatio=function GetDampingRatio(){return this.m_dampingRatio;};_proto54.InitVelocityConstraints=function InitVelocityConstraints(data){this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIB=this.m_bodyB.m_invI;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qB=this.m_qB.SetAngle(aB);var mass=this.m_bodyB.GetMass();var omega=2*b2_pi*this.m_frequencyHz;var d=2*mass*this.m_dampingRatio*omega;var k=mass*(omega*omega);var h=data.step.dt;this.m_gamma=h*(d+h*k);if(this.m_gamma!==0){this.m_gamma=1/this.m_gamma;}this.m_beta=h*k*this.m_gamma;b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var K=this.m_K;K.ex.x=this.m_invMassB+this.m_invIB*this.m_rB.y*this.m_rB.y+this.m_gamma;K.ex.y=-this.m_invIB*this.m_rB.x*this.m_rB.y;K.ey.x=K.ex.y;K.ey.y=this.m_invMassB+this.m_invIB*this.m_rB.x*this.m_rB.x+this.m_gamma;K.GetInverse(this.m_mass);this.m_C.x=cB.x+this.m_rB.x-this.m_targetA.x;this.m_C.y=cB.y+this.m_rB.y-this.m_targetA.y;this.m_C.SelfMul(this.m_beta);wB*=0.98;if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);vB.x+=this.m_invMassB*this.m_impulse.x;vB.y+=this.m_invMassB*this.m_impulse.y;wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,this.m_impulse);}else {this.m_impulse.SetZero();}data.velocities[this.m_indexB].w=wB;};_proto54.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var Cdot=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2MouseJoint.SolveVelocityConstraints_s_Cdot);var impulse=b2Mat22.MulMV(this.m_mass,b2Vec2.AddVV(Cdot,b2Vec2.AddVV(this.m_C,b2Vec2.MulSV(this.m_gamma,this.m_impulse,b2Vec2.s_t0),b2Vec2.s_t0),b2Vec2.s_t0).SelfNeg(),b2MouseJoint.SolveVelocityConstraints_s_impulse);var oldImpulse=b2MouseJoint.SolveVelocityConstraints_s_oldImpulse.Copy(this.m_impulse);this.m_impulse.SelfAdd(impulse);var maxImpulse=data.step.dt*this.m_maxForce;if(this.m_impulse.LengthSquared()>maxImpulse*maxImpulse){this.m_impulse.SelfMul(maxImpulse/this.m_impulse.Length());}b2Vec2.SubVV(this.m_impulse,oldImpulse,impulse);vB.SelfMulAdd(this.m_invMassB,impulse);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,impulse);data.velocities[this.m_indexB].w=wB;};_proto54.SolvePositionConstraints=function SolvePositionConstraints(data){return true;};_proto54.GetAnchorA=function GetAnchorA(out){out.x=this.m_targetA.x;out.y=this.m_targetA.y;return out;};_proto54.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto54.GetReactionForce=function GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt,this.m_impulse,out);};_proto54.GetReactionTorque=function GetReactionTorque(inv_dt){return 0;};_proto54.Dump=function Dump(log){log("Mouse joint dumping is not supported.\n");};_proto54.ShiftOrigin=function ShiftOrigin(newOrigin){this.m_targetA.SelfSub(newOrigin);};return b2MouseJoint;}(b2Joint);b2MouseJoint.SolveVelocityConstraints_s_Cdot=new b2Vec2();b2MouseJoint.SolveVelocityConstraints_s_impulse=new b2Vec2();b2MouseJoint.SolveVelocityConstraints_s_oldImpulse=new b2Vec2();var b2PrismaticJointDef=function(_b2JointDef7){_inheritsLoose(b2PrismaticJointDef,_b2JointDef7);function b2PrismaticJointDef(){var _this18;_this18=_b2JointDef7.call(this,exports$1.b2JointType.e_prismaticJoint)||this;_this18.localAnchorA=new b2Vec2();_this18.localAnchorB=new b2Vec2();_this18.localAxisA=new b2Vec2(1,0);_this18.referenceAngle=0;_this18.enableLimit=false;_this18.lowerTranslation=0;_this18.upperTranslation=0;_this18.enableMotor=false;_this18.maxMotorForce=0;_this18.motorSpeed=0;return _this18;}var _proto55=b2PrismaticJointDef.prototype;_proto55.Initialize=function Initialize(bA,bB,anchor,axis){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);this.bodyA.GetLocalVector(axis,this.localAxisA);this.referenceAngle=this.bodyB.GetAngle()-this.bodyA.GetAngle();};return b2PrismaticJointDef;}(b2JointDef);var b2PrismaticJoint=function(_b2Joint7){_inheritsLoose(b2PrismaticJoint,_b2Joint7);function b2PrismaticJoint(def){var _this19;_this19=_b2Joint7.call(this,def)||this;_this19.m_localAnchorA=new b2Vec2();_this19.m_localAnchorB=new b2Vec2();_this19.m_localXAxisA=new b2Vec2();_this19.m_localYAxisA=new b2Vec2();_this19.m_referenceAngle=0;_this19.m_impulse=new b2Vec3(0,0,0);_this19.m_motorImpulse=0;_this19.m_lowerTranslation=0;_this19.m_upperTranslation=0;_this19.m_maxMotorForce=0;_this19.m_motorSpeed=0;_this19.m_enableLimit=false;_this19.m_enableMotor=false;_this19.m_limitState=exports$1.b2LimitState.e_inactiveLimit;_this19.m_indexA=0;_this19.m_indexB=0;_this19.m_localCenterA=new b2Vec2();_this19.m_localCenterB=new b2Vec2();_this19.m_invMassA=0;_this19.m_invMassB=0;_this19.m_invIA=0;_this19.m_invIB=0;_this19.m_axis=new b2Vec2(0,0);_this19.m_perp=new b2Vec2(0,0);_this19.m_s1=0;_this19.m_s2=0;_this19.m_a1=0;_this19.m_a2=0;_this19.m_K=new b2Mat33();_this19.m_K3=new b2Mat33();_this19.m_K2=new b2Mat22();_this19.m_motorMass=0;_this19.m_qA=new b2Rot();_this19.m_qB=new b2Rot();_this19.m_lalcA=new b2Vec2();_this19.m_lalcB=new b2Vec2();_this19.m_rA=new b2Vec2();_this19.m_rB=new b2Vec2();_this19.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));_this19.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));_this19.m_localXAxisA.Copy(b2Maybe(def.localAxisA,new b2Vec2(1,0))).SelfNormalize();b2Vec2.CrossOneV(_this19.m_localXAxisA,_this19.m_localYAxisA);_this19.m_referenceAngle=b2Maybe(def.referenceAngle,0);_this19.m_lowerTranslation=b2Maybe(def.lowerTranslation,0);_this19.m_upperTranslation=b2Maybe(def.upperTranslation,0);_this19.m_maxMotorForce=b2Maybe(def.maxMotorForce,0);_this19.m_motorSpeed=b2Maybe(def.motorSpeed,0);_this19.m_enableLimit=b2Maybe(def.enableLimit,false);_this19.m_enableMotor=b2Maybe(def.enableMotor,false);return _this19;}var _proto56=b2PrismaticJoint.prototype;_proto56.InitVelocityConstraints=function InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var d=b2Vec2.AddVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),b2Vec2.SubVV(rB,rA,b2Vec2.s_t1),b2PrismaticJoint.InitVelocityConstraints_s_d);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;{b2Rot.MulRV(qA,this.m_localXAxisA,this.m_axis);this.m_a1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_axis);this.m_a2=b2Vec2.CrossVV(rB,this.m_axis);this.m_motorMass=mA+mB+iA*this.m_a1*this.m_a1+iB*this.m_a2*this.m_a2;if(this.m_motorMass>0){this.m_motorMass=1/this.m_motorMass;}}{b2Rot.MulRV(qA,this.m_localYAxisA,this.m_perp);this.m_s1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_perp);this.m_s2=b2Vec2.CrossVV(rB,this.m_perp);this.m_K.ex.x=mA+mB+iA*this.m_s1*this.m_s1+iB*this.m_s2*this.m_s2;this.m_K.ex.y=iA*this.m_s1+iB*this.m_s2;this.m_K.ex.z=iA*this.m_s1*this.m_a1+iB*this.m_s2*this.m_a2;this.m_K.ey.x=this.m_K.ex.y;this.m_K.ey.y=iA+iB;if(this.m_K.ey.y===0){this.m_K.ey.y=1;}this.m_K.ey.z=iA*this.m_a1+iB*this.m_a2;this.m_K.ez.x=this.m_K.ex.z;this.m_K.ez.y=this.m_K.ey.z;this.m_K.ez.z=mA+mB+iA*this.m_a1*this.m_a1+iB*this.m_a2*this.m_a2;}if(this.m_enableLimit){var jointTranslation=b2Vec2.DotVV(this.m_axis,d);if(b2Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2_linearSlop){this.m_limitState=exports$1.b2LimitState.e_equalLimits;}else if(jointTranslation<=this.m_lowerTranslation){if(this.m_limitState!==exports$1.b2LimitState.e_atLowerLimit){this.m_limitState=exports$1.b2LimitState.e_atLowerLimit;this.m_impulse.z=0;}}else if(jointTranslation>=this.m_upperTranslation){if(this.m_limitState!==exports$1.b2LimitState.e_atUpperLimit){this.m_limitState=exports$1.b2LimitState.e_atUpperLimit;this.m_impulse.z=0;}}else {this.m_limitState=exports$1.b2LimitState.e_inactiveLimit;this.m_impulse.z=0;}}else {this.m_limitState=exports$1.b2LimitState.e_inactiveLimit;this.m_impulse.z=0;}if(!this.m_enableMotor){this.m_motorImpulse=0;}if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);this.m_motorImpulse*=data.step.dtRatio;var P=b2Vec2.AddVV(b2Vec2.MulSV(this.m_impulse.x,this.m_perp,b2Vec2.s_t0),b2Vec2.MulSV(this.m_motorImpulse+this.m_impulse.z,this.m_axis,b2Vec2.s_t1),b2PrismaticJoint.InitVelocityConstraints_s_P);var LA=this.m_impulse.x*this.m_s1+this.m_impulse.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_a1;var LB=this.m_impulse.x*this.m_s2+this.m_impulse.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_a2;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB;}else {this.m_impulse.SetZero();this.m_motorImpulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto56.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;if(this.m_enableMotor&&this.m_limitState!==exports$1.b2LimitState.e_equalLimits){var Cdot=b2Vec2.DotVV(this.m_axis,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_a2*wB-this.m_a1*wA;var impulse=this.m_motorMass*(this.m_motorSpeed-Cdot);var oldImpulse=this.m_motorImpulse;var maxImpulse=data.step.dt*this.m_maxMotorForce;this.m_motorImpulse=b2Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;var P=b2Vec2.MulSV(impulse,this.m_axis,b2PrismaticJoint.SolveVelocityConstraints_s_P);var LA=impulse*this.m_a1;var LB=impulse*this.m_a2;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB;}var Cdot1_x=b2Vec2.DotVV(this.m_perp,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_s2*wB-this.m_s1*wA;var Cdot1_y=wB-wA;if(this.m_enableLimit&&this.m_limitState!==exports$1.b2LimitState.e_inactiveLimit){var Cdot2=b2Vec2.DotVV(this.m_axis,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_a2*wB-this.m_a1*wA;var f1=b2PrismaticJoint.SolveVelocityConstraints_s_f1.Copy(this.m_impulse);var df3=this.m_K.Solve33(-Cdot1_x,-Cdot1_y,-Cdot2,b2PrismaticJoint.SolveVelocityConstraints_s_df3);this.m_impulse.SelfAdd(df3);if(this.m_limitState===exports$1.b2LimitState.e_atLowerLimit){this.m_impulse.z=b2Max(this.m_impulse.z,0);}else if(this.m_limitState===exports$1.b2LimitState.e_atUpperLimit){this.m_impulse.z=b2Min(this.m_impulse.z,0);}var b_x=-Cdot1_x-(this.m_impulse.z-f1.z)*this.m_K.ez.x;var b_y=-Cdot1_y-(this.m_impulse.z-f1.z)*this.m_K.ez.y;var f2r=this.m_K.Solve22(b_x,b_y,b2PrismaticJoint.SolveVelocityConstraints_s_f2r);f2r.x+=f1.x;f2r.y+=f1.y;this.m_impulse.x=f2r.x;this.m_impulse.y=f2r.y;df3.x=this.m_impulse.x-f1.x;df3.y=this.m_impulse.y-f1.y;df3.z=this.m_impulse.z-f1.z;var _P3=b2Vec2.AddVV(b2Vec2.MulSV(df3.x,this.m_perp,b2Vec2.s_t0),b2Vec2.MulSV(df3.z,this.m_axis,b2Vec2.s_t1),b2PrismaticJoint.SolveVelocityConstraints_s_P);var _LA=df3.x*this.m_s1+df3.y+df3.z*this.m_a1;var _LB=df3.x*this.m_s2+df3.y+df3.z*this.m_a2;vA.SelfMulSub(mA,_P3);wA-=iA*_LA;vB.SelfMulAdd(mB,_P3);wB+=iB*_LB;}else {var df2=this.m_K.Solve22(-Cdot1_x,-Cdot1_y,b2PrismaticJoint.SolveVelocityConstraints_s_df2);this.m_impulse.x+=df2.x;this.m_impulse.y+=df2.y;var _P4=b2Vec2.MulSV(df2.x,this.m_perp,b2PrismaticJoint.SolveVelocityConstraints_s_P);var _LA2=df2.x*this.m_s1+df2.y;var _LB2=df2.x*this.m_s2+df2.y;vA.SelfMulSub(mA,_P4);wA-=iA*_LA2;vB.SelfMulAdd(mB,_P4);wB+=iB*_LB2;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto56.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var d=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2PrismaticJoint.SolvePositionConstraints_s_d);var axis=b2Rot.MulRV(qA,this.m_localXAxisA,this.m_axis);var a1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),axis);var a2=b2Vec2.CrossVV(rB,axis);var perp=b2Rot.MulRV(qA,this.m_localYAxisA,this.m_perp);var s1=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),perp);var s2=b2Vec2.CrossVV(rB,perp);var impulse=b2PrismaticJoint.SolvePositionConstraints_s_impulse;var C1_x=b2Vec2.DotVV(perp,d);var C1_y=aB-aA-this.m_referenceAngle;var linearError=b2Abs(C1_x);var angularError=b2Abs(C1_y);var active=false;var C2=0;if(this.m_enableLimit){var translation=b2Vec2.DotVV(axis,d);if(b2Abs(this.m_upperTranslation-this.m_lowerTranslation)<2*b2_linearSlop){C2=b2Clamp(translation,-b2_maxLinearCorrection,b2_maxLinearCorrection);linearError=b2Max(linearError,b2Abs(translation));active=true;}else if(translation<=this.m_lowerTranslation){C2=b2Clamp(translation-this.m_lowerTranslation+b2_linearSlop,-b2_maxLinearCorrection,0);linearError=b2Max(linearError,this.m_lowerTranslation-translation);active=true;}else if(translation>=this.m_upperTranslation){C2=b2Clamp(translation-this.m_upperTranslation-b2_linearSlop,0,b2_maxLinearCorrection);linearError=b2Max(linearError,translation-this.m_upperTranslation);active=true;}}if(active){var k11=mA+mB+iA*s1*s1+iB*s2*s2;var k12=iA*s1+iB*s2;var k13=iA*s1*a1+iB*s2*a2;var k22=iA+iB;if(k22===0){k22=1;}var k23=iA*a1+iB*a2;var k33=mA+mB+iA*a1*a1+iB*a2*a2;var K=this.m_K3;K.ex.SetXYZ(k11,k12,k13);K.ey.SetXYZ(k12,k22,k23);K.ez.SetXYZ(k13,k23,k33);impulse=K.Solve33(-C1_x,-C1_y,-C2,impulse);}else {var _k=mA+mB+iA*s1*s1+iB*s2*s2;var _k2=iA*s1+iB*s2;var _k3=iA+iB;if(_k3===0){_k3=1;}var K2=this.m_K2;K2.ex.Set(_k,_k2);K2.ey.Set(_k2,_k3);var impulse1=K2.Solve(-C1_x,-C1_y,b2PrismaticJoint.SolvePositionConstraints_s_impulse1);impulse.x=impulse1.x;impulse.y=impulse1.y;impulse.z=0;}var P=b2Vec2.AddVV(b2Vec2.MulSV(impulse.x,perp,b2Vec2.s_t0),b2Vec2.MulSV(impulse.z,axis,b2Vec2.s_t1),b2PrismaticJoint.SolvePositionConstraints_s_P);var LA=impulse.x*s1+impulse.y+impulse.z*a1;var LB=impulse.x*s2+impulse.y+impulse.z*a2;cA.SelfMulSub(mA,P);aA-=iA*LA;cB.SelfMulAdd(mB,P);aB+=iB*LB;data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return linearError<=b2_linearSlop&&angularError<=b2_angularSlop;};_proto56.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto56.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto56.GetReactionForce=function GetReactionForce(inv_dt,out){out.x=inv_dt*(this.m_impulse.x*this.m_perp.x+(this.m_motorImpulse+this.m_impulse.z)*this.m_axis.x);out.y=inv_dt*(this.m_impulse.x*this.m_perp.y+(this.m_motorImpulse+this.m_impulse.z)*this.m_axis.y);return out;};_proto56.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.y;};_proto56.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto56.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto56.GetLocalAxisA=function GetLocalAxisA(){return this.m_localXAxisA;};_proto56.GetReferenceAngle=function GetReferenceAngle(){return this.m_referenceAngle;};_proto56.GetJointTranslation=function GetJointTranslation(){var pA=this.m_bodyA.GetWorldPoint(this.m_localAnchorA,b2PrismaticJoint.GetJointTranslation_s_pA);var pB=this.m_bodyB.GetWorldPoint(this.m_localAnchorB,b2PrismaticJoint.GetJointTranslation_s_pB);var d=b2Vec2.SubVV(pB,pA,b2PrismaticJoint.GetJointTranslation_s_d);var axis=this.m_bodyA.GetWorldVector(this.m_localXAxisA,b2PrismaticJoint.GetJointTranslation_s_axis);var translation=b2Vec2.DotVV(d,axis);return translation;};_proto56.GetJointSpeed=function GetJointSpeed(){var bA=this.m_bodyA;var bB=this.m_bodyB;b2Vec2.SubVV(this.m_localAnchorA,bA.m_sweep.localCenter,this.m_lalcA);var rA=b2Rot.MulRV(bA.m_xf.q,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,bB.m_sweep.localCenter,this.m_lalcB);var rB=b2Rot.MulRV(bB.m_xf.q,this.m_lalcB,this.m_rB);var pA=b2Vec2.AddVV(bA.m_sweep.c,rA,b2Vec2.s_t0);var pB=b2Vec2.AddVV(bB.m_sweep.c,rB,b2Vec2.s_t1);var d=b2Vec2.SubVV(pB,pA,b2Vec2.s_t2);var axis=bA.GetWorldVector(this.m_localXAxisA,this.m_axis);var vA=bA.m_linearVelocity;var vB=bB.m_linearVelocity;var wA=bA.m_angularVelocity;var wB=bB.m_angularVelocity;var speed=b2Vec2.DotVV(d,b2Vec2.CrossSV(wA,axis,b2Vec2.s_t0))+b2Vec2.DotVV(axis,b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,rA,b2Vec2.s_t1),b2Vec2.s_t0));return speed;};_proto56.IsLimitEnabled=function IsLimitEnabled(){return this.m_enableLimit;};_proto56.EnableLimit=function EnableLimit(flag){if(flag!==this.m_enableLimit){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableLimit=flag;this.m_impulse.z=0;}};_proto56.GetLowerLimit=function GetLowerLimit(){return this.m_lowerTranslation;};_proto56.GetUpperLimit=function GetUpperLimit(){return this.m_upperTranslation;};_proto56.SetLimits=function SetLimits(lower,upper){if(lower!==this.m_lowerTranslation||upper!==this.m_upperTranslation){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_lowerTranslation=lower;this.m_upperTranslation=upper;this.m_impulse.z=0;}};_proto56.IsMotorEnabled=function IsMotorEnabled(){return this.m_enableMotor;};_proto56.EnableMotor=function EnableMotor(flag){if(flag!==this.m_enableMotor){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag;}};_proto56.SetMotorSpeed=function SetMotorSpeed(speed){if(speed!==this.m_motorSpeed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed;}};_proto56.GetMotorSpeed=function GetMotorSpeed(){return this.m_motorSpeed;};_proto56.SetMaxMotorForce=function SetMaxMotorForce(force){if(force!==this.m_maxMotorForce){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorForce=force;}};_proto56.GetMaxMotorForce=function GetMaxMotorForce(){return this.m_maxMotorForce;};_proto56.GetMotorForce=function GetMotorForce(inv_dt){return inv_dt*this.m_motorImpulse;};_proto56.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2PrismaticJointDef = new b2PrismaticJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.localAxisA.Set(%.15f, %.15f);\n",this.m_localXAxisA.x,this.m_localXAxisA.y);log("  jd.referenceAngle = %.15f;\n",this.m_referenceAngle);log("  jd.enableLimit = %s;\n",this.m_enableLimit?"true":"false");log("  jd.lowerTranslation = %.15f;\n",this.m_lowerTranslation);log("  jd.upperTranslation = %.15f;\n",this.m_upperTranslation);log("  jd.enableMotor = %s;\n",this.m_enableMotor?"true":"false");log("  jd.motorSpeed = %.15f;\n",this.m_motorSpeed);log("  jd.maxMotorForce = %.15f;\n",this.m_maxMotorForce);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);};return b2PrismaticJoint;}(b2Joint);b2PrismaticJoint.InitVelocityConstraints_s_d=new b2Vec2();b2PrismaticJoint.InitVelocityConstraints_s_P=new b2Vec2();b2PrismaticJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2PrismaticJoint.SolveVelocityConstraints_s_f2r=new b2Vec2();b2PrismaticJoint.SolveVelocityConstraints_s_f1=new b2Vec3();b2PrismaticJoint.SolveVelocityConstraints_s_df3=new b2Vec3();b2PrismaticJoint.SolveVelocityConstraints_s_df2=new b2Vec2();b2PrismaticJoint.SolvePositionConstraints_s_d=new b2Vec2();b2PrismaticJoint.SolvePositionConstraints_s_impulse=new b2Vec3();b2PrismaticJoint.SolvePositionConstraints_s_impulse1=new b2Vec2();b2PrismaticJoint.SolvePositionConstraints_s_P=new b2Vec2();b2PrismaticJoint.GetJointTranslation_s_pA=new b2Vec2();b2PrismaticJoint.GetJointTranslation_s_pB=new b2Vec2();b2PrismaticJoint.GetJointTranslation_s_d=new b2Vec2();b2PrismaticJoint.GetJointTranslation_s_axis=new b2Vec2();var b2_minPulleyLength=2;var b2PulleyJointDef=function(_b2JointDef8){_inheritsLoose(b2PulleyJointDef,_b2JointDef8);function b2PulleyJointDef(){var _this20;_this20=_b2JointDef8.call(this,exports$1.b2JointType.e_pulleyJoint)||this;_this20.groundAnchorA=new b2Vec2(-1,1);_this20.groundAnchorB=new b2Vec2(1,1);_this20.localAnchorA=new b2Vec2(-1,0);_this20.localAnchorB=new b2Vec2(1,0);_this20.lengthA=0;_this20.lengthB=0;_this20.ratio=1;_this20.collideConnected=true;return _this20;}var _proto57=b2PulleyJointDef.prototype;_proto57.Initialize=function Initialize(bA,bB,groundA,groundB,anchorA,anchorB,r){this.bodyA=bA;this.bodyB=bB;this.groundAnchorA.Copy(groundA);this.groundAnchorB.Copy(groundB);this.bodyA.GetLocalPoint(anchorA,this.localAnchorA);this.bodyB.GetLocalPoint(anchorB,this.localAnchorB);this.lengthA=b2Vec2.DistanceVV(anchorA,groundA);this.lengthB=b2Vec2.DistanceVV(anchorB,groundB);this.ratio=r;};return b2PulleyJointDef;}(b2JointDef);var b2PulleyJoint=function(_b2Joint8){_inheritsLoose(b2PulleyJoint,_b2Joint8);function b2PulleyJoint(def){var _this21;_this21=_b2Joint8.call(this,def)||this;_this21.m_groundAnchorA=new b2Vec2();_this21.m_groundAnchorB=new b2Vec2();_this21.m_lengthA=0;_this21.m_lengthB=0;_this21.m_localAnchorA=new b2Vec2();_this21.m_localAnchorB=new b2Vec2();_this21.m_constant=0;_this21.m_ratio=0;_this21.m_impulse=0;_this21.m_indexA=0;_this21.m_indexB=0;_this21.m_uA=new b2Vec2();_this21.m_uB=new b2Vec2();_this21.m_rA=new b2Vec2();_this21.m_rB=new b2Vec2();_this21.m_localCenterA=new b2Vec2();_this21.m_localCenterB=new b2Vec2();_this21.m_invMassA=0;_this21.m_invMassB=0;_this21.m_invIA=0;_this21.m_invIB=0;_this21.m_mass=0;_this21.m_qA=new b2Rot();_this21.m_qB=new b2Rot();_this21.m_lalcA=new b2Vec2();_this21.m_lalcB=new b2Vec2();_this21.m_groundAnchorA.Copy(b2Maybe(def.groundAnchorA,new b2Vec2(-1,1)));_this21.m_groundAnchorB.Copy(b2Maybe(def.groundAnchorB,new b2Vec2(1,0)));_this21.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,new b2Vec2(-1,0)));_this21.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,new b2Vec2(1,0)));_this21.m_lengthA=b2Maybe(def.lengthA,0);_this21.m_lengthB=b2Maybe(def.lengthB,0);_this21.m_ratio=b2Maybe(def.ratio,1);_this21.m_constant=b2Maybe(def.lengthA,0)+_this21.m_ratio*b2Maybe(def.lengthB,0);_this21.m_impulse=0;return _this21;}var _proto58=b2PulleyJoint.prototype;_proto58.InitVelocityConstraints=function InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);this.m_uA.Copy(cA).SelfAdd(this.m_rA).SelfSub(this.m_groundAnchorA);this.m_uB.Copy(cB).SelfAdd(this.m_rB).SelfSub(this.m_groundAnchorB);var lengthA=this.m_uA.Length();var lengthB=this.m_uB.Length();if(lengthA>10*b2_linearSlop){this.m_uA.SelfMul(1/lengthA);}else {this.m_uA.SetZero();}if(lengthB>10*b2_linearSlop){this.m_uB.SelfMul(1/lengthB);}else {this.m_uB.SetZero();}var ruA=b2Vec2.CrossVV(this.m_rA,this.m_uA);var ruB=b2Vec2.CrossVV(this.m_rB,this.m_uB);var mA=this.m_invMassA+this.m_invIA*ruA*ruA;var mB=this.m_invMassB+this.m_invIB*ruB*ruB;this.m_mass=mA+this.m_ratio*this.m_ratio*mB;if(this.m_mass>0){this.m_mass=1/this.m_mass;}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;var PA=b2Vec2.MulSV(-this.m_impulse,this.m_uA,b2PulleyJoint.InitVelocityConstraints_s_PA);var PB=b2Vec2.MulSV(-this.m_ratio*this.m_impulse,this.m_uB,b2PulleyJoint.InitVelocityConstraints_s_PB);vA.SelfMulAdd(this.m_invMassA,PA);wA+=this.m_invIA*b2Vec2.CrossVV(this.m_rA,PA);vB.SelfMulAdd(this.m_invMassB,PB);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,PB);}else {this.m_impulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto58.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2PulleyJoint.SolveVelocityConstraints_s_vpA);var vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2PulleyJoint.SolveVelocityConstraints_s_vpB);var Cdot=-b2Vec2.DotVV(this.m_uA,vpA)-this.m_ratio*b2Vec2.DotVV(this.m_uB,vpB);var impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;var PA=b2Vec2.MulSV(-impulse,this.m_uA,b2PulleyJoint.SolveVelocityConstraints_s_PA);var PB=b2Vec2.MulSV(-this.m_ratio*impulse,this.m_uB,b2PulleyJoint.SolveVelocityConstraints_s_PB);vA.SelfMulAdd(this.m_invMassA,PA);wA+=this.m_invIA*b2Vec2.CrossVV(this.m_rA,PA);vB.SelfMulAdd(this.m_invMassB,PB);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,PB);data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto58.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var uA=this.m_uA.Copy(cA).SelfAdd(rA).SelfSub(this.m_groundAnchorA);var uB=this.m_uB.Copy(cB).SelfAdd(rB).SelfSub(this.m_groundAnchorB);var lengthA=uA.Length();var lengthB=uB.Length();if(lengthA>10*b2_linearSlop){uA.SelfMul(1/lengthA);}else {uA.SetZero();}if(lengthB>10*b2_linearSlop){uB.SelfMul(1/lengthB);}else {uB.SetZero();}var ruA=b2Vec2.CrossVV(rA,uA);var ruB=b2Vec2.CrossVV(rB,uB);var mA=this.m_invMassA+this.m_invIA*ruA*ruA;var mB=this.m_invMassB+this.m_invIB*ruB*ruB;var mass=mA+this.m_ratio*this.m_ratio*mB;if(mass>0){mass=1/mass;}var C=this.m_constant-lengthA-this.m_ratio*lengthB;var linearError=b2Abs(C);var impulse=-mass*C;var PA=b2Vec2.MulSV(-impulse,uA,b2PulleyJoint.SolvePositionConstraints_s_PA);var PB=b2Vec2.MulSV(-this.m_ratio*impulse,uB,b2PulleyJoint.SolvePositionConstraints_s_PB);cA.SelfMulAdd(this.m_invMassA,PA);aA+=this.m_invIA*b2Vec2.CrossVV(rA,PA);cB.SelfMulAdd(this.m_invMassB,PB);aB+=this.m_invIB*b2Vec2.CrossVV(rB,PB);data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return linearError<b2_linearSlop;};_proto58.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto58.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto58.GetReactionForce=function GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse*this.m_uB.x;out.y=inv_dt*this.m_impulse*this.m_uB.y;return out;};_proto58.GetReactionTorque=function GetReactionTorque(inv_dt){return 0;};_proto58.GetGroundAnchorA=function GetGroundAnchorA(){return this.m_groundAnchorA;};_proto58.GetGroundAnchorB=function GetGroundAnchorB(){return this.m_groundAnchorB;};_proto58.GetLengthA=function GetLengthA(){return this.m_lengthA;};_proto58.GetLengthB=function GetLengthB(){return this.m_lengthB;};_proto58.GetRatio=function GetRatio(){return this.m_ratio;};_proto58.GetCurrentLengthA=function GetCurrentLengthA(){var p=this.m_bodyA.GetWorldPoint(this.m_localAnchorA,b2PulleyJoint.GetCurrentLengthA_s_p);var s=this.m_groundAnchorA;return b2Vec2.DistanceVV(p,s);};_proto58.GetCurrentLengthB=function GetCurrentLengthB(){var p=this.m_bodyB.GetWorldPoint(this.m_localAnchorB,b2PulleyJoint.GetCurrentLengthB_s_p);var s=this.m_groundAnchorB;return b2Vec2.DistanceVV(p,s);};_proto58.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2PulleyJointDef = new b2PulleyJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.groundAnchorA.Set(%.15f, %.15f);\n",this.m_groundAnchorA.x,this.m_groundAnchorA.y);log("  jd.groundAnchorB.Set(%.15f, %.15f);\n",this.m_groundAnchorB.x,this.m_groundAnchorB.y);log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.lengthA = %.15f;\n",this.m_lengthA);log("  jd.lengthB = %.15f;\n",this.m_lengthB);log("  jd.ratio = %.15f;\n",this.m_ratio);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);};_proto58.ShiftOrigin=function ShiftOrigin(newOrigin){this.m_groundAnchorA.SelfSub(newOrigin);this.m_groundAnchorB.SelfSub(newOrigin);};return b2PulleyJoint;}(b2Joint);b2PulleyJoint.InitVelocityConstraints_s_PA=new b2Vec2();b2PulleyJoint.InitVelocityConstraints_s_PB=new b2Vec2();b2PulleyJoint.SolveVelocityConstraints_s_vpA=new b2Vec2();b2PulleyJoint.SolveVelocityConstraints_s_vpB=new b2Vec2();b2PulleyJoint.SolveVelocityConstraints_s_PA=new b2Vec2();b2PulleyJoint.SolveVelocityConstraints_s_PB=new b2Vec2();b2PulleyJoint.SolvePositionConstraints_s_PA=new b2Vec2();b2PulleyJoint.SolvePositionConstraints_s_PB=new b2Vec2();b2PulleyJoint.GetCurrentLengthA_s_p=new b2Vec2();b2PulleyJoint.GetCurrentLengthB_s_p=new b2Vec2();var b2RevoluteJointDef=function(_b2JointDef9){_inheritsLoose(b2RevoluteJointDef,_b2JointDef9);function b2RevoluteJointDef(){var _this22;_this22=_b2JointDef9.call(this,exports$1.b2JointType.e_revoluteJoint)||this;_this22.localAnchorA=new b2Vec2(0,0);_this22.localAnchorB=new b2Vec2(0,0);_this22.referenceAngle=0;_this22.enableLimit=false;_this22.lowerAngle=0;_this22.upperAngle=0;_this22.enableMotor=false;_this22.motorSpeed=0;_this22.maxMotorTorque=0;return _this22;}var _proto59=b2RevoluteJointDef.prototype;_proto59.Initialize=function Initialize(bA,bB,anchor){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);this.referenceAngle=this.bodyB.GetAngle()-this.bodyA.GetAngle();};return b2RevoluteJointDef;}(b2JointDef);var b2RevoluteJoint=function(_b2Joint9){_inheritsLoose(b2RevoluteJoint,_b2Joint9);function b2RevoluteJoint(def){var _this23;_this23=_b2Joint9.call(this,def)||this;_this23.m_localAnchorA=new b2Vec2();_this23.m_localAnchorB=new b2Vec2();_this23.m_impulse=new b2Vec3();_this23.m_motorImpulse=0;_this23.m_enableMotor=false;_this23.m_maxMotorTorque=0;_this23.m_motorSpeed=0;_this23.m_enableLimit=false;_this23.m_referenceAngle=0;_this23.m_lowerAngle=0;_this23.m_upperAngle=0;_this23.m_indexA=0;_this23.m_indexB=0;_this23.m_rA=new b2Vec2();_this23.m_rB=new b2Vec2();_this23.m_localCenterA=new b2Vec2();_this23.m_localCenterB=new b2Vec2();_this23.m_invMassA=0;_this23.m_invMassB=0;_this23.m_invIA=0;_this23.m_invIB=0;_this23.m_mass=new b2Mat33();_this23.m_motorMass=0;_this23.m_limitState=exports$1.b2LimitState.e_inactiveLimit;_this23.m_qA=new b2Rot();_this23.m_qB=new b2Rot();_this23.m_lalcA=new b2Vec2();_this23.m_lalcB=new b2Vec2();_this23.m_K=new b2Mat22();_this23.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));_this23.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));_this23.m_referenceAngle=b2Maybe(def.referenceAngle,0);_this23.m_impulse.SetZero();_this23.m_motorImpulse=0;_this23.m_lowerAngle=b2Maybe(def.lowerAngle,0);_this23.m_upperAngle=b2Maybe(def.upperAngle,0);_this23.m_maxMotorTorque=b2Maybe(def.maxMotorTorque,0);_this23.m_motorSpeed=b2Maybe(def.motorSpeed,0);_this23.m_enableLimit=b2Maybe(def.enableLimit,false);_this23.m_enableMotor=b2Maybe(def.enableMotor,false);_this23.m_limitState=exports$1.b2LimitState.e_inactiveLimit;return _this23;}var _proto60=b2RevoluteJoint.prototype;_proto60.InitVelocityConstraints=function InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var fixedRotation=iA+iB===0;this.m_mass.ex.x=mA+mB+this.m_rA.y*this.m_rA.y*iA+this.m_rB.y*this.m_rB.y*iB;this.m_mass.ey.x=-this.m_rA.y*this.m_rA.x*iA-this.m_rB.y*this.m_rB.x*iB;this.m_mass.ez.x=-this.m_rA.y*iA-this.m_rB.y*iB;this.m_mass.ex.y=this.m_mass.ey.x;this.m_mass.ey.y=mA+mB+this.m_rA.x*this.m_rA.x*iA+this.m_rB.x*this.m_rB.x*iB;this.m_mass.ez.y=this.m_rA.x*iA+this.m_rB.x*iB;this.m_mass.ex.z=this.m_mass.ez.x;this.m_mass.ey.z=this.m_mass.ez.y;this.m_mass.ez.z=iA+iB;this.m_motorMass=iA+iB;if(this.m_motorMass>0){this.m_motorMass=1/this.m_motorMass;}if(!this.m_enableMotor||fixedRotation){this.m_motorImpulse=0;}if(this.m_enableLimit&&!fixedRotation){var jointAngle=aB-aA-this.m_referenceAngle;if(b2Abs(this.m_upperAngle-this.m_lowerAngle)<2*b2_angularSlop){this.m_limitState=exports$1.b2LimitState.e_equalLimits;}else if(jointAngle<=this.m_lowerAngle){if(this.m_limitState!==exports$1.b2LimitState.e_atLowerLimit){this.m_impulse.z=0;}this.m_limitState=exports$1.b2LimitState.e_atLowerLimit;}else if(jointAngle>=this.m_upperAngle){if(this.m_limitState!==exports$1.b2LimitState.e_atUpperLimit){this.m_impulse.z=0;}this.m_limitState=exports$1.b2LimitState.e_atUpperLimit;}else {this.m_limitState=exports$1.b2LimitState.e_inactiveLimit;this.m_impulse.z=0;}}else {this.m_limitState=exports$1.b2LimitState.e_inactiveLimit;}if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);this.m_motorImpulse*=data.step.dtRatio;var P=b2RevoluteJoint.InitVelocityConstraints_s_P.Set(this.m_impulse.x,this.m_impulse.y);vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+this.m_motorImpulse+this.m_impulse.z);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+this.m_motorImpulse+this.m_impulse.z);}else {this.m_impulse.SetZero();this.m_motorImpulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto60.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var fixedRotation=iA+iB===0;if(this.m_enableMotor&&this.m_limitState!==exports$1.b2LimitState.e_equalLimits&&!fixedRotation){var Cdot=wB-wA-this.m_motorSpeed;var impulse=-this.m_motorMass*Cdot;var oldImpulse=this.m_motorImpulse;var maxImpulse=data.step.dt*this.m_maxMotorTorque;this.m_motorImpulse=b2Clamp(this.m_motorImpulse+impulse,-maxImpulse,maxImpulse);impulse=this.m_motorImpulse-oldImpulse;wA-=iA*impulse;wB+=iB*impulse;}if(this.m_enableLimit&&this.m_limitState!==exports$1.b2LimitState.e_inactiveLimit&&!fixedRotation){var Cdot1=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2RevoluteJoint.SolveVelocityConstraints_s_Cdot1);var Cdot2=wB-wA;var impulse_v3=this.m_mass.Solve33(Cdot1.x,Cdot1.y,Cdot2,b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v3).SelfNeg();if(this.m_limitState===exports$1.b2LimitState.e_equalLimits){this.m_impulse.SelfAdd(impulse_v3);}else if(this.m_limitState===exports$1.b2LimitState.e_atLowerLimit){var newImpulse=this.m_impulse.z+impulse_v3.z;if(newImpulse<0){var rhs_x=-Cdot1.x+this.m_impulse.z*this.m_mass.ez.x;var rhs_y=-Cdot1.y+this.m_impulse.z*this.m_mass.ez.y;var reduced_v2=this.m_mass.Solve22(rhs_x,rhs_y,b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2);impulse_v3.x=reduced_v2.x;impulse_v3.y=reduced_v2.y;impulse_v3.z=-this.m_impulse.z;this.m_impulse.x+=reduced_v2.x;this.m_impulse.y+=reduced_v2.y;this.m_impulse.z=0;}else {this.m_impulse.SelfAdd(impulse_v3);}}else if(this.m_limitState===exports$1.b2LimitState.e_atUpperLimit){var _newImpulse=this.m_impulse.z+impulse_v3.z;if(_newImpulse>0){var _rhs_x=-Cdot1.x+this.m_impulse.z*this.m_mass.ez.x;var _rhs_y=-Cdot1.y+this.m_impulse.z*this.m_mass.ez.y;var _reduced_v=this.m_mass.Solve22(_rhs_x,_rhs_y,b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2);impulse_v3.x=_reduced_v.x;impulse_v3.y=_reduced_v.y;impulse_v3.z=-this.m_impulse.z;this.m_impulse.x+=_reduced_v.x;this.m_impulse.y+=_reduced_v.y;this.m_impulse.z=0;}else {this.m_impulse.SelfAdd(impulse_v3);}}var P=b2RevoluteJoint.SolveVelocityConstraints_s_P.Set(impulse_v3.x,impulse_v3.y);vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+impulse_v3.z);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+impulse_v3.z);}else {var Cdot_v2=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2RevoluteJoint.SolveVelocityConstraints_s_Cdot_v2);var impulse_v2=this.m_mass.Solve22(-Cdot_v2.x,-Cdot_v2.y,b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v2);this.m_impulse.x+=impulse_v2.x;this.m_impulse.y+=impulse_v2.y;vA.SelfMulSub(mA,impulse_v2);wA-=iA*b2Vec2.CrossVV(this.m_rA,impulse_v2);vB.SelfMulAdd(mB,impulse_v2);wB+=iB*b2Vec2.CrossVV(this.m_rB,impulse_v2);}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto60.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);var angularError=0;var positionError=0;var fixedRotation=this.m_invIA+this.m_invIB===0;if(this.m_enableLimit&&this.m_limitState!==exports$1.b2LimitState.e_inactiveLimit&&!fixedRotation){var angle=aB-aA-this.m_referenceAngle;var limitImpulse=0;if(this.m_limitState===exports$1.b2LimitState.e_equalLimits){var C=b2Clamp(angle-this.m_lowerAngle,-b2_maxAngularCorrection,b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*C;angularError=b2Abs(C);}else if(this.m_limitState===exports$1.b2LimitState.e_atLowerLimit){var _C=angle-this.m_lowerAngle;angularError=-_C;_C=b2Clamp(_C+b2_angularSlop,-b2_maxAngularCorrection,0);limitImpulse=-this.m_motorMass*_C;}else if(this.m_limitState===exports$1.b2LimitState.e_atUpperLimit){var _C2=angle-this.m_upperAngle;angularError=_C2;_C2=b2Clamp(_C2-b2_angularSlop,0,b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*_C2;}aA-=this.m_invIA*limitImpulse;aB+=this.m_invIB*limitImpulse;}{qA.SetAngle(aA);qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var C_v2=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2RevoluteJoint.SolvePositionConstraints_s_C_v2);positionError=C_v2.Length();var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var K=this.m_K;K.ex.x=mA+mB+iA*rA.y*rA.y+iB*rB.y*rB.y;K.ex.y=-iA*rA.x*rA.y-iB*rB.x*rB.y;K.ey.x=K.ex.y;K.ey.y=mA+mB+iA*rA.x*rA.x+iB*rB.x*rB.x;var impulse=K.Solve(C_v2.x,C_v2.y,b2RevoluteJoint.SolvePositionConstraints_s_impulse).SelfNeg();cA.SelfMulSub(mA,impulse);aA-=iA*b2Vec2.CrossVV(rA,impulse);cB.SelfMulAdd(mB,impulse);aB+=iB*b2Vec2.CrossVV(rB,impulse);}data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return positionError<=b2_linearSlop&&angularError<=b2_angularSlop;};_proto60.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto60.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto60.GetReactionForce=function GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse.x;out.y=inv_dt*this.m_impulse.y;return out;};_proto60.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.z;};_proto60.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto60.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto60.GetReferenceAngle=function GetReferenceAngle(){return this.m_referenceAngle;};_proto60.GetJointAngle=function GetJointAngle(){return this.m_bodyB.m_sweep.a-this.m_bodyA.m_sweep.a-this.m_referenceAngle;};_proto60.GetJointSpeed=function GetJointSpeed(){return this.m_bodyB.m_angularVelocity-this.m_bodyA.m_angularVelocity;};_proto60.IsMotorEnabled=function IsMotorEnabled(){return this.m_enableMotor;};_proto60.EnableMotor=function EnableMotor(flag){if(flag!==this.m_enableMotor){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag;}};_proto60.GetMotorTorque=function GetMotorTorque(inv_dt){return inv_dt*this.m_motorImpulse;};_proto60.GetMotorSpeed=function GetMotorSpeed(){return this.m_motorSpeed;};_proto60.SetMaxMotorTorque=function SetMaxMotorTorque(torque){if(torque!==this.m_maxMotorTorque){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorTorque=torque;}};_proto60.GetMaxMotorTorque=function GetMaxMotorTorque(){return this.m_maxMotorTorque;};_proto60.IsLimitEnabled=function IsLimitEnabled(){return this.m_enableLimit;};_proto60.EnableLimit=function EnableLimit(flag){if(flag!==this.m_enableLimit){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableLimit=flag;this.m_impulse.z=0;}};_proto60.GetLowerLimit=function GetLowerLimit(){return this.m_lowerAngle;};_proto60.GetUpperLimit=function GetUpperLimit(){return this.m_upperAngle;};_proto60.SetLimits=function SetLimits(lower,upper){if(lower!==this.m_lowerAngle||upper!==this.m_upperAngle){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_impulse.z=0;this.m_lowerAngle=lower;this.m_upperAngle=upper;}};_proto60.SetMotorSpeed=function SetMotorSpeed(speed){if(speed!==this.m_motorSpeed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed;}};_proto60.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2RevoluteJointDef = new b2RevoluteJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.referenceAngle = %.15f;\n",this.m_referenceAngle);log("  jd.enableLimit = %s;\n",this.m_enableLimit?"true":"false");log("  jd.lowerAngle = %.15f;\n",this.m_lowerAngle);log("  jd.upperAngle = %.15f;\n",this.m_upperAngle);log("  jd.enableMotor = %s;\n",this.m_enableMotor?"true":"false");log("  jd.motorSpeed = %.15f;\n",this.m_motorSpeed);log("  jd.maxMotorTorque = %.15f;\n",this.m_maxMotorTorque);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);};return b2RevoluteJoint;}(b2Joint);b2RevoluteJoint.InitVelocityConstraints_s_P=new b2Vec2();b2RevoluteJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2RevoluteJoint.SolveVelocityConstraints_s_Cdot_v2=new b2Vec2();b2RevoluteJoint.SolveVelocityConstraints_s_Cdot1=new b2Vec2();b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v3=new b2Vec3();b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2=new b2Vec2();b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v2=new b2Vec2();b2RevoluteJoint.SolvePositionConstraints_s_C_v2=new b2Vec2();b2RevoluteJoint.SolvePositionConstraints_s_impulse=new b2Vec2();var b2RopeJointDef=function(_b2JointDef10){_inheritsLoose(b2RopeJointDef,_b2JointDef10);function b2RopeJointDef(){var _this24;_this24=_b2JointDef10.call(this,exports$1.b2JointType.e_ropeJoint)||this;_this24.localAnchorA=new b2Vec2(-1,0);_this24.localAnchorB=new b2Vec2(1,0);_this24.maxLength=0;return _this24;}return b2RopeJointDef;}(b2JointDef);var b2RopeJoint=function(_b2Joint10){_inheritsLoose(b2RopeJoint,_b2Joint10);function b2RopeJoint(def){var _this25;_this25=_b2Joint10.call(this,def)||this;_this25.m_localAnchorA=new b2Vec2();_this25.m_localAnchorB=new b2Vec2();_this25.m_maxLength=0;_this25.m_length=0;_this25.m_impulse=0;_this25.m_indexA=0;_this25.m_indexB=0;_this25.m_u=new b2Vec2();_this25.m_rA=new b2Vec2();_this25.m_rB=new b2Vec2();_this25.m_localCenterA=new b2Vec2();_this25.m_localCenterB=new b2Vec2();_this25.m_invMassA=0;_this25.m_invMassB=0;_this25.m_invIA=0;_this25.m_invIB=0;_this25.m_mass=0;_this25.m_state=exports$1.b2LimitState.e_inactiveLimit;_this25.m_qA=new b2Rot();_this25.m_qB=new b2Rot();_this25.m_lalcA=new b2Vec2();_this25.m_lalcB=new b2Vec2();_this25.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,new b2Vec2(-1,0)));_this25.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,new b2Vec2(1,0)));_this25.m_maxLength=b2Maybe(def.maxLength,0);return _this25;}var _proto61=b2RopeJoint.prototype;_proto61.InitVelocityConstraints=function InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);this.m_u.Copy(cB).SelfAdd(this.m_rB).SelfSub(cA).SelfSub(this.m_rA);this.m_length=this.m_u.Length();var C=this.m_length-this.m_maxLength;if(C>0){this.m_state=exports$1.b2LimitState.e_atUpperLimit;}else {this.m_state=exports$1.b2LimitState.e_inactiveLimit;}if(this.m_length>b2_linearSlop){this.m_u.SelfMul(1/this.m_length);}else {this.m_u.SetZero();this.m_mass=0;this.m_impulse=0;return;}var crA=b2Vec2.CrossVV(this.m_rA,this.m_u);var crB=b2Vec2.CrossVV(this.m_rB,this.m_u);var invMass=this.m_invMassA+this.m_invIA*crA*crA+this.m_invMassB+this.m_invIB*crB*crB;this.m_mass=invMass!==0?1/invMass:0;if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;var P=b2Vec2.MulSV(this.m_impulse,this.m_u,b2RopeJoint.InitVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P);}else {this.m_impulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto61.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var vpA=b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2RopeJoint.SolveVelocityConstraints_s_vpA);var vpB=b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2RopeJoint.SolveVelocityConstraints_s_vpB);var C=this.m_length-this.m_maxLength;var Cdot=b2Vec2.DotVV(this.m_u,b2Vec2.SubVV(vpB,vpA,b2Vec2.s_t0));if(C<0){Cdot+=data.step.inv_dt*C;}var impulse=-this.m_mass*Cdot;var oldImpulse=this.m_impulse;this.m_impulse=b2Min(0,this.m_impulse+impulse);impulse=this.m_impulse-oldImpulse;var P=b2Vec2.MulSV(impulse,this.m_u,b2RopeJoint.SolveVelocityConstraints_s_P);vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*b2Vec2.CrossVV(this.m_rB,P);data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto61.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var u=this.m_u.Copy(cB).SelfAdd(rB).SelfSub(cA).SelfSub(rA);var length=u.Normalize();var C=length-this.m_maxLength;C=b2Clamp(C,0,b2_maxLinearCorrection);var impulse=-this.m_mass*C;var P=b2Vec2.MulSV(impulse,u,b2RopeJoint.SolvePositionConstraints_s_P);cA.SelfMulSub(this.m_invMassA,P);aA-=this.m_invIA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(this.m_invMassB,P);aB+=this.m_invIB*b2Vec2.CrossVV(rB,P);data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return length-this.m_maxLength<b2_linearSlop;};_proto61.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto61.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto61.GetReactionForce=function GetReactionForce(inv_dt,out){return b2Vec2.MulSV(inv_dt*this.m_impulse,this.m_u,out);};_proto61.GetReactionTorque=function GetReactionTorque(inv_dt){return 0;};_proto61.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto61.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto61.SetMaxLength=function SetMaxLength(length){this.m_maxLength=length;};_proto61.GetMaxLength=function GetMaxLength(){return this.m_maxLength;};_proto61.GetLimitState=function GetLimitState(){return this.m_state;};_proto61.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2RopeJointDef = new b2RopeJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.maxLength = %.15f;\n",this.m_maxLength);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);};return b2RopeJoint;}(b2Joint);b2RopeJoint.InitVelocityConstraints_s_P=new b2Vec2();b2RopeJoint.SolveVelocityConstraints_s_vpA=new b2Vec2();b2RopeJoint.SolveVelocityConstraints_s_vpB=new b2Vec2();b2RopeJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2RopeJoint.SolvePositionConstraints_s_P=new b2Vec2();var b2WeldJointDef=function(_b2JointDef11){_inheritsLoose(b2WeldJointDef,_b2JointDef11);function b2WeldJointDef(){var _this26;_this26=_b2JointDef11.call(this,exports$1.b2JointType.e_weldJoint)||this;_this26.localAnchorA=new b2Vec2();_this26.localAnchorB=new b2Vec2();_this26.referenceAngle=0;_this26.frequencyHz=0;_this26.dampingRatio=0;return _this26;}var _proto62=b2WeldJointDef.prototype;_proto62.Initialize=function Initialize(bA,bB,anchor){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);this.referenceAngle=this.bodyB.GetAngle()-this.bodyA.GetAngle();};return b2WeldJointDef;}(b2JointDef);var b2WeldJoint=function(_b2Joint11){_inheritsLoose(b2WeldJoint,_b2Joint11);function b2WeldJoint(def){var _this27;_this27=_b2Joint11.call(this,def)||this;_this27.m_frequencyHz=0;_this27.m_dampingRatio=0;_this27.m_bias=0;_this27.m_localAnchorA=new b2Vec2();_this27.m_localAnchorB=new b2Vec2();_this27.m_referenceAngle=0;_this27.m_gamma=0;_this27.m_impulse=new b2Vec3(0,0,0);_this27.m_indexA=0;_this27.m_indexB=0;_this27.m_rA=new b2Vec2();_this27.m_rB=new b2Vec2();_this27.m_localCenterA=new b2Vec2();_this27.m_localCenterB=new b2Vec2();_this27.m_invMassA=0;_this27.m_invMassB=0;_this27.m_invIA=0;_this27.m_invIB=0;_this27.m_mass=new b2Mat33();_this27.m_qA=new b2Rot();_this27.m_qB=new b2Rot();_this27.m_lalcA=new b2Vec2();_this27.m_lalcB=new b2Vec2();_this27.m_K=new b2Mat33();_this27.m_frequencyHz=b2Maybe(def.frequencyHz,0);_this27.m_dampingRatio=b2Maybe(def.dampingRatio,0);_this27.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));_this27.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));_this27.m_referenceAngle=b2Maybe(def.referenceAngle,0);_this27.m_impulse.SetZero();return _this27;}var _proto63=b2WeldJoint.prototype;_proto63.InitVelocityConstraints=function InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var K=this.m_K;K.ex.x=mA+mB+this.m_rA.y*this.m_rA.y*iA+this.m_rB.y*this.m_rB.y*iB;K.ey.x=-this.m_rA.y*this.m_rA.x*iA-this.m_rB.y*this.m_rB.x*iB;K.ez.x=-this.m_rA.y*iA-this.m_rB.y*iB;K.ex.y=K.ey.x;K.ey.y=mA+mB+this.m_rA.x*this.m_rA.x*iA+this.m_rB.x*this.m_rB.x*iB;K.ez.y=this.m_rA.x*iA+this.m_rB.x*iB;K.ex.z=K.ez.x;K.ey.z=K.ez.y;K.ez.z=iA+iB;if(this.m_frequencyHz>0){K.GetInverse22(this.m_mass);var invM=iA+iB;var m=invM>0?1/invM:0;var C=aB-aA-this.m_referenceAngle;var omega=2*b2_pi*this.m_frequencyHz;var d=2*m*this.m_dampingRatio*omega;var k=m*omega*omega;var h=data.step.dt;this.m_gamma=h*(d+h*k);this.m_gamma=this.m_gamma!==0?1/this.m_gamma:0;this.m_bias=C*h*k*this.m_gamma;invM+=this.m_gamma;this.m_mass.ez.z=invM!==0?1/invM:0;}else {K.GetSymInverse33(this.m_mass);this.m_gamma=0;this.m_bias=0;}if(data.step.warmStarting){this.m_impulse.SelfMul(data.step.dtRatio);var P=b2WeldJoint.InitVelocityConstraints_s_P.Set(this.m_impulse.x,this.m_impulse.y);vA.SelfMulSub(mA,P);wA-=iA*(b2Vec2.CrossVV(this.m_rA,P)+this.m_impulse.z);vB.SelfMulAdd(mB,P);wB+=iB*(b2Vec2.CrossVV(this.m_rB,P)+this.m_impulse.z);}else {this.m_impulse.SetZero();}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto63.SolveVelocityConstraints=function SolveVelocityConstraints(data){var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;if(this.m_frequencyHz>0){var Cdot2=wB-wA;var impulse2=-this.m_mass.ez.z*(Cdot2+this.m_bias+this.m_gamma*this.m_impulse.z);this.m_impulse.z+=impulse2;wA-=iA*impulse2;wB+=iB*impulse2;var Cdot1=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2WeldJoint.SolveVelocityConstraints_s_Cdot1);var impulse1=b2Mat33.MulM33XY(this.m_mass,Cdot1.x,Cdot1.y,b2WeldJoint.SolveVelocityConstraints_s_impulse1).SelfNeg();this.m_impulse.x+=impulse1.x;this.m_impulse.y+=impulse1.y;var P=impulse1;vA.SelfMulSub(mA,P);wA-=iA*b2Vec2.CrossVV(this.m_rA,P);vB.SelfMulAdd(mB,P);wB+=iB*b2Vec2.CrossVV(this.m_rB,P);}else {var _Cdot=b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,this.m_rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,this.m_rA,b2Vec2.s_t1),b2WeldJoint.SolveVelocityConstraints_s_Cdot1);var _Cdot2=wB-wA;var impulse=b2Mat33.MulM33XYZ(this.m_mass,_Cdot.x,_Cdot.y,_Cdot2,b2WeldJoint.SolveVelocityConstraints_s_impulse).SelfNeg();this.m_impulse.SelfAdd(impulse);var _P5=b2WeldJoint.SolveVelocityConstraints_s_P.Set(impulse.x,impulse.y);vA.SelfMulSub(mA,_P5);wA-=iA*(b2Vec2.CrossVV(this.m_rA,_P5)+impulse.z);vB.SelfMulAdd(mB,_P5);wB+=iB*(b2Vec2.CrossVV(this.m_rB,_P5)+impulse.z);}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto63.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var positionError,angularError;var K=this.m_K;K.ex.x=mA+mB+rA.y*rA.y*iA+rB.y*rB.y*iB;K.ey.x=-rA.y*rA.x*iA-rB.y*rB.x*iB;K.ez.x=-rA.y*iA-rB.y*iB;K.ex.y=K.ey.x;K.ey.y=mA+mB+rA.x*rA.x*iA+rB.x*rB.x*iB;K.ez.y=rA.x*iA+rB.x*iB;K.ex.z=K.ez.x;K.ey.z=K.ez.y;K.ez.z=iA+iB;if(this.m_frequencyHz>0){var C1=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2WeldJoint.SolvePositionConstraints_s_C1);positionError=C1.Length();angularError=0;var P=K.Solve22(C1.x,C1.y,b2WeldJoint.SolvePositionConstraints_s_P).SelfNeg();cA.SelfMulSub(mA,P);aA-=iA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(mB,P);aB+=iB*b2Vec2.CrossVV(rB,P);}else {var _C3=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2WeldJoint.SolvePositionConstraints_s_C1);var C2=aB-aA-this.m_referenceAngle;positionError=_C3.Length();angularError=b2Abs(C2);var impulse=K.Solve33(_C3.x,_C3.y,C2,b2WeldJoint.SolvePositionConstraints_s_impulse).SelfNeg();var _P6=b2WeldJoint.SolvePositionConstraints_s_P.Set(impulse.x,impulse.y);cA.SelfMulSub(mA,_P6);aA-=iA*(b2Vec2.CrossVV(this.m_rA,_P6)+impulse.z);cB.SelfMulAdd(mB,_P6);aB+=iB*(b2Vec2.CrossVV(this.m_rB,_P6)+impulse.z);}data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return positionError<=b2_linearSlop&&angularError<=b2_angularSlop;};_proto63.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto63.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto63.GetReactionForce=function GetReactionForce(inv_dt,out){out.x=inv_dt*this.m_impulse.x;out.y=inv_dt*this.m_impulse.y;return out;};_proto63.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_impulse.z;};_proto63.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto63.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto63.GetReferenceAngle=function GetReferenceAngle(){return this.m_referenceAngle;};_proto63.SetFrequency=function SetFrequency(hz){this.m_frequencyHz=hz;};_proto63.GetFrequency=function GetFrequency(){return this.m_frequencyHz;};_proto63.SetDampingRatio=function SetDampingRatio(ratio){this.m_dampingRatio=ratio;};_proto63.GetDampingRatio=function GetDampingRatio(){return this.m_dampingRatio;};_proto63.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2WeldJointDef = new b2WeldJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.referenceAngle = %.15f;\n",this.m_referenceAngle);log("  jd.frequencyHz = %.15f;\n",this.m_frequencyHz);log("  jd.dampingRatio = %.15f;\n",this.m_dampingRatio);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);};return b2WeldJoint;}(b2Joint);b2WeldJoint.InitVelocityConstraints_s_P=new b2Vec2();b2WeldJoint.SolveVelocityConstraints_s_Cdot1=new b2Vec2();b2WeldJoint.SolveVelocityConstraints_s_impulse1=new b2Vec2();b2WeldJoint.SolveVelocityConstraints_s_impulse=new b2Vec3();b2WeldJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2WeldJoint.SolvePositionConstraints_s_C1=new b2Vec2();b2WeldJoint.SolvePositionConstraints_s_P=new b2Vec2();b2WeldJoint.SolvePositionConstraints_s_impulse=new b2Vec3();var b2WheelJointDef=function(_b2JointDef12){_inheritsLoose(b2WheelJointDef,_b2JointDef12);function b2WheelJointDef(){var _this28;_this28=_b2JointDef12.call(this,exports$1.b2JointType.e_wheelJoint)||this;_this28.localAnchorA=new b2Vec2(0,0);_this28.localAnchorB=new b2Vec2(0,0);_this28.localAxisA=new b2Vec2(1,0);_this28.enableMotor=false;_this28.maxMotorTorque=0;_this28.motorSpeed=0;_this28.frequencyHz=2;_this28.dampingRatio=0.7;return _this28;}var _proto64=b2WheelJointDef.prototype;_proto64.Initialize=function Initialize(bA,bB,anchor,axis){this.bodyA=bA;this.bodyB=bB;this.bodyA.GetLocalPoint(anchor,this.localAnchorA);this.bodyB.GetLocalPoint(anchor,this.localAnchorB);this.bodyA.GetLocalVector(axis,this.localAxisA);};return b2WheelJointDef;}(b2JointDef);var b2WheelJoint=function(_b2Joint12){_inheritsLoose(b2WheelJoint,_b2Joint12);function b2WheelJoint(def){var _this29;_this29=_b2Joint12.call(this,def)||this;_this29.m_frequencyHz=0;_this29.m_dampingRatio=0;_this29.m_localAnchorA=new b2Vec2();_this29.m_localAnchorB=new b2Vec2();_this29.m_localXAxisA=new b2Vec2();_this29.m_localYAxisA=new b2Vec2();_this29.m_impulse=0;_this29.m_motorImpulse=0;_this29.m_springImpulse=0;_this29.m_maxMotorTorque=0;_this29.m_motorSpeed=0;_this29.m_enableMotor=false;_this29.m_indexA=0;_this29.m_indexB=0;_this29.m_localCenterA=new b2Vec2();_this29.m_localCenterB=new b2Vec2();_this29.m_invMassA=0;_this29.m_invMassB=0;_this29.m_invIA=0;_this29.m_invIB=0;_this29.m_ax=new b2Vec2();_this29.m_ay=new b2Vec2();_this29.m_sAx=0;_this29.m_sBx=0;_this29.m_sAy=0;_this29.m_sBy=0;_this29.m_mass=0;_this29.m_motorMass=0;_this29.m_springMass=0;_this29.m_bias=0;_this29.m_gamma=0;_this29.m_qA=new b2Rot();_this29.m_qB=new b2Rot();_this29.m_lalcA=new b2Vec2();_this29.m_lalcB=new b2Vec2();_this29.m_rA=new b2Vec2();_this29.m_rB=new b2Vec2();_this29.m_frequencyHz=b2Maybe(def.frequencyHz,2);_this29.m_dampingRatio=b2Maybe(def.dampingRatio,0.7);_this29.m_localAnchorA.Copy(b2Maybe(def.localAnchorA,b2Vec2.ZERO));_this29.m_localAnchorB.Copy(b2Maybe(def.localAnchorB,b2Vec2.ZERO));_this29.m_localXAxisA.Copy(b2Maybe(def.localAxisA,b2Vec2.UNITX));b2Vec2.CrossOneV(_this29.m_localXAxisA,_this29.m_localYAxisA);_this29.m_maxMotorTorque=b2Maybe(def.maxMotorTorque,0);_this29.m_motorSpeed=b2Maybe(def.motorSpeed,0);_this29.m_enableMotor=b2Maybe(def.enableMotor,false);_this29.m_ax.SetZero();_this29.m_ay.SetZero();return _this29;}var _proto65=b2WheelJoint.prototype;_proto65.GetMotorSpeed=function GetMotorSpeed(){return this.m_motorSpeed;};_proto65.GetMaxMotorTorque=function GetMaxMotorTorque(){return this.m_maxMotorTorque;};_proto65.SetSpringFrequencyHz=function SetSpringFrequencyHz(hz){this.m_frequencyHz=hz;};_proto65.GetSpringFrequencyHz=function GetSpringFrequencyHz(){return this.m_frequencyHz;};_proto65.SetSpringDampingRatio=function SetSpringDampingRatio(ratio){this.m_dampingRatio=ratio;};_proto65.GetSpringDampingRatio=function GetSpringDampingRatio(){return this.m_dampingRatio;};_proto65.InitVelocityConstraints=function InitVelocityConstraints(data){this.m_indexA=this.m_bodyA.m_islandIndex;this.m_indexB=this.m_bodyB.m_islandIndex;this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter);this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter);this.m_invMassA=this.m_bodyA.m_invMass;this.m_invMassB=this.m_bodyB.m_invMass;this.m_invIA=this.m_bodyA.m_invI;this.m_invIB=this.m_bodyB.m_invI;var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var d=b2Vec2.SubVV(b2Vec2.AddVV(cB,rB,b2Vec2.s_t0),b2Vec2.AddVV(cA,rA,b2Vec2.s_t1),b2WheelJoint.InitVelocityConstraints_s_d);{b2Rot.MulRV(qA,this.m_localYAxisA,this.m_ay);this.m_sAy=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_ay);this.m_sBy=b2Vec2.CrossVV(rB,this.m_ay);this.m_mass=mA+mB+iA*this.m_sAy*this.m_sAy+iB*this.m_sBy*this.m_sBy;if(this.m_mass>0){this.m_mass=1/this.m_mass;}}this.m_springMass=0;this.m_bias=0;this.m_gamma=0;if(this.m_frequencyHz>0){b2Rot.MulRV(qA,this.m_localXAxisA,this.m_ax);this.m_sAx=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),this.m_ax);this.m_sBx=b2Vec2.CrossVV(rB,this.m_ax);var invMass=mA+mB+iA*this.m_sAx*this.m_sAx+iB*this.m_sBx*this.m_sBx;if(invMass>0){this.m_springMass=1/invMass;var C=b2Vec2.DotVV(d,this.m_ax);var omega=2*b2_pi*this.m_frequencyHz;var damp=2*this.m_springMass*this.m_dampingRatio*omega;var k=this.m_springMass*omega*omega;var h=data.step.dt;this.m_gamma=h*(damp+h*k);if(this.m_gamma>0){this.m_gamma=1/this.m_gamma;}this.m_bias=C*h*k*this.m_gamma;this.m_springMass=invMass+this.m_gamma;if(this.m_springMass>0){this.m_springMass=1/this.m_springMass;}}}else {this.m_springImpulse=0;}if(this.m_enableMotor){this.m_motorMass=iA+iB;if(this.m_motorMass>0){this.m_motorMass=1/this.m_motorMass;}}else {this.m_motorMass=0;this.m_motorImpulse=0;}if(data.step.warmStarting){this.m_impulse*=data.step.dtRatio;this.m_springImpulse*=data.step.dtRatio;this.m_motorImpulse*=data.step.dtRatio;var P=b2Vec2.AddVV(b2Vec2.MulSV(this.m_impulse,this.m_ay,b2Vec2.s_t0),b2Vec2.MulSV(this.m_springImpulse,this.m_ax,b2Vec2.s_t1),b2WheelJoint.InitVelocityConstraints_s_P);var LA=this.m_impulse*this.m_sAy+this.m_springImpulse*this.m_sAx+this.m_motorImpulse;var LB=this.m_impulse*this.m_sBy+this.m_springImpulse*this.m_sBx+this.m_motorImpulse;vA.SelfMulSub(this.m_invMassA,P);wA-=this.m_invIA*LA;vB.SelfMulAdd(this.m_invMassB,P);wB+=this.m_invIB*LB;}else {this.m_impulse=0;this.m_springImpulse=0;this.m_motorImpulse=0;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto65.SolveVelocityConstraints=function SolveVelocityConstraints(data){var mA=this.m_invMassA,mB=this.m_invMassB;var iA=this.m_invIA,iB=this.m_invIB;var vA=data.velocities[this.m_indexA].v;var wA=data.velocities[this.m_indexA].w;var vB=data.velocities[this.m_indexB].v;var wB=data.velocities[this.m_indexB].w;{var Cdot=b2Vec2.DotVV(this.m_ax,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_sBx*wB-this.m_sAx*wA;var impulse=-this.m_springMass*(Cdot+this.m_bias+this.m_gamma*this.m_springImpulse);this.m_springImpulse+=impulse;var P=b2Vec2.MulSV(impulse,this.m_ax,b2WheelJoint.SolveVelocityConstraints_s_P);var LA=impulse*this.m_sAx;var LB=impulse*this.m_sBx;vA.SelfMulSub(mA,P);wA-=iA*LA;vB.SelfMulAdd(mB,P);wB+=iB*LB;}{var _Cdot3=wB-wA-this.m_motorSpeed;var _impulse=-this.m_motorMass*_Cdot3;var oldImpulse=this.m_motorImpulse;var maxImpulse=data.step.dt*this.m_maxMotorTorque;this.m_motorImpulse=b2Clamp(this.m_motorImpulse+_impulse,-maxImpulse,maxImpulse);_impulse=this.m_motorImpulse-oldImpulse;wA-=iA*_impulse;wB+=iB*_impulse;}{var _Cdot4=b2Vec2.DotVV(this.m_ay,b2Vec2.SubVV(vB,vA,b2Vec2.s_t0))+this.m_sBy*wB-this.m_sAy*wA;var _impulse2=-this.m_mass*_Cdot4;this.m_impulse+=_impulse2;var _P7=b2Vec2.MulSV(_impulse2,this.m_ay,b2WheelJoint.SolveVelocityConstraints_s_P);var _LA3=_impulse2*this.m_sAy;var _LB3=_impulse2*this.m_sBy;vA.SelfMulSub(mA,_P7);wA-=iA*_LA3;vB.SelfMulAdd(mB,_P7);wB+=iB*_LB3;}data.velocities[this.m_indexA].w=wA;data.velocities[this.m_indexB].w=wB;};_proto65.SolvePositionConstraints=function SolvePositionConstraints(data){var cA=data.positions[this.m_indexA].c;var aA=data.positions[this.m_indexA].a;var cB=data.positions[this.m_indexB].c;var aB=data.positions[this.m_indexB].a;var qA=this.m_qA.SetAngle(aA),qB=this.m_qB.SetAngle(aB);b2Vec2.SubVV(this.m_localAnchorA,this.m_localCenterA,this.m_lalcA);var rA=b2Rot.MulRV(qA,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,this.m_localCenterB,this.m_lalcB);var rB=b2Rot.MulRV(qB,this.m_lalcB,this.m_rB);var d=b2Vec2.AddVV(b2Vec2.SubVV(cB,cA,b2Vec2.s_t0),b2Vec2.SubVV(rB,rA,b2Vec2.s_t1),b2WheelJoint.SolvePositionConstraints_s_d);var ay=b2Rot.MulRV(qA,this.m_localYAxisA,this.m_ay);var sAy=b2Vec2.CrossVV(b2Vec2.AddVV(d,rA,b2Vec2.s_t0),ay);var sBy=b2Vec2.CrossVV(rB,ay);var C=b2Vec2.DotVV(d,this.m_ay);var k=this.m_invMassA+this.m_invMassB+this.m_invIA*this.m_sAy*this.m_sAy+this.m_invIB*this.m_sBy*this.m_sBy;var impulse;if(k!==0){impulse=-C/k;}else {impulse=0;}var P=b2Vec2.MulSV(impulse,ay,b2WheelJoint.SolvePositionConstraints_s_P);var LA=impulse*sAy;var LB=impulse*sBy;cA.SelfMulSub(this.m_invMassA,P);aA-=this.m_invIA*LA;cB.SelfMulAdd(this.m_invMassB,P);aB+=this.m_invIB*LB;data.positions[this.m_indexA].a=aA;data.positions[this.m_indexB].a=aB;return b2Abs(C)<=b2_linearSlop;};_proto65.GetDefinition=function GetDefinition(def){return def;};_proto65.GetAnchorA=function GetAnchorA(out){return this.m_bodyA.GetWorldPoint(this.m_localAnchorA,out);};_proto65.GetAnchorB=function GetAnchorB(out){return this.m_bodyB.GetWorldPoint(this.m_localAnchorB,out);};_proto65.GetReactionForce=function GetReactionForce(inv_dt,out){out.x=inv_dt*(this.m_impulse*this.m_ay.x+this.m_springImpulse*this.m_ax.x);out.y=inv_dt*(this.m_impulse*this.m_ay.y+this.m_springImpulse*this.m_ax.y);return out;};_proto65.GetReactionTorque=function GetReactionTorque(inv_dt){return inv_dt*this.m_motorImpulse;};_proto65.GetLocalAnchorA=function GetLocalAnchorA(){return this.m_localAnchorA;};_proto65.GetLocalAnchorB=function GetLocalAnchorB(){return this.m_localAnchorB;};_proto65.GetLocalAxisA=function GetLocalAxisA(){return this.m_localXAxisA;};_proto65.GetJointTranslation=function GetJointTranslation(){return this.GetPrismaticJointTranslation();};_proto65.GetJointLinearSpeed=function GetJointLinearSpeed(){return this.GetPrismaticJointSpeed();};_proto65.GetJointAngle=function GetJointAngle(){return this.GetRevoluteJointAngle();};_proto65.GetJointAngularSpeed=function GetJointAngularSpeed(){return this.GetRevoluteJointSpeed();};_proto65.GetPrismaticJointTranslation=function GetPrismaticJointTranslation(){var bA=this.m_bodyA;var bB=this.m_bodyB;var pA=bA.GetWorldPoint(this.m_localAnchorA,new b2Vec2());var pB=bB.GetWorldPoint(this.m_localAnchorB,new b2Vec2());var d=b2Vec2.SubVV(pB,pA,new b2Vec2());var axis=bA.GetWorldVector(this.m_localXAxisA,new b2Vec2());var translation=b2Vec2.DotVV(d,axis);return translation;};_proto65.GetPrismaticJointSpeed=function GetPrismaticJointSpeed(){var bA=this.m_bodyA;var bB=this.m_bodyB;b2Vec2.SubVV(this.m_localAnchorA,bA.m_sweep.localCenter,this.m_lalcA);var rA=b2Rot.MulRV(bA.m_xf.q,this.m_lalcA,this.m_rA);b2Vec2.SubVV(this.m_localAnchorB,bB.m_sweep.localCenter,this.m_lalcB);var rB=b2Rot.MulRV(bB.m_xf.q,this.m_lalcB,this.m_rB);var pA=b2Vec2.AddVV(bA.m_sweep.c,rA,b2Vec2.s_t0);var pB=b2Vec2.AddVV(bB.m_sweep.c,rB,b2Vec2.s_t1);var d=b2Vec2.SubVV(pB,pA,b2Vec2.s_t2);var axis=bA.GetWorldVector(this.m_localXAxisA,new b2Vec2());var vA=bA.m_linearVelocity;var vB=bB.m_linearVelocity;var wA=bA.m_angularVelocity;var wB=bB.m_angularVelocity;var speed=b2Vec2.DotVV(d,b2Vec2.CrossSV(wA,axis,b2Vec2.s_t0))+b2Vec2.DotVV(axis,b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,rA,b2Vec2.s_t1),b2Vec2.s_t0));return speed;};_proto65.GetRevoluteJointAngle=function GetRevoluteJointAngle(){return this.m_bodyB.m_sweep.a-this.m_bodyA.m_sweep.a;};_proto65.GetRevoluteJointSpeed=function GetRevoluteJointSpeed(){var wA=this.m_bodyA.m_angularVelocity;var wB=this.m_bodyB.m_angularVelocity;return wB-wA;};_proto65.IsMotorEnabled=function IsMotorEnabled(){return this.m_enableMotor;};_proto65.EnableMotor=function EnableMotor(flag){if(flag!==this.m_enableMotor){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_enableMotor=flag;}};_proto65.SetMotorSpeed=function SetMotorSpeed(speed){if(speed!==this.m_motorSpeed){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_motorSpeed=speed;}};_proto65.SetMaxMotorTorque=function SetMaxMotorTorque(force){if(force!==this.m_maxMotorTorque){this.m_bodyA.SetAwake(true);this.m_bodyB.SetAwake(true);this.m_maxMotorTorque=force;}};_proto65.GetMotorTorque=function GetMotorTorque(inv_dt){return inv_dt*this.m_motorImpulse;};_proto65.Dump=function Dump(log){var indexA=this.m_bodyA.m_islandIndex;var indexB=this.m_bodyB.m_islandIndex;log("  const jd: b2WheelJointDef = new b2WheelJointDef();\n");log("  jd.bodyA = bodies[%d];\n",indexA);log("  jd.bodyB = bodies[%d];\n",indexB);log("  jd.collideConnected = %s;\n",this.m_collideConnected?"true":"false");log("  jd.localAnchorA.Set(%.15f, %.15f);\n",this.m_localAnchorA.x,this.m_localAnchorA.y);log("  jd.localAnchorB.Set(%.15f, %.15f);\n",this.m_localAnchorB.x,this.m_localAnchorB.y);log("  jd.localAxisA.Set(%.15f, %.15f);\n",this.m_localXAxisA.x,this.m_localXAxisA.y);log("  jd.enableMotor = %s;\n",this.m_enableMotor?"true":"false");log("  jd.motorSpeed = %.15f;\n",this.m_motorSpeed);log("  jd.maxMotorTorque = %.15f;\n",this.m_maxMotorTorque);log("  jd.frequencyHz = %.15f;\n",this.m_frequencyHz);log("  jd.dampingRatio = %.15f;\n",this.m_dampingRatio);log("  joints[%d] = this.m_world.CreateJoint(jd);\n",this.m_index);};return b2WheelJoint;}(b2Joint);b2WheelJoint.InitVelocityConstraints_s_d=new b2Vec2();b2WheelJoint.InitVelocityConstraints_s_P=new b2Vec2();b2WheelJoint.SolveVelocityConstraints_s_P=new b2Vec2();b2WheelJoint.SolvePositionConstraints_s_d=new b2Vec2();b2WheelJoint.SolvePositionConstraints_s_P=new b2Vec2();function b2MixFriction(friction1,friction2){return b2Sqrt(friction1*friction2);}function b2MixRestitution(restitution1,restitution2){return restitution1>restitution2?restitution1:restitution2;}var b2ContactEdge=function(){function b2ContactEdge(contact){this._other=null;this.prev=null;this.next=null;this.contact=contact;}var _proto66=b2ContactEdge.prototype;_proto66.Reset=function Reset(){this._other=null;this.prev=null;this.next=null;};_createClass(b2ContactEdge,[{key:"other",get:function get(){if(this._other===null){throw new Error();}return this._other;},set:function set(value){if(this._other!==null){throw new Error();}this._other=value;}}]);return b2ContactEdge;}();var b2Contact=function(){function b2Contact(){this.m_islandFlag=false;this.m_touchingFlag=false;this.m_enabledFlag=false;this.m_filterFlag=false;this.m_bulletHitFlag=false;this.m_toiFlag=false;this.m_prev=null;this.m_next=null;this.m_nodeA=new b2ContactEdge(this);this.m_nodeB=new b2ContactEdge(this);this.m_indexA=0;this.m_indexB=0;this.m_manifold=new b2Manifold();this.m_toiCount=0;this.m_toi=0;this.m_friction=0;this.m_restitution=0;this.m_tangentSpeed=0;this.m_oldManifold=new b2Manifold();}var _proto67=b2Contact.prototype;_proto67.GetManifold=function GetManifold(){return this.m_manifold;};_proto67.GetWorldManifold=function GetWorldManifold(worldManifold){var bodyA=this.m_fixtureA.GetBody();var bodyB=this.m_fixtureB.GetBody();var shapeA=this.GetShapeA();var shapeB=this.GetShapeB();worldManifold.Initialize(this.m_manifold,bodyA.GetTransform(),shapeA.m_radius,bodyB.GetTransform(),shapeB.m_radius);};_proto67.IsTouching=function IsTouching(){return this.m_touchingFlag;};_proto67.SetEnabled=function SetEnabled(flag){this.m_enabledFlag=flag;};_proto67.IsEnabled=function IsEnabled(){return this.m_enabledFlag;};_proto67.GetNext=function GetNext(){return this.m_next;};_proto67.GetFixtureA=function GetFixtureA(){return this.m_fixtureA;};_proto67.GetChildIndexA=function GetChildIndexA(){return this.m_indexA;};_proto67.GetShapeA=function GetShapeA(){return this.m_fixtureA.GetShape();};_proto67.GetFixtureB=function GetFixtureB(){return this.m_fixtureB;};_proto67.GetChildIndexB=function GetChildIndexB(){return this.m_indexB;};_proto67.GetShapeB=function GetShapeB(){return this.m_fixtureB.GetShape();};_proto67.FlagForFiltering=function FlagForFiltering(){this.m_filterFlag=true;};_proto67.SetFriction=function SetFriction(friction){this.m_friction=friction;};_proto67.GetFriction=function GetFriction(){return this.m_friction;};_proto67.ResetFriction=function ResetFriction(){this.m_friction=b2MixFriction(this.m_fixtureA.m_friction,this.m_fixtureB.m_friction);};_proto67.SetRestitution=function SetRestitution(restitution){this.m_restitution=restitution;};_proto67.GetRestitution=function GetRestitution(){return this.m_restitution;};_proto67.ResetRestitution=function ResetRestitution(){this.m_restitution=b2MixRestitution(this.m_fixtureA.m_restitution,this.m_fixtureB.m_restitution);};_proto67.SetTangentSpeed=function SetTangentSpeed(speed){this.m_tangentSpeed=speed;};_proto67.GetTangentSpeed=function GetTangentSpeed(){return this.m_tangentSpeed;};_proto67.Reset=function Reset(fixtureA,indexA,fixtureB,indexB){this.m_islandFlag=false;this.m_touchingFlag=false;this.m_enabledFlag=true;this.m_filterFlag=false;this.m_bulletHitFlag=false;this.m_toiFlag=false;this.m_fixtureA=fixtureA;this.m_fixtureB=fixtureB;this.m_indexA=indexA;this.m_indexB=indexB;this.m_manifold.pointCount=0;this.m_prev=null;this.m_next=null;this.m_nodeA.Reset();this.m_nodeB.Reset();this.m_toiCount=0;this.m_friction=b2MixFriction(this.m_fixtureA.m_friction,this.m_fixtureB.m_friction);this.m_restitution=b2MixRestitution(this.m_fixtureA.m_restitution,this.m_fixtureB.m_restitution);};_proto67.Update=function Update(listener){var tManifold=this.m_oldManifold;this.m_oldManifold=this.m_manifold;this.m_manifold=tManifold;this.m_enabledFlag=true;var touching=false;var wasTouching=this.m_touchingFlag;var sensorA=this.m_fixtureA.IsSensor();var sensorB=this.m_fixtureB.IsSensor();var sensor=sensorA||sensorB;var bodyA=this.m_fixtureA.GetBody();var bodyB=this.m_fixtureB.GetBody();var xfA=bodyA.GetTransform();var xfB=bodyB.GetTransform();if(sensor){var shapeA=this.GetShapeA();var shapeB=this.GetShapeB();touching=b2TestOverlapShape(shapeA,this.m_indexA,shapeB,this.m_indexB,xfA,xfB);this.m_manifold.pointCount=0;}else {this.Evaluate(this.m_manifold,xfA,xfB);touching=this.m_manifold.pointCount>0;for(var i=0;i<this.m_manifold.pointCount;++i){var mp2=this.m_manifold.points[i];mp2.normalImpulse=0;mp2.tangentImpulse=0;var id2=mp2.id;for(var j=0;j<this.m_oldManifold.pointCount;++j){var mp1=this.m_oldManifold.points[j];if(mp1.id.key===id2.key){mp2.normalImpulse=mp1.normalImpulse;mp2.tangentImpulse=mp1.tangentImpulse;break;}}}if(touching!==wasTouching){bodyA.SetAwake(true);bodyB.SetAwake(true);}}this.m_touchingFlag=touching;if(!wasTouching&&touching&&listener){listener.BeginContact(this);}if(wasTouching&&!touching&&listener){listener.EndContact(this);}if(!sensor&&touching&&listener){listener.PreSolve(this,this.m_oldManifold);}};_proto67.ComputeTOI=function ComputeTOI(sweepA,sweepB){var input=b2Contact.ComputeTOI_s_input;input.proxyA.SetShape(this.GetShapeA(),this.m_indexA);input.proxyB.SetShape(this.GetShapeB(),this.m_indexB);input.sweepA.Copy(sweepA);input.sweepB.Copy(sweepB);input.tMax=b2_linearSlop;var output=b2Contact.ComputeTOI_s_output;b2TimeOfImpact(output,input);return output.t;};return b2Contact;}();b2Contact.ComputeTOI_s_input=new b2TOIInput();b2Contact.ComputeTOI_s_output=new b2TOIOutput();var b2CircleContact=function(_b2Contact){_inheritsLoose(b2CircleContact,_b2Contact);function b2CircleContact(){return _b2Contact.apply(this,arguments)||this;}b2CircleContact.Create=function Create(){return new b2CircleContact();};b2CircleContact.Destroy=function Destroy(contact){};var _proto68=b2CircleContact.prototype;_proto68.Evaluate=function Evaluate(manifold,xfA,xfB){b2CollideCircles(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);};return b2CircleContact;}(b2Contact);var b2PolygonContact=function(_b2Contact2){_inheritsLoose(b2PolygonContact,_b2Contact2);function b2PolygonContact(){return _b2Contact2.apply(this,arguments)||this;}b2PolygonContact.Create=function Create(){return new b2PolygonContact();};b2PolygonContact.Destroy=function Destroy(contact){};var _proto69=b2PolygonContact.prototype;_proto69.Evaluate=function Evaluate(manifold,xfA,xfB){b2CollidePolygons(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);};return b2PolygonContact;}(b2Contact);var b2PolygonAndCircleContact=function(_b2Contact3){_inheritsLoose(b2PolygonAndCircleContact,_b2Contact3);function b2PolygonAndCircleContact(){return _b2Contact3.apply(this,arguments)||this;}b2PolygonAndCircleContact.Create=function Create(){return new b2PolygonAndCircleContact();};b2PolygonAndCircleContact.Destroy=function Destroy(contact){};var _proto70=b2PolygonAndCircleContact.prototype;_proto70.Evaluate=function Evaluate(manifold,xfA,xfB){b2CollidePolygonAndCircle(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);};return b2PolygonAndCircleContact;}(b2Contact);var b2EdgeAndCircleContact=function(_b2Contact4){_inheritsLoose(b2EdgeAndCircleContact,_b2Contact4);function b2EdgeAndCircleContact(){return _b2Contact4.apply(this,arguments)||this;}b2EdgeAndCircleContact.Create=function Create(){return new b2EdgeAndCircleContact();};b2EdgeAndCircleContact.Destroy=function Destroy(contact){};var _proto71=b2EdgeAndCircleContact.prototype;_proto71.Evaluate=function Evaluate(manifold,xfA,xfB){b2CollideEdgeAndCircle(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);};return b2EdgeAndCircleContact;}(b2Contact);var b2EdgeAndPolygonContact=function(_b2Contact5){_inheritsLoose(b2EdgeAndPolygonContact,_b2Contact5);function b2EdgeAndPolygonContact(){return _b2Contact5.apply(this,arguments)||this;}b2EdgeAndPolygonContact.Create=function Create(){return new b2EdgeAndPolygonContact();};b2EdgeAndPolygonContact.Destroy=function Destroy(contact){};var _proto72=b2EdgeAndPolygonContact.prototype;_proto72.Evaluate=function Evaluate(manifold,xfA,xfB){b2CollideEdgeAndPolygon(manifold,this.GetShapeA(),xfA,this.GetShapeB(),xfB);};return b2EdgeAndPolygonContact;}(b2Contact);var b2ChainAndCircleContact=function(_b2Contact6){_inheritsLoose(b2ChainAndCircleContact,_b2Contact6);function b2ChainAndCircleContact(){return _b2Contact6.apply(this,arguments)||this;}b2ChainAndCircleContact.Create=function Create(){return new b2ChainAndCircleContact();};b2ChainAndCircleContact.Destroy=function Destroy(contact){};var _proto73=b2ChainAndCircleContact.prototype;_proto73.Evaluate=function Evaluate(manifold,xfA,xfB){var edge=b2ChainAndCircleContact.Evaluate_s_edge;this.GetShapeA().GetChildEdge(edge,this.m_indexA);b2CollideEdgeAndCircle(manifold,edge,xfA,this.GetShapeB(),xfB);};return b2ChainAndCircleContact;}(b2Contact);b2ChainAndCircleContact.Evaluate_s_edge=new b2EdgeShape();var b2ChainAndPolygonContact=function(_b2Contact7){_inheritsLoose(b2ChainAndPolygonContact,_b2Contact7);function b2ChainAndPolygonContact(){return _b2Contact7.apply(this,arguments)||this;}b2ChainAndPolygonContact.Create=function Create(){return new b2ChainAndPolygonContact();};b2ChainAndPolygonContact.Destroy=function Destroy(contact){};var _proto74=b2ChainAndPolygonContact.prototype;_proto74.Evaluate=function Evaluate(manifold,xfA,xfB){var edge=b2ChainAndPolygonContact.Evaluate_s_edge;this.GetShapeA().GetChildEdge(edge,this.m_indexA);b2CollideEdgeAndPolygon(manifold,edge,xfA,this.GetShapeB(),xfB);};return b2ChainAndPolygonContact;}(b2Contact);b2ChainAndPolygonContact.Evaluate_s_edge=new b2EdgeShape();var b2ContactRegister=function b2ContactRegister(){this.pool=[];this.createFcn=null;this.destroyFcn=null;this.primary=false;};var b2ContactFactory=function(){function b2ContactFactory(){this.m_registers=[];this.InitializeRegisters();}var _proto75=b2ContactFactory.prototype;_proto75.AddType=function AddType(createFcn,destroyFcn,typeA,typeB){var pool=[];function poolCreateFcn(){return pool.pop()||createFcn();}function poolDestroyFcn(contact){pool.push(contact);}this.m_registers[typeA][typeB].pool=pool;this.m_registers[typeA][typeB].createFcn=poolCreateFcn;this.m_registers[typeA][typeB].destroyFcn=poolDestroyFcn;this.m_registers[typeA][typeB].primary=true;if(typeA!==typeB){this.m_registers[typeB][typeA].pool=pool;this.m_registers[typeB][typeA].createFcn=poolCreateFcn;this.m_registers[typeB][typeA].destroyFcn=poolDestroyFcn;this.m_registers[typeB][typeA].primary=false;}};_proto75.InitializeRegisters=function InitializeRegisters(){for(var i=0;i<exports$1.b2ShapeType.e_shapeTypeCount;i++){this.m_registers[i]=[];for(var j=0;j<exports$1.b2ShapeType.e_shapeTypeCount;j++){this.m_registers[i][j]=new b2ContactRegister();}}this.AddType(b2CircleContact.Create,b2CircleContact.Destroy,exports$1.b2ShapeType.e_circleShape,exports$1.b2ShapeType.e_circleShape);this.AddType(b2PolygonAndCircleContact.Create,b2PolygonAndCircleContact.Destroy,exports$1.b2ShapeType.e_polygonShape,exports$1.b2ShapeType.e_circleShape);this.AddType(b2PolygonContact.Create,b2PolygonContact.Destroy,exports$1.b2ShapeType.e_polygonShape,exports$1.b2ShapeType.e_polygonShape);this.AddType(b2EdgeAndCircleContact.Create,b2EdgeAndCircleContact.Destroy,exports$1.b2ShapeType.e_edgeShape,exports$1.b2ShapeType.e_circleShape);this.AddType(b2EdgeAndPolygonContact.Create,b2EdgeAndPolygonContact.Destroy,exports$1.b2ShapeType.e_edgeShape,exports$1.b2ShapeType.e_polygonShape);this.AddType(b2ChainAndCircleContact.Create,b2ChainAndCircleContact.Destroy,exports$1.b2ShapeType.e_chainShape,exports$1.b2ShapeType.e_circleShape);this.AddType(b2ChainAndPolygonContact.Create,b2ChainAndPolygonContact.Destroy,exports$1.b2ShapeType.e_chainShape,exports$1.b2ShapeType.e_polygonShape);};_proto75.Create=function Create(fixtureA,indexA,fixtureB,indexB){var typeA=fixtureA.GetType();var typeB=fixtureB.GetType();var reg=this.m_registers[typeA][typeB];if(reg.createFcn){var c=reg.createFcn();if(reg.primary){c.Reset(fixtureA,indexA,fixtureB,indexB);}else {c.Reset(fixtureB,indexB,fixtureA,indexA);}return c;}else {return null;}};_proto75.Destroy=function Destroy(contact){var typeA=contact.m_fixtureA.GetType();var typeB=contact.m_fixtureB.GetType();var reg=this.m_registers[typeA][typeB];if(reg.destroyFcn){reg.destroyFcn(contact);}};return b2ContactFactory;}();var b2DestructionListener=function(){function b2DestructionListener(){}var _proto76=b2DestructionListener.prototype;_proto76.SayGoodbyeJoint=function SayGoodbyeJoint(joint){};_proto76.SayGoodbyeFixture=function SayGoodbyeFixture(fixture){};_proto76.SayGoodbyeParticleGroup=function SayGoodbyeParticleGroup(group){};_proto76.SayGoodbyeParticle=function SayGoodbyeParticle(system,index){};return b2DestructionListener;}();var b2ContactFilter=function(){function b2ContactFilter(){}var _proto77=b2ContactFilter.prototype;_proto77.ShouldCollide=function ShouldCollide(fixtureA,fixtureB){var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(bodyB.GetType()===exports$1.b2BodyType.b2_staticBody&&bodyA.GetType()===exports$1.b2BodyType.b2_staticBody){return false;}if(!bodyB.ShouldCollideConnected(bodyA)){return false;}var filter1=fixtureA.GetFilterData();var filter2=fixtureB.GetFilterData();if(filter1.groupIndex===filter2.groupIndex&&filter1.groupIndex!==0){return filter1.groupIndex>0;}var collide=(filter1.maskBits&filter2.categoryBits)!==0&&(filter1.categoryBits&filter2.maskBits)!==0;return collide;};_proto77.ShouldCollideFixtureParticle=function ShouldCollideFixtureParticle(fixture,system,index){return true;};_proto77.ShouldCollideParticleParticle=function ShouldCollideParticleParticle(system,indexA,indexB){return true;};return b2ContactFilter;}();b2ContactFilter.b2_defaultFilter=new b2ContactFilter();var b2ContactImpulse=function b2ContactImpulse(){this.normalImpulses=b2MakeNumberArray(b2_maxManifoldPoints);this.tangentImpulses=b2MakeNumberArray(b2_maxManifoldPoints);this.count=0;};var b2ContactListener=function(){function b2ContactListener(){}var _proto78=b2ContactListener.prototype;_proto78.BeginContact=function BeginContact(contact){};_proto78.EndContact=function EndContact(contact){};_proto78.BeginContactFixtureParticle=function BeginContactFixtureParticle(system,contact){};_proto78.EndContactFixtureParticle=function EndContactFixtureParticle(system,contact){};_proto78.BeginContactParticleParticle=function BeginContactParticleParticle(system,contact){};_proto78.EndContactParticleParticle=function EndContactParticleParticle(system,contact){};_proto78.PreSolve=function PreSolve(contact,oldManifold){};_proto78.PostSolve=function PostSolve(contact,impulse){};return b2ContactListener;}();b2ContactListener.b2_defaultListener=new b2ContactListener();var b2QueryCallback=function(){function b2QueryCallback(){}var _proto79=b2QueryCallback.prototype;_proto79.ReportFixture=function ReportFixture(fixture){return true;};_proto79.ReportParticle=function ReportParticle(system,index){return false;};_proto79.ShouldQueryParticleSystem=function ShouldQueryParticleSystem(system){return true;};return b2QueryCallback;}();var b2RayCastCallback=function(){function b2RayCastCallback(){}var _proto80=b2RayCastCallback.prototype;_proto80.ReportFixture=function ReportFixture(fixture,point,normal,fraction){return fraction;};_proto80.ReportParticle=function ReportParticle(system,index,point,normal,fraction){return 0;};_proto80.ShouldQueryParticleSystem=function ShouldQueryParticleSystem(system){return true;};return b2RayCastCallback;}();var b2ContactManager=function(){function b2ContactManager(){this.m_broadPhase=new b2BroadPhase();this.m_contactList=null;this.m_contactCount=0;this.m_contactFilter=b2ContactFilter.b2_defaultFilter;this.m_contactListener=b2ContactListener.b2_defaultListener;this.m_contactFactory=new b2ContactFactory();}var _proto81=b2ContactManager.prototype;_proto81.AddPair=function AddPair(proxyA,proxyB){var fixtureA=proxyA.fixture;var fixtureB=proxyB.fixture;var indexA=proxyA.childIndex;var indexB=proxyB.childIndex;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(bodyA===bodyB){return;}var edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){var fA=edge.contact.GetFixtureA();var fB=edge.contact.GetFixtureB();var iA=edge.contact.GetChildIndexA();var iB=edge.contact.GetChildIndexB();if(fA===fixtureA&&fB===fixtureB&&iA===indexA&&iB===indexB){return;}if(fA===fixtureB&&fB===fixtureA&&iA===indexB&&iB===indexA){return;}}edge=edge.next;}if(this.m_contactFilter&&!this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)){return;}var c=this.m_contactFactory.Create(fixtureA,indexA,fixtureB,indexB);if(c===null){return;}fixtureA=c.GetFixtureA();fixtureB=c.GetFixtureB();indexA=c.GetChildIndexA();indexB=c.GetChildIndexB();bodyA=fixtureA.m_body;bodyB=fixtureB.m_body;c.m_prev=null;c.m_next=this.m_contactList;if(this.m_contactList!==null){this.m_contactList.m_prev=c;}this.m_contactList=c;c.m_nodeA.other=bodyB;c.m_nodeA.prev=null;c.m_nodeA.next=bodyA.m_contactList;if(bodyA.m_contactList!==null){bodyA.m_contactList.prev=c.m_nodeA;}bodyA.m_contactList=c.m_nodeA;c.m_nodeB.other=bodyA;c.m_nodeB.prev=null;c.m_nodeB.next=bodyB.m_contactList;if(bodyB.m_contactList!==null){bodyB.m_contactList.prev=c.m_nodeB;}bodyB.m_contactList=c.m_nodeB;if(!fixtureA.IsSensor()&&!fixtureB.IsSensor()){bodyA.SetAwake(true);bodyB.SetAwake(true);}++this.m_contactCount;};_proto81.FindNewContacts=function FindNewContacts(){var _this30=this;this.m_broadPhase.UpdatePairs(function(proxyA,proxyB){_this30.AddPair(proxyA,proxyB);});};_proto81.Destroy=function Destroy(c){var fixtureA=c.GetFixtureA();var fixtureB=c.GetFixtureB();var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(this.m_contactListener&&c.IsTouching()){this.m_contactListener.EndContact(c);}if(c.m_prev){c.m_prev.m_next=c.m_next;}if(c.m_next){c.m_next.m_prev=c.m_prev;}if(c===this.m_contactList){this.m_contactList=c.m_next;}if(c.m_nodeA.prev){c.m_nodeA.prev.next=c.m_nodeA.next;}if(c.m_nodeA.next){c.m_nodeA.next.prev=c.m_nodeA.prev;}if(c.m_nodeA===bodyA.m_contactList){bodyA.m_contactList=c.m_nodeA.next;}if(c.m_nodeB.prev){c.m_nodeB.prev.next=c.m_nodeB.next;}if(c.m_nodeB.next){c.m_nodeB.next.prev=c.m_nodeB.prev;}if(c.m_nodeB===bodyB.m_contactList){bodyB.m_contactList=c.m_nodeB.next;}if(c.m_manifold.pointCount>0&&!fixtureA.IsSensor()&&!fixtureB.IsSensor()){fixtureA.GetBody().SetAwake(true);fixtureB.GetBody().SetAwake(true);}this.m_contactFactory.Destroy(c);--this.m_contactCount;};_proto81.Collide=function Collide(){var c=this.m_contactList;while(c){var fixtureA=c.GetFixtureA();var fixtureB=c.GetFixtureB();var indexA=c.GetChildIndexA();var indexB=c.GetChildIndexB();var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();if(c.m_filterFlag){if(this.m_contactFilter&&!this.m_contactFilter.ShouldCollide(fixtureA,fixtureB)){var cNuke=c;c=cNuke.m_next;this.Destroy(cNuke);continue;}c.m_filterFlag=false;}var activeA=bodyA.IsAwake()&&bodyA.m_type!==exports$1.b2BodyType.b2_staticBody;var activeB=bodyB.IsAwake()&&bodyB.m_type!==exports$1.b2BodyType.b2_staticBody;if(!activeA&&!activeB){c=c.m_next;continue;}var treeNodeA=fixtureA.m_proxies[indexA].treeNode;var treeNodeB=fixtureB.m_proxies[indexB].treeNode;var overlap=b2TestOverlapAABB(treeNodeA.aabb,treeNodeB.aabb);if(!overlap){var _cNuke=c;c=_cNuke.m_next;this.Destroy(_cNuke);continue;}c.Update(this.m_contactListener);c=c.m_next;}};return b2ContactManager;}();var b2Profile=function(){function b2Profile(){this.step=0;this.collide=0;this.solve=0;this.solveInit=0;this.solveVelocity=0;this.solvePosition=0;this.broadphase=0;this.solveTOI=0;}var _proto82=b2Profile.prototype;_proto82.Reset=function Reset(){this.step=0;this.collide=0;this.solve=0;this.solveInit=0;this.solveVelocity=0;this.solvePosition=0;this.broadphase=0;this.solveTOI=0;return this;};return b2Profile;}();var b2TimeStep=function(){function b2TimeStep(){this.dt=0;this.inv_dt=0;this.dtRatio=0;this.velocityIterations=0;this.positionIterations=0;this.particleIterations=0;this.warmStarting=false;}var _proto83=b2TimeStep.prototype;_proto83.Copy=function Copy(step){this.dt=step.dt;this.inv_dt=step.inv_dt;this.dtRatio=step.dtRatio;this.positionIterations=step.positionIterations;this.velocityIterations=step.velocityIterations;this.particleIterations=step.particleIterations;this.warmStarting=step.warmStarting;return this;};return b2TimeStep;}();var b2Position=function(){function b2Position(){this.c=new b2Vec2();this.a=0;}b2Position.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2Position();});};return b2Position;}();var b2Velocity=function(){function b2Velocity(){this.v=new b2Vec2();this.w=0;}b2Velocity.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2Velocity();});};return b2Velocity;}();var b2SolverData=function b2SolverData(){this.step=new b2TimeStep();};var g_blockSolve=false;var b2VelocityConstraintPoint=function(){function b2VelocityConstraintPoint(){this.rA=new b2Vec2();this.rB=new b2Vec2();this.normalImpulse=0;this.tangentImpulse=0;this.normalMass=0;this.tangentMass=0;this.velocityBias=0;}b2VelocityConstraintPoint.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2VelocityConstraintPoint();});};return b2VelocityConstraintPoint;}();var b2ContactVelocityConstraint=function(){function b2ContactVelocityConstraint(){this.points=b2VelocityConstraintPoint.MakeArray(b2_maxManifoldPoints);this.normal=new b2Vec2();this.tangent=new b2Vec2();this.normalMass=new b2Mat22();this.K=new b2Mat22();this.indexA=0;this.indexB=0;this.invMassA=0;this.invMassB=0;this.invIA=0;this.invIB=0;this.friction=0;this.restitution=0;this.tangentSpeed=0;this.pointCount=0;this.contactIndex=0;}b2ContactVelocityConstraint.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2ContactVelocityConstraint();});};return b2ContactVelocityConstraint;}();var b2ContactPositionConstraint=function(){function b2ContactPositionConstraint(){this.localPoints=b2Vec2.MakeArray(b2_maxManifoldPoints);this.localNormal=new b2Vec2();this.localPoint=new b2Vec2();this.indexA=0;this.indexB=0;this.invMassA=0;this.invMassB=0;this.localCenterA=new b2Vec2();this.localCenterB=new b2Vec2();this.invIA=0;this.invIB=0;this.type=exports$1.b2ManifoldType.e_unknown;this.radiusA=0;this.radiusB=0;this.pointCount=0;}b2ContactPositionConstraint.MakeArray=function MakeArray(length){return b2MakeArray(length,function(i){return new b2ContactPositionConstraint();});};return b2ContactPositionConstraint;}();var b2ContactSolverDef=function b2ContactSolverDef(){this.step=new b2TimeStep();this.count=0;};var b2PositionSolverManifold=function(){function b2PositionSolverManifold(){this.normal=new b2Vec2();this.point=new b2Vec2();this.separation=0;}var _proto84=b2PositionSolverManifold.prototype;_proto84.Initialize=function Initialize(pc,xfA,xfB,index){var pointA=b2PositionSolverManifold.Initialize_s_pointA;var pointB=b2PositionSolverManifold.Initialize_s_pointB;var planePoint=b2PositionSolverManifold.Initialize_s_planePoint;var clipPoint=b2PositionSolverManifold.Initialize_s_clipPoint;switch(pc.type){case exports$1.b2ManifoldType.e_circles:{b2Transform.MulXV(xfA,pc.localPoint,pointA);b2Transform.MulXV(xfB,pc.localPoints[0],pointB);b2Vec2.SubVV(pointB,pointA,this.normal).SelfNormalize();b2Vec2.MidVV(pointA,pointB,this.point);this.separation=b2Vec2.DotVV(b2Vec2.SubVV(pointB,pointA,b2Vec2.s_t0),this.normal)-pc.radiusA-pc.radiusB;break;}case exports$1.b2ManifoldType.e_faceA:{b2Rot.MulRV(xfA.q,pc.localNormal,this.normal);b2Transform.MulXV(xfA,pc.localPoint,planePoint);b2Transform.MulXV(xfB,pc.localPoints[index],clipPoint);this.separation=b2Vec2.DotVV(b2Vec2.SubVV(clipPoint,planePoint,b2Vec2.s_t0),this.normal)-pc.radiusA-pc.radiusB;this.point.Copy(clipPoint);break;}case exports$1.b2ManifoldType.e_faceB:{b2Rot.MulRV(xfB.q,pc.localNormal,this.normal);b2Transform.MulXV(xfB,pc.localPoint,planePoint);b2Transform.MulXV(xfA,pc.localPoints[index],clipPoint);this.separation=b2Vec2.DotVV(b2Vec2.SubVV(clipPoint,planePoint,b2Vec2.s_t0),this.normal)-pc.radiusA-pc.radiusB;this.point.Copy(clipPoint);this.normal.SelfNeg();break;}}};return b2PositionSolverManifold;}();b2PositionSolverManifold.Initialize_s_pointA=new b2Vec2();b2PositionSolverManifold.Initialize_s_pointB=new b2Vec2();b2PositionSolverManifold.Initialize_s_planePoint=new b2Vec2();b2PositionSolverManifold.Initialize_s_clipPoint=new b2Vec2();var b2ContactSolver=function(){function b2ContactSolver(){this.m_step=new b2TimeStep();this.m_positionConstraints=b2ContactPositionConstraint.MakeArray(1024);this.m_velocityConstraints=b2ContactVelocityConstraint.MakeArray(1024);this.m_count=0;}var _proto85=b2ContactSolver.prototype;_proto85.Initialize=function Initialize(def){this.m_step.Copy(def.step);this.m_count=def.count;if(this.m_positionConstraints.length<this.m_count){var new_length=b2Max(this.m_positionConstraints.length*2,this.m_count);while(this.m_positionConstraints.length<new_length){this.m_positionConstraints[this.m_positionConstraints.length]=new b2ContactPositionConstraint();}}if(this.m_velocityConstraints.length<this.m_count){var _new_length=b2Max(this.m_velocityConstraints.length*2,this.m_count);while(this.m_velocityConstraints.length<_new_length){this.m_velocityConstraints[this.m_velocityConstraints.length]=new b2ContactVelocityConstraint();}}this.m_positions=def.positions;this.m_velocities=def.velocities;this.m_contacts=def.contacts;for(var i=0;i<this.m_count;++i){var contact=this.m_contacts[i];var fixtureA=contact.m_fixtureA;var fixtureB=contact.m_fixtureB;var shapeA=fixtureA.GetShape();var shapeB=fixtureB.GetShape();var radiusA=shapeA.m_radius;var radiusB=shapeB.m_radius;var bodyA=fixtureA.GetBody();var bodyB=fixtureB.GetBody();var manifold=contact.GetManifold();var pointCount=manifold.pointCount;var vc=this.m_velocityConstraints[i];vc.friction=contact.m_friction;vc.restitution=contact.m_restitution;vc.tangentSpeed=contact.m_tangentSpeed;vc.indexA=bodyA.m_islandIndex;vc.indexB=bodyB.m_islandIndex;vc.invMassA=bodyA.m_invMass;vc.invMassB=bodyB.m_invMass;vc.invIA=bodyA.m_invI;vc.invIB=bodyB.m_invI;vc.contactIndex=i;vc.pointCount=pointCount;vc.K.SetZero();vc.normalMass.SetZero();var pc=this.m_positionConstraints[i];pc.indexA=bodyA.m_islandIndex;pc.indexB=bodyB.m_islandIndex;pc.invMassA=bodyA.m_invMass;pc.invMassB=bodyB.m_invMass;pc.localCenterA.Copy(bodyA.m_sweep.localCenter);pc.localCenterB.Copy(bodyB.m_sweep.localCenter);pc.invIA=bodyA.m_invI;pc.invIB=bodyB.m_invI;pc.localNormal.Copy(manifold.localNormal);pc.localPoint.Copy(manifold.localPoint);pc.pointCount=pointCount;pc.radiusA=radiusA;pc.radiusB=radiusB;pc.type=manifold.type;for(var j=0;j<pointCount;++j){var cp=manifold.points[j];var vcp=vc.points[j];if(this.m_step.warmStarting){vcp.normalImpulse=this.m_step.dtRatio*cp.normalImpulse;vcp.tangentImpulse=this.m_step.dtRatio*cp.tangentImpulse;}else {vcp.normalImpulse=0;vcp.tangentImpulse=0;}vcp.rA.SetZero();vcp.rB.SetZero();vcp.normalMass=0;vcp.tangentMass=0;vcp.velocityBias=0;pc.localPoints[j].Copy(cp.localPoint);}}return this;};_proto85.InitializeVelocityConstraints=function InitializeVelocityConstraints(){var xfA=b2ContactSolver.InitializeVelocityConstraints_s_xfA;var xfB=b2ContactSolver.InitializeVelocityConstraints_s_xfB;var worldManifold=b2ContactSolver.InitializeVelocityConstraints_s_worldManifold;var k_maxConditionNumber=1000;for(var i=0;i<this.m_count;++i){var vc=this.m_velocityConstraints[i];var pc=this.m_positionConstraints[i];var radiusA=pc.radiusA;var radiusB=pc.radiusB;var manifold=this.m_contacts[vc.contactIndex].GetManifold();var indexA=vc.indexA;var indexB=vc.indexB;var mA=vc.invMassA;var mB=vc.invMassB;var iA=vc.invIA;var iB=vc.invIB;var localCenterA=pc.localCenterA;var localCenterB=pc.localCenterB;var cA=this.m_positions[indexA].c;var aA=this.m_positions[indexA].a;var vA=this.m_velocities[indexA].v;var wA=this.m_velocities[indexA].w;var cB=this.m_positions[indexB].c;var aB=this.m_positions[indexB].a;var vB=this.m_velocities[indexB].v;var wB=this.m_velocities[indexB].w;xfA.q.SetAngle(aA);xfB.q.SetAngle(aB);b2Vec2.SubVV(cA,b2Rot.MulRV(xfA.q,localCenterA,b2Vec2.s_t0),xfA.p);b2Vec2.SubVV(cB,b2Rot.MulRV(xfB.q,localCenterB,b2Vec2.s_t0),xfB.p);worldManifold.Initialize(manifold,xfA,radiusA,xfB,radiusB);vc.normal.Copy(worldManifold.normal);b2Vec2.CrossVOne(vc.normal,vc.tangent);var pointCount=vc.pointCount;for(var j=0;j<pointCount;++j){var vcp=vc.points[j];b2Vec2.SubVV(worldManifold.points[j],cA,vcp.rA);b2Vec2.SubVV(worldManifold.points[j],cB,vcp.rB);var rnA=b2Vec2.CrossVV(vcp.rA,vc.normal);var rnB=b2Vec2.CrossVV(vcp.rB,vc.normal);var kNormal=mA+mB+iA*rnA*rnA+iB*rnB*rnB;vcp.normalMass=kNormal>0?1/kNormal:0;var tangent=vc.tangent;var rtA=b2Vec2.CrossVV(vcp.rA,tangent);var rtB=b2Vec2.CrossVV(vcp.rB,tangent);var kTangent=mA+mB+iA*rtA*rtA+iB*rtB*rtB;vcp.tangentMass=kTangent>0?1/kTangent:0;vcp.velocityBias=0;var vRel=b2Vec2.DotVV(vc.normal,b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,vcp.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,vcp.rA,b2Vec2.s_t1),b2Vec2.s_t0));if(vRel<-b2_velocityThreshold){vcp.velocityBias+=-vc.restitution*vRel;}}if(vc.pointCount===2&&g_blockSolve){var vcp1=vc.points[0];var vcp2=vc.points[1];var rn1A=b2Vec2.CrossVV(vcp1.rA,vc.normal);var rn1B=b2Vec2.CrossVV(vcp1.rB,vc.normal);var rn2A=b2Vec2.CrossVV(vcp2.rA,vc.normal);var rn2B=b2Vec2.CrossVV(vcp2.rB,vc.normal);var k11=mA+mB+iA*rn1A*rn1A+iB*rn1B*rn1B;var k22=mA+mB+iA*rn2A*rn2A+iB*rn2B*rn2B;var k12=mA+mB+iA*rn1A*rn2A+iB*rn1B*rn2B;if(k11*k11<k_maxConditionNumber*(k11*k22-k12*k12)){vc.K.ex.Set(k11,k12);vc.K.ey.Set(k12,k22);vc.K.GetInverse(vc.normalMass);}else {vc.pointCount=1;}}}};_proto85.WarmStart=function WarmStart(){var P=b2ContactSolver.WarmStart_s_P;for(var i=0;i<this.m_count;++i){var vc=this.m_velocityConstraints[i];var indexA=vc.indexA;var indexB=vc.indexB;var mA=vc.invMassA;var iA=vc.invIA;var mB=vc.invMassB;var iB=vc.invIB;var pointCount=vc.pointCount;var vA=this.m_velocities[indexA].v;var wA=this.m_velocities[indexA].w;var vB=this.m_velocities[indexB].v;var wB=this.m_velocities[indexB].w;var normal=vc.normal;var tangent=vc.tangent;for(var j=0;j<pointCount;++j){var vcp=vc.points[j];b2Vec2.AddVV(b2Vec2.MulSV(vcp.normalImpulse,normal,b2Vec2.s_t0),b2Vec2.MulSV(vcp.tangentImpulse,tangent,b2Vec2.s_t1),P);wA-=iA*b2Vec2.CrossVV(vcp.rA,P);vA.SelfMulSub(mA,P);wB+=iB*b2Vec2.CrossVV(vcp.rB,P);vB.SelfMulAdd(mB,P);}this.m_velocities[indexA].w=wA;this.m_velocities[indexB].w=wB;}};_proto85.SolveVelocityConstraints=function SolveVelocityConstraints(){var dv=b2ContactSolver.SolveVelocityConstraints_s_dv;var dv1=b2ContactSolver.SolveVelocityConstraints_s_dv1;var dv2=b2ContactSolver.SolveVelocityConstraints_s_dv2;var P=b2ContactSolver.SolveVelocityConstraints_s_P;var a=b2ContactSolver.SolveVelocityConstraints_s_a;var b=b2ContactSolver.SolveVelocityConstraints_s_b;var x=b2ContactSolver.SolveVelocityConstraints_s_x;var d=b2ContactSolver.SolveVelocityConstraints_s_d;var P1=b2ContactSolver.SolveVelocityConstraints_s_P1;var P2=b2ContactSolver.SolveVelocityConstraints_s_P2;var P1P2=b2ContactSolver.SolveVelocityConstraints_s_P1P2;for(var i=0;i<this.m_count;++i){var vc=this.m_velocityConstraints[i];var indexA=vc.indexA;var indexB=vc.indexB;var mA=vc.invMassA;var iA=vc.invIA;var mB=vc.invMassB;var iB=vc.invIB;var pointCount=vc.pointCount;var vA=this.m_velocities[indexA].v;var wA=this.m_velocities[indexA].w;var vB=this.m_velocities[indexB].v;var wB=this.m_velocities[indexB].w;var normal=vc.normal;var tangent=vc.tangent;var friction=vc.friction;for(var j=0;j<pointCount;++j){var vcp=vc.points[j];b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,vcp.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,vcp.rA,b2Vec2.s_t1),dv);var vt=b2Vec2.DotVV(dv,tangent)-vc.tangentSpeed;var lambda=vcp.tangentMass*-vt;var maxFriction=friction*vcp.normalImpulse;var newImpulse=b2Clamp(vcp.tangentImpulse+lambda,-maxFriction,maxFriction);lambda=newImpulse-vcp.tangentImpulse;vcp.tangentImpulse=newImpulse;b2Vec2.MulSV(lambda,tangent,P);vA.SelfMulSub(mA,P);wA-=iA*b2Vec2.CrossVV(vcp.rA,P);vB.SelfMulAdd(mB,P);wB+=iB*b2Vec2.CrossVV(vcp.rB,P);}if(vc.pointCount===1||g_blockSolve===false){for(var _j3=0;_j3<pointCount;++_j3){var _vcp=vc.points[_j3];b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,_vcp.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,_vcp.rA,b2Vec2.s_t1),dv);var vn=b2Vec2.DotVV(dv,normal);var _lambda=-_vcp.normalMass*(vn-_vcp.velocityBias);var _newImpulse2=b2Max(_vcp.normalImpulse+_lambda,0);_lambda=_newImpulse2-_vcp.normalImpulse;_vcp.normalImpulse=_newImpulse2;b2Vec2.MulSV(_lambda,normal,P);vA.SelfMulSub(mA,P);wA-=iA*b2Vec2.CrossVV(_vcp.rA,P);vB.SelfMulAdd(mB,P);wB+=iB*b2Vec2.CrossVV(_vcp.rB,P);}}else {var cp1=vc.points[0];var cp2=vc.points[1];a.Set(cp1.normalImpulse,cp2.normalImpulse);b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,cp1.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,cp1.rA,b2Vec2.s_t1),dv1);b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB,wB,cp2.rB,b2Vec2.s_t0),b2Vec2.AddVCrossSV(vA,wA,cp2.rA,b2Vec2.s_t1),dv2);var vn1=b2Vec2.DotVV(dv1,normal);var vn2=b2Vec2.DotVV(dv2,normal);b.x=vn1-cp1.velocityBias;b.y=vn2-cp2.velocityBias;b.SelfSub(b2Mat22.MulMV(vc.K,a,b2Vec2.s_t0));for(;;){b2Mat22.MulMV(vc.normalMass,b,x).SelfNeg();if(x.x>=0&&x.y>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break;}x.x=-cp1.normalMass*b.x;x.y=0;vn1=0;vn2=vc.K.ex.y*x.x+b.y;if(x.x>=0&&vn2>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break;}x.x=0;x.y=-cp2.normalMass*b.y;vn1=vc.K.ey.x*x.y+b.x;vn2=0;if(x.y>=0&&vn1>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break;}x.x=0;x.y=0;vn1=b.x;vn2=b.y;if(vn1>=0&&vn2>=0){b2Vec2.SubVV(x,a,d);b2Vec2.MulSV(d.x,normal,P1);b2Vec2.MulSV(d.y,normal,P2);b2Vec2.AddVV(P1,P2,P1P2);vA.SelfMulSub(mA,P1P2);wA-=iA*(b2Vec2.CrossVV(cp1.rA,P1)+b2Vec2.CrossVV(cp2.rA,P2));vB.SelfMulAdd(mB,P1P2);wB+=iB*(b2Vec2.CrossVV(cp1.rB,P1)+b2Vec2.CrossVV(cp2.rB,P2));cp1.normalImpulse=x.x;cp2.normalImpulse=x.y;break;}break;}}this.m_velocities[indexA].w=wA;this.m_velocities[indexB].w=wB;}};_proto85.StoreImpulses=function StoreImpulses(){for(var i=0;i<this.m_count;++i){var vc=this.m_velocityConstraints[i];var manifold=this.m_contacts[vc.contactIndex].GetManifold();for(var j=0;j<vc.pointCount;++j){manifold.points[j].normalImpulse=vc.points[j].normalImpulse;manifold.points[j].tangentImpulse=vc.points[j].tangentImpulse;}}};_proto85.SolvePositionConstraints=function SolvePositionConstraints(){var xfA=b2ContactSolver.SolvePositionConstraints_s_xfA;var xfB=b2ContactSolver.SolvePositionConstraints_s_xfB;var psm=b2ContactSolver.SolvePositionConstraints_s_psm;var rA=b2ContactSolver.SolvePositionConstraints_s_rA;var rB=b2ContactSolver.SolvePositionConstraints_s_rB;var P=b2ContactSolver.SolvePositionConstraints_s_P;var minSeparation=0;for(var i=0;i<this.m_count;++i){var pc=this.m_positionConstraints[i];var indexA=pc.indexA;var indexB=pc.indexB;var localCenterA=pc.localCenterA;var mA=pc.invMassA;var iA=pc.invIA;var localCenterB=pc.localCenterB;var mB=pc.invMassB;var iB=pc.invIB;var pointCount=pc.pointCount;var cA=this.m_positions[indexA].c;var aA=this.m_positions[indexA].a;var cB=this.m_positions[indexB].c;var aB=this.m_positions[indexB].a;for(var j=0;j<pointCount;++j){xfA.q.SetAngle(aA);xfB.q.SetAngle(aB);b2Vec2.SubVV(cA,b2Rot.MulRV(xfA.q,localCenterA,b2Vec2.s_t0),xfA.p);b2Vec2.SubVV(cB,b2Rot.MulRV(xfB.q,localCenterB,b2Vec2.s_t0),xfB.p);psm.Initialize(pc,xfA,xfB,j);var normal=psm.normal;var point=psm.point;var separation=psm.separation;b2Vec2.SubVV(point,cA,rA);b2Vec2.SubVV(point,cB,rB);minSeparation=b2Min(minSeparation,separation);var C=b2Clamp(b2_baumgarte*(separation+b2_linearSlop),-b2_maxLinearCorrection,0);var rnA=b2Vec2.CrossVV(rA,normal);var rnB=b2Vec2.CrossVV(rB,normal);var K=mA+mB+iA*rnA*rnA+iB*rnB*rnB;var impulse=K>0?-C/K:0;b2Vec2.MulSV(impulse,normal,P);cA.SelfMulSub(mA,P);aA-=iA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(mB,P);aB+=iB*b2Vec2.CrossVV(rB,P);}this.m_positions[indexA].a=aA;this.m_positions[indexB].a=aB;}return minSeparation>-3*b2_linearSlop;};_proto85.SolveTOIPositionConstraints=function SolveTOIPositionConstraints(toiIndexA,toiIndexB){var xfA=b2ContactSolver.SolveTOIPositionConstraints_s_xfA;var xfB=b2ContactSolver.SolveTOIPositionConstraints_s_xfB;var psm=b2ContactSolver.SolveTOIPositionConstraints_s_psm;var rA=b2ContactSolver.SolveTOIPositionConstraints_s_rA;var rB=b2ContactSolver.SolveTOIPositionConstraints_s_rB;var P=b2ContactSolver.SolveTOIPositionConstraints_s_P;var minSeparation=0;for(var i=0;i<this.m_count;++i){var pc=this.m_positionConstraints[i];var indexA=pc.indexA;var indexB=pc.indexB;var localCenterA=pc.localCenterA;var localCenterB=pc.localCenterB;var pointCount=pc.pointCount;var mA=0;var iA=0;if(indexA===toiIndexA||indexA===toiIndexB){mA=pc.invMassA;iA=pc.invIA;}var mB=0;var iB=0;if(indexB===toiIndexA||indexB===toiIndexB){mB=pc.invMassB;iB=pc.invIB;}var cA=this.m_positions[indexA].c;var aA=this.m_positions[indexA].a;var cB=this.m_positions[indexB].c;var aB=this.m_positions[indexB].a;for(var j=0;j<pointCount;++j){xfA.q.SetAngle(aA);xfB.q.SetAngle(aB);b2Vec2.SubVV(cA,b2Rot.MulRV(xfA.q,localCenterA,b2Vec2.s_t0),xfA.p);b2Vec2.SubVV(cB,b2Rot.MulRV(xfB.q,localCenterB,b2Vec2.s_t0),xfB.p);psm.Initialize(pc,xfA,xfB,j);var normal=psm.normal;var point=psm.point;var separation=psm.separation;b2Vec2.SubVV(point,cA,rA);b2Vec2.SubVV(point,cB,rB);minSeparation=b2Min(minSeparation,separation);var C=b2Clamp(b2_toiBaumgarte*(separation+b2_linearSlop),-b2_maxLinearCorrection,0);var rnA=b2Vec2.CrossVV(rA,normal);var rnB=b2Vec2.CrossVV(rB,normal);var K=mA+mB+iA*rnA*rnA+iB*rnB*rnB;var impulse=K>0?-C/K:0;b2Vec2.MulSV(impulse,normal,P);cA.SelfMulSub(mA,P);aA-=iA*b2Vec2.CrossVV(rA,P);cB.SelfMulAdd(mB,P);aB+=iB*b2Vec2.CrossVV(rB,P);}this.m_positions[indexA].a=aA;this.m_positions[indexB].a=aB;}return minSeparation>=-1.5*b2_linearSlop;};return b2ContactSolver;}();b2ContactSolver.InitializeVelocityConstraints_s_xfA=new b2Transform();b2ContactSolver.InitializeVelocityConstraints_s_xfB=new b2Transform();b2ContactSolver.InitializeVelocityConstraints_s_worldManifold=new b2WorldManifold();b2ContactSolver.WarmStart_s_P=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_dv=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_dv1=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_dv2=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_P=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_a=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_b=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_x=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_d=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_P1=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_P2=new b2Vec2();b2ContactSolver.SolveVelocityConstraints_s_P1P2=new b2Vec2();b2ContactSolver.SolvePositionConstraints_s_xfA=new b2Transform();b2ContactSolver.SolvePositionConstraints_s_xfB=new b2Transform();b2ContactSolver.SolvePositionConstraints_s_psm=new b2PositionSolverManifold();b2ContactSolver.SolvePositionConstraints_s_rA=new b2Vec2();b2ContactSolver.SolvePositionConstraints_s_rB=new b2Vec2();b2ContactSolver.SolvePositionConstraints_s_P=new b2Vec2();b2ContactSolver.SolveTOIPositionConstraints_s_xfA=new b2Transform();b2ContactSolver.SolveTOIPositionConstraints_s_xfB=new b2Transform();b2ContactSolver.SolveTOIPositionConstraints_s_psm=new b2PositionSolverManifold();b2ContactSolver.SolveTOIPositionConstraints_s_rA=new b2Vec2();b2ContactSolver.SolveTOIPositionConstraints_s_rB=new b2Vec2();b2ContactSolver.SolveTOIPositionConstraints_s_P=new b2Vec2();var b2Island=function(){function b2Island(){this.m_bodies=[];this.m_contacts=[];this.m_joints=[];this.m_positions=b2Position.MakeArray(1024);this.m_velocities=b2Velocity.MakeArray(1024);this.m_bodyCount=0;this.m_jointCount=0;this.m_contactCount=0;this.m_bodyCapacity=0;this.m_contactCapacity=0;this.m_jointCapacity=0;}var _proto86=b2Island.prototype;_proto86.Initialize=function Initialize(bodyCapacity,contactCapacity,jointCapacity,listener){this.m_bodyCapacity=bodyCapacity;this.m_contactCapacity=contactCapacity;this.m_jointCapacity=jointCapacity;this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;this.m_listener=listener;if(this.m_positions.length<bodyCapacity){var new_length=b2Max(this.m_positions.length*2,bodyCapacity);while(this.m_positions.length<new_length){this.m_positions[this.m_positions.length]=new b2Position();}}if(this.m_velocities.length<bodyCapacity){var _new_length2=b2Max(this.m_velocities.length*2,bodyCapacity);while(this.m_velocities.length<_new_length2){this.m_velocities[this.m_velocities.length]=new b2Velocity();}}};_proto86.Clear=function Clear(){this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;};_proto86.AddBody=function AddBody(body){body.m_islandIndex=this.m_bodyCount;this.m_bodies[this.m_bodyCount++]=body;};_proto86.AddContact=function AddContact(contact){this.m_contacts[this.m_contactCount++]=contact;};_proto86.AddJoint=function AddJoint(joint){this.m_joints[this.m_jointCount++]=joint;};_proto86.Solve=function Solve(profile,step,gravity,allowSleep){var timer=b2Island.s_timer.Reset();var h=step.dt;for(var i=0;i<this.m_bodyCount;++i){var b=this.m_bodies[i];this.m_positions[i].c.Copy(b.m_sweep.c);var a=b.m_sweep.a;var v=this.m_velocities[i].v.Copy(b.m_linearVelocity);var w=b.m_angularVelocity;b.m_sweep.c0.Copy(b.m_sweep.c);b.m_sweep.a0=b.m_sweep.a;if(b.m_type===exports$1.b2BodyType.b2_dynamicBody){v.x+=h*(b.m_gravityScale*gravity.x+b.m_invMass*b.m_force.x);v.y+=h*(b.m_gravityScale*gravity.y+b.m_invMass*b.m_force.y);w+=h*b.m_invI*b.m_torque;v.SelfMul(1.0/(1.0+h*b.m_linearDamping));w*=1.0/(1.0+h*b.m_angularDamping);}this.m_positions[i].a=a;this.m_velocities[i].w=w;}timer.Reset();var solverData=b2Island.s_solverData;solverData.step.Copy(step);solverData.positions=this.m_positions;solverData.velocities=this.m_velocities;var contactSolverDef=b2Island.s_contactSolverDef;contactSolverDef.step.Copy(step);contactSolverDef.contacts=this.m_contacts;contactSolverDef.count=this.m_contactCount;contactSolverDef.positions=this.m_positions;contactSolverDef.velocities=this.m_velocities;var contactSolver=b2Island.s_contactSolver.Initialize(contactSolverDef);contactSolver.InitializeVelocityConstraints();if(step.warmStarting){contactSolver.WarmStart();}for(var _i15=0;_i15<this.m_jointCount;++_i15){this.m_joints[_i15].InitVelocityConstraints(solverData);}profile.solveInit=timer.GetMilliseconds();timer.Reset();for(var _i16=0;_i16<step.velocityIterations;++_i16){for(var j=0;j<this.m_jointCount;++j){this.m_joints[j].SolveVelocityConstraints(solverData);}contactSolver.SolveVelocityConstraints();}contactSolver.StoreImpulses();profile.solveVelocity=timer.GetMilliseconds();for(var _i17=0;_i17<this.m_bodyCount;++_i17){var c=this.m_positions[_i17].c;var _a=this.m_positions[_i17].a;var _v3=this.m_velocities[_i17].v;var _w=this.m_velocities[_i17].w;var translation=b2Vec2.MulSV(h,_v3,b2Island.s_translation);if(b2Vec2.DotVV(translation,translation)>b2_maxTranslationSquared){var ratio=b2_maxTranslation/translation.Length();_v3.SelfMul(ratio);}var rotation=h*_w;if(rotation*rotation>b2_maxRotationSquared){var _ratio=b2_maxRotation/b2Abs(rotation);_w*=_ratio;}c.x+=h*_v3.x;c.y+=h*_v3.y;_a+=h*_w;this.m_positions[_i17].a=_a;this.m_velocities[_i17].w=_w;}timer.Reset();var positionSolved=false;for(var _i18=0;_i18<step.positionIterations;++_i18){var contactsOkay=contactSolver.SolvePositionConstraints();var jointsOkay=true;for(var _j4=0;_j4<this.m_jointCount;++_j4){var jointOkay=this.m_joints[_j4].SolvePositionConstraints(solverData);jointsOkay=jointsOkay&&jointOkay;}if(contactsOkay&&jointsOkay){positionSolved=true;break;}}for(var _i19=0;_i19<this.m_bodyCount;++_i19){var body=this.m_bodies[_i19];body.m_sweep.c.Copy(this.m_positions[_i19].c);body.m_sweep.a=this.m_positions[_i19].a;body.m_linearVelocity.Copy(this.m_velocities[_i19].v);body.m_angularVelocity=this.m_velocities[_i19].w;body.SynchronizeTransform();}profile.solvePosition=timer.GetMilliseconds();this.Report(contactSolver.m_velocityConstraints);if(allowSleep){var minSleepTime=b2_maxFloat;var linTolSqr=b2_linearSleepTolerance*b2_linearSleepTolerance;var angTolSqr=b2_angularSleepTolerance*b2_angularSleepTolerance;for(var _i20=0;_i20<this.m_bodyCount;++_i20){var _b=this.m_bodies[_i20];if(_b.GetType()===exports$1.b2BodyType.b2_staticBody){continue;}if(!_b.m_autoSleepFlag||_b.m_angularVelocity*_b.m_angularVelocity>angTolSqr||b2Vec2.DotVV(_b.m_linearVelocity,_b.m_linearVelocity)>linTolSqr){_b.m_sleepTime=0;minSleepTime=0;}else {_b.m_sleepTime+=h;minSleepTime=b2Min(minSleepTime,_b.m_sleepTime);}}if(minSleepTime>=b2_timeToSleep&&positionSolved){for(var _i21=0;_i21<this.m_bodyCount;++_i21){var _b2=this.m_bodies[_i21];_b2.SetAwake(false);}}}};_proto86.SolveTOI=function SolveTOI(subStep,toiIndexA,toiIndexB){for(var i=0;i<this.m_bodyCount;++i){var b=this.m_bodies[i];this.m_positions[i].c.Copy(b.m_sweep.c);this.m_positions[i].a=b.m_sweep.a;this.m_velocities[i].v.Copy(b.m_linearVelocity);this.m_velocities[i].w=b.m_angularVelocity;}var contactSolverDef=b2Island.s_contactSolverDef;contactSolverDef.contacts=this.m_contacts;contactSolverDef.count=this.m_contactCount;contactSolverDef.step.Copy(subStep);contactSolverDef.positions=this.m_positions;contactSolverDef.velocities=this.m_velocities;var contactSolver=b2Island.s_contactSolver.Initialize(contactSolverDef);for(var _i22=0;_i22<subStep.positionIterations;++_i22){var contactsOkay=contactSolver.SolveTOIPositionConstraints(toiIndexA,toiIndexB);if(contactsOkay){break;}}this.m_bodies[toiIndexA].m_sweep.c0.Copy(this.m_positions[toiIndexA].c);this.m_bodies[toiIndexA].m_sweep.a0=this.m_positions[toiIndexA].a;this.m_bodies[toiIndexB].m_sweep.c0.Copy(this.m_positions[toiIndexB].c);this.m_bodies[toiIndexB].m_sweep.a0=this.m_positions[toiIndexB].a;contactSolver.InitializeVelocityConstraints();for(var _i23=0;_i23<subStep.velocityIterations;++_i23){contactSolver.SolveVelocityConstraints();}var h=subStep.dt;for(var _i24=0;_i24<this.m_bodyCount;++_i24){var c=this.m_positions[_i24].c;var a=this.m_positions[_i24].a;var v=this.m_velocities[_i24].v;var w=this.m_velocities[_i24].w;var translation=b2Vec2.MulSV(h,v,b2Island.s_translation);if(b2Vec2.DotVV(translation,translation)>b2_maxTranslationSquared){var ratio=b2_maxTranslation/translation.Length();v.SelfMul(ratio);}var rotation=h*w;if(rotation*rotation>b2_maxRotationSquared){var _ratio2=b2_maxRotation/b2Abs(rotation);w*=_ratio2;}c.SelfMulAdd(h,v);a+=h*w;this.m_positions[_i24].a=a;this.m_velocities[_i24].w=w;var body=this.m_bodies[_i24];body.m_sweep.c.Copy(c);body.m_sweep.a=a;body.m_linearVelocity.Copy(v);body.m_angularVelocity=w;body.SynchronizeTransform();}this.Report(contactSolver.m_velocityConstraints);};_proto86.Report=function Report(constraints){if(this.m_listener===null){return;}for(var i=0;i<this.m_contactCount;++i){var c=this.m_contacts[i];if(!c){continue;}var vc=constraints[i];var impulse=b2Island.s_impulse;impulse.count=vc.pointCount;for(var j=0;j<vc.pointCount;++j){impulse.normalImpulses[j]=vc.points[j].normalImpulse;impulse.tangentImpulses[j]=vc.points[j].tangentImpulse;}this.m_listener.PostSolve(c,impulse);}};return b2Island;}();b2Island.s_timer=new b2Timer();b2Island.s_solverData=new b2SolverData();b2Island.s_contactSolverDef=new b2ContactSolverDef();b2Island.s_contactSolver=new b2ContactSolver();b2Island.s_translation=new b2Vec2();b2Island.s_impulse=new b2ContactImpulse();(function(b2ParticleFlag){b2ParticleFlag[b2ParticleFlag["b2_waterParticle"]=0]="b2_waterParticle";b2ParticleFlag[b2ParticleFlag["b2_zombieParticle"]=2]="b2_zombieParticle";b2ParticleFlag[b2ParticleFlag["b2_wallParticle"]=4]="b2_wallParticle";b2ParticleFlag[b2ParticleFlag["b2_springParticle"]=8]="b2_springParticle";b2ParticleFlag[b2ParticleFlag["b2_elasticParticle"]=16]="b2_elasticParticle";b2ParticleFlag[b2ParticleFlag["b2_viscousParticle"]=32]="b2_viscousParticle";b2ParticleFlag[b2ParticleFlag["b2_powderParticle"]=64]="b2_powderParticle";b2ParticleFlag[b2ParticleFlag["b2_tensileParticle"]=128]="b2_tensileParticle";b2ParticleFlag[b2ParticleFlag["b2_colorMixingParticle"]=256]="b2_colorMixingParticle";b2ParticleFlag[b2ParticleFlag["b2_destructionListenerParticle"]=512]="b2_destructionListenerParticle";b2ParticleFlag[b2ParticleFlag["b2_barrierParticle"]=1024]="b2_barrierParticle";b2ParticleFlag[b2ParticleFlag["b2_staticPressureParticle"]=2048]="b2_staticPressureParticle";b2ParticleFlag[b2ParticleFlag["b2_reactiveParticle"]=4096]="b2_reactiveParticle";b2ParticleFlag[b2ParticleFlag["b2_repulsiveParticle"]=8192]="b2_repulsiveParticle";b2ParticleFlag[b2ParticleFlag["b2_fixtureContactListenerParticle"]=16384]="b2_fixtureContactListenerParticle";b2ParticleFlag[b2ParticleFlag["b2_particleContactListenerParticle"]=32768]="b2_particleContactListenerParticle";b2ParticleFlag[b2ParticleFlag["b2_fixtureContactFilterParticle"]=65536]="b2_fixtureContactFilterParticle";b2ParticleFlag[b2ParticleFlag["b2_particleContactFilterParticle"]=131072]="b2_particleContactFilterParticle";})(exports$1.b2ParticleFlag||(exports$1.b2ParticleFlag={}));var b2ParticleDef=function b2ParticleDef(){this.flags=0;this.position=new b2Vec2();this.velocity=new b2Vec2();this.color=new b2Color(0,0,0,0);this.lifetime=0.0;this.userData=null;this.group=null;};function b2CalculateParticleIterations(gravity,radius,timeStep){var B2_MAX_RECOMMENDED_PARTICLE_ITERATIONS=8;var B2_RADIUS_THRESHOLD=0.01;var iterations=Math.ceil(Math.sqrt(gravity/(B2_RADIUS_THRESHOLD*radius))*timeStep);return b2Clamp(iterations,1,B2_MAX_RECOMMENDED_PARTICLE_ITERATIONS);}var b2ParticleHandle=function(){function b2ParticleHandle(){this.m_index=b2_invalidParticleIndex;}var _proto87=b2ParticleHandle.prototype;_proto87.GetIndex=function GetIndex(){return this.m_index;};_proto87.SetIndex=function SetIndex(index){this.m_index=index;};return b2ParticleHandle;}();(function(b2ParticleGroupFlag){b2ParticleGroupFlag[b2ParticleGroupFlag["b2_solidParticleGroup"]=1]="b2_solidParticleGroup";b2ParticleGroupFlag[b2ParticleGroupFlag["b2_rigidParticleGroup"]=2]="b2_rigidParticleGroup";b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupCanBeEmpty"]=4]="b2_particleGroupCanBeEmpty";b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupWillBeDestroyed"]=8]="b2_particleGroupWillBeDestroyed";b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupNeedsUpdateDepth"]=16]="b2_particleGroupNeedsUpdateDepth";b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupInternalMask"]=24]="b2_particleGroupInternalMask";})(exports$1.b2ParticleGroupFlag||(exports$1.b2ParticleGroupFlag={}));var b2ParticleGroupDef=function b2ParticleGroupDef(){this.flags=0;this.groupFlags=0;this.position=new b2Vec2();this.angle=0.0;this.linearVelocity=new b2Vec2();this.angularVelocity=0.0;this.color=new b2Color();this.strength=1.0;this.shapeCount=0;this.stride=0;this.particleCount=0;this.lifetime=0;this.userData=null;this.group=null;};var b2ParticleGroup=function(){function b2ParticleGroup(system){this.m_firstIndex=0;this.m_lastIndex=0;this.m_groupFlags=0;this.m_strength=1.0;this.m_prev=null;this.m_next=null;this.m_timestamp=-1;this.m_mass=0.0;this.m_inertia=0.0;this.m_center=new b2Vec2();this.m_linearVelocity=new b2Vec2();this.m_angularVelocity=0.0;this.m_transform=new b2Transform();this.m_userData=null;this.m_system=system;}var _proto88=b2ParticleGroup.prototype;_proto88.GetNext=function GetNext(){return this.m_next;};_proto88.GetParticleSystem=function GetParticleSystem(){return this.m_system;};_proto88.GetParticleCount=function GetParticleCount(){return this.m_lastIndex-this.m_firstIndex;};_proto88.GetBufferIndex=function GetBufferIndex(){return this.m_firstIndex;};_proto88.ContainsParticle=function ContainsParticle(index){return this.m_firstIndex<=index&&index<this.m_lastIndex;};_proto88.GetAllParticleFlags=function GetAllParticleFlags(){if(!this.m_system.m_flagsBuffer.data){throw new Error();}var flags=0;for(var i=this.m_firstIndex;i<this.m_lastIndex;i++){flags|=this.m_system.m_flagsBuffer.data[i];}return flags;};_proto88.GetGroupFlags=function GetGroupFlags(){return this.m_groupFlags;};_proto88.SetGroupFlags=function SetGroupFlags(flags){flags|=this.m_groupFlags&exports$1.b2ParticleGroupFlag.b2_particleGroupInternalMask;this.m_system.SetGroupFlags(this,flags);};_proto88.GetMass=function GetMass(){this.UpdateStatistics();return this.m_mass;};_proto88.GetInertia=function GetInertia(){this.UpdateStatistics();return this.m_inertia;};_proto88.GetCenter=function GetCenter(){this.UpdateStatistics();return this.m_center;};_proto88.GetLinearVelocity=function GetLinearVelocity(){this.UpdateStatistics();return this.m_linearVelocity;};_proto88.GetAngularVelocity=function GetAngularVelocity(){this.UpdateStatistics();return this.m_angularVelocity;};_proto88.GetTransform=function GetTransform(){return this.m_transform;};_proto88.GetPosition=function GetPosition(){return this.m_transform.p;};_proto88.GetAngle=function GetAngle(){return this.m_transform.q.GetAngle();};_proto88.GetLinearVelocityFromWorldPoint=function GetLinearVelocityFromWorldPoint(worldPoint,out){var s_t0=b2ParticleGroup.GetLinearVelocityFromWorldPoint_s_t0;this.UpdateStatistics();return b2Vec2.AddVCrossSV(this.m_linearVelocity,this.m_angularVelocity,b2Vec2.SubVV(worldPoint,this.m_center,s_t0),out);};_proto88.GetUserData=function GetUserData(){return this.m_userData;};_proto88.SetUserData=function SetUserData(data){this.m_userData=data;};_proto88.ApplyForce=function ApplyForce(force){this.m_system.ApplyForce(this.m_firstIndex,this.m_lastIndex,force);};_proto88.ApplyLinearImpulse=function ApplyLinearImpulse(impulse){this.m_system.ApplyLinearImpulse(this.m_firstIndex,this.m_lastIndex,impulse);};_proto88.DestroyParticles=function DestroyParticles(callDestructionListener){if(this.m_system.m_world.IsLocked()){throw new Error();}for(var i=this.m_firstIndex;i<this.m_lastIndex;i++){this.m_system.DestroyParticle(i,callDestructionListener);}};_proto88.UpdateStatistics=function UpdateStatistics(){if(!this.m_system.m_positionBuffer.data){throw new Error();}if(!this.m_system.m_velocityBuffer.data){throw new Error();}var p=new b2Vec2();var v=new b2Vec2();if(this.m_timestamp!==this.m_system.m_timestamp){var m=this.m_system.GetParticleMass();this.m_mass=m*(this.m_lastIndex-this.m_firstIndex);this.m_center.SetZero();this.m_linearVelocity.SetZero();for(var i=this.m_firstIndex;i<this.m_lastIndex;i++){this.m_center.SelfMulAdd(m,this.m_system.m_positionBuffer.data[i]);this.m_linearVelocity.SelfMulAdd(m,this.m_system.m_velocityBuffer.data[i]);}if(this.m_mass>0){var inv_mass=1/this.m_mass;this.m_center.SelfMul(inv_mass);this.m_linearVelocity.SelfMul(inv_mass);}this.m_inertia=0;this.m_angularVelocity=0;for(var _i25=this.m_firstIndex;_i25<this.m_lastIndex;_i25++){b2Vec2.SubVV(this.m_system.m_positionBuffer.data[_i25],this.m_center,p);b2Vec2.SubVV(this.m_system.m_velocityBuffer.data[_i25],this.m_linearVelocity,v);this.m_inertia+=m*b2Vec2.DotVV(p,p);this.m_angularVelocity+=m*b2Vec2.CrossVV(p,v);}if(this.m_inertia>0){this.m_angularVelocity*=1/this.m_inertia;}this.m_timestamp=this.m_system.m_timestamp;}};return b2ParticleGroup;}();b2ParticleGroup.GetLinearVelocityFromWorldPoint_s_t0=new b2Vec2();var b2StackQueue=function(){function b2StackQueue(capacity){this.m_buffer=[];this.m_front=0;this.m_back=0;this.m_buffer.fill(null,0,capacity);}var _proto89=b2StackQueue.prototype;_proto89.Push=function Push(item){if(this.m_back>=this.m_capacity){for(var i=this.m_front;i<this.m_back;i++){this.m_buffer[i-this.m_front]=this.m_buffer[i];}this.m_back-=this.m_front;this.m_front=0;}this.m_buffer[this.m_back]=item;this.m_back++;};_proto89.Pop=function Pop(){this.m_buffer[this.m_front]=null;this.m_front++;};_proto89.Empty=function Empty(){return this.m_front===this.m_back;};_proto89.Front=function Front(){var item=this.m_buffer[this.m_front];if(!item){throw new Error();}return item;};_createClass(b2StackQueue,[{key:"m_capacity",get:function get(){return this.m_buffer.length;}}]);return b2StackQueue;}();var b2VoronoiDiagram=function(){function b2VoronoiDiagram(generatorCapacity){this.m_generatorCapacity=0;this.m_generatorCount=0;this.m_countX=0;this.m_countY=0;this.m_diagram=[];this.m_generatorBuffer=b2MakeArray(generatorCapacity,function(index){return new b2VoronoiDiagram_Generator();});this.m_generatorCapacity=generatorCapacity;}var _proto90=b2VoronoiDiagram.prototype;_proto90.AddGenerator=function AddGenerator(center,tag,necessary){var g=this.m_generatorBuffer[this.m_generatorCount++];g.center.Copy(center);g.tag=tag;g.necessary=necessary;};_proto90.Generate=function Generate(radius,margin){var inverseRadius=1/radius;var lower=new b2Vec2(+b2_maxFloat,+b2_maxFloat);var upper=new b2Vec2(-b2_maxFloat,-b2_maxFloat);var necessary_count=0;for(var k=0;k<this.m_generatorCount;k++){var g=this.m_generatorBuffer[k];if(g.necessary){b2Vec2.MinV(lower,g.center,lower);b2Vec2.MaxV(upper,g.center,upper);++necessary_count;}}if(necessary_count===0){this.m_countX=0;this.m_countY=0;return;}lower.x-=margin;lower.y-=margin;upper.x+=margin;upper.y+=margin;this.m_countX=1+Math.floor(inverseRadius*(upper.x-lower.x));this.m_countY=1+Math.floor(inverseRadius*(upper.y-lower.y));this.m_diagram=[];var queue=new b2StackQueue(4*this.m_countX*this.m_countY);for(var _k4=0;_k4<this.m_generatorCount;_k4++){var _g=this.m_generatorBuffer[_k4];_g.center.SelfSub(lower).SelfMul(inverseRadius);var x=Math.floor(_g.center.x);var y=Math.floor(_g.center.y);if(x>=0&&y>=0&&x<this.m_countX&&y<this.m_countY){queue.Push(new b2VoronoiDiagram_Task(x,y,x+y*this.m_countX,_g));}}while(!queue.Empty()){var task=queue.Front();var _x=task.m_x;var _y=task.m_y;var i=task.m_i;var _g2=task.m_generator;queue.Pop();if(!this.m_diagram[i]){this.m_diagram[i]=_g2;if(_x>0){queue.Push(new b2VoronoiDiagram_Task(_x-1,_y,i-1,_g2));}if(_y>0){queue.Push(new b2VoronoiDiagram_Task(_x,_y-1,i-this.m_countX,_g2));}if(_x<this.m_countX-1){queue.Push(new b2VoronoiDiagram_Task(_x+1,_y,i+1,_g2));}if(_y<this.m_countY-1){queue.Push(new b2VoronoiDiagram_Task(_x,_y+1,i+this.m_countX,_g2));}}}for(var _y2=0;_y2<this.m_countY;_y2++){for(var _x2=0;_x2<this.m_countX-1;_x2++){var _i26=_x2+_y2*this.m_countX;var a=this.m_diagram[_i26];var b=this.m_diagram[_i26+1];if(a!==b){queue.Push(new b2VoronoiDiagram_Task(_x2,_y2,_i26,b));queue.Push(new b2VoronoiDiagram_Task(_x2+1,_y2,_i26+1,a));}}}for(var _y3=0;_y3<this.m_countY-1;_y3++){for(var _x3=0;_x3<this.m_countX;_x3++){var _i27=_x3+_y3*this.m_countX;var _a2=this.m_diagram[_i27];var _b3=this.m_diagram[_i27+this.m_countX];if(_a2!==_b3){queue.Push(new b2VoronoiDiagram_Task(_x3,_y3,_i27,_b3));queue.Push(new b2VoronoiDiagram_Task(_x3,_y3+1,_i27+this.m_countX,_a2));}}}while(!queue.Empty()){var _task=queue.Front();var _x4=_task.m_x;var _y4=_task.m_y;var _i28=_task.m_i;var _k5=_task.m_generator;queue.Pop();var _a3=this.m_diagram[_i28];var _b4=_k5;if(_a3!==_b4){var ax=_a3.center.x-_x4;var ay=_a3.center.y-_y4;var bx=_b4.center.x-_x4;var by=_b4.center.y-_y4;var a2=ax*ax+ay*ay;var b2=bx*bx+by*by;if(a2>b2){this.m_diagram[_i28]=_b4;if(_x4>0){queue.Push(new b2VoronoiDiagram_Task(_x4-1,_y4,_i28-1,_b4));}if(_y4>0){queue.Push(new b2VoronoiDiagram_Task(_x4,_y4-1,_i28-this.m_countX,_b4));}if(_x4<this.m_countX-1){queue.Push(new b2VoronoiDiagram_Task(_x4+1,_y4,_i28+1,_b4));}if(_y4<this.m_countY-1){queue.Push(new b2VoronoiDiagram_Task(_x4,_y4+1,_i28+this.m_countX,_b4));}}}}};_proto90.GetNodes=function GetNodes(callback){for(var y=0;y<this.m_countY-1;y++){for(var x=0;x<this.m_countX-1;x++){var i=x+y*this.m_countX;var a=this.m_diagram[i];var b=this.m_diagram[i+1];var c=this.m_diagram[i+this.m_countX];var d=this.m_diagram[i+1+this.m_countX];if(b!==c){if(a!==b&&a!==c&&(a.necessary||b.necessary||c.necessary)){callback(a.tag,b.tag,c.tag);}if(d!==b&&d!==c&&(a.necessary||b.necessary||c.necessary)){callback(b.tag,d.tag,c.tag);}}}}};return b2VoronoiDiagram;}();var b2VoronoiDiagram_Generator=function b2VoronoiDiagram_Generator(){this.center=new b2Vec2();this.tag=0;this.necessary=false;};var b2VoronoiDiagram_Task=function b2VoronoiDiagram_Task(x,y,i,g){this.m_x=x;this.m_y=y;this.m_i=i;this.m_generator=g;};function std_iter_swap$1(array,a,b){var tmp=array[a];array[a]=array[b];array[b]=tmp;}function default_compare$1(a,b){return a<b;}function std_sort$1(array,first,len,cmp){if(first===void 0){first=0;}if(len===void 0){len=array.length-first;}if(cmp===void 0){cmp=default_compare$1;}var left=first;var stack=[];var pos=0;for(;;){for(;left+1<len;len++){var pivot=array[left+Math.floor(Math.random()*(len-left))];stack[pos++]=len;for(var right=left-1;;){while(cmp(array[++right],pivot)){}while(cmp(pivot,array[--len])){}if(right>=len){break;}std_iter_swap$1(array,right,len);}}if(pos===0){break;}left=len;len=stack[--pos];}return array;}function std_stable_sort(array,first,len,cmp){if(first===void 0){first=0;}if(len===void 0){len=array.length-first;}if(cmp===void 0){cmp=default_compare$1;}return std_sort$1(array,first,len,cmp);}function std_remove_if(array,predicate,length){if(length===void 0){length=array.length;}var l=0;for(var c=0;c<length;++c){if(predicate(array[c])){continue;}if(c===l){++l;continue;}std_iter_swap$1(array,l++,c);}return l;}function std_lower_bound(array,first,last,val,cmp){var count=last-first;while(count>0){var step=Math.floor(count/2);var it=first+step;if(cmp(array[it],val)){first=++it;count-=step+1;}else {count=step;}}return first;}function std_upper_bound(array,first,last,val,cmp){var count=last-first;while(count>0){var step=Math.floor(count/2);var it=first+step;if(!cmp(val,array[it])){first=++it;count-=step+1;}else {count=step;}}return first;}function std_rotate(array,first,n_first,last){var next=n_first;while(first!==next){std_iter_swap$1(array,first++,next++);if(next===last){next=n_first;}else if(first===n_first){n_first=next;}}}function std_unique(array,first,last,cmp){if(first===last){return last;}var result=first;while(++first!==last){if(!cmp(array[result],array[first])){std_iter_swap$1(array,++result,first);}}return ++result;}var b2GrowableBuffer=function(){function b2GrowableBuffer(allocator){this.data=[];this.count=0;this.capacity=0;this.allocator=allocator;}var _proto91=b2GrowableBuffer.prototype;_proto91.Append=function Append(){if(this.count>=this.capacity){this.Grow();}return this.count++;};_proto91.Reserve=function Reserve(newCapacity){if(this.capacity>=newCapacity){return;}for(var i=this.capacity;i<newCapacity;++i){this.data[i]=this.allocator();}this.capacity=newCapacity;};_proto91.Grow=function Grow(){var newCapacity=this.capacity?2*this.capacity:b2_minParticleSystemBufferCapacity;this.Reserve(newCapacity);};_proto91.Free=function Free(){if(this.data.length===0){return;}this.data=[];this.capacity=0;this.count=0;};_proto91.Shorten=function Shorten(newEnd){};_proto91.Data=function Data(){return this.data;};_proto91.GetCount=function GetCount(){return this.count;};_proto91.SetCount=function SetCount(newCount){this.count=newCount;};_proto91.GetCapacity=function GetCapacity(){return this.capacity;};_proto91.RemoveIf=function RemoveIf(pred){this.count=std_remove_if(this.data,pred,this.count);};_proto91.Unique=function Unique(pred){this.count=std_unique(this.data,0,this.count,pred);};return b2GrowableBuffer;}();var b2FixtureParticleQueryCallback=function(_b2QueryCallback){_inheritsLoose(b2FixtureParticleQueryCallback,_b2QueryCallback);function b2FixtureParticleQueryCallback(system){var _this31;_this31=_b2QueryCallback.call(this)||this;_this31.m_system=system;return _this31;}var _proto92=b2FixtureParticleQueryCallback.prototype;_proto92.ShouldQueryParticleSystem=function ShouldQueryParticleSystem(system){return false;};_proto92.ReportFixture=function ReportFixture(fixture){if(fixture.IsSensor()){return true;}var shape=fixture.GetShape();var childCount=shape.GetChildCount();for(var childIndex=0;childIndex<childCount;childIndex++){var aabb=fixture.GetAABB(childIndex);var enumerator=this.m_system.GetInsideBoundsEnumerator(aabb);var index=void 0;while((index=enumerator.GetNext())>=0){this.ReportFixtureAndParticle(fixture,childIndex,index);}}return true;};_proto92.ReportParticle=function ReportParticle(system,index){return false;};_proto92.ReportFixtureAndParticle=function ReportFixtureAndParticle(fixture,childIndex,index){};return b2FixtureParticleQueryCallback;}(b2QueryCallback);var b2ParticleContact=function(){function b2ParticleContact(){this.indexA=0;this.indexB=0;this.weight=0;this.normal=new b2Vec2();this.flags=0;}var _proto93=b2ParticleContact.prototype;_proto93.SetIndices=function SetIndices(a,b){this.indexA=a;this.indexB=b;};_proto93.SetWeight=function SetWeight(w){this.weight=w;};_proto93.SetNormal=function SetNormal(n){this.normal.Copy(n);};_proto93.SetFlags=function SetFlags(f){this.flags=f;};_proto93.GetIndexA=function GetIndexA(){return this.indexA;};_proto93.GetIndexB=function GetIndexB(){return this.indexB;};_proto93.GetWeight=function GetWeight(){return this.weight;};_proto93.GetNormal=function GetNormal(){return this.normal;};_proto93.GetFlags=function GetFlags(){return this.flags;};_proto93.IsEqual=function IsEqual(rhs){return this.indexA===rhs.indexA&&this.indexB===rhs.indexB&&this.flags===rhs.flags&&this.weight===rhs.weight&&this.normal.x===rhs.normal.x&&this.normal.y===rhs.normal.y;};_proto93.IsNotEqual=function IsNotEqual(rhs){return !this.IsEqual(rhs);};_proto93.ApproximatelyEqual=function ApproximatelyEqual(rhs){var MAX_WEIGHT_DIFF=0.01;var MAX_NORMAL_DIFF_SQ=0.01*0.01;return this.indexA===rhs.indexA&&this.indexB===rhs.indexB&&this.flags===rhs.flags&&b2Abs(this.weight-rhs.weight)<MAX_WEIGHT_DIFF&&b2Vec2.DistanceSquaredVV(this.normal,rhs.normal)<MAX_NORMAL_DIFF_SQ;};return b2ParticleContact;}();var b2ParticleBodyContact=function b2ParticleBodyContact(){this.index=0;this.weight=0.0;this.normal=new b2Vec2();this.mass=0.0;};var b2ParticlePair=function b2ParticlePair(){this.indexA=0;this.indexB=0;this.flags=0;this.strength=0.0;this.distance=0.0;};var b2ParticleTriad=function b2ParticleTriad(){this.indexA=0;this.indexB=0;this.indexC=0;this.flags=0;this.strength=0.0;this.pa=new b2Vec2(0.0,0.0);this.pb=new b2Vec2(0.0,0.0);this.pc=new b2Vec2(0.0,0.0);this.ka=0.0;this.kb=0.0;this.kc=0.0;this.s=0.0;};var b2ParticleSystemDef=function(){function b2ParticleSystemDef(){this.strictContactCheck=false;this.density=1.0;this.gravityScale=1.0;this.radius=1.0;this.maxCount=0;this.pressureStrength=0.005;this.dampingStrength=1.0;this.elasticStrength=0.25;this.springStrength=0.25;this.viscousStrength=0.25;this.surfaceTensionPressureStrength=0.2;this.surfaceTensionNormalStrength=0.2;this.repulsiveStrength=1.0;this.powderStrength=0.5;this.ejectionStrength=0.5;this.staticPressureStrength=0.2;this.staticPressureRelaxation=0.2;this.staticPressureIterations=8;this.colorMixingStrength=0.5;this.destroyByAge=true;this.lifetimeGranularity=1.0/60.0;}var _proto94=b2ParticleSystemDef.prototype;_proto94.Copy=function Copy(def){this.strictContactCheck=def.strictContactCheck;this.density=def.density;this.gravityScale=def.gravityScale;this.radius=def.radius;this.maxCount=def.maxCount;this.pressureStrength=def.pressureStrength;this.dampingStrength=def.dampingStrength;this.elasticStrength=def.elasticStrength;this.springStrength=def.springStrength;this.viscousStrength=def.viscousStrength;this.surfaceTensionPressureStrength=def.surfaceTensionPressureStrength;this.surfaceTensionNormalStrength=def.surfaceTensionNormalStrength;this.repulsiveStrength=def.repulsiveStrength;this.powderStrength=def.powderStrength;this.ejectionStrength=def.ejectionStrength;this.staticPressureStrength=def.staticPressureStrength;this.staticPressureRelaxation=def.staticPressureRelaxation;this.staticPressureIterations=def.staticPressureIterations;this.colorMixingStrength=def.colorMixingStrength;this.destroyByAge=def.destroyByAge;this.lifetimeGranularity=def.lifetimeGranularity;return this;};_proto94.Clone=function Clone(){return new b2ParticleSystemDef().Copy(this);};return b2ParticleSystemDef;}();var b2ParticleSystem=function(){function b2ParticleSystem(def,world){this.m_paused=false;this.m_timestamp=0;this.m_allParticleFlags=0;this.m_needsUpdateAllParticleFlags=false;this.m_allGroupFlags=0;this.m_needsUpdateAllGroupFlags=false;this.m_hasForce=false;this.m_iterationIndex=0;this.m_inverseDensity=0.0;this.m_particleDiameter=0.0;this.m_inverseDiameter=0.0;this.m_squaredDiameter=0.0;this.m_count=0;this.m_internalAllocatedCapacity=0;this.m_handleIndexBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_flagsBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_positionBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_velocityBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_forceBuffer=[];this.m_weightBuffer=[];this.m_staticPressureBuffer=[];this.m_accumulationBuffer=[];this.m_accumulation2Buffer=[];this.m_depthBuffer=[];this.m_colorBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_groupBuffer=[];this.m_userDataBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_stuckThreshold=0;this.m_lastBodyContactStepBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_bodyContactCountBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_consecutiveContactStepsBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_stuckParticleBuffer=new b2GrowableBuffer(function(){return 0;});this.m_proxyBuffer=new b2GrowableBuffer(function(){return new b2ParticleSystem_Proxy();});this.m_contactBuffer=new b2GrowableBuffer(function(){return new b2ParticleContact();});this.m_bodyContactBuffer=new b2GrowableBuffer(function(){return new b2ParticleBodyContact();});this.m_pairBuffer=new b2GrowableBuffer(function(){return new b2ParticlePair();});this.m_triadBuffer=new b2GrowableBuffer(function(){return new b2ParticleTriad();});this.m_expirationTimeBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_indexByExpirationTimeBuffer=new b2ParticleSystem_UserOverridableBuffer();this.m_timeElapsed=0;this.m_expirationTimeBufferRequiresSorting=false;this.m_groupCount=0;this.m_groupList=null;this.m_def=new b2ParticleSystemDef();this.m_prev=null;this.m_next=null;this.UpdateBodyContacts_callback=null;this.SolveCollision_callback=null;this.SetStrictContactCheck(def.strictContactCheck);this.SetDensity(def.density);this.SetGravityScale(def.gravityScale);this.SetRadius(def.radius);this.SetMaxParticleCount(def.maxCount);this.m_def=def.Clone();this.m_world=world;this.SetDestructionByAge(this.m_def.destroyByAge);}b2ParticleSystem.computeTag=function computeTag(x,y){return (y+b2ParticleSystem.yOffset>>>0<<b2ParticleSystem.yShift)+(b2ParticleSystem.xScale*x+b2ParticleSystem.xOffset>>>0)>>>0;};b2ParticleSystem.computeRelativeTag=function computeRelativeTag(tag,x,y){return tag+(y<<b2ParticleSystem.yShift)+(x<<b2ParticleSystem.xShift)>>>0;};var _proto95=b2ParticleSystem.prototype;_proto95.Drop=function Drop(){while(this.m_groupList){this.DestroyParticleGroup(this.m_groupList);}this.FreeUserOverridableBuffer(this.m_handleIndexBuffer);this.FreeUserOverridableBuffer(this.m_flagsBuffer);this.FreeUserOverridableBuffer(this.m_lastBodyContactStepBuffer);this.FreeUserOverridableBuffer(this.m_bodyContactCountBuffer);this.FreeUserOverridableBuffer(this.m_consecutiveContactStepsBuffer);this.FreeUserOverridableBuffer(this.m_positionBuffer);this.FreeUserOverridableBuffer(this.m_velocityBuffer);this.FreeUserOverridableBuffer(this.m_colorBuffer);this.FreeUserOverridableBuffer(this.m_userDataBuffer);this.FreeUserOverridableBuffer(this.m_expirationTimeBuffer);this.FreeUserOverridableBuffer(this.m_indexByExpirationTimeBuffer);this.FreeBuffer(this.m_forceBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_weightBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_staticPressureBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_accumulationBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_accumulation2Buffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_depthBuffer,this.m_internalAllocatedCapacity);this.FreeBuffer(this.m_groupBuffer,this.m_internalAllocatedCapacity);};_proto95.CreateParticle=function CreateParticle(def){if(this.m_world.IsLocked()){throw new Error();}if(this.m_count>=this.m_internalAllocatedCapacity){var capacity=this.m_count?2*this.m_count:b2_minParticleSystemBufferCapacity;this.ReallocateInternalAllocatedBuffers(capacity);}if(this.m_count>=this.m_internalAllocatedCapacity){if(this.m_def.destroyByAge){this.DestroyOldestParticle(0,false);this.SolveZombie();}else {return b2_invalidParticleIndex;}}var index=this.m_count++;this.m_flagsBuffer.data[index]=0;if(this.m_lastBodyContactStepBuffer.data){this.m_lastBodyContactStepBuffer.data[index]=0;}if(this.m_bodyContactCountBuffer.data){this.m_bodyContactCountBuffer.data[index]=0;}if(this.m_consecutiveContactStepsBuffer.data){this.m_consecutiveContactStepsBuffer.data[index]=0;}this.m_positionBuffer.data[index]=(this.m_positionBuffer.data[index]||new b2Vec2()).Copy(b2Maybe(def.position,b2Vec2.ZERO));this.m_velocityBuffer.data[index]=(this.m_velocityBuffer.data[index]||new b2Vec2()).Copy(b2Maybe(def.velocity,b2Vec2.ZERO));this.m_weightBuffer[index]=0;this.m_forceBuffer[index]=(this.m_forceBuffer[index]||new b2Vec2()).SetZero();if(this.m_staticPressureBuffer){this.m_staticPressureBuffer[index]=0;}if(this.m_depthBuffer){this.m_depthBuffer[index]=0;}var color=new b2Color().Copy(b2Maybe(def.color,b2Color.ZERO));if(this.m_colorBuffer.data||!color.IsZero()){this.m_colorBuffer.data=this.RequestBuffer(this.m_colorBuffer.data);this.m_colorBuffer.data[index]=(this.m_colorBuffer.data[index]||new b2Color()).Copy(color);}if(this.m_userDataBuffer.data||def.userData){this.m_userDataBuffer.data=this.RequestBuffer(this.m_userDataBuffer.data);this.m_userDataBuffer.data[index]=def.userData;}if(this.m_handleIndexBuffer.data){this.m_handleIndexBuffer.data[index]=null;}var proxy=this.m_proxyBuffer.data[this.m_proxyBuffer.Append()];var lifetime=b2Maybe(def.lifetime,0.0);var finiteLifetime=lifetime>0.0;if(this.m_expirationTimeBuffer.data||finiteLifetime){this.SetParticleLifetime(index,finiteLifetime?lifetime:this.ExpirationTimeToLifetime(-this.GetQuantizedTimeElapsed()));this.m_indexByExpirationTimeBuffer.data[index]=index;}proxy.index=index;var group=b2Maybe(def.group,null);this.m_groupBuffer[index]=group;if(group){if(group.m_firstIndex<group.m_lastIndex){this.RotateBuffer(group.m_firstIndex,group.m_lastIndex,index);group.m_lastIndex=index+1;}else {group.m_firstIndex=index;group.m_lastIndex=index+1;}}this.SetParticleFlags(index,b2Maybe(def.flags,0));return index;};_proto95.GetParticleHandleFromIndex=function GetParticleHandleFromIndex(index){this.m_handleIndexBuffer.data=this.RequestBuffer(this.m_handleIndexBuffer.data);var handle=this.m_handleIndexBuffer.data[index];if(handle){return handle;}handle=new b2ParticleHandle();handle.SetIndex(index);this.m_handleIndexBuffer.data[index]=handle;return handle;};_proto95.DestroyParticle=function DestroyParticle(index,callDestructionListener){if(callDestructionListener===void 0){callDestructionListener=false;}var flags=exports$1.b2ParticleFlag.b2_zombieParticle;if(callDestructionListener){flags|=exports$1.b2ParticleFlag.b2_destructionListenerParticle;}this.SetParticleFlags(index,this.m_flagsBuffer.data[index]|flags);};_proto95.DestroyOldestParticle=function DestroyOldestParticle(index,callDestructionListener){if(callDestructionListener===void 0){callDestructionListener=false;}var particleCount=this.GetParticleCount();var oldestFiniteLifetimeParticle=this.m_indexByExpirationTimeBuffer.data[particleCount-(index+1)];var oldestInfiniteLifetimeParticle=this.m_indexByExpirationTimeBuffer.data[index];this.DestroyParticle(this.m_expirationTimeBuffer.data[oldestFiniteLifetimeParticle]>0.0?oldestFiniteLifetimeParticle:oldestInfiniteLifetimeParticle,callDestructionListener);};_proto95.DestroyParticlesInShape=function DestroyParticlesInShape(shape,xf,callDestructionListener){if(callDestructionListener===void 0){callDestructionListener=false;}var s_aabb=b2ParticleSystem.DestroyParticlesInShape_s_aabb;if(this.m_world.IsLocked()){throw new Error();}var callback=new b2ParticleSystem_DestroyParticlesInShapeCallback(this,shape,xf,callDestructionListener);var aabb=s_aabb;shape.ComputeAABB(aabb,xf,0);this.m_world.QueryAABB(callback,aabb);return callback.Destroyed();};_proto95.CreateParticleGroup=function CreateParticleGroup(groupDef){var s_transform=b2ParticleSystem.CreateParticleGroup_s_transform;if(this.m_world.IsLocked()){throw new Error();}var transform=s_transform;transform.SetPositionAngle(b2Maybe(groupDef.position,b2Vec2.ZERO),b2Maybe(groupDef.angle,0));var firstIndex=this.m_count;if(groupDef.shape){this.CreateParticlesWithShapeForGroup(groupDef.shape,groupDef,transform);}if(groupDef.shapes){this.CreateParticlesWithShapesForGroup(groupDef.shapes,b2Maybe(groupDef.shapeCount,groupDef.shapes.length),groupDef,transform);}if(groupDef.positionData){var count=b2Maybe(groupDef.particleCount,groupDef.positionData.length);for(var i=0;i<count;i++){var p=groupDef.positionData[i];this.CreateParticleForGroup(groupDef,transform,p);}}var lastIndex=this.m_count;var group=new b2ParticleGroup(this);group.m_firstIndex=firstIndex;group.m_lastIndex=lastIndex;group.m_strength=b2Maybe(groupDef.strength,1);group.m_userData=groupDef.userData;group.m_transform.Copy(transform);group.m_prev=null;group.m_next=this.m_groupList;if(this.m_groupList){this.m_groupList.m_prev=group;}this.m_groupList=group;++this.m_groupCount;for(var _i29=firstIndex;_i29<lastIndex;_i29++){this.m_groupBuffer[_i29]=group;}this.SetGroupFlags(group,b2Maybe(groupDef.groupFlags,0));var filter=new b2ParticleSystem_ConnectionFilter();this.UpdateContacts(true);this.UpdatePairsAndTriads(firstIndex,lastIndex,filter);if(groupDef.group){this.JoinParticleGroups(groupDef.group,group);group=groupDef.group;}return group;};_proto95.JoinParticleGroups=function JoinParticleGroups(groupA,groupB){if(this.m_world.IsLocked()){throw new Error();}this.RotateBuffer(groupB.m_firstIndex,groupB.m_lastIndex,this.m_count);this.RotateBuffer(groupA.m_firstIndex,groupA.m_lastIndex,groupB.m_firstIndex);var filter=new b2ParticleSystem_JoinParticleGroupsFilter(groupB.m_firstIndex);this.UpdateContacts(true);this.UpdatePairsAndTriads(groupA.m_firstIndex,groupB.m_lastIndex,filter);for(var i=groupB.m_firstIndex;i<groupB.m_lastIndex;i++){this.m_groupBuffer[i]=groupA;}var groupFlags=groupA.m_groupFlags|groupB.m_groupFlags;this.SetGroupFlags(groupA,groupFlags);groupA.m_lastIndex=groupB.m_lastIndex;groupB.m_firstIndex=groupB.m_lastIndex;this.DestroyParticleGroup(groupB);};_proto95.SplitParticleGroup=function SplitParticleGroup(group){this.UpdateContacts(true);var particleCount=group.GetParticleCount();var nodeBuffer=b2MakeArray(particleCount,function(index){return new b2ParticleSystem_ParticleListNode();});b2ParticleSystem.InitializeParticleLists(group,nodeBuffer);this.MergeParticleListsInContact(group,nodeBuffer);var survivingList=b2ParticleSystem.FindLongestParticleList(group,nodeBuffer);this.MergeZombieParticleListNodes(group,nodeBuffer,survivingList);this.CreateParticleGroupsFromParticleList(group,nodeBuffer,survivingList);this.UpdatePairsAndTriadsWithParticleList(group,nodeBuffer);};_proto95.GetParticleGroupList=function GetParticleGroupList(){return this.m_groupList;};_proto95.GetParticleGroupCount=function GetParticleGroupCount(){return this.m_groupCount;};_proto95.GetParticleCount=function GetParticleCount(){return this.m_count;};_proto95.GetMaxParticleCount=function GetMaxParticleCount(){return this.m_def.maxCount;};_proto95.SetMaxParticleCount=function SetMaxParticleCount(count){this.m_def.maxCount=count;};_proto95.GetAllParticleFlags=function GetAllParticleFlags(){return this.m_allParticleFlags;};_proto95.GetAllGroupFlags=function GetAllGroupFlags(){return this.m_allGroupFlags;};_proto95.SetPaused=function SetPaused(paused){this.m_paused=paused;};_proto95.GetPaused=function GetPaused(){return this.m_paused;};_proto95.SetDensity=function SetDensity(density){this.m_def.density=density;this.m_inverseDensity=1/this.m_def.density;};_proto95.GetDensity=function GetDensity(){return this.m_def.density;};_proto95.SetGravityScale=function SetGravityScale(gravityScale){this.m_def.gravityScale=gravityScale;};_proto95.GetGravityScale=function GetGravityScale(){return this.m_def.gravityScale;};_proto95.SetDamping=function SetDamping(damping){this.m_def.dampingStrength=damping;};_proto95.GetDamping=function GetDamping(){return this.m_def.dampingStrength;};_proto95.SetStaticPressureIterations=function SetStaticPressureIterations(iterations){this.m_def.staticPressureIterations=iterations;};_proto95.GetStaticPressureIterations=function GetStaticPressureIterations(){return this.m_def.staticPressureIterations;};_proto95.SetRadius=function SetRadius(radius){this.m_particleDiameter=2*radius;this.m_squaredDiameter=this.m_particleDiameter*this.m_particleDiameter;this.m_inverseDiameter=1/this.m_particleDiameter;};_proto95.GetRadius=function GetRadius(){return this.m_particleDiameter/2;};_proto95.GetPositionBuffer=function GetPositionBuffer(){return this.m_positionBuffer.data;};_proto95.GetVelocityBuffer=function GetVelocityBuffer(){return this.m_velocityBuffer.data;};_proto95.GetColorBuffer=function GetColorBuffer(){this.m_colorBuffer.data=this.RequestBuffer(this.m_colorBuffer.data);return this.m_colorBuffer.data;};_proto95.GetGroupBuffer=function GetGroupBuffer(){return this.m_groupBuffer;};_proto95.GetWeightBuffer=function GetWeightBuffer(){return this.m_weightBuffer;};_proto95.GetUserDataBuffer=function GetUserDataBuffer(){this.m_userDataBuffer.data=this.RequestBuffer(this.m_userDataBuffer.data);return this.m_userDataBuffer.data;};_proto95.GetFlagsBuffer=function GetFlagsBuffer(){return this.m_flagsBuffer.data;};_proto95.SetParticleFlags=function SetParticleFlags(index,newFlags){var oldFlags=this.m_flagsBuffer.data[index];if(oldFlags&~newFlags){this.m_needsUpdateAllParticleFlags=true;}if(~this.m_allParticleFlags&newFlags){if(newFlags&exports$1.b2ParticleFlag.b2_tensileParticle){this.m_accumulation2Buffer=this.RequestBuffer(this.m_accumulation2Buffer);}if(newFlags&exports$1.b2ParticleFlag.b2_colorMixingParticle){this.m_colorBuffer.data=this.RequestBuffer(this.m_colorBuffer.data);}this.m_allParticleFlags|=newFlags;}this.m_flagsBuffer.data[index]=newFlags;};_proto95.GetParticleFlags=function GetParticleFlags(index){return this.m_flagsBuffer.data[index];};_proto95.SetFlagsBuffer=function SetFlagsBuffer(buffer){this.SetUserOverridableBuffer(this.m_flagsBuffer,buffer);};_proto95.SetPositionBuffer=function SetPositionBuffer(buffer){if(buffer instanceof Float32Array){if(buffer.length%2!==0){throw new Error();}var count=buffer.length/2;var array=new Array(count);for(var i=0;i<count;++i){array[i]=new b2Vec2(buffer.subarray(i*2,i*2+2));}buffer=array;}this.SetUserOverridableBuffer(this.m_positionBuffer,buffer);};_proto95.SetVelocityBuffer=function SetVelocityBuffer(buffer){if(buffer instanceof Float32Array){if(buffer.length%2!==0){throw new Error();}var count=buffer.length/2;var array=new Array(count);for(var i=0;i<count;++i){array[i]=new b2Vec2(buffer.subarray(i*2,i*2+2));}buffer=array;}this.SetUserOverridableBuffer(this.m_velocityBuffer,buffer);};_proto95.SetColorBuffer=function SetColorBuffer(buffer){if(buffer instanceof Float32Array){if(buffer.length%4!==0){throw new Error();}var count=buffer.length/4;var array=new Array(count);for(var i=0;i<count;++i){array[i]=new b2Color(buffer.subarray(i*4,i*4+4));}buffer=array;}this.SetUserOverridableBuffer(this.m_colorBuffer,buffer);};_proto95.SetUserDataBuffer=function SetUserDataBuffer(buffer){this.SetUserOverridableBuffer(this.m_userDataBuffer,buffer);};_proto95.GetContacts=function GetContacts(){return this.m_contactBuffer.data;};_proto95.GetContactCount=function GetContactCount(){return this.m_contactBuffer.count;};_proto95.GetBodyContacts=function GetBodyContacts(){return this.m_bodyContactBuffer.data;};_proto95.GetBodyContactCount=function GetBodyContactCount(){return this.m_bodyContactBuffer.count;};_proto95.GetPairs=function GetPairs(){return this.m_pairBuffer.data;};_proto95.GetPairCount=function GetPairCount(){return this.m_pairBuffer.count;};_proto95.GetTriads=function GetTriads(){return this.m_triadBuffer.data;};_proto95.GetTriadCount=function GetTriadCount(){return this.m_triadBuffer.count;};_proto95.SetStuckThreshold=function SetStuckThreshold(steps){this.m_stuckThreshold=steps;if(steps>0){this.m_lastBodyContactStepBuffer.data=this.RequestBuffer(this.m_lastBodyContactStepBuffer.data);this.m_bodyContactCountBuffer.data=this.RequestBuffer(this.m_bodyContactCountBuffer.data);this.m_consecutiveContactStepsBuffer.data=this.RequestBuffer(this.m_consecutiveContactStepsBuffer.data);}};_proto95.GetStuckCandidates=function GetStuckCandidates(){return this.m_stuckParticleBuffer.Data();};_proto95.GetStuckCandidateCount=function GetStuckCandidateCount(){return this.m_stuckParticleBuffer.GetCount();};_proto95.ComputeCollisionEnergy=function ComputeCollisionEnergy(){var s_v=b2ParticleSystem.ComputeCollisionEnergy_s_v;var vel_data=this.m_velocityBuffer.data;var sum_v2=0;for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;var n=contact.normal;var v=b2Vec2.SubVV(vel_data[b],vel_data[a],s_v);var vn=b2Vec2.DotVV(v,n);if(vn<0){sum_v2+=vn*vn;}}return 0.5*this.GetParticleMass()*sum_v2;};_proto95.SetStrictContactCheck=function SetStrictContactCheck(enabled){this.m_def.strictContactCheck=enabled;};_proto95.GetStrictContactCheck=function GetStrictContactCheck(){return this.m_def.strictContactCheck;};_proto95.SetParticleLifetime=function SetParticleLifetime(index,lifetime){var initializeExpirationTimes=this.m_indexByExpirationTimeBuffer.data===null;this.m_expirationTimeBuffer.data=this.RequestBuffer(this.m_expirationTimeBuffer.data);this.m_indexByExpirationTimeBuffer.data=this.RequestBuffer(this.m_indexByExpirationTimeBuffer.data);if(initializeExpirationTimes){var particleCount=this.GetParticleCount();for(var i=0;i<particleCount;++i){this.m_indexByExpirationTimeBuffer.data[i]=i;}}var quantizedLifetime=lifetime/this.m_def.lifetimeGranularity;var newExpirationTime=quantizedLifetime>0.0?this.GetQuantizedTimeElapsed()+quantizedLifetime:quantizedLifetime;if(newExpirationTime!==this.m_expirationTimeBuffer.data[index]){this.m_expirationTimeBuffer.data[index]=newExpirationTime;this.m_expirationTimeBufferRequiresSorting=true;}};_proto95.GetParticleLifetime=function GetParticleLifetime(index){return this.ExpirationTimeToLifetime(this.GetExpirationTimeBuffer()[index]);};_proto95.SetDestructionByAge=function SetDestructionByAge(enable){if(enable){this.GetExpirationTimeBuffer();}this.m_def.destroyByAge=enable;};_proto95.GetDestructionByAge=function GetDestructionByAge(){return this.m_def.destroyByAge;};_proto95.GetExpirationTimeBuffer=function GetExpirationTimeBuffer(){this.m_expirationTimeBuffer.data=this.RequestBuffer(this.m_expirationTimeBuffer.data);return this.m_expirationTimeBuffer.data;};_proto95.ExpirationTimeToLifetime=function ExpirationTimeToLifetime(expirationTime){return (expirationTime>0?expirationTime-this.GetQuantizedTimeElapsed():expirationTime)*this.m_def.lifetimeGranularity;};_proto95.GetIndexByExpirationTimeBuffer=function GetIndexByExpirationTimeBuffer(){if(this.GetParticleCount()){this.SetParticleLifetime(0,this.GetParticleLifetime(0));}else {this.m_indexByExpirationTimeBuffer.data=this.RequestBuffer(this.m_indexByExpirationTimeBuffer.data);}return this.m_indexByExpirationTimeBuffer.data;};_proto95.ParticleApplyLinearImpulse=function ParticleApplyLinearImpulse(index,impulse){this.ApplyLinearImpulse(index,index+1,impulse);};_proto95.ApplyLinearImpulse=function ApplyLinearImpulse(firstIndex,lastIndex,impulse){var vel_data=this.m_velocityBuffer.data;var numParticles=lastIndex-firstIndex;var totalMass=numParticles*this.GetParticleMass();var velocityDelta=new b2Vec2().Copy(impulse).SelfMul(1/totalMass);for(var i=firstIndex;i<lastIndex;i++){vel_data[i].SelfAdd(velocityDelta);}};b2ParticleSystem.IsSignificantForce=function IsSignificantForce(force){return force.x!==0||force.y!==0;};_proto95.ParticleApplyForce=function ParticleApplyForce(index,force){if(b2ParticleSystem.IsSignificantForce(force)&&this.ForceCanBeApplied(this.m_flagsBuffer.data[index])){this.PrepareForceBuffer();this.m_forceBuffer[index].SelfAdd(force);}};_proto95.ApplyForce=function ApplyForce(firstIndex,lastIndex,force){var distributedForce=new b2Vec2().Copy(force).SelfMul(1/(lastIndex-firstIndex));if(b2ParticleSystem.IsSignificantForce(distributedForce)){this.PrepareForceBuffer();for(var i=firstIndex;i<lastIndex;i++){this.m_forceBuffer[i].SelfAdd(distributedForce);}}};_proto95.GetNext=function GetNext(){return this.m_next;};_proto95.QueryAABB=function QueryAABB(callback,aabb){if(this.m_proxyBuffer.count===0){return;}var beginProxy=0;var endProxy=this.m_proxyBuffer.count;var firstProxy=std_lower_bound(this.m_proxyBuffer.data,beginProxy,endProxy,b2ParticleSystem.computeTag(this.m_inverseDiameter*aabb.lowerBound.x,this.m_inverseDiameter*aabb.lowerBound.y),b2ParticleSystem_Proxy.CompareProxyTag);var lastProxy=std_upper_bound(this.m_proxyBuffer.data,firstProxy,endProxy,b2ParticleSystem.computeTag(this.m_inverseDiameter*aabb.upperBound.x,this.m_inverseDiameter*aabb.upperBound.y),b2ParticleSystem_Proxy.CompareTagProxy);var pos_data=this.m_positionBuffer.data;for(var k=firstProxy;k<lastProxy;++k){var proxy=this.m_proxyBuffer.data[k];var i=proxy.index;var p=pos_data[i];if(aabb.lowerBound.x<p.x&&p.x<aabb.upperBound.x&&aabb.lowerBound.y<p.y&&p.y<aabb.upperBound.y){if(!callback.ReportParticle(this,i)){break;}}}};_proto95.QueryShapeAABB=function QueryShapeAABB(callback,shape,xf,childIndex){if(childIndex===void 0){childIndex=0;}var s_aabb=b2ParticleSystem.QueryShapeAABB_s_aabb;var aabb=s_aabb;shape.ComputeAABB(aabb,xf,childIndex);this.QueryAABB(callback,aabb);};_proto95.QueryPointAABB=function QueryPointAABB(callback,point,slop){if(slop===void 0){slop=b2_linearSlop;}var s_aabb=b2ParticleSystem.QueryPointAABB_s_aabb;var aabb=s_aabb;aabb.lowerBound.Set(point.x-slop,point.y-slop);aabb.upperBound.Set(point.x+slop,point.y+slop);this.QueryAABB(callback,aabb);};_proto95.RayCast=function RayCast(callback,point1,point2){var s_aabb=b2ParticleSystem.RayCast_s_aabb;var s_p=b2ParticleSystem.RayCast_s_p;var s_v=b2ParticleSystem.RayCast_s_v;var s_n=b2ParticleSystem.RayCast_s_n;var s_point=b2ParticleSystem.RayCast_s_point;if(this.m_proxyBuffer.count===0){return;}var pos_data=this.m_positionBuffer.data;var aabb=s_aabb;b2Vec2.MinV(point1,point2,aabb.lowerBound);b2Vec2.MaxV(point1,point2,aabb.upperBound);var fraction=1;var v=b2Vec2.SubVV(point2,point1,s_v);var v2=b2Vec2.DotVV(v,v);var enumerator=this.GetInsideBoundsEnumerator(aabb);var i;while((i=enumerator.GetNext())>=0){var p=b2Vec2.SubVV(point1,pos_data[i],s_p);var pv=b2Vec2.DotVV(p,v);var p2=b2Vec2.DotVV(p,p);var determinant=pv*pv-v2*(p2-this.m_squaredDiameter);if(determinant>=0){var sqrtDeterminant=b2Sqrt(determinant);var t=(-pv-sqrtDeterminant)/v2;if(t>fraction){continue;}if(t<0){t=(-pv+sqrtDeterminant)/v2;if(t<0||t>fraction){continue;}}var n=b2Vec2.AddVMulSV(p,t,v,s_n);n.Normalize();var f=callback.ReportParticle(this,i,b2Vec2.AddVMulSV(point1,t,v,s_point),n,t);fraction=b2Min(fraction,f);if(fraction<=0){break;}}}};_proto95.ComputeAABB=function ComputeAABB(aabb){var particleCount=this.GetParticleCount();aabb.lowerBound.x=+b2_maxFloat;aabb.lowerBound.y=+b2_maxFloat;aabb.upperBound.x=-b2_maxFloat;aabb.upperBound.y=-b2_maxFloat;var pos_data=this.m_positionBuffer.data;for(var i=0;i<particleCount;i++){var p=pos_data[i];b2Vec2.MinV(aabb.lowerBound,p,aabb.lowerBound);b2Vec2.MaxV(aabb.upperBound,p,aabb.upperBound);}aabb.lowerBound.x-=this.m_particleDiameter;aabb.lowerBound.y-=this.m_particleDiameter;aabb.upperBound.x+=this.m_particleDiameter;aabb.upperBound.y+=this.m_particleDiameter;};_proto95.FreeBuffer=function FreeBuffer(b,capacity){if(b===null){return;}b.length=0;};_proto95.FreeUserOverridableBuffer=function FreeUserOverridableBuffer(b){if(b.userSuppliedCapacity===0){this.FreeBuffer(b.data,this.m_internalAllocatedCapacity);}};_proto95.ReallocateBuffer3=function ReallocateBuffer3(oldBuffer,oldCapacity,newCapacity){if(newCapacity<=oldCapacity){throw new Error();}var newBuffer=oldBuffer?oldBuffer.slice():[];newBuffer.length=newCapacity;return newBuffer;};_proto95.ReallocateBuffer5=function ReallocateBuffer5(buffer,userSuppliedCapacity,oldCapacity,newCapacity,deferred){if(newCapacity<=oldCapacity){throw new Error();}if(!(!userSuppliedCapacity||newCapacity<=userSuppliedCapacity)){throw new Error();}if((!deferred||buffer)&&!userSuppliedCapacity){buffer=this.ReallocateBuffer3(buffer,oldCapacity,newCapacity);}return buffer;};_proto95.ReallocateBuffer4=function ReallocateBuffer4(buffer,oldCapacity,newCapacity,deferred){return this.ReallocateBuffer5(buffer.data,buffer.userSuppliedCapacity,oldCapacity,newCapacity,deferred);};_proto95.RequestBuffer=function RequestBuffer(buffer){if(!buffer){if(this.m_internalAllocatedCapacity===0){this.ReallocateInternalAllocatedBuffers(b2_minParticleSystemBufferCapacity);}buffer=[];buffer.length=this.m_internalAllocatedCapacity;}return buffer;};_proto95.ReallocateHandleBuffers=function ReallocateHandleBuffers(newCapacity){this.m_handleIndexBuffer.data=this.ReallocateBuffer4(this.m_handleIndexBuffer,this.m_internalAllocatedCapacity,newCapacity,true);};_proto95.ReallocateInternalAllocatedBuffers=function ReallocateInternalAllocatedBuffers(capacity){function LimitCapacity(capacity,maxCount){return maxCount&&capacity>maxCount?maxCount:capacity;}capacity=LimitCapacity(capacity,this.m_def.maxCount);capacity=LimitCapacity(capacity,this.m_flagsBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_positionBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_velocityBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_colorBuffer.userSuppliedCapacity);capacity=LimitCapacity(capacity,this.m_userDataBuffer.userSuppliedCapacity);if(this.m_internalAllocatedCapacity<capacity){this.ReallocateHandleBuffers(capacity);this.m_flagsBuffer.data=this.ReallocateBuffer4(this.m_flagsBuffer,this.m_internalAllocatedCapacity,capacity,false);var stuck=this.m_stuckThreshold>0;this.m_lastBodyContactStepBuffer.data=this.ReallocateBuffer4(this.m_lastBodyContactStepBuffer,this.m_internalAllocatedCapacity,capacity,stuck);this.m_bodyContactCountBuffer.data=this.ReallocateBuffer4(this.m_bodyContactCountBuffer,this.m_internalAllocatedCapacity,capacity,stuck);this.m_consecutiveContactStepsBuffer.data=this.ReallocateBuffer4(this.m_consecutiveContactStepsBuffer,this.m_internalAllocatedCapacity,capacity,stuck);this.m_positionBuffer.data=this.ReallocateBuffer4(this.m_positionBuffer,this.m_internalAllocatedCapacity,capacity,false);this.m_velocityBuffer.data=this.ReallocateBuffer4(this.m_velocityBuffer,this.m_internalAllocatedCapacity,capacity,false);this.m_forceBuffer=this.ReallocateBuffer5(this.m_forceBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_weightBuffer=this.ReallocateBuffer5(this.m_weightBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_staticPressureBuffer=this.ReallocateBuffer5(this.m_staticPressureBuffer,0,this.m_internalAllocatedCapacity,capacity,true);this.m_accumulationBuffer=this.ReallocateBuffer5(this.m_accumulationBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_accumulation2Buffer=this.ReallocateBuffer5(this.m_accumulation2Buffer,0,this.m_internalAllocatedCapacity,capacity,true);this.m_depthBuffer=this.ReallocateBuffer5(this.m_depthBuffer,0,this.m_internalAllocatedCapacity,capacity,true);this.m_colorBuffer.data=this.ReallocateBuffer4(this.m_colorBuffer,this.m_internalAllocatedCapacity,capacity,true);this.m_groupBuffer=this.ReallocateBuffer5(this.m_groupBuffer,0,this.m_internalAllocatedCapacity,capacity,false);this.m_userDataBuffer.data=this.ReallocateBuffer4(this.m_userDataBuffer,this.m_internalAllocatedCapacity,capacity,true);this.m_expirationTimeBuffer.data=this.ReallocateBuffer4(this.m_expirationTimeBuffer,this.m_internalAllocatedCapacity,capacity,true);this.m_indexByExpirationTimeBuffer.data=this.ReallocateBuffer4(this.m_indexByExpirationTimeBuffer,this.m_internalAllocatedCapacity,capacity,false);this.m_internalAllocatedCapacity=capacity;}};_proto95.CreateParticleForGroup=function CreateParticleForGroup(groupDef,xf,p){var particleDef=new b2ParticleDef();particleDef.flags=b2Maybe(groupDef.flags,0);b2Transform.MulXV(xf,p,particleDef.position);b2Vec2.AddVV(b2Maybe(groupDef.linearVelocity,b2Vec2.ZERO),b2Vec2.CrossSV(b2Maybe(groupDef.angularVelocity,0),b2Vec2.SubVV(particleDef.position,b2Maybe(groupDef.position,b2Vec2.ZERO),b2Vec2.s_t0),b2Vec2.s_t0),particleDef.velocity);particleDef.color.Copy(b2Maybe(groupDef.color,b2Color.ZERO));particleDef.lifetime=b2Maybe(groupDef.lifetime,0);particleDef.userData=groupDef.userData;this.CreateParticle(particleDef);};_proto95.CreateParticlesStrokeShapeForGroup=function CreateParticlesStrokeShapeForGroup(shape,groupDef,xf){var s_edge=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_edge;var s_d=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_d;var s_p=b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_p;var stride=b2Maybe(groupDef.stride,0);if(stride===0){stride=this.GetParticleStride();}var positionOnEdge=0;var childCount=shape.GetChildCount();for(var childIndex=0;childIndex<childCount;childIndex++){var edge=null;if(shape.GetType()===exports$1.b2ShapeType.e_edgeShape){edge=shape;}else {edge=s_edge;shape.GetChildEdge(edge,childIndex);}var d=b2Vec2.SubVV(edge.m_vertex2,edge.m_vertex1,s_d);var edgeLength=d.Length();while(positionOnEdge<edgeLength){var p=b2Vec2.AddVMulSV(edge.m_vertex1,positionOnEdge/edgeLength,d,s_p);this.CreateParticleForGroup(groupDef,xf,p);positionOnEdge+=stride;}positionOnEdge-=edgeLength;}};_proto95.CreateParticlesFillShapeForGroup=function CreateParticlesFillShapeForGroup(shape,groupDef,xf){var s_aabb=b2ParticleSystem.CreateParticlesFillShapeForGroup_s_aabb;var s_p=b2ParticleSystem.CreateParticlesFillShapeForGroup_s_p;var stride=b2Maybe(groupDef.stride,0);if(stride===0){stride=this.GetParticleStride();}var identity=b2Transform.IDENTITY;var aabb=s_aabb;shape.ComputeAABB(aabb,identity,0);for(var y=Math.floor(aabb.lowerBound.y/stride)*stride;y<aabb.upperBound.y;y+=stride){for(var x=Math.floor(aabb.lowerBound.x/stride)*stride;x<aabb.upperBound.x;x+=stride){var p=s_p.Set(x,y);if(shape.TestPoint(identity,p)){this.CreateParticleForGroup(groupDef,xf,p);}}}};_proto95.CreateParticlesWithShapeForGroup=function CreateParticlesWithShapeForGroup(shape,groupDef,xf){switch(shape.GetType()){case exports$1.b2ShapeType.e_edgeShape:case exports$1.b2ShapeType.e_chainShape:this.CreateParticlesStrokeShapeForGroup(shape,groupDef,xf);break;case exports$1.b2ShapeType.e_polygonShape:case exports$1.b2ShapeType.e_circleShape:this.CreateParticlesFillShapeForGroup(shape,groupDef,xf);break;}};_proto95.CreateParticlesWithShapesForGroup=function CreateParticlesWithShapesForGroup(shapes,shapeCount,groupDef,xf){var compositeShape=new b2ParticleSystem_CompositeShape(shapes,shapeCount);this.CreateParticlesFillShapeForGroup(compositeShape,groupDef,xf);};_proto95.CloneParticle=function CloneParticle(oldIndex,group){var def=new b2ParticleDef();def.flags=this.m_flagsBuffer.data[oldIndex];def.position.Copy(this.m_positionBuffer.data[oldIndex]);def.velocity.Copy(this.m_velocityBuffer.data[oldIndex]);if(this.m_colorBuffer.data){def.color.Copy(this.m_colorBuffer.data[oldIndex]);}if(this.m_userDataBuffer.data){def.userData=this.m_userDataBuffer.data[oldIndex];}def.group=group;var newIndex=this.CreateParticle(def);if(this.m_handleIndexBuffer.data){var handle=this.m_handleIndexBuffer.data[oldIndex];if(handle){handle.SetIndex(newIndex);}this.m_handleIndexBuffer.data[newIndex]=handle;this.m_handleIndexBuffer.data[oldIndex]=null;}if(this.m_lastBodyContactStepBuffer.data){this.m_lastBodyContactStepBuffer.data[newIndex]=this.m_lastBodyContactStepBuffer.data[oldIndex];}if(this.m_bodyContactCountBuffer.data){this.m_bodyContactCountBuffer.data[newIndex]=this.m_bodyContactCountBuffer.data[oldIndex];}if(this.m_consecutiveContactStepsBuffer.data){this.m_consecutiveContactStepsBuffer.data[newIndex]=this.m_consecutiveContactStepsBuffer.data[oldIndex];}if(this.m_hasForce){this.m_forceBuffer[newIndex].Copy(this.m_forceBuffer[oldIndex]);}if(this.m_staticPressureBuffer){this.m_staticPressureBuffer[newIndex]=this.m_staticPressureBuffer[oldIndex];}if(this.m_depthBuffer){this.m_depthBuffer[newIndex]=this.m_depthBuffer[oldIndex];}if(this.m_expirationTimeBuffer.data){this.m_expirationTimeBuffer.data[newIndex]=this.m_expirationTimeBuffer.data[oldIndex];}return newIndex;};_proto95.DestroyParticlesInGroup=function DestroyParticlesInGroup(group,callDestructionListener){if(callDestructionListener===void 0){callDestructionListener=false;}for(var i=group.m_firstIndex;i<group.m_lastIndex;i++){this.DestroyParticle(i,callDestructionListener);}};_proto95.DestroyParticleGroup=function DestroyParticleGroup(group){if(this.m_world.m_destructionListener){this.m_world.m_destructionListener.SayGoodbyeParticleGroup(group);}this.SetGroupFlags(group,0);for(var i=group.m_firstIndex;i<group.m_lastIndex;i++){this.m_groupBuffer[i]=null;}if(group.m_prev){group.m_prev.m_next=group.m_next;}if(group.m_next){group.m_next.m_prev=group.m_prev;}if(group===this.m_groupList){this.m_groupList=group.m_next;}--this.m_groupCount;};b2ParticleSystem.ParticleCanBeConnected=function ParticleCanBeConnected(flags,group){return (flags&(exports$1.b2ParticleFlag.b2_wallParticle|exports$1.b2ParticleFlag.b2_springParticle|exports$1.b2ParticleFlag.b2_elasticParticle))!==0||group!==null&&(group.GetGroupFlags()&exports$1.b2ParticleGroupFlag.b2_rigidParticleGroup)!==0;};_proto95.UpdatePairsAndTriads=function UpdatePairsAndTriads(firstIndex,lastIndex,filter){var s_dab=b2ParticleSystem.UpdatePairsAndTriads_s_dab;var s_dbc=b2ParticleSystem.UpdatePairsAndTriads_s_dbc;var s_dca=b2ParticleSystem.UpdatePairsAndTriads_s_dca;var pos_data=this.m_positionBuffer.data;var particleFlags=0;for(var i=firstIndex;i<lastIndex;i++){particleFlags|=this.m_flagsBuffer.data[i];}if(particleFlags&b2ParticleSystem.k_pairFlags){for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;var af=this.m_flagsBuffer.data[a];var bf=this.m_flagsBuffer.data[b];var groupA=this.m_groupBuffer[a];var groupB=this.m_groupBuffer[b];if(a>=firstIndex&&a<lastIndex&&b>=firstIndex&&b<lastIndex&&!((af|bf)&exports$1.b2ParticleFlag.b2_zombieParticle)&&(af|bf)&b2ParticleSystem.k_pairFlags&&(filter.IsNecessary(a)||filter.IsNecessary(b))&&b2ParticleSystem.ParticleCanBeConnected(af,groupA)&&b2ParticleSystem.ParticleCanBeConnected(bf,groupB)&&filter.ShouldCreatePair(a,b)){var pair=this.m_pairBuffer.data[this.m_pairBuffer.Append()];pair.indexA=a;pair.indexB=b;pair.flags=contact.flags;pair.strength=b2Min(groupA?groupA.m_strength:1,groupB?groupB.m_strength:1);pair.distance=b2Vec2.DistanceVV(pos_data[a],pos_data[b]);}std_stable_sort(this.m_pairBuffer.data,0,this.m_pairBuffer.count,b2ParticleSystem.ComparePairIndices);this.m_pairBuffer.Unique(b2ParticleSystem.MatchPairIndices);}}if(particleFlags&b2ParticleSystem.k_triadFlags){var diagram=new b2VoronoiDiagram(lastIndex-firstIndex);for(var _i30=firstIndex;_i30<lastIndex;_i30++){var flags=this.m_flagsBuffer.data[_i30];var group=this.m_groupBuffer[_i30];if(!(flags&exports$1.b2ParticleFlag.b2_zombieParticle)&&b2ParticleSystem.ParticleCanBeConnected(flags,group)){diagram.AddGenerator(pos_data[_i30],_i30,filter.IsNecessary(_i30));}}var stride=this.GetParticleStride();diagram.Generate(stride/2,stride*2);var system=this;var callback=function callback(a,b,c){var af=system.m_flagsBuffer.data[a];var bf=system.m_flagsBuffer.data[b];var cf=system.m_flagsBuffer.data[c];if((af|bf|cf)&b2ParticleSystem.k_triadFlags&&filter.ShouldCreateTriad(a,b,c)){var pa=pos_data[a];var pb=pos_data[b];var pc=pos_data[c];var dab=b2Vec2.SubVV(pa,pb,s_dab);var dbc=b2Vec2.SubVV(pb,pc,s_dbc);var dca=b2Vec2.SubVV(pc,pa,s_dca);var maxDistanceSquared=b2_maxTriadDistanceSquared*system.m_squaredDiameter;if(b2Vec2.DotVV(dab,dab)>maxDistanceSquared||b2Vec2.DotVV(dbc,dbc)>maxDistanceSquared||b2Vec2.DotVV(dca,dca)>maxDistanceSquared){return;}var _groupA=system.m_groupBuffer[a];var _groupB=system.m_groupBuffer[b];var groupC=system.m_groupBuffer[c];var triad=system.m_triadBuffer.data[system.m_triadBuffer.Append()];triad.indexA=a;triad.indexB=b;triad.indexC=c;triad.flags=af|bf|cf;triad.strength=b2Min(b2Min(_groupA?_groupA.m_strength:1,_groupB?_groupB.m_strength:1),groupC?groupC.m_strength:1);var midPoint_x=(pa.x+pb.x+pc.x)/3.0;var midPoint_y=(pa.y+pb.y+pc.y)/3.0;triad.pa.x=pa.x-midPoint_x;triad.pa.y=pa.y-midPoint_y;triad.pb.x=pb.x-midPoint_x;triad.pb.y=pb.y-midPoint_y;triad.pc.x=pc.x-midPoint_x;triad.pc.y=pc.y-midPoint_y;triad.ka=-b2Vec2.DotVV(dca,dab);triad.kb=-b2Vec2.DotVV(dab,dbc);triad.kc=-b2Vec2.DotVV(dbc,dca);triad.s=b2Vec2.CrossVV(pa,pb)+b2Vec2.CrossVV(pb,pc)+b2Vec2.CrossVV(pc,pa);}};diagram.GetNodes(callback);std_stable_sort(this.m_triadBuffer.data,0,this.m_triadBuffer.count,b2ParticleSystem.CompareTriadIndices);this.m_triadBuffer.Unique(b2ParticleSystem.MatchTriadIndices);}};_proto95.UpdatePairsAndTriadsWithReactiveParticles=function UpdatePairsAndTriadsWithReactiveParticles(){var filter=new b2ParticleSystem_ReactiveFilter(this.m_flagsBuffer);this.UpdatePairsAndTriads(0,this.m_count,filter);for(var i=0;i<this.m_count;i++){this.m_flagsBuffer.data[i]&=~exports$1.b2ParticleFlag.b2_reactiveParticle;}this.m_allParticleFlags&=~exports$1.b2ParticleFlag.b2_reactiveParticle;};b2ParticleSystem.ComparePairIndices=function ComparePairIndices(a,b){var diffA=a.indexA-b.indexA;if(diffA!==0){return diffA<0;}return a.indexB<b.indexB;};b2ParticleSystem.MatchPairIndices=function MatchPairIndices(a,b){return a.indexA===b.indexA&&a.indexB===b.indexB;};b2ParticleSystem.CompareTriadIndices=function CompareTriadIndices(a,b){var diffA=a.indexA-b.indexA;if(diffA!==0){return diffA<0;}var diffB=a.indexB-b.indexB;if(diffB!==0){return diffB<0;}return a.indexC<b.indexC;};b2ParticleSystem.MatchTriadIndices=function MatchTriadIndices(a,b){return a.indexA===b.indexA&&a.indexB===b.indexB&&a.indexC===b.indexC;};b2ParticleSystem.InitializeParticleLists=function InitializeParticleLists(group,nodeBuffer){var bufferIndex=group.GetBufferIndex();var particleCount=group.GetParticleCount();for(var i=0;i<particleCount;i++){var node=nodeBuffer[i];node.list=node;node.next=null;node.count=1;node.index=i+bufferIndex;}};_proto95.MergeParticleListsInContact=function MergeParticleListsInContact(group,nodeBuffer){var bufferIndex=group.GetBufferIndex();for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;if(!group.ContainsParticle(a)||!group.ContainsParticle(b)){continue;}var listA=nodeBuffer[a-bufferIndex].list;var listB=nodeBuffer[b-bufferIndex].list;if(listA===listB){continue;}if(listA.count<listB.count){var _tmp=listA;listA=listB;listB=_tmp;}b2ParticleSystem.MergeParticleLists(listA,listB);}};b2ParticleSystem.MergeParticleLists=function MergeParticleLists(listA,listB){for(var b=listB;;){b.list=listA;var nextB=b.next;if(nextB){b=nextB;}else {b.next=listA.next;break;}}listA.next=listB;listA.count+=listB.count;listB.count=0;};b2ParticleSystem.FindLongestParticleList=function FindLongestParticleList(group,nodeBuffer){var particleCount=group.GetParticleCount();var result=nodeBuffer[0];for(var i=0;i<particleCount;i++){var node=nodeBuffer[i];if(result.count<node.count){result=node;}}return result;};_proto95.MergeZombieParticleListNodes=function MergeZombieParticleListNodes(group,nodeBuffer,survivingList){var particleCount=group.GetParticleCount();for(var i=0;i<particleCount;i++){var node=nodeBuffer[i];if(node!==survivingList&&this.m_flagsBuffer.data[node.index]&exports$1.b2ParticleFlag.b2_zombieParticle){b2ParticleSystem.MergeParticleListAndNode(survivingList,node);}}};b2ParticleSystem.MergeParticleListAndNode=function MergeParticleListAndNode(list,node){node.list=list;node.next=list.next;list.next=node;list.count++;node.count=0;};_proto95.CreateParticleGroupsFromParticleList=function CreateParticleGroupsFromParticleList(group,nodeBuffer,survivingList){var particleCount=group.GetParticleCount();var def=new b2ParticleGroupDef();def.groupFlags=group.GetGroupFlags();def.userData=group.GetUserData();for(var i=0;i<particleCount;i++){var list=nodeBuffer[i];if(!list.count||list===survivingList){continue;}var newGroup=this.CreateParticleGroup(def);for(var node=list;node;node=node.next){var oldIndex=node.index;var newIndex=this.CloneParticle(oldIndex,newGroup);this.m_flagsBuffer.data[oldIndex]|=exports$1.b2ParticleFlag.b2_zombieParticle;node.index=newIndex;}}};_proto95.UpdatePairsAndTriadsWithParticleList=function UpdatePairsAndTriadsWithParticleList(group,nodeBuffer){var bufferIndex=group.GetBufferIndex();for(var k=0;k<this.m_pairBuffer.count;k++){var pair=this.m_pairBuffer.data[k];var a=pair.indexA;var b=pair.indexB;if(group.ContainsParticle(a)){pair.indexA=nodeBuffer[a-bufferIndex].index;}if(group.ContainsParticle(b)){pair.indexB=nodeBuffer[b-bufferIndex].index;}}for(var _k6=0;_k6<this.m_triadBuffer.count;_k6++){var triad=this.m_triadBuffer.data[_k6];var _a4=triad.indexA;var _b5=triad.indexB;var c=triad.indexC;if(group.ContainsParticle(_a4)){triad.indexA=nodeBuffer[_a4-bufferIndex].index;}if(group.ContainsParticle(_b5)){triad.indexB=nodeBuffer[_b5-bufferIndex].index;}if(group.ContainsParticle(c)){triad.indexC=nodeBuffer[c-bufferIndex].index;}}};_proto95.ComputeDepth=function ComputeDepth(){var contactGroups=[];var contactGroupsCount=0;for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;var groupA=this.m_groupBuffer[a];var groupB=this.m_groupBuffer[b];if(groupA&&groupA===groupB&&groupA.m_groupFlags&exports$1.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth){contactGroups[contactGroupsCount++]=contact;}}var groupsToUpdate=[];var groupsToUpdateCount=0;for(var group=this.m_groupList;group;group=group.GetNext()){if(group.m_groupFlags&exports$1.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth){groupsToUpdate[groupsToUpdateCount++]=group;this.SetGroupFlags(group,group.m_groupFlags&~exports$1.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth);for(var i=group.m_firstIndex;i<group.m_lastIndex;i++){this.m_accumulationBuffer[i]=0;}}}for(var _k7=0;_k7<contactGroupsCount;_k7++){var _contact=contactGroups[_k7];var _a5=_contact.indexA;var _b6=_contact.indexB;var w=_contact.weight;this.m_accumulationBuffer[_a5]+=w;this.m_accumulationBuffer[_b6]+=w;}for(var _i31=0;_i31<groupsToUpdateCount;_i31++){var _group=groupsToUpdate[_i31];for(var _i32=_group.m_firstIndex;_i32<_group.m_lastIndex;_i32++){var _w2=this.m_accumulationBuffer[_i32];this.m_depthBuffer[_i32]=_w2<0.8?0:b2_maxFloat;}}var iterationCount=b2Sqrt(this.m_count)>>0;for(var t=0;t<iterationCount;t++){var updated=false;for(var _k8=0;_k8<contactGroupsCount;_k8++){var _contact2=contactGroups[_k8];var _a6=_contact2.indexA;var _b7=_contact2.indexB;var r=1-_contact2.weight;var ap0=this.m_depthBuffer[_a6];var bp0=this.m_depthBuffer[_b7];var ap1=bp0+r;var bp1=ap0+r;if(ap0>ap1){this.m_depthBuffer[_a6]=ap1;updated=true;}if(bp0>bp1){this.m_depthBuffer[_b7]=bp1;updated=true;}}if(!updated){break;}}for(var _i33=0;_i33<groupsToUpdateCount;_i33++){var _group2=groupsToUpdate[_i33];for(var _i34=_group2.m_firstIndex;_i34<_group2.m_lastIndex;_i34++){if(this.m_depthBuffer[_i34]<b2_maxFloat){this.m_depthBuffer[_i34]*=this.m_particleDiameter;}else {this.m_depthBuffer[_i34]=0;}}}};_proto95.GetInsideBoundsEnumerator=function GetInsideBoundsEnumerator(aabb){var lowerTag=b2ParticleSystem.computeTag(this.m_inverseDiameter*aabb.lowerBound.x-1,this.m_inverseDiameter*aabb.lowerBound.y-1);var upperTag=b2ParticleSystem.computeTag(this.m_inverseDiameter*aabb.upperBound.x+1,this.m_inverseDiameter*aabb.upperBound.y+1);var beginProxy=0;var endProxy=this.m_proxyBuffer.count;var firstProxy=std_lower_bound(this.m_proxyBuffer.data,beginProxy,endProxy,lowerTag,b2ParticleSystem_Proxy.CompareProxyTag);var lastProxy=std_upper_bound(this.m_proxyBuffer.data,beginProxy,endProxy,upperTag,b2ParticleSystem_Proxy.CompareTagProxy);return new b2ParticleSystem_InsideBoundsEnumerator(this,lowerTag,upperTag,firstProxy,lastProxy);};_proto95.UpdateAllParticleFlags=function UpdateAllParticleFlags(){this.m_allParticleFlags=0;for(var i=0;i<this.m_count;i++){this.m_allParticleFlags|=this.m_flagsBuffer.data[i];}this.m_needsUpdateAllParticleFlags=false;};_proto95.UpdateAllGroupFlags=function UpdateAllGroupFlags(){this.m_allGroupFlags=0;for(var group=this.m_groupList;group;group=group.GetNext()){this.m_allGroupFlags|=group.m_groupFlags;}this.m_needsUpdateAllGroupFlags=false;};_proto95.AddContact=function AddContact(a,b,contacts){var flags_data=this.m_flagsBuffer.data;var pos_data=this.m_positionBuffer.data;var d=b2Vec2.SubVV(pos_data[b],pos_data[a],b2ParticleSystem.AddContact_s_d);var distBtParticlesSq=b2Vec2.DotVV(d,d);if(0<distBtParticlesSq&&distBtParticlesSq<this.m_squaredDiameter){var invD=b2InvSqrt(distBtParticlesSq);var contact=this.m_contactBuffer.data[this.m_contactBuffer.Append()];contact.indexA=a;contact.indexB=b;contact.flags=flags_data[a]|flags_data[b];contact.weight=1-distBtParticlesSq*invD*this.m_inverseDiameter;contact.normal.x=invD*d.x;contact.normal.y=invD*d.y;}};_proto95.FindContacts_Reference=function FindContacts_Reference(contacts){var beginProxy=0;var endProxy=this.m_proxyBuffer.count;this.m_contactBuffer.count=0;for(var a=beginProxy,c=beginProxy;a<endProxy;a++){var rightTag=b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag,1,0);for(var b=a+1;b<endProxy;b++){if(rightTag<this.m_proxyBuffer.data[b].tag){break;}this.AddContact(this.m_proxyBuffer.data[a].index,this.m_proxyBuffer.data[b].index,this.m_contactBuffer);}var bottomLeftTag=b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag,-1,1);for(;c<endProxy;c++){if(bottomLeftTag<=this.m_proxyBuffer.data[c].tag){break;}}var bottomRightTag=b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag,1,1);for(var _b8=c;_b8<endProxy;_b8++){if(bottomRightTag<this.m_proxyBuffer.data[_b8].tag){break;}this.AddContact(this.m_proxyBuffer.data[a].index,this.m_proxyBuffer.data[_b8].index,this.m_contactBuffer);}}};_proto95.FindContacts=function FindContacts(contacts){this.FindContacts_Reference(contacts);};_proto95.UpdateProxies_Reference=function UpdateProxies_Reference(proxies){var pos_data=this.m_positionBuffer.data;var inv_diam=this.m_inverseDiameter;for(var k=0;k<this.m_proxyBuffer.count;++k){var proxy=this.m_proxyBuffer.data[k];var i=proxy.index;var p=pos_data[i];proxy.tag=b2ParticleSystem.computeTag(inv_diam*p.x,inv_diam*p.y);}};_proto95.UpdateProxies=function UpdateProxies(proxies){this.UpdateProxies_Reference(proxies);};_proto95.SortProxies=function SortProxies(proxies){std_sort$1(this.m_proxyBuffer.data,0,this.m_proxyBuffer.count,b2ParticleSystem_Proxy.CompareProxyProxy);};_proto95.FilterContacts=function FilterContacts(contacts){var contactFilter=this.GetParticleContactFilter();if(contactFilter===null){return;}var system=this;var predicate=function predicate(contact){return (contact.flags&exports$1.b2ParticleFlag.b2_particleContactFilterParticle)!==0&&!contactFilter.ShouldCollideParticleParticle(system,contact.indexA,contact.indexB);};this.m_contactBuffer.RemoveIf(predicate);};_proto95.NotifyContactListenerPreContact=function NotifyContactListenerPreContact(particlePairs){var contactListener=this.GetParticleContactListener();if(contactListener===null){return;}particlePairs.Initialize(this.m_contactBuffer,this.m_flagsBuffer);throw new Error();};_proto95.NotifyContactListenerPostContact=function NotifyContactListenerPostContact(particlePairs){var contactListener=this.GetParticleContactListener();if(contactListener===null){return;}for(var k=0;k<this.m_contactBuffer.count;++k){var contact=this.m_contactBuffer.data[k];{contactListener.BeginContactParticleParticle(this,contact);}}throw new Error();};b2ParticleSystem.b2ParticleContactIsZombie=function b2ParticleContactIsZombie(contact){return (contact.flags&exports$1.b2ParticleFlag.b2_zombieParticle)===exports$1.b2ParticleFlag.b2_zombieParticle;};_proto95.UpdateContacts=function UpdateContacts(exceptZombie){this.UpdateProxies(this.m_proxyBuffer);this.SortProxies(this.m_proxyBuffer);var particlePairs=new b2ParticlePairSet();this.NotifyContactListenerPreContact(particlePairs);this.FindContacts(this.m_contactBuffer);this.FilterContacts(this.m_contactBuffer);this.NotifyContactListenerPostContact(particlePairs);if(exceptZombie){this.m_contactBuffer.RemoveIf(b2ParticleSystem.b2ParticleContactIsZombie);}};_proto95.NotifyBodyContactListenerPreContact=function NotifyBodyContactListenerPreContact(fixtureSet){var contactListener=this.GetFixtureContactListener();if(contactListener===null){return;}fixtureSet.Initialize(this.m_bodyContactBuffer,this.m_flagsBuffer);throw new Error();};_proto95.NotifyBodyContactListenerPostContact=function NotifyBodyContactListenerPostContact(fixtureSet){var contactListener=this.GetFixtureContactListener();if(contactListener===null){return;}for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];{contactListener.BeginContactFixtureParticle(this,contact);}}throw new Error();};_proto95.UpdateBodyContacts=function UpdateBodyContacts(){var s_aabb=b2ParticleSystem.UpdateBodyContacts_s_aabb;var fixtureSet=new b2ParticleSystem_FixtureParticleSet();this.NotifyBodyContactListenerPreContact(fixtureSet);if(this.m_stuckThreshold>0){var particleCount=this.GetParticleCount();for(var i=0;i<particleCount;i++){this.m_bodyContactCountBuffer.data[i]=0;if(this.m_timestamp>this.m_lastBodyContactStepBuffer.data[i]+1){this.m_consecutiveContactStepsBuffer.data[i]=0;}}}this.m_bodyContactBuffer.SetCount(0);this.m_stuckParticleBuffer.SetCount(0);var aabb=s_aabb;this.ComputeAABB(aabb);if(this.UpdateBodyContacts_callback===null){this.UpdateBodyContacts_callback=new b2ParticleSystem_UpdateBodyContactsCallback(this);}var callback=this.UpdateBodyContacts_callback;callback.m_contactFilter=this.GetFixtureContactFilter();this.m_world.QueryAABB(callback,aabb);if(this.m_def.strictContactCheck){this.RemoveSpuriousBodyContacts();}this.NotifyBodyContactListenerPostContact(fixtureSet);};_proto95.Solve=function Solve(step){var s_subStep=b2ParticleSystem.Solve_s_subStep;if(this.m_count===0){return;}if(this.m_expirationTimeBuffer.data){this.SolveLifetimes(step);}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_zombieParticle){this.SolveZombie();}if(this.m_needsUpdateAllParticleFlags){this.UpdateAllParticleFlags();}if(this.m_needsUpdateAllGroupFlags){this.UpdateAllGroupFlags();}if(this.m_paused){return;}for(this.m_iterationIndex=0;this.m_iterationIndex<step.particleIterations;this.m_iterationIndex++){++this.m_timestamp;var subStep=s_subStep.Copy(step);subStep.dt/=step.particleIterations;subStep.inv_dt*=step.particleIterations;this.UpdateContacts(false);this.UpdateBodyContacts();this.ComputeWeight();if(this.m_allGroupFlags&exports$1.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth){this.ComputeDepth();}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_reactiveParticle){this.UpdatePairsAndTriadsWithReactiveParticles();}if(this.m_hasForce){this.SolveForce(subStep);}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_viscousParticle){this.SolveViscous();}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_repulsiveParticle){this.SolveRepulsive(subStep);}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_powderParticle){this.SolvePowder(subStep);}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_tensileParticle){this.SolveTensile(subStep);}if(this.m_allGroupFlags&exports$1.b2ParticleGroupFlag.b2_solidParticleGroup){this.SolveSolid(subStep);}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_colorMixingParticle){this.SolveColorMixing();}this.SolveGravity(subStep);if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_staticPressureParticle){this.SolveStaticPressure(subStep);}this.SolvePressure(subStep);this.SolveDamping(subStep);if(this.m_allParticleFlags&b2ParticleSystem.k_extraDampingFlags){this.SolveExtraDamping();}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_elasticParticle){this.SolveElastic(subStep);}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_springParticle){this.SolveSpring(subStep);}this.LimitVelocity(subStep);if(this.m_allGroupFlags&exports$1.b2ParticleGroupFlag.b2_rigidParticleGroup){this.SolveRigidDamping();}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_barrierParticle){this.SolveBarrier(subStep);}this.SolveCollision(subStep);if(this.m_allGroupFlags&exports$1.b2ParticleGroupFlag.b2_rigidParticleGroup){this.SolveRigid(subStep);}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_wallParticle){this.SolveWall();}for(var i=0;i<this.m_count;i++){this.m_positionBuffer.data[i].SelfMulAdd(subStep.dt,this.m_velocityBuffer.data[i]);}}};_proto95.SolveCollision=function SolveCollision(step){var s_aabb=b2ParticleSystem.SolveCollision_s_aabb;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var aabb=s_aabb;aabb.lowerBound.x=+b2_maxFloat;aabb.lowerBound.y=+b2_maxFloat;aabb.upperBound.x=-b2_maxFloat;aabb.upperBound.y=-b2_maxFloat;for(var i=0;i<this.m_count;i++){var v=vel_data[i];var p1=pos_data[i];var p2_x=p1.x+step.dt*v.x;var p2_y=p1.y+step.dt*v.y;aabb.lowerBound.x=b2Min(aabb.lowerBound.x,b2Min(p1.x,p2_x));aabb.lowerBound.y=b2Min(aabb.lowerBound.y,b2Min(p1.y,p2_y));aabb.upperBound.x=b2Max(aabb.upperBound.x,b2Max(p1.x,p2_x));aabb.upperBound.y=b2Max(aabb.upperBound.y,b2Max(p1.y,p2_y));}if(this.SolveCollision_callback===null){this.SolveCollision_callback=new b2ParticleSystem_SolveCollisionCallback(this,step);}var callback=this.SolveCollision_callback;callback.m_step=step;this.m_world.QueryAABB(callback,aabb);};_proto95.LimitVelocity=function LimitVelocity(step){var vel_data=this.m_velocityBuffer.data;var criticalVelocitySquared=this.GetCriticalVelocitySquared(step);for(var i=0;i<this.m_count;i++){var v=vel_data[i];var v2=b2Vec2.DotVV(v,v);if(v2>criticalVelocitySquared){v.SelfMul(b2Sqrt(criticalVelocitySquared/v2));}}};_proto95.SolveGravity=function SolveGravity(step){var s_gravity=b2ParticleSystem.SolveGravity_s_gravity;var vel_data=this.m_velocityBuffer.data;var gravity=b2Vec2.MulSV(step.dt*this.m_def.gravityScale,this.m_world.GetGravity(),s_gravity);for(var i=0;i<this.m_count;i++){vel_data[i].SelfAdd(gravity);}};_proto95.SolveBarrier=function SolveBarrier(step){var s_aabb=b2ParticleSystem.SolveBarrier_s_aabb;var s_va=b2ParticleSystem.SolveBarrier_s_va;var s_vb=b2ParticleSystem.SolveBarrier_s_vb;var s_pba=b2ParticleSystem.SolveBarrier_s_pba;var s_vba=b2ParticleSystem.SolveBarrier_s_vba;var s_vc=b2ParticleSystem.SolveBarrier_s_vc;var s_pca=b2ParticleSystem.SolveBarrier_s_pca;var s_vca=b2ParticleSystem.SolveBarrier_s_vca;var s_qba=b2ParticleSystem.SolveBarrier_s_qba;var s_qca=b2ParticleSystem.SolveBarrier_s_qca;var s_dv=b2ParticleSystem.SolveBarrier_s_dv;var s_f=b2ParticleSystem.SolveBarrier_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;for(var i=0;i<this.m_count;i++){var flags=this.m_flagsBuffer.data[i];if((flags&b2ParticleSystem.k_barrierWallFlags)!==0){vel_data[i].SetZero();}}var tmax=b2_barrierCollisionTime*step.dt;var mass=this.GetParticleMass();for(var k=0;k<this.m_pairBuffer.count;k++){var pair=this.m_pairBuffer.data[k];if(pair.flags&exports$1.b2ParticleFlag.b2_barrierParticle){var a=pair.indexA;var b=pair.indexB;var pa=pos_data[a];var pb=pos_data[b];var aabb=s_aabb;b2Vec2.MinV(pa,pb,aabb.lowerBound);b2Vec2.MaxV(pa,pb,aabb.upperBound);var aGroup=this.m_groupBuffer[a];var bGroup=this.m_groupBuffer[b];var va=this.GetLinearVelocity(aGroup,a,pa,s_va);var vb=this.GetLinearVelocity(bGroup,b,pb,s_vb);var pba=b2Vec2.SubVV(pb,pa,s_pba);var vba=b2Vec2.SubVV(vb,va,s_vba);var enumerator=this.GetInsideBoundsEnumerator(aabb);var c=void 0;while((c=enumerator.GetNext())>=0){var pc=pos_data[c];var cGroup=this.m_groupBuffer[c];if(aGroup!==cGroup&&bGroup!==cGroup){var vc=this.GetLinearVelocity(cGroup,c,pc,s_vc);var pca=b2Vec2.SubVV(pc,pa,s_pca);var vca=b2Vec2.SubVV(vc,va,s_vca);var e2=b2Vec2.CrossVV(vba,vca);var e1=b2Vec2.CrossVV(pba,vca)-b2Vec2.CrossVV(pca,vba);var e0=b2Vec2.CrossVV(pba,pca);var s=void 0,t=void 0;var qba=s_qba,qca=s_qca;if(e2===0){if(e1===0){continue;}t=-e0/e1;if(!(t>=0&&t<tmax)){continue;}b2Vec2.AddVMulSV(pba,t,vba,qba);b2Vec2.AddVMulSV(pca,t,vca,qca);s=b2Vec2.DotVV(qba,qca)/b2Vec2.DotVV(qba,qba);if(!(s>=0&&s<=1)){continue;}}else {var det=e1*e1-4*e0*e2;if(det<0){continue;}var sqrtDet=b2Sqrt(det);var t1=(-e1-sqrtDet)/(2*e2);var t2=(-e1+sqrtDet)/(2*e2);if(t1>t2){var tmp=t1;t1=t2;t2=tmp;}t=t1;b2Vec2.AddVMulSV(pba,t,vba,qba);b2Vec2.AddVMulSV(pca,t,vca,qca);s=b2Vec2.DotVV(qba,qca)/b2Vec2.DotVV(qba,qba);if(!(t>=0&&t<tmax&&s>=0&&s<=1)){t=t2;if(!(t>=0&&t<tmax)){continue;}b2Vec2.AddVMulSV(pba,t,vba,qba);b2Vec2.AddVMulSV(pca,t,vca,qca);s=b2Vec2.DotVV(qba,qca)/b2Vec2.DotVV(qba,qba);if(!(s>=0&&s<=1)){continue;}}}var dv=s_dv;dv.x=va.x+s*vba.x-vc.x;dv.y=va.y+s*vba.y-vc.y;var f=b2Vec2.MulSV(mass,dv,s_f);if(cGroup&&this.IsRigidGroup(cGroup)){var _mass=cGroup.GetMass();var inertia=cGroup.GetInertia();if(_mass>0){cGroup.m_linearVelocity.SelfMulAdd(1/_mass,f);}if(inertia>0){cGroup.m_angularVelocity+=b2Vec2.CrossVV(b2Vec2.SubVV(pc,cGroup.GetCenter(),b2Vec2.s_t0),f)/inertia;}}else {vel_data[c].SelfAdd(dv);}this.ParticleApplyForce(c,f.SelfMul(-step.inv_dt));}}}}};_proto95.SolveStaticPressure=function SolveStaticPressure(step){this.m_staticPressureBuffer=this.RequestBuffer(this.m_staticPressureBuffer);var criticalPressure=this.GetCriticalPressure(step);var pressurePerWeight=this.m_def.staticPressureStrength*criticalPressure;var maxPressure=b2_maxParticlePressure*criticalPressure;var relaxation=this.m_def.staticPressureRelaxation;for(var t=0;t<this.m_def.staticPressureIterations;t++){for(var i=0;i<this.m_count;i++){this.m_accumulationBuffer[i]=0;}for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];if(contact.flags&exports$1.b2ParticleFlag.b2_staticPressureParticle){var a=contact.indexA;var b=contact.indexB;var w=contact.weight;this.m_accumulationBuffer[a]+=w*this.m_staticPressureBuffer[b];this.m_accumulationBuffer[b]+=w*this.m_staticPressureBuffer[a];}}for(var _i35=0;_i35<this.m_count;_i35++){var _w3=this.m_weightBuffer[_i35];if(this.m_flagsBuffer.data[_i35]&exports$1.b2ParticleFlag.b2_staticPressureParticle){var wh=this.m_accumulationBuffer[_i35];var h=(wh+pressurePerWeight*(_w3-b2_minParticleWeight))/(_w3+relaxation);this.m_staticPressureBuffer[_i35]=b2Clamp(h,0.0,maxPressure);}else {this.m_staticPressureBuffer[_i35]=0;}}}};_proto95.ComputeWeight=function ComputeWeight(){for(var k=0;k<this.m_count;k++){this.m_weightBuffer[k]=0;}for(var _k9=0;_k9<this.m_bodyContactBuffer.count;_k9++){var contact=this.m_bodyContactBuffer.data[_k9];var a=contact.index;var w=contact.weight;this.m_weightBuffer[a]+=w;}for(var _k10=0;_k10<this.m_contactBuffer.count;_k10++){var _contact3=this.m_contactBuffer.data[_k10];var _a7=_contact3.indexA;var b=_contact3.indexB;var _w4=_contact3.weight;this.m_weightBuffer[_a7]+=_w4;this.m_weightBuffer[b]+=_w4;}};_proto95.SolvePressure=function SolvePressure(step){var s_f=b2ParticleSystem.SolvePressure_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var criticalPressure=this.GetCriticalPressure(step);var pressurePerWeight=this.m_def.pressureStrength*criticalPressure;var maxPressure=b2_maxParticlePressure*criticalPressure;for(var i=0;i<this.m_count;i++){var w=this.m_weightBuffer[i];var h=pressurePerWeight*b2Max(0.0,w-b2_minParticleWeight);this.m_accumulationBuffer[i]=b2Min(h,maxPressure);}if(this.m_allParticleFlags&b2ParticleSystem.k_noPressureFlags){for(var _i36=0;_i36<this.m_count;_i36++){if(this.m_flagsBuffer.data[_i36]&b2ParticleSystem.k_noPressureFlags){this.m_accumulationBuffer[_i36]=0;}}}if(this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_staticPressureParticle){for(var _i37=0;_i37<this.m_count;_i37++){if(this.m_flagsBuffer.data[_i37]&exports$1.b2ParticleFlag.b2_staticPressureParticle){this.m_accumulationBuffer[_i37]+=this.m_staticPressureBuffer[_i37];}}}var velocityPerPressure=step.dt/(this.m_def.density*this.m_particleDiameter);var inv_mass=this.GetParticleInvMass();for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;var b=contact.body;var _w5=contact.weight;var m=contact.mass;var n=contact.normal;var p=pos_data[a];var _h=this.m_accumulationBuffer[a]+pressurePerWeight*_w5;var f=b2Vec2.MulSV(velocityPerPressure*_w5*m*_h,n,s_f);vel_data[a].SelfMulSub(inv_mass,f);b.ApplyLinearImpulse(f,p,true);}for(var _k11=0;_k11<this.m_contactBuffer.count;_k11++){var _contact4=this.m_contactBuffer.data[_k11];var _a8=_contact4.indexA;var _b9=_contact4.indexB;var _w6=_contact4.weight;var _n=_contact4.normal;var _h2=this.m_accumulationBuffer[_a8]+this.m_accumulationBuffer[_b9];var _f2=b2Vec2.MulSV(velocityPerPressure*_w6*_h2,_n,s_f);vel_data[_a8].SelfSub(_f2);vel_data[_b9].SelfAdd(_f2);}};_proto95.SolveDamping=function SolveDamping(step){var s_v=b2ParticleSystem.SolveDamping_s_v;var s_f=b2ParticleSystem.SolveDamping_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var linearDamping=this.m_def.dampingStrength;var quadraticDamping=1/this.GetCriticalVelocity(step);var inv_mass=this.GetParticleInvMass();for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;var b=contact.body;var w=contact.weight;var m=contact.mass;var n=contact.normal;var p=pos_data[a];var v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,b2Vec2.s_t0),vel_data[a],s_v);var vn=b2Vec2.DotVV(v,n);if(vn<0){var damping=b2Max(linearDamping*w,b2Min(-quadraticDamping*vn,0.5));var f=b2Vec2.MulSV(damping*m*vn,n,s_f);vel_data[a].SelfMulAdd(inv_mass,f);b.ApplyLinearImpulse(f.SelfNeg(),p,true);}}for(var _k12=0;_k12<this.m_contactBuffer.count;_k12++){var _contact5=this.m_contactBuffer.data[_k12];var _a9=_contact5.indexA;var _b10=_contact5.indexB;var _w7=_contact5.weight;var _n2=_contact5.normal;var _v4=b2Vec2.SubVV(vel_data[_b10],vel_data[_a9],s_v);var _vn=b2Vec2.DotVV(_v4,_n2);if(_vn<0){var _damping=b2Max(linearDamping*_w7,b2Min(-quadraticDamping*_vn,0.5));var _f3=b2Vec2.MulSV(_damping*_vn,_n2,s_f);vel_data[_a9].SelfAdd(_f3);vel_data[_b10].SelfSub(_f3);}}};_proto95.SolveRigidDamping=function SolveRigidDamping(){var s_t0=b2ParticleSystem.SolveRigidDamping_s_t0;var s_t1=b2ParticleSystem.SolveRigidDamping_s_t1;var s_p=b2ParticleSystem.SolveRigidDamping_s_p;var s_v=b2ParticleSystem.SolveRigidDamping_s_v;var invMassA=[0.0],invInertiaA=[0.0],tangentDistanceA=[0.0];var invMassB=[0.0],invInertiaB=[0.0],tangentDistanceB=[0.0];var pos_data=this.m_positionBuffer.data;var damping=this.m_def.dampingStrength;for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;var aGroup=this.m_groupBuffer[a];if(aGroup&&this.IsRigidGroup(aGroup)){var b=contact.body;var n=contact.normal;var w=contact.weight;var p=pos_data[a];var v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,s_t0),aGroup.GetLinearVelocityFromWorldPoint(p,s_t1),s_v);var vn=b2Vec2.DotVV(v,n);if(vn<0){this.InitDampingParameterWithRigidGroupOrParticle(invMassA,invInertiaA,tangentDistanceA,true,aGroup,a,p,n);this.InitDampingParameter(invMassB,invInertiaB,tangentDistanceB,b.GetMass(),b.GetInertia()-b.GetMass()*b.GetLocalCenter().LengthSquared(),b.GetWorldCenter(),p,n);var f=damping*b2Min(w,1.0)*this.ComputeDampingImpulse(invMassA[0],invInertiaA[0],tangentDistanceA[0],invMassB[0],invInertiaB[0],tangentDistanceB[0],vn);this.ApplyDamping(invMassA[0],invInertiaA[0],tangentDistanceA[0],true,aGroup,a,f,n);b.ApplyLinearImpulse(b2Vec2.MulSV(-f,n,b2Vec2.s_t0),p,true);}}}for(var _k13=0;_k13<this.m_contactBuffer.count;_k13++){var _contact6=this.m_contactBuffer.data[_k13];var _a10=_contact6.indexA;var _b11=_contact6.indexB;var _n3=_contact6.normal;var _w8=_contact6.weight;var _aGroup=this.m_groupBuffer[_a10];var bGroup=this.m_groupBuffer[_b11];var aRigid=this.IsRigidGroup(_aGroup);var bRigid=this.IsRigidGroup(bGroup);if(_aGroup!==bGroup&&(aRigid||bRigid)){var _p=b2Vec2.MidVV(pos_data[_a10],pos_data[_b11],s_p);var _v5=b2Vec2.SubVV(this.GetLinearVelocity(bGroup,_b11,_p,s_t0),this.GetLinearVelocity(_aGroup,_a10,_p,s_t1),s_v);var _vn2=b2Vec2.DotVV(_v5,_n3);if(_vn2<0){this.InitDampingParameterWithRigidGroupOrParticle(invMassA,invInertiaA,tangentDistanceA,aRigid,_aGroup,_a10,_p,_n3);this.InitDampingParameterWithRigidGroupOrParticle(invMassB,invInertiaB,tangentDistanceB,bRigid,bGroup,_b11,_p,_n3);var _f4=damping*_w8*this.ComputeDampingImpulse(invMassA[0],invInertiaA[0],tangentDistanceA[0],invMassB[0],invInertiaB[0],tangentDistanceB[0],_vn2);this.ApplyDamping(invMassA[0],invInertiaA[0],tangentDistanceA[0],aRigid,_aGroup,_a10,_f4,_n3);this.ApplyDamping(invMassB[0],invInertiaB[0],tangentDistanceB[0],bRigid,bGroup,_b11,-_f4,_n3);}}}};_proto95.SolveExtraDamping=function SolveExtraDamping(){var s_v=b2ParticleSystem.SolveExtraDamping_s_v;var s_f=b2ParticleSystem.SolveExtraDamping_s_f;var vel_data=this.m_velocityBuffer.data;var pos_data=this.m_positionBuffer.data;var inv_mass=this.GetParticleInvMass();for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;if(this.m_flagsBuffer.data[a]&b2ParticleSystem.k_extraDampingFlags){var b=contact.body;var m=contact.mass;var n=contact.normal;var p=pos_data[a];var v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,b2Vec2.s_t0),vel_data[a],s_v);var vn=b2Vec2.DotVV(v,n);if(vn<0){var f=b2Vec2.MulSV(0.5*m*vn,n,s_f);vel_data[a].SelfMulAdd(inv_mass,f);b.ApplyLinearImpulse(f.SelfNeg(),p,true);}}}};_proto95.SolveWall=function SolveWall(){var vel_data=this.m_velocityBuffer.data;for(var i=0;i<this.m_count;i++){if(this.m_flagsBuffer.data[i]&exports$1.b2ParticleFlag.b2_wallParticle){vel_data[i].SetZero();}}};_proto95.SolveRigid=function SolveRigid(step){var s_position=b2ParticleSystem.SolveRigid_s_position;var s_rotation=b2ParticleSystem.SolveRigid_s_rotation;var s_transform=b2ParticleSystem.SolveRigid_s_transform;var s_velocityTransform=b2ParticleSystem.SolveRigid_s_velocityTransform;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;for(var group=this.m_groupList;group;group=group.GetNext()){if(group.m_groupFlags&exports$1.b2ParticleGroupFlag.b2_rigidParticleGroup){group.UpdateStatistics();var rotation=s_rotation;rotation.SetAngle(step.dt*group.m_angularVelocity);var position=b2Vec2.AddVV(group.m_center,b2Vec2.SubVV(b2Vec2.MulSV(step.dt,group.m_linearVelocity,b2Vec2.s_t0),b2Rot.MulRV(rotation,group.m_center,b2Vec2.s_t1),b2Vec2.s_t0),s_position);var transform=s_transform;transform.SetPositionRotation(position,rotation);b2Transform.MulXX(transform,group.m_transform,group.m_transform);var velocityTransform=s_velocityTransform;velocityTransform.p.x=step.inv_dt*transform.p.x;velocityTransform.p.y=step.inv_dt*transform.p.y;velocityTransform.q.s=step.inv_dt*transform.q.s;velocityTransform.q.c=step.inv_dt*(transform.q.c-1);for(var i=group.m_firstIndex;i<group.m_lastIndex;i++){b2Transform.MulXV(velocityTransform,pos_data[i],vel_data[i]);}}}};_proto95.SolveElastic=function SolveElastic(step){var s_pa=b2ParticleSystem.SolveElastic_s_pa;var s_pb=b2ParticleSystem.SolveElastic_s_pb;var s_pc=b2ParticleSystem.SolveElastic_s_pc;var s_r=b2ParticleSystem.SolveElastic_s_r;var s_t0=b2ParticleSystem.SolveElastic_s_t0;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var elasticStrength=step.inv_dt*this.m_def.elasticStrength;for(var k=0;k<this.m_triadBuffer.count;k++){var triad=this.m_triadBuffer.data[k];if(triad.flags&exports$1.b2ParticleFlag.b2_elasticParticle){var a=triad.indexA;var b=triad.indexB;var c=triad.indexC;var oa=triad.pa;var ob=triad.pb;var oc=triad.pc;var pa=s_pa.Copy(pos_data[a]);var pb=s_pb.Copy(pos_data[b]);var pc=s_pc.Copy(pos_data[c]);var va=vel_data[a];var vb=vel_data[b];var vc=vel_data[c];pa.SelfMulAdd(step.dt,va);pb.SelfMulAdd(step.dt,vb);pc.SelfMulAdd(step.dt,vc);var midPoint_x=(pa.x+pb.x+pc.x)/3.0;var midPoint_y=(pa.y+pb.y+pc.y)/3.0;pa.x-=midPoint_x;pa.y-=midPoint_y;pb.x-=midPoint_x;pb.y-=midPoint_y;pc.x-=midPoint_x;pc.y-=midPoint_y;var r=s_r;r.s=b2Vec2.CrossVV(oa,pa)+b2Vec2.CrossVV(ob,pb)+b2Vec2.CrossVV(oc,pc);r.c=b2Vec2.DotVV(oa,pa)+b2Vec2.DotVV(ob,pb)+b2Vec2.DotVV(oc,pc);var r2=r.s*r.s+r.c*r.c;var invR=b2InvSqrt(r2);if(!isFinite(invR)){invR=1.98177537e+019;}r.s*=invR;r.c*=invR;var strength=elasticStrength*triad.strength;b2Rot.MulRV(r,oa,s_t0);b2Vec2.SubVV(s_t0,pa,s_t0);b2Vec2.MulSV(strength,s_t0,s_t0);va.SelfAdd(s_t0);b2Rot.MulRV(r,ob,s_t0);b2Vec2.SubVV(s_t0,pb,s_t0);b2Vec2.MulSV(strength,s_t0,s_t0);vb.SelfAdd(s_t0);b2Rot.MulRV(r,oc,s_t0);b2Vec2.SubVV(s_t0,pc,s_t0);b2Vec2.MulSV(strength,s_t0,s_t0);vc.SelfAdd(s_t0);}}};_proto95.SolveSpring=function SolveSpring(step){var s_pa=b2ParticleSystem.SolveSpring_s_pa;var s_pb=b2ParticleSystem.SolveSpring_s_pb;var s_d=b2ParticleSystem.SolveSpring_s_d;var s_f=b2ParticleSystem.SolveSpring_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var springStrength=step.inv_dt*this.m_def.springStrength;for(var k=0;k<this.m_pairBuffer.count;k++){var pair=this.m_pairBuffer.data[k];if(pair.flags&exports$1.b2ParticleFlag.b2_springParticle){var a=pair.indexA;var b=pair.indexB;var pa=s_pa.Copy(pos_data[a]);var pb=s_pb.Copy(pos_data[b]);var va=vel_data[a];var vb=vel_data[b];pa.SelfMulAdd(step.dt,va);pb.SelfMulAdd(step.dt,vb);var d=b2Vec2.SubVV(pb,pa,s_d);var r0=pair.distance;var r1=d.Length();var strength=springStrength*pair.strength;var f=b2Vec2.MulSV(strength*(r0-r1)/r1,d,s_f);va.SelfSub(f);vb.SelfAdd(f);}}};_proto95.SolveTensile=function SolveTensile(step){var s_weightedNormal=b2ParticleSystem.SolveTensile_s_weightedNormal;var s_s=b2ParticleSystem.SolveTensile_s_s;var s_f=b2ParticleSystem.SolveTensile_s_f;var vel_data=this.m_velocityBuffer.data;for(var i=0;i<this.m_count;i++){this.m_accumulation2Buffer[i]=new b2Vec2();this.m_accumulation2Buffer[i].SetZero();}for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];if(contact.flags&exports$1.b2ParticleFlag.b2_tensileParticle){var a=contact.indexA;var b=contact.indexB;var w=contact.weight;var n=contact.normal;var weightedNormal=b2Vec2.MulSV((1-w)*w,n,s_weightedNormal);this.m_accumulation2Buffer[a].SelfSub(weightedNormal);this.m_accumulation2Buffer[b].SelfAdd(weightedNormal);}}var criticalVelocity=this.GetCriticalVelocity(step);var pressureStrength=this.m_def.surfaceTensionPressureStrength*criticalVelocity;var normalStrength=this.m_def.surfaceTensionNormalStrength*criticalVelocity;var maxVelocityVariation=b2_maxParticleForce*criticalVelocity;for(var _k14=0;_k14<this.m_contactBuffer.count;_k14++){var _contact7=this.m_contactBuffer.data[_k14];if(_contact7.flags&exports$1.b2ParticleFlag.b2_tensileParticle){var _a11=_contact7.indexA;var _b12=_contact7.indexB;var _w9=_contact7.weight;var _n4=_contact7.normal;var h=this.m_weightBuffer[_a11]+this.m_weightBuffer[_b12];var s=b2Vec2.SubVV(this.m_accumulation2Buffer[_b12],this.m_accumulation2Buffer[_a11],s_s);var fn=b2Min(pressureStrength*(h-2)+normalStrength*b2Vec2.DotVV(s,_n4),maxVelocityVariation)*_w9;var f=b2Vec2.MulSV(fn,_n4,s_f);vel_data[_a11].SelfSub(f);vel_data[_b12].SelfAdd(f);}}};_proto95.SolveViscous=function SolveViscous(){var s_v=b2ParticleSystem.SolveViscous_s_v;var s_f=b2ParticleSystem.SolveViscous_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var viscousStrength=this.m_def.viscousStrength;var inv_mass=this.GetParticleInvMass();for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;if(this.m_flagsBuffer.data[a]&exports$1.b2ParticleFlag.b2_viscousParticle){var b=contact.body;var w=contact.weight;var m=contact.mass;var p=pos_data[a];var v=b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p,b2Vec2.s_t0),vel_data[a],s_v);var f=b2Vec2.MulSV(viscousStrength*m*w,v,s_f);vel_data[a].SelfMulAdd(inv_mass,f);b.ApplyLinearImpulse(f.SelfNeg(),p,true);}}for(var _k15=0;_k15<this.m_contactBuffer.count;_k15++){var _contact8=this.m_contactBuffer.data[_k15];if(_contact8.flags&exports$1.b2ParticleFlag.b2_viscousParticle){var _a12=_contact8.indexA;var _b13=_contact8.indexB;var _w10=_contact8.weight;var _v6=b2Vec2.SubVV(vel_data[_b13],vel_data[_a12],s_v);var _f5=b2Vec2.MulSV(viscousStrength*_w10,_v6,s_f);vel_data[_a12].SelfAdd(_f5);vel_data[_b13].SelfSub(_f5);}}};_proto95.SolveRepulsive=function SolveRepulsive(step){var s_f=b2ParticleSystem.SolveRepulsive_s_f;var vel_data=this.m_velocityBuffer.data;var repulsiveStrength=this.m_def.repulsiveStrength*this.GetCriticalVelocity(step);for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];if(contact.flags&exports$1.b2ParticleFlag.b2_repulsiveParticle){var a=contact.indexA;var b=contact.indexB;if(this.m_groupBuffer[a]!==this.m_groupBuffer[b]){var w=contact.weight;var n=contact.normal;var f=b2Vec2.MulSV(repulsiveStrength*w,n,s_f);vel_data[a].SelfSub(f);vel_data[b].SelfAdd(f);}}}};_proto95.SolvePowder=function SolvePowder(step){var s_f=b2ParticleSystem.SolvePowder_s_f;var pos_data=this.m_positionBuffer.data;var vel_data=this.m_velocityBuffer.data;var powderStrength=this.m_def.powderStrength*this.GetCriticalVelocity(step);var minWeight=1.0-b2_particleStride;var inv_mass=this.GetParticleInvMass();for(var k=0;k<this.m_bodyContactBuffer.count;k++){var contact=this.m_bodyContactBuffer.data[k];var a=contact.index;if(this.m_flagsBuffer.data[a]&exports$1.b2ParticleFlag.b2_powderParticle){var w=contact.weight;if(w>minWeight){var b=contact.body;var m=contact.mass;var p=pos_data[a];var n=contact.normal;var f=b2Vec2.MulSV(powderStrength*m*(w-minWeight),n,s_f);vel_data[a].SelfMulSub(inv_mass,f);b.ApplyLinearImpulse(f,p,true);}}}for(var _k16=0;_k16<this.m_contactBuffer.count;_k16++){var _contact9=this.m_contactBuffer.data[_k16];if(_contact9.flags&exports$1.b2ParticleFlag.b2_powderParticle){var _w11=_contact9.weight;if(_w11>minWeight){var _a13=_contact9.indexA;var _b14=_contact9.indexB;var _n5=_contact9.normal;var _f6=b2Vec2.MulSV(powderStrength*(_w11-minWeight),_n5,s_f);vel_data[_a13].SelfSub(_f6);vel_data[_b14].SelfAdd(_f6);}}}};_proto95.SolveSolid=function SolveSolid(step){var s_f=b2ParticleSystem.SolveSolid_s_f;var vel_data=this.m_velocityBuffer.data;this.m_depthBuffer=this.RequestBuffer(this.m_depthBuffer);var ejectionStrength=step.inv_dt*this.m_def.ejectionStrength;for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;if(this.m_groupBuffer[a]!==this.m_groupBuffer[b]){var w=contact.weight;var n=contact.normal;var h=this.m_depthBuffer[a]+this.m_depthBuffer[b];var f=b2Vec2.MulSV(ejectionStrength*h*w,n,s_f);vel_data[a].SelfSub(f);vel_data[b].SelfAdd(f);}}};_proto95.SolveForce=function SolveForce(step){var vel_data=this.m_velocityBuffer.data;var velocityPerForce=step.dt*this.GetParticleInvMass();for(var i=0;i<this.m_count;i++){vel_data[i].SelfMulAdd(velocityPerForce,this.m_forceBuffer[i]);}this.m_hasForce=false;};_proto95.SolveColorMixing=function SolveColorMixing(){var colorMixing=0.5*this.m_def.colorMixingStrength;if(colorMixing){for(var k=0;k<this.m_contactBuffer.count;k++){var contact=this.m_contactBuffer.data[k];var a=contact.indexA;var b=contact.indexB;if(this.m_flagsBuffer.data[a]&this.m_flagsBuffer.data[b]&exports$1.b2ParticleFlag.b2_colorMixingParticle){var colorA=this.m_colorBuffer.data[a];var colorB=this.m_colorBuffer.data[b];b2Color.MixColors(colorA,colorB,colorMixing);}}}};_proto95.SolveZombie=function SolveZombie(){var newCount=0;var newIndices=[];for(var i=0;i<this.m_count;i++){newIndices[i]=b2_invalidParticleIndex;}var allParticleFlags=0;for(var _i38=0;_i38<this.m_count;_i38++){var flags=this.m_flagsBuffer.data[_i38];if(flags&exports$1.b2ParticleFlag.b2_zombieParticle){var destructionListener=this.m_world.m_destructionListener;if(flags&exports$1.b2ParticleFlag.b2_destructionListenerParticle&&destructionListener){destructionListener.SayGoodbyeParticle(this,_i38);}if(this.m_handleIndexBuffer.data){var handle=this.m_handleIndexBuffer.data[_i38];if(handle){handle.SetIndex(b2_invalidParticleIndex);this.m_handleIndexBuffer.data[_i38]=null;}}newIndices[_i38]=b2_invalidParticleIndex;}else {newIndices[_i38]=newCount;if(_i38!==newCount){if(this.m_handleIndexBuffer.data){var _handle=this.m_handleIndexBuffer.data[_i38];if(_handle){_handle.SetIndex(newCount);}this.m_handleIndexBuffer.data[newCount]=_handle;}this.m_flagsBuffer.data[newCount]=this.m_flagsBuffer.data[_i38];if(this.m_lastBodyContactStepBuffer.data){this.m_lastBodyContactStepBuffer.data[newCount]=this.m_lastBodyContactStepBuffer.data[_i38];}if(this.m_bodyContactCountBuffer.data){this.m_bodyContactCountBuffer.data[newCount]=this.m_bodyContactCountBuffer.data[_i38];}if(this.m_consecutiveContactStepsBuffer.data){this.m_consecutiveContactStepsBuffer.data[newCount]=this.m_consecutiveContactStepsBuffer.data[_i38];}this.m_positionBuffer.data[newCount].Copy(this.m_positionBuffer.data[_i38]);this.m_velocityBuffer.data[newCount].Copy(this.m_velocityBuffer.data[_i38]);this.m_groupBuffer[newCount]=this.m_groupBuffer[_i38];if(this.m_hasForce){this.m_forceBuffer[newCount].Copy(this.m_forceBuffer[_i38]);}if(this.m_staticPressureBuffer){this.m_staticPressureBuffer[newCount]=this.m_staticPressureBuffer[_i38];}if(this.m_depthBuffer){this.m_depthBuffer[newCount]=this.m_depthBuffer[_i38];}if(this.m_colorBuffer.data){this.m_colorBuffer.data[newCount].Copy(this.m_colorBuffer.data[_i38]);}if(this.m_userDataBuffer.data){this.m_userDataBuffer.data[newCount]=this.m_userDataBuffer.data[_i38];}if(this.m_expirationTimeBuffer.data){this.m_expirationTimeBuffer.data[newCount]=this.m_expirationTimeBuffer.data[_i38];}}newCount++;allParticleFlags|=flags;}}var Test={IsProxyInvalid:function IsProxyInvalid(proxy){return proxy.index<0;},IsContactInvalid:function IsContactInvalid(contact){return contact.indexA<0||contact.indexB<0;},IsBodyContactInvalid:function IsBodyContactInvalid(contact){return contact.index<0;},IsPairInvalid:function IsPairInvalid(pair){return pair.indexA<0||pair.indexB<0;},IsTriadInvalid:function IsTriadInvalid(triad){return triad.indexA<0||triad.indexB<0||triad.indexC<0;}};for(var k=0;k<this.m_proxyBuffer.count;k++){var proxy=this.m_proxyBuffer.data[k];proxy.index=newIndices[proxy.index];}this.m_proxyBuffer.RemoveIf(Test.IsProxyInvalid);for(var _k17=0;_k17<this.m_contactBuffer.count;_k17++){var contact=this.m_contactBuffer.data[_k17];contact.indexA=newIndices[contact.indexA];contact.indexB=newIndices[contact.indexB];}this.m_contactBuffer.RemoveIf(Test.IsContactInvalid);for(var _k18=0;_k18<this.m_bodyContactBuffer.count;_k18++){var _contact10=this.m_bodyContactBuffer.data[_k18];_contact10.index=newIndices[_contact10.index];}this.m_bodyContactBuffer.RemoveIf(Test.IsBodyContactInvalid);for(var _k19=0;_k19<this.m_pairBuffer.count;_k19++){var pair=this.m_pairBuffer.data[_k19];pair.indexA=newIndices[pair.indexA];pair.indexB=newIndices[pair.indexB];}this.m_pairBuffer.RemoveIf(Test.IsPairInvalid);for(var _k20=0;_k20<this.m_triadBuffer.count;_k20++){var triad=this.m_triadBuffer.data[_k20];triad.indexA=newIndices[triad.indexA];triad.indexB=newIndices[triad.indexB];triad.indexC=newIndices[triad.indexC];}this.m_triadBuffer.RemoveIf(Test.IsTriadInvalid);if(this.m_indexByExpirationTimeBuffer.data){var writeOffset=0;for(var readOffset=0;readOffset<this.m_count;readOffset++){var newIndex=newIndices[this.m_indexByExpirationTimeBuffer.data[readOffset]];if(newIndex!==b2_invalidParticleIndex){this.m_indexByExpirationTimeBuffer.data[writeOffset++]=newIndex;}}}for(var group=this.m_groupList;group;group=group.GetNext()){var firstIndex=newCount;var lastIndex=0;var modified=false;for(var _i39=group.m_firstIndex;_i39<group.m_lastIndex;_i39++){var j=newIndices[_i39];if(j>=0){firstIndex=b2Min(firstIndex,j);lastIndex=b2Max(lastIndex,j+1);}else {modified=true;}}if(firstIndex<lastIndex){group.m_firstIndex=firstIndex;group.m_lastIndex=lastIndex;if(modified){if(group.m_groupFlags&exports$1.b2ParticleGroupFlag.b2_solidParticleGroup){this.SetGroupFlags(group,group.m_groupFlags|exports$1.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth);}}}else {group.m_firstIndex=0;group.m_lastIndex=0;if(!(group.m_groupFlags&exports$1.b2ParticleGroupFlag.b2_particleGroupCanBeEmpty)){this.SetGroupFlags(group,group.m_groupFlags|exports$1.b2ParticleGroupFlag.b2_particleGroupWillBeDestroyed);}}}this.m_count=newCount;this.m_allParticleFlags=allParticleFlags;this.m_needsUpdateAllParticleFlags=false;for(var _group3=this.m_groupList;_group3;){var next=_group3.GetNext();if(_group3.m_groupFlags&exports$1.b2ParticleGroupFlag.b2_particleGroupWillBeDestroyed){this.DestroyParticleGroup(_group3);}_group3=next;}};_proto95.SolveLifetimes=function SolveLifetimes(step){this.m_timeElapsed=this.LifetimeToExpirationTime(step.dt);var quantizedTimeElapsed=this.GetQuantizedTimeElapsed();var expirationTimes=this.m_expirationTimeBuffer.data;var expirationTimeIndices=this.m_indexByExpirationTimeBuffer.data;var particleCount=this.GetParticleCount();if(this.m_expirationTimeBufferRequiresSorting){var ExpirationTimeComparator=function ExpirationTimeComparator(particleIndexA,particleIndexB){var expirationTimeA=expirationTimes[particleIndexA];var expirationTimeB=expirationTimes[particleIndexB];var infiniteExpirationTimeA=expirationTimeA<=0.0;var infiniteExpirationTimeB=expirationTimeB<=0.0;return infiniteExpirationTimeA===infiniteExpirationTimeB?expirationTimeA>expirationTimeB:infiniteExpirationTimeA;};std_sort$1(expirationTimeIndices,0,particleCount,ExpirationTimeComparator);this.m_expirationTimeBufferRequiresSorting=false;}for(var i=particleCount-1;i>=0;--i){var particleIndex=expirationTimeIndices[i];var expirationTime=expirationTimes[particleIndex];if(quantizedTimeElapsed<expirationTime||expirationTime<=0){break;}this.DestroyParticle(particleIndex);}};_proto95.RotateBuffer=function RotateBuffer(start,mid,end){if(start===mid||mid===end){return;}function newIndices(i){if(i<start){return i;}else if(i<mid){return i+end-mid;}else if(i<end){return i+start-mid;}else {return i;}}std_rotate(this.m_flagsBuffer.data,start,mid,end);if(this.m_lastBodyContactStepBuffer.data){std_rotate(this.m_lastBodyContactStepBuffer.data,start,mid,end);}if(this.m_bodyContactCountBuffer.data){std_rotate(this.m_bodyContactCountBuffer.data,start,mid,end);}if(this.m_consecutiveContactStepsBuffer.data){std_rotate(this.m_consecutiveContactStepsBuffer.data,start,mid,end);}std_rotate(this.m_positionBuffer.data,start,mid,end);std_rotate(this.m_velocityBuffer.data,start,mid,end);std_rotate(this.m_groupBuffer,start,mid,end);if(this.m_hasForce){std_rotate(this.m_forceBuffer,start,mid,end);}if(this.m_staticPressureBuffer){std_rotate(this.m_staticPressureBuffer,start,mid,end);}if(this.m_depthBuffer){std_rotate(this.m_depthBuffer,start,mid,end);}if(this.m_colorBuffer.data){std_rotate(this.m_colorBuffer.data,start,mid,end);}if(this.m_userDataBuffer.data){std_rotate(this.m_userDataBuffer.data,start,mid,end);}if(this.m_handleIndexBuffer.data){std_rotate(this.m_handleIndexBuffer.data,start,mid,end);for(var i=start;i<end;++i){var handle=this.m_handleIndexBuffer.data[i];if(handle){handle.SetIndex(newIndices(handle.GetIndex()));}}}if(this.m_expirationTimeBuffer.data){std_rotate(this.m_expirationTimeBuffer.data,start,mid,end);var particleCount=this.GetParticleCount();var indexByExpirationTime=this.m_indexByExpirationTimeBuffer.data;for(var _i40=0;_i40<particleCount;++_i40){indexByExpirationTime[_i40]=newIndices(indexByExpirationTime[_i40]);}}for(var k=0;k<this.m_proxyBuffer.count;k++){var proxy=this.m_proxyBuffer.data[k];proxy.index=newIndices(proxy.index);}for(var _k21=0;_k21<this.m_contactBuffer.count;_k21++){var contact=this.m_contactBuffer.data[_k21];contact.indexA=newIndices(contact.indexA);contact.indexB=newIndices(contact.indexB);}for(var _k22=0;_k22<this.m_bodyContactBuffer.count;_k22++){var _contact11=this.m_bodyContactBuffer.data[_k22];_contact11.index=newIndices(_contact11.index);}for(var _k23=0;_k23<this.m_pairBuffer.count;_k23++){var pair=this.m_pairBuffer.data[_k23];pair.indexA=newIndices(pair.indexA);pair.indexB=newIndices(pair.indexB);}for(var _k24=0;_k24<this.m_triadBuffer.count;_k24++){var triad=this.m_triadBuffer.data[_k24];triad.indexA=newIndices(triad.indexA);triad.indexB=newIndices(triad.indexB);triad.indexC=newIndices(triad.indexC);}for(var group=this.m_groupList;group;group=group.GetNext()){group.m_firstIndex=newIndices(group.m_firstIndex);group.m_lastIndex=newIndices(group.m_lastIndex-1)+1;}};_proto95.GetCriticalVelocity=function GetCriticalVelocity(step){return this.m_particleDiameter*step.inv_dt;};_proto95.GetCriticalVelocitySquared=function GetCriticalVelocitySquared(step){var velocity=this.GetCriticalVelocity(step);return velocity*velocity;};_proto95.GetCriticalPressure=function GetCriticalPressure(step){return this.m_def.density*this.GetCriticalVelocitySquared(step);};_proto95.GetParticleStride=function GetParticleStride(){return b2_particleStride*this.m_particleDiameter;};_proto95.GetParticleMass=function GetParticleMass(){var stride=this.GetParticleStride();return this.m_def.density*stride*stride;};_proto95.GetParticleInvMass=function GetParticleInvMass(){var inverseStride=this.m_inverseDiameter*(1.0/b2_particleStride);return this.m_inverseDensity*inverseStride*inverseStride;};_proto95.GetFixtureContactFilter=function GetFixtureContactFilter(){return this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_fixtureContactFilterParticle?this.m_world.m_contactManager.m_contactFilter:null;};_proto95.GetParticleContactFilter=function GetParticleContactFilter(){return this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_particleContactFilterParticle?this.m_world.m_contactManager.m_contactFilter:null;};_proto95.GetFixtureContactListener=function GetFixtureContactListener(){return this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_fixtureContactListenerParticle?this.m_world.m_contactManager.m_contactListener:null;};_proto95.GetParticleContactListener=function GetParticleContactListener(){return this.m_allParticleFlags&exports$1.b2ParticleFlag.b2_particleContactListenerParticle?this.m_world.m_contactManager.m_contactListener:null;};_proto95.SetUserOverridableBuffer=function SetUserOverridableBuffer(buffer,data){buffer.data=data;buffer.userSuppliedCapacity=data.length;};_proto95.SetGroupFlags=function SetGroupFlags(group,newFlags){var oldFlags=group.m_groupFlags;if((oldFlags^newFlags)&exports$1.b2ParticleGroupFlag.b2_solidParticleGroup){newFlags|=exports$1.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth;}if(oldFlags&~newFlags){this.m_needsUpdateAllGroupFlags=true;}if(~this.m_allGroupFlags&newFlags){if(newFlags&exports$1.b2ParticleGroupFlag.b2_solidParticleGroup){this.m_depthBuffer=this.RequestBuffer(this.m_depthBuffer);}this.m_allGroupFlags|=newFlags;}group.m_groupFlags=newFlags;};b2ParticleSystem.BodyContactCompare=function BodyContactCompare(lhs,rhs){if(lhs.index===rhs.index){return lhs.weight>rhs.weight;}return lhs.index<rhs.index;};_proto95.RemoveSpuriousBodyContacts=function RemoveSpuriousBodyContacts(){std_sort$1(this.m_bodyContactBuffer.data,0,this.m_bodyContactBuffer.count,b2ParticleSystem.BodyContactCompare);var s_n=b2ParticleSystem.RemoveSpuriousBodyContacts_s_n;var s_pos=b2ParticleSystem.RemoveSpuriousBodyContacts_s_pos;var s_normal=b2ParticleSystem.RemoveSpuriousBodyContacts_s_normal;var k_maxContactsPerPoint=3;var system=this;var lastIndex=-1;var currentContacts=0;var b2ParticleBodyContactRemovePredicate=function b2ParticleBodyContactRemovePredicate(contact){if(contact.index!==lastIndex){currentContacts=0;lastIndex=contact.index;}if(currentContacts++>k_maxContactsPerPoint){return true;}var n=s_n.Copy(contact.normal);n.SelfMul(system.m_particleDiameter*(1-contact.weight));var pos=b2Vec2.AddVV(system.m_positionBuffer.data[contact.index],n,s_pos);if(!contact.fixture.TestPoint(pos)){var childCount=contact.fixture.GetShape().GetChildCount();for(var childIndex=0;childIndex<childCount;childIndex++){var normal=s_normal;var distance=contact.fixture.ComputeDistance(pos,normal,childIndex);if(distance<b2_linearSlop){return false;}}return true;}return false;};this.m_bodyContactBuffer.count=std_remove_if(this.m_bodyContactBuffer.data,b2ParticleBodyContactRemovePredicate,this.m_bodyContactBuffer.count);};_proto95.DetectStuckParticle=function DetectStuckParticle(particle){if(this.m_stuckThreshold<=0){return;}++this.m_bodyContactCountBuffer.data[particle];if(this.m_bodyContactCountBuffer.data[particle]===2){++this.m_consecutiveContactStepsBuffer.data[particle];if(this.m_consecutiveContactStepsBuffer.data[particle]>this.m_stuckThreshold){this.m_stuckParticleBuffer.data[this.m_stuckParticleBuffer.Append()]=particle;}}this.m_lastBodyContactStepBuffer.data[particle]=this.m_timestamp;};_proto95.ValidateParticleIndex=function ValidateParticleIndex(index){return index>=0&&index<this.GetParticleCount()&&index!==b2_invalidParticleIndex;};_proto95.GetQuantizedTimeElapsed=function GetQuantizedTimeElapsed(){return Math.floor(this.m_timeElapsed/0x100000000);};_proto95.LifetimeToExpirationTime=function LifetimeToExpirationTime(lifetime){return this.m_timeElapsed+Math.floor(lifetime/this.m_def.lifetimeGranularity*0x100000000);};_proto95.ForceCanBeApplied=function ForceCanBeApplied(flags){return !(flags&exports$1.b2ParticleFlag.b2_wallParticle);};_proto95.PrepareForceBuffer=function PrepareForceBuffer(){if(!this.m_hasForce){for(var i=0;i<this.m_count;i++){this.m_forceBuffer[i].SetZero();}this.m_hasForce=true;}};_proto95.IsRigidGroup=function IsRigidGroup(group){return group!==null&&(group.m_groupFlags&exports$1.b2ParticleGroupFlag.b2_rigidParticleGroup)!==0;};_proto95.GetLinearVelocity=function GetLinearVelocity(group,particleIndex,point,out){if(group&&this.IsRigidGroup(group)){return group.GetLinearVelocityFromWorldPoint(point,out);}else {return out.Copy(this.m_velocityBuffer.data[particleIndex]);}};_proto95.InitDampingParameter=function InitDampingParameter(invMass,invInertia,tangentDistance,mass,inertia,center,point,normal){invMass[0]=mass>0?1/mass:0;invInertia[0]=inertia>0?1/inertia:0;tangentDistance[0]=b2Vec2.CrossVV(b2Vec2.SubVV(point,center,b2Vec2.s_t0),normal);};_proto95.InitDampingParameterWithRigidGroupOrParticle=function InitDampingParameterWithRigidGroupOrParticle(invMass,invInertia,tangentDistance,isRigidGroup,group,particleIndex,point,normal){if(group&&isRigidGroup){this.InitDampingParameter(invMass,invInertia,tangentDistance,group.GetMass(),group.GetInertia(),group.GetCenter(),point,normal);}else {var flags=this.m_flagsBuffer.data[particleIndex];this.InitDampingParameter(invMass,invInertia,tangentDistance,flags&exports$1.b2ParticleFlag.b2_wallParticle?0:this.GetParticleMass(),0,point,point,normal);}};_proto95.ComputeDampingImpulse=function ComputeDampingImpulse(invMassA,invInertiaA,tangentDistanceA,invMassB,invInertiaB,tangentDistanceB,normalVelocity){var invMass=invMassA+invInertiaA*tangentDistanceA*tangentDistanceA+invMassB+invInertiaB*tangentDistanceB*tangentDistanceB;return invMass>0?normalVelocity/invMass:0;};_proto95.ApplyDamping=function ApplyDamping(invMass,invInertia,tangentDistance,isRigidGroup,group,particleIndex,impulse,normal){if(group&&isRigidGroup){group.m_linearVelocity.SelfMulAdd(impulse*invMass,normal);group.m_angularVelocity+=impulse*tangentDistance*invInertia;}else {this.m_velocityBuffer.data[particleIndex].SelfMulAdd(impulse*invMass,normal);}};return b2ParticleSystem;}();b2ParticleSystem.xTruncBits=12;b2ParticleSystem.yTruncBits=12;b2ParticleSystem.tagBits=8*4;b2ParticleSystem.yOffset=1<<b2ParticleSystem.yTruncBits-1;b2ParticleSystem.yShift=b2ParticleSystem.tagBits-b2ParticleSystem.yTruncBits;b2ParticleSystem.xShift=b2ParticleSystem.tagBits-b2ParticleSystem.yTruncBits-b2ParticleSystem.xTruncBits;b2ParticleSystem.xScale=1<<b2ParticleSystem.xShift;b2ParticleSystem.xOffset=b2ParticleSystem.xScale*(1<<b2ParticleSystem.xTruncBits-1);b2ParticleSystem.yMask=(1<<b2ParticleSystem.yTruncBits)-1<<b2ParticleSystem.yShift;b2ParticleSystem.xMask=~b2ParticleSystem.yMask;b2ParticleSystem.DestroyParticlesInShape_s_aabb=new b2AABB();b2ParticleSystem.CreateParticleGroup_s_transform=new b2Transform();b2ParticleSystem.ComputeCollisionEnergy_s_v=new b2Vec2();b2ParticleSystem.QueryShapeAABB_s_aabb=new b2AABB();b2ParticleSystem.QueryPointAABB_s_aabb=new b2AABB();b2ParticleSystem.RayCast_s_aabb=new b2AABB();b2ParticleSystem.RayCast_s_p=new b2Vec2();b2ParticleSystem.RayCast_s_v=new b2Vec2();b2ParticleSystem.RayCast_s_n=new b2Vec2();b2ParticleSystem.RayCast_s_point=new b2Vec2();b2ParticleSystem.k_pairFlags=exports$1.b2ParticleFlag.b2_springParticle;b2ParticleSystem.k_triadFlags=exports$1.b2ParticleFlag.b2_elasticParticle;b2ParticleSystem.k_noPressureFlags=exports$1.b2ParticleFlag.b2_powderParticle|exports$1.b2ParticleFlag.b2_tensileParticle;b2ParticleSystem.k_extraDampingFlags=exports$1.b2ParticleFlag.b2_staticPressureParticle;b2ParticleSystem.k_barrierWallFlags=exports$1.b2ParticleFlag.b2_barrierParticle|exports$1.b2ParticleFlag.b2_wallParticle;b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_edge=new b2EdgeShape();b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_d=new b2Vec2();b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_p=new b2Vec2();b2ParticleSystem.CreateParticlesFillShapeForGroup_s_aabb=new b2AABB();b2ParticleSystem.CreateParticlesFillShapeForGroup_s_p=new b2Vec2();b2ParticleSystem.UpdatePairsAndTriads_s_dab=new b2Vec2();b2ParticleSystem.UpdatePairsAndTriads_s_dbc=new b2Vec2();b2ParticleSystem.UpdatePairsAndTriads_s_dca=new b2Vec2();b2ParticleSystem.AddContact_s_d=new b2Vec2();b2ParticleSystem.UpdateBodyContacts_s_aabb=new b2AABB();b2ParticleSystem.Solve_s_subStep=new b2TimeStep();b2ParticleSystem.SolveCollision_s_aabb=new b2AABB();b2ParticleSystem.SolveGravity_s_gravity=new b2Vec2();b2ParticleSystem.SolveBarrier_s_aabb=new b2AABB();b2ParticleSystem.SolveBarrier_s_va=new b2Vec2();b2ParticleSystem.SolveBarrier_s_vb=new b2Vec2();b2ParticleSystem.SolveBarrier_s_pba=new b2Vec2();b2ParticleSystem.SolveBarrier_s_vba=new b2Vec2();b2ParticleSystem.SolveBarrier_s_vc=new b2Vec2();b2ParticleSystem.SolveBarrier_s_pca=new b2Vec2();b2ParticleSystem.SolveBarrier_s_vca=new b2Vec2();b2ParticleSystem.SolveBarrier_s_qba=new b2Vec2();b2ParticleSystem.SolveBarrier_s_qca=new b2Vec2();b2ParticleSystem.SolveBarrier_s_dv=new b2Vec2();b2ParticleSystem.SolveBarrier_s_f=new b2Vec2();b2ParticleSystem.SolvePressure_s_f=new b2Vec2();b2ParticleSystem.SolveDamping_s_v=new b2Vec2();b2ParticleSystem.SolveDamping_s_f=new b2Vec2();b2ParticleSystem.SolveRigidDamping_s_t0=new b2Vec2();b2ParticleSystem.SolveRigidDamping_s_t1=new b2Vec2();b2ParticleSystem.SolveRigidDamping_s_p=new b2Vec2();b2ParticleSystem.SolveRigidDamping_s_v=new b2Vec2();b2ParticleSystem.SolveExtraDamping_s_v=new b2Vec2();b2ParticleSystem.SolveExtraDamping_s_f=new b2Vec2();b2ParticleSystem.SolveRigid_s_position=new b2Vec2();b2ParticleSystem.SolveRigid_s_rotation=new b2Rot();b2ParticleSystem.SolveRigid_s_transform=new b2Transform();b2ParticleSystem.SolveRigid_s_velocityTransform=new b2Transform();b2ParticleSystem.SolveElastic_s_pa=new b2Vec2();b2ParticleSystem.SolveElastic_s_pb=new b2Vec2();b2ParticleSystem.SolveElastic_s_pc=new b2Vec2();b2ParticleSystem.SolveElastic_s_r=new b2Rot();b2ParticleSystem.SolveElastic_s_t0=new b2Vec2();b2ParticleSystem.SolveSpring_s_pa=new b2Vec2();b2ParticleSystem.SolveSpring_s_pb=new b2Vec2();b2ParticleSystem.SolveSpring_s_d=new b2Vec2();b2ParticleSystem.SolveSpring_s_f=new b2Vec2();b2ParticleSystem.SolveTensile_s_weightedNormal=new b2Vec2();b2ParticleSystem.SolveTensile_s_s=new b2Vec2();b2ParticleSystem.SolveTensile_s_f=new b2Vec2();b2ParticleSystem.SolveViscous_s_v=new b2Vec2();b2ParticleSystem.SolveViscous_s_f=new b2Vec2();b2ParticleSystem.SolveRepulsive_s_f=new b2Vec2();b2ParticleSystem.SolvePowder_s_f=new b2Vec2();b2ParticleSystem.SolveSolid_s_f=new b2Vec2();b2ParticleSystem.RemoveSpuriousBodyContacts_s_n=new b2Vec2();b2ParticleSystem.RemoveSpuriousBodyContacts_s_pos=new b2Vec2();b2ParticleSystem.RemoveSpuriousBodyContacts_s_normal=new b2Vec2();var b2ParticleSystem_UserOverridableBuffer=function(){function b2ParticleSystem_UserOverridableBuffer(){this._data=null;this.userSuppliedCapacity=0;}_createClass(b2ParticleSystem_UserOverridableBuffer,[{key:"data",get:function get(){return this._data;},set:function set(value){this._data=value;}}]);return b2ParticleSystem_UserOverridableBuffer;}();var b2ParticleSystem_Proxy=function(){function b2ParticleSystem_Proxy(){this.index=b2_invalidParticleIndex;this.tag=0;}b2ParticleSystem_Proxy.CompareProxyProxy=function CompareProxyProxy(a,b){return a.tag<b.tag;};b2ParticleSystem_Proxy.CompareTagProxy=function CompareTagProxy(a,b){return a<b.tag;};b2ParticleSystem_Proxy.CompareProxyTag=function CompareProxyTag(a,b){return a.tag<b;};return b2ParticleSystem_Proxy;}();var b2ParticleSystem_InsideBoundsEnumerator=function(){function b2ParticleSystem_InsideBoundsEnumerator(system,lower,upper,first,last){this.m_system=system;this.m_xLower=(lower&b2ParticleSystem.xMask)>>>0;this.m_xUpper=(upper&b2ParticleSystem.xMask)>>>0;this.m_yLower=(lower&b2ParticleSystem.yMask)>>>0;this.m_yUpper=(upper&b2ParticleSystem.yMask)>>>0;this.m_first=first;this.m_last=last;}var _proto96=b2ParticleSystem_InsideBoundsEnumerator.prototype;_proto96.GetNext=function GetNext(){while(this.m_first<this.m_last){var xTag=(this.m_system.m_proxyBuffer.data[this.m_first].tag&b2ParticleSystem.xMask)>>>0;if(xTag>=this.m_xLower&&xTag<=this.m_xUpper){return this.m_system.m_proxyBuffer.data[this.m_first++].index;}this.m_first++;}return b2_invalidParticleIndex;};return b2ParticleSystem_InsideBoundsEnumerator;}();var b2ParticleSystem_ParticleListNode=function b2ParticleSystem_ParticleListNode(){this.next=null;this.count=0;this.index=0;};var b2ParticleSystem_FixedSetAllocator=function(){function b2ParticleSystem_FixedSetAllocator(){}var _proto97=b2ParticleSystem_FixedSetAllocator.prototype;_proto97.Allocate=function Allocate(itemSize,count){return count;};_proto97.Clear=function Clear(){};_proto97.GetCount=function GetCount(){return 0;};_proto97.Invalidate=function Invalidate(itemIndex){};_proto97.GetValidBuffer=function GetValidBuffer(){return [];};_proto97.GetBuffer=function GetBuffer(){return [];};_proto97.SetCount=function SetCount(count){};return b2ParticleSystem_FixedSetAllocator;}();var b2ParticleSystem_FixtureParticle=function b2ParticleSystem_FixtureParticle(fixture,particle){this.second=b2_invalidParticleIndex;this.first=fixture;this.second=particle;};var b2ParticleSystem_FixtureParticleSet=function(_b2ParticleSystem_Fix){_inheritsLoose(b2ParticleSystem_FixtureParticleSet,_b2ParticleSystem_Fix);function b2ParticleSystem_FixtureParticleSet(){return _b2ParticleSystem_Fix.apply(this,arguments)||this;}var _proto98=b2ParticleSystem_FixtureParticleSet.prototype;_proto98.Initialize=function Initialize(bodyContactBuffer,flagsBuffer){};_proto98.Find=function Find(pair){return b2_invalidParticleIndex;};return b2ParticleSystem_FixtureParticleSet;}(b2ParticleSystem_FixedSetAllocator);var b2ParticleSystem_ParticlePair=function b2ParticleSystem_ParticlePair(particleA,particleB){this.first=b2_invalidParticleIndex;this.second=b2_invalidParticleIndex;this.first=particleA;this.second=particleB;};var b2ParticlePairSet=function(_b2ParticleSystem_Fix2){_inheritsLoose(b2ParticlePairSet,_b2ParticleSystem_Fix2);function b2ParticlePairSet(){return _b2ParticleSystem_Fix2.apply(this,arguments)||this;}var _proto99=b2ParticlePairSet.prototype;_proto99.Initialize=function Initialize(contactBuffer,flagsBuffer){};_proto99.Find=function Find(pair){return b2_invalidParticleIndex;};return b2ParticlePairSet;}(b2ParticleSystem_FixedSetAllocator);var b2ParticleSystem_ConnectionFilter=function(){function b2ParticleSystem_ConnectionFilter(){}var _proto100=b2ParticleSystem_ConnectionFilter.prototype;_proto100.IsNecessary=function IsNecessary(index){return true;};_proto100.ShouldCreatePair=function ShouldCreatePair(a,b){return true;};_proto100.ShouldCreateTriad=function ShouldCreateTriad(a,b,c){return true;};return b2ParticleSystem_ConnectionFilter;}();var b2ParticleSystem_DestroyParticlesInShapeCallback=function(_b2QueryCallback2){_inheritsLoose(b2ParticleSystem_DestroyParticlesInShapeCallback,_b2QueryCallback2);function b2ParticleSystem_DestroyParticlesInShapeCallback(system,shape,xf,callDestructionListener){var _this32;_this32=_b2QueryCallback2.call(this)||this;_this32.m_callDestructionListener=false;_this32.m_destroyed=0;_this32.m_system=system;_this32.m_shape=shape;_this32.m_xf=xf;_this32.m_callDestructionListener=callDestructionListener;_this32.m_destroyed=0;return _this32;}var _proto101=b2ParticleSystem_DestroyParticlesInShapeCallback.prototype;_proto101.ReportFixture=function ReportFixture(fixture){return false;};_proto101.ReportParticle=function ReportParticle(particleSystem,index){if(particleSystem!==this.m_system){return false;}if(this.m_shape.TestPoint(this.m_xf,this.m_system.m_positionBuffer.data[index])){this.m_system.DestroyParticle(index,this.m_callDestructionListener);this.m_destroyed++;}return true;};_proto101.Destroyed=function Destroyed(){return this.m_destroyed;};return b2ParticleSystem_DestroyParticlesInShapeCallback;}(b2QueryCallback);var b2ParticleSystem_JoinParticleGroupsFilter=function(_b2ParticleSystem_Con){_inheritsLoose(b2ParticleSystem_JoinParticleGroupsFilter,_b2ParticleSystem_Con);function b2ParticleSystem_JoinParticleGroupsFilter(threshold){var _this33;_this33=_b2ParticleSystem_Con.call(this)||this;_this33.m_threshold=0;_this33.m_threshold=threshold;return _this33;}var _proto102=b2ParticleSystem_JoinParticleGroupsFilter.prototype;_proto102.ShouldCreatePair=function ShouldCreatePair(a,b){return a<this.m_threshold&&this.m_threshold<=b||b<this.m_threshold&&this.m_threshold<=a;};_proto102.ShouldCreateTriad=function ShouldCreateTriad(a,b,c){return (a<this.m_threshold||b<this.m_threshold||c<this.m_threshold)&&(this.m_threshold<=a||this.m_threshold<=b||this.m_threshold<=c);};return b2ParticleSystem_JoinParticleGroupsFilter;}(b2ParticleSystem_ConnectionFilter);var b2ParticleSystem_CompositeShape=function(_b2Shape5){_inheritsLoose(b2ParticleSystem_CompositeShape,_b2Shape5);function b2ParticleSystem_CompositeShape(shapes,shapeCount){var _this34;if(shapeCount===void 0){shapeCount=shapes.length;}_this34=_b2Shape5.call(this,exports$1.b2ShapeType.e_unknown,0)||this;_this34.m_shapeCount=0;_this34.m_shapes=shapes;_this34.m_shapeCount=shapeCount;return _this34;}var _proto103=b2ParticleSystem_CompositeShape.prototype;_proto103.Clone=function Clone(){throw new Error();};_proto103.GetChildCount=function GetChildCount(){return 1;};_proto103.TestPoint=function TestPoint(xf,p){for(var i=0;i<this.m_shapeCount;i++){if(this.m_shapes[i].TestPoint(xf,p)){return true;}}return false;};_proto103.ComputeDistance=function ComputeDistance(xf,p,normal,childIndex){return 0;};_proto103.RayCast=function RayCast(output,input,xf,childIndex){return false;};_proto103.ComputeAABB=function ComputeAABB(aabb,xf,childIndex){var s_subaabb=new b2AABB();aabb.lowerBound.x=+b2_maxFloat;aabb.lowerBound.y=+b2_maxFloat;aabb.upperBound.x=-b2_maxFloat;aabb.upperBound.y=-b2_maxFloat;for(var i=0;i<this.m_shapeCount;i++){var childCount=this.m_shapes[i].GetChildCount();for(var j=0;j<childCount;j++){var subaabb=s_subaabb;this.m_shapes[i].ComputeAABB(subaabb,xf,j);aabb.Combine1(subaabb);}}};_proto103.ComputeMass=function ComputeMass(massData,density){};_proto103.SetupDistanceProxy=function SetupDistanceProxy(proxy,index){};_proto103.ComputeSubmergedArea=function ComputeSubmergedArea(normal,offset,xf,c){return 0;};_proto103.Dump=function Dump(log){};return b2ParticleSystem_CompositeShape;}(b2Shape);var b2ParticleSystem_ReactiveFilter=function(_b2ParticleSystem_Con2){_inheritsLoose(b2ParticleSystem_ReactiveFilter,_b2ParticleSystem_Con2);function b2ParticleSystem_ReactiveFilter(flagsBuffer){var _this35;_this35=_b2ParticleSystem_Con2.call(this)||this;_this35.m_flagsBuffer=flagsBuffer;return _this35;}var _proto104=b2ParticleSystem_ReactiveFilter.prototype;_proto104.IsNecessary=function IsNecessary(index){return (this.m_flagsBuffer.data[index]&exports$1.b2ParticleFlag.b2_reactiveParticle)!==0;};return b2ParticleSystem_ReactiveFilter;}(b2ParticleSystem_ConnectionFilter);var b2ParticleSystem_UpdateBodyContactsCallback=function(_b2FixtureParticleQue){_inheritsLoose(b2ParticleSystem_UpdateBodyContactsCallback,_b2FixtureParticleQue);function b2ParticleSystem_UpdateBodyContactsCallback(system,contactFilter){var _this36;if(contactFilter===void 0){contactFilter=null;}_this36=_b2FixtureParticleQue.call(this,system)||this;_this36.m_contactFilter=null;_this36.m_contactFilter=contactFilter;return _this36;}var _proto105=b2ParticleSystem_UpdateBodyContactsCallback.prototype;_proto105.ShouldCollideFixtureParticle=function ShouldCollideFixtureParticle(fixture,particleSystem,particleIndex){if(this.m_contactFilter){var flags=this.m_system.GetFlagsBuffer();if(flags[particleIndex]&exports$1.b2ParticleFlag.b2_fixtureContactFilterParticle){return this.m_contactFilter.ShouldCollideFixtureParticle(fixture,this.m_system,particleIndex);}}return true;};_proto105.ReportFixtureAndParticle=function ReportFixtureAndParticle(fixture,childIndex,a){var s_n=b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_n;var s_rp=b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_rp;var ap=this.m_system.m_positionBuffer.data[a];var n=s_n;var d=fixture.ComputeDistance(ap,n,childIndex);if(d<this.m_system.m_particleDiameter&&this.ShouldCollideFixtureParticle(fixture,this.m_system,a)){var b=fixture.GetBody();var bp=b.GetWorldCenter();var bm=b.GetMass();var bI=b.GetInertia()-bm*b.GetLocalCenter().LengthSquared();var invBm=bm>0?1/bm:0;var invBI=bI>0?1/bI:0;var invAm=this.m_system.m_flagsBuffer.data[a]&exports$1.b2ParticleFlag.b2_wallParticle?0:this.m_system.GetParticleInvMass();var rp=b2Vec2.SubVV(ap,bp,s_rp);var rpn=b2Vec2.CrossVV(rp,n);var invM=invAm+invBm+invBI*rpn*rpn;var contact=this.m_system.m_bodyContactBuffer.data[this.m_system.m_bodyContactBuffer.Append()];contact.index=a;contact.body=b;contact.fixture=fixture;contact.weight=1-d*this.m_system.m_inverseDiameter;contact.normal.Copy(n.SelfNeg());contact.mass=invM>0?1/invM:0;this.m_system.DetectStuckParticle(a);}};return b2ParticleSystem_UpdateBodyContactsCallback;}(b2FixtureParticleQueryCallback);b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_n=new b2Vec2();b2ParticleSystem_UpdateBodyContactsCallback.ReportFixtureAndParticle_s_rp=new b2Vec2();var b2ParticleSystem_SolveCollisionCallback=function(_b2FixtureParticleQue2){_inheritsLoose(b2ParticleSystem_SolveCollisionCallback,_b2FixtureParticleQue2);function b2ParticleSystem_SolveCollisionCallback(system,step){var _this37;_this37=_b2FixtureParticleQue2.call(this,system)||this;_this37.m_step=step;return _this37;}var _proto106=b2ParticleSystem_SolveCollisionCallback.prototype;_proto106.ReportFixtureAndParticle=function ReportFixtureAndParticle(fixture,childIndex,a){var s_p1=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_p1;var s_output=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_output;var s_input=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_input;var s_p=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_p;var s_v=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_v;var s_f=b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_f;var body=fixture.GetBody();var ap=this.m_system.m_positionBuffer.data[a];var av=this.m_system.m_velocityBuffer.data[a];var output=s_output;var input=s_input;if(this.m_system.m_iterationIndex===0){var p1=b2Transform.MulTXV(body.m_xf0,ap,s_p1);if(fixture.GetShape().GetType()===exports$1.b2ShapeType.e_circleShape){p1.SelfSub(body.GetLocalCenter());b2Rot.MulRV(body.m_xf0.q,p1,p1);b2Rot.MulTRV(body.m_xf.q,p1,p1);p1.SelfAdd(body.GetLocalCenter());}b2Transform.MulXV(body.m_xf,p1,input.p1);}else {input.p1.Copy(ap);}b2Vec2.AddVMulSV(ap,this.m_step.dt,av,input.p2);input.maxFraction=1;if(fixture.RayCast(output,input,childIndex)){var n=output.normal;var p=s_p;p.x=(1-output.fraction)*input.p1.x+output.fraction*input.p2.x+b2_linearSlop*n.x;p.y=(1-output.fraction)*input.p1.y+output.fraction*input.p2.y+b2_linearSlop*n.y;var v=s_v;v.x=this.m_step.inv_dt*(p.x-ap.x);v.y=this.m_step.inv_dt*(p.y-ap.y);this.m_system.m_velocityBuffer.data[a].Copy(v);var f=s_f;f.x=this.m_step.inv_dt*this.m_system.GetParticleMass()*(av.x-v.x);f.y=this.m_step.inv_dt*this.m_system.GetParticleMass()*(av.y-v.y);this.m_system.ParticleApplyForce(a,f);}};_proto106.ReportParticle=function ReportParticle(system,index){return false;};return b2ParticleSystem_SolveCollisionCallback;}(b2FixtureParticleQueryCallback);b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_p1=new b2Vec2();b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_output=new b2RayCastOutput();b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_input=new b2RayCastInput();b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_p=new b2Vec2();b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_v=new b2Vec2();b2ParticleSystem_SolveCollisionCallback.ReportFixtureAndParticle_s_f=new b2Vec2();var b2World=function(){function b2World(gravity){this.m_newFixture=false;this.m_locked=false;this.m_clearForces=true;this.m_contactManager=new b2ContactManager();this.m_bodyList=null;this.m_jointList=null;this.m_particleSystemList=null;this.m_bodyCount=0;this.m_jointCount=0;this.m_gravity=new b2Vec2();this.m_allowSleep=true;this.m_destructionListener=null;this.m_debugDraw=null;this.m_inv_dt0=0;this.m_warmStarting=true;this.m_continuousPhysics=true;this.m_subStepping=false;this.m_stepComplete=true;this.m_profile=new b2Profile();this.m_island=new b2Island();this.s_stack=[];this.m_controllerList=null;this.m_controllerCount=0;this.m_gravity.Copy(gravity);}var _proto107=b2World.prototype;_proto107.SetDestructionListener=function SetDestructionListener(listener){this.m_destructionListener=listener;};_proto107.SetContactFilter=function SetContactFilter(filter){this.m_contactManager.m_contactFilter=filter;};_proto107.SetContactListener=function SetContactListener(listener){this.m_contactManager.m_contactListener=listener;};_proto107.SetDebugDraw=function SetDebugDraw(debugDraw){this.m_debugDraw=debugDraw;};_proto107.CreateBody=function CreateBody(def){if(def===void 0){def={};}if(this.IsLocked()){throw new Error();}var b=new b2Body(def,this);b.m_prev=null;b.m_next=this.m_bodyList;if(this.m_bodyList){this.m_bodyList.m_prev=b;}this.m_bodyList=b;++this.m_bodyCount;return b;};_proto107.DestroyBody=function DestroyBody(b){if(this.IsLocked()){throw new Error();}var je=b.m_jointList;while(je){var je0=je;je=je.next;if(this.m_destructionListener){this.m_destructionListener.SayGoodbyeJoint(je0.joint);}this.DestroyJoint(je0.joint);b.m_jointList=je;}b.m_jointList=null;var coe=b.m_controllerList;while(coe){var coe0=coe;coe=coe.nextController;coe0.controller.RemoveBody(b);}var ce=b.m_contactList;while(ce){var ce0=ce;ce=ce.next;this.m_contactManager.Destroy(ce0.contact);}b.m_contactList=null;var f=b.m_fixtureList;while(f){var f0=f;f=f.m_next;if(this.m_destructionListener){this.m_destructionListener.SayGoodbyeFixture(f0);}f0.DestroyProxies();f0.Reset();b.m_fixtureList=f;b.m_fixtureCount-=1;}b.m_fixtureList=null;b.m_fixtureCount=0;if(b.m_prev){b.m_prev.m_next=b.m_next;}if(b.m_next){b.m_next.m_prev=b.m_prev;}if(b===this.m_bodyList){this.m_bodyList=b.m_next;}--this.m_bodyCount;};b2World._Joint_Create=function _Joint_Create(def){switch(def.type){case exports$1.b2JointType.e_distanceJoint:return new b2DistanceJoint(def);case exports$1.b2JointType.e_mouseJoint:return new b2MouseJoint(def);case exports$1.b2JointType.e_prismaticJoint:return new b2PrismaticJoint(def);case exports$1.b2JointType.e_revoluteJoint:return new b2RevoluteJoint(def);case exports$1.b2JointType.e_pulleyJoint:return new b2PulleyJoint(def);case exports$1.b2JointType.e_gearJoint:return new b2GearJoint(def);case exports$1.b2JointType.e_wheelJoint:return new b2WheelJoint(def);case exports$1.b2JointType.e_weldJoint:return new b2WeldJoint(def);case exports$1.b2JointType.e_frictionJoint:return new b2FrictionJoint(def);case exports$1.b2JointType.e_ropeJoint:return new b2RopeJoint(def);case exports$1.b2JointType.e_motorJoint:return new b2MotorJoint(def);case exports$1.b2JointType.e_areaJoint:return new b2AreaJoint(def);}throw new Error();};b2World._Joint_Destroy=function _Joint_Destroy(joint){};_proto107.CreateJoint=function CreateJoint(def){if(this.IsLocked()){throw new Error();}var j=b2World._Joint_Create(def);j.m_prev=null;j.m_next=this.m_jointList;if(this.m_jointList){this.m_jointList.m_prev=j;}this.m_jointList=j;++this.m_jointCount;j.m_edgeA.prev=null;j.m_edgeA.next=j.m_bodyA.m_jointList;if(j.m_bodyA.m_jointList){j.m_bodyA.m_jointList.prev=j.m_edgeA;}j.m_bodyA.m_jointList=j.m_edgeA;j.m_edgeB.prev=null;j.m_edgeB.next=j.m_bodyB.m_jointList;if(j.m_bodyB.m_jointList){j.m_bodyB.m_jointList.prev=j.m_edgeB;}j.m_bodyB.m_jointList=j.m_edgeB;var bodyA=j.m_bodyA;var bodyB=j.m_bodyB;var collideConnected=j.m_collideConnected;if(!collideConnected){var edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){edge.contact.FlagForFiltering();}edge=edge.next;}}return j;};_proto107.DestroyJoint=function DestroyJoint(j){if(this.IsLocked()){throw new Error();}if(j.m_prev){j.m_prev.m_next=j.m_next;}if(j.m_next){j.m_next.m_prev=j.m_prev;}if(j===this.m_jointList){this.m_jointList=j.m_next;}var bodyA=j.m_bodyA;var bodyB=j.m_bodyB;var collideConnected=j.m_collideConnected;bodyA.SetAwake(true);bodyB.SetAwake(true);if(j.m_edgeA.prev){j.m_edgeA.prev.next=j.m_edgeA.next;}if(j.m_edgeA.next){j.m_edgeA.next.prev=j.m_edgeA.prev;}if(j.m_edgeA===bodyA.m_jointList){bodyA.m_jointList=j.m_edgeA.next;}j.m_edgeA.Reset();if(j.m_edgeB.prev){j.m_edgeB.prev.next=j.m_edgeB.next;}if(j.m_edgeB.next){j.m_edgeB.next.prev=j.m_edgeB.prev;}if(j.m_edgeB===bodyB.m_jointList){bodyB.m_jointList=j.m_edgeB.next;}j.m_edgeB.Reset();b2World._Joint_Destroy(j);--this.m_jointCount;if(!collideConnected){var edge=bodyB.GetContactList();while(edge){if(edge.other===bodyA){edge.contact.FlagForFiltering();}edge=edge.next;}}};_proto107.CreateParticleSystem=function CreateParticleSystem(def){if(this.IsLocked()){throw new Error();}var p=new b2ParticleSystem(def,this);p.m_prev=null;p.m_next=this.m_particleSystemList;if(this.m_particleSystemList){this.m_particleSystemList.m_prev=p;}this.m_particleSystemList=p;return p;};_proto107.DestroyParticleSystem=function DestroyParticleSystem(p){if(this.IsLocked()){throw new Error();}if(p.m_prev){p.m_prev.m_next=p.m_next;}if(p.m_next){p.m_next.m_prev=p.m_prev;}if(p===this.m_particleSystemList){this.m_particleSystemList=p.m_next;}};_proto107.CalculateReasonableParticleIterations=function CalculateReasonableParticleIterations(timeStep){if(this.m_particleSystemList===null){return 1;}function GetSmallestRadius(world){var smallestRadius=b2_maxFloat;for(var system=world.GetParticleSystemList();system!==null;system=system.m_next){smallestRadius=b2Min(smallestRadius,system.GetRadius());}return smallestRadius;}return b2CalculateParticleIterations(this.m_gravity.Length(),GetSmallestRadius(this),timeStep);};_proto107.Step=function Step(dt,velocityIterations,positionIterations,particleIterations){if(particleIterations===void 0){particleIterations=this.CalculateReasonableParticleIterations(dt);}var stepTimer=b2World.Step_s_stepTimer.Reset();if(this.m_newFixture){this.m_contactManager.FindNewContacts();this.m_newFixture=false;}this.m_locked=true;var step=b2World.Step_s_step;step.dt=dt;step.velocityIterations=velocityIterations;step.positionIterations=positionIterations;step.particleIterations=particleIterations;if(dt>0){step.inv_dt=1/dt;}else {step.inv_dt=0;}step.dtRatio=this.m_inv_dt0*dt;step.warmStarting=this.m_warmStarting;var timer=b2World.Step_s_timer.Reset();this.m_contactManager.Collide();this.m_profile.collide=timer.GetMilliseconds();if(this.m_stepComplete&&step.dt>0){var _timer=b2World.Step_s_timer.Reset();for(var p=this.m_particleSystemList;p;p=p.m_next){p.Solve(step);}this.Solve(step);this.m_profile.solve=_timer.GetMilliseconds();}if(this.m_continuousPhysics&&step.dt>0){var _timer2=b2World.Step_s_timer.Reset();this.SolveTOI(step);this.m_profile.solveTOI=_timer2.GetMilliseconds();}if(step.dt>0){this.m_inv_dt0=step.inv_dt;}if(this.m_clearForces){this.ClearForces();}this.m_locked=false;this.m_profile.step=stepTimer.GetMilliseconds();};_proto107.ClearForces=function ClearForces(){for(var body=this.m_bodyList;body;body=body.m_next){body.m_force.SetZero();body.m_torque=0;}};_proto107.DrawParticleSystem=function DrawParticleSystem(system){if(this.m_debugDraw===null){return;}var particleCount=system.GetParticleCount();if(particleCount){var radius=system.GetRadius();var positionBuffer=system.GetPositionBuffer();if(system.m_colorBuffer.data){var colorBuffer=system.GetColorBuffer();this.m_debugDraw.DrawParticles(positionBuffer,radius,colorBuffer,particleCount);}else {this.m_debugDraw.DrawParticles(positionBuffer,radius,null,particleCount);}}};_proto107.DrawDebugData=function DrawDebugData(){if(this.m_debugDraw===null){return;}var flags=this.m_debugDraw.GetFlags();var color=b2World.DrawDebugData_s_color.SetRGB(0,0,0);if(flags&exports$1.b2DrawFlags.e_shapeBit){for(var b=this.m_bodyList;b;b=b.m_next){var xf=b.m_xf;this.m_debugDraw.PushTransform(xf);for(var f=b.GetFixtureList();f;f=f.m_next){if(!b.IsActive()){color.SetRGB(0.5,0.5,0.3);this.DrawShape(f,color);}else if(b.GetType()===exports$1.b2BodyType.b2_staticBody){color.SetRGB(0.5,0.9,0.5);this.DrawShape(f,color);}else if(b.GetType()===exports$1.b2BodyType.b2_kinematicBody){color.SetRGB(0.5,0.5,0.9);this.DrawShape(f,color);}else if(!b.IsAwake()){color.SetRGB(0.6,0.6,0.6);this.DrawShape(f,color);}else {color.SetRGB(0.9,0.7,0.7);this.DrawShape(f,color);}}this.m_debugDraw.PopTransform(xf);}}if(flags&exports$1.b2DrawFlags.e_particleBit){for(var p=this.m_particleSystemList;p;p=p.m_next){this.DrawParticleSystem(p);}}if(flags&exports$1.b2DrawFlags.e_jointBit){for(var j=this.m_jointList;j;j=j.m_next){this.DrawJoint(j);}}if(flags&exports$1.b2DrawFlags.e_aabbBit){color.SetRGB(0.9,0.3,0.9);var vs=b2World.DrawDebugData_s_vs;for(var _b15=this.m_bodyList;_b15;_b15=_b15.m_next){if(!_b15.IsActive()){continue;}for(var _f7=_b15.GetFixtureList();_f7;_f7=_f7.m_next){for(var i=0;i<_f7.m_proxyCount;++i){var proxy=_f7.m_proxies[i];var aabb=proxy.treeNode.aabb;vs[0].Set(aabb.lowerBound.x,aabb.lowerBound.y);vs[1].Set(aabb.upperBound.x,aabb.lowerBound.y);vs[2].Set(aabb.upperBound.x,aabb.upperBound.y);vs[3].Set(aabb.lowerBound.x,aabb.upperBound.y);this.m_debugDraw.DrawPolygon(vs,4,color);}}}}if(flags&exports$1.b2DrawFlags.e_centerOfMassBit){for(var _b16=this.m_bodyList;_b16;_b16=_b16.m_next){var _xf=b2World.DrawDebugData_s_xf;_xf.q.Copy(_b16.m_xf.q);_xf.p.Copy(_b16.GetWorldCenter());this.m_debugDraw.DrawTransform(_xf);}}if(flags&exports$1.b2DrawFlags.e_controllerBit){for(var c=this.m_controllerList;c;c=c.m_next){c.Draw(this.m_debugDraw);}}};_proto107.QueryAABB=function QueryAABB(){if((arguments.length<=0?undefined:arguments[0])instanceof b2QueryCallback){this._QueryAABB(arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}else {this._QueryAABB(null,arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}};_proto107._QueryAABB=function _QueryAABB(callback,aabb,fn){this.m_contactManager.m_broadPhase.Query(aabb,function(proxy){var fixture_proxy=proxy.userData;var fixture=fixture_proxy.fixture;if(callback){return callback.ReportFixture(fixture);}else if(fn){return fn(fixture);}return true;});if(callback instanceof b2QueryCallback){for(var p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryAABB(callback,aabb);}}}};_proto107.QueryAllAABB=function QueryAllAABB(aabb,out){if(out===void 0){out=[];}this.QueryAABB(aabb,function(fixture){out.push(fixture);return true;});return out;};_proto107.QueryPointAABB=function QueryPointAABB(){if((arguments.length<=0?undefined:arguments[0])instanceof b2QueryCallback){this._QueryPointAABB(arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}else {this._QueryPointAABB(null,arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}};_proto107._QueryPointAABB=function _QueryPointAABB(callback,point,fn){this.m_contactManager.m_broadPhase.QueryPoint(point,function(proxy){var fixture_proxy=proxy.userData;var fixture=fixture_proxy.fixture;if(callback){return callback.ReportFixture(fixture);}else if(fn){return fn(fixture);}return true;});if(callback instanceof b2QueryCallback){for(var p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryPointAABB(callback,point);}}}};_proto107.QueryAllPointAABB=function QueryAllPointAABB(point,out){if(out===void 0){out=[];}this.QueryPointAABB(point,function(fixture){out.push(fixture);return true;});return out;};_proto107.QueryFixtureShape=function QueryFixtureShape(){if((arguments.length<=0?undefined:arguments[0])instanceof b2QueryCallback){this._QueryFixtureShape(arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1],arguments.length<=2?undefined:arguments[2],arguments.length<=3?undefined:arguments[3]);}else {this._QueryFixtureShape(null,arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1],arguments.length<=2?undefined:arguments[2],arguments.length<=3?undefined:arguments[3]);}};_proto107._QueryFixtureShape=function _QueryFixtureShape(callback,shape,index,transform,fn){var aabb=b2World.QueryFixtureShape_s_aabb;shape.ComputeAABB(aabb,transform,index);this.m_contactManager.m_broadPhase.Query(aabb,function(proxy){var fixture_proxy=proxy.userData;var fixture=fixture_proxy.fixture;if(b2TestOverlapShape(shape,index,fixture.GetShape(),fixture_proxy.childIndex,transform,fixture.GetBody().GetTransform())){if(callback){return callback.ReportFixture(fixture);}else if(fn){return fn(fixture);}}return true;});if(callback instanceof b2QueryCallback){for(var p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryAABB(callback,aabb);}}}};_proto107.QueryAllFixtureShape=function QueryAllFixtureShape(shape,index,transform,out){if(out===void 0){out=[];}this.QueryFixtureShape(shape,index,transform,function(fixture){out.push(fixture);return true;});return out;};_proto107.QueryFixturePoint=function QueryFixturePoint(){if((arguments.length<=0?undefined:arguments[0])instanceof b2QueryCallback){this._QueryFixturePoint(arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}else {this._QueryFixturePoint(null,arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1]);}};_proto107._QueryFixturePoint=function _QueryFixturePoint(callback,point,fn){this.m_contactManager.m_broadPhase.QueryPoint(point,function(proxy){var fixture_proxy=proxy.userData;var fixture=fixture_proxy.fixture;if(fixture.TestPoint(point)){if(callback){return callback.ReportFixture(fixture);}else if(fn){return fn(fixture);}}return true;});if(callback){for(var p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.QueryPointAABB(callback,point);}}}};_proto107.QueryAllFixturePoint=function QueryAllFixturePoint(point,out){if(out===void 0){out=[];}this.QueryFixturePoint(point,function(fixture){out.push(fixture);return true;});return out;};_proto107.RayCast=function RayCast(){if((arguments.length<=0?undefined:arguments[0])instanceof b2RayCastCallback){this._RayCast(arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1],arguments.length<=2?undefined:arguments[2]);}else {this._RayCast(null,arguments.length<=0?undefined:arguments[0],arguments.length<=1?undefined:arguments[1],arguments.length<=2?undefined:arguments[2]);}};_proto107._RayCast=function _RayCast(callback,point1,point2,fn){var input=b2World.RayCast_s_input;input.maxFraction=1;input.p1.Copy(point1);input.p2.Copy(point2);this.m_contactManager.m_broadPhase.RayCast(input,function(input,proxy){var fixture_proxy=proxy.userData;var fixture=fixture_proxy.fixture;var index=fixture_proxy.childIndex;var output=b2World.RayCast_s_output;var hit=fixture.RayCast(output,input,index);if(hit){var fraction=output.fraction;var point=b2World.RayCast_s_point;point.Set((1-fraction)*point1.x+fraction*point2.x,(1-fraction)*point1.y+fraction*point2.y);if(callback){return callback.ReportFixture(fixture,point,output.normal,fraction);}else if(fn){return fn(fixture,point,output.normal,fraction);}}return input.maxFraction;});if(callback){for(var p=this.m_particleSystemList;p;p=p.m_next){if(callback.ShouldQueryParticleSystem(p)){p.RayCast(callback,point1,point2);}}}};_proto107.RayCastOne=function RayCastOne(point1,point2){var result=null;var min_fraction=1;this.RayCast(point1,point2,function(fixture,point,normal,fraction){if(fraction<min_fraction){min_fraction=fraction;result=fixture;}return min_fraction;});return result;};_proto107.RayCastAll=function RayCastAll(point1,point2,out){if(out===void 0){out=[];}this.RayCast(point1,point2,function(fixture,point,normal,fraction){out.push(fixture);return 1;});return out;};_proto107.GetBodyList=function GetBodyList(){return this.m_bodyList;};_proto107.GetJointList=function GetJointList(){return this.m_jointList;};_proto107.GetParticleSystemList=function GetParticleSystemList(){return this.m_particleSystemList;};_proto107.GetContactList=function GetContactList(){return this.m_contactManager.m_contactList;};_proto107.SetAllowSleeping=function SetAllowSleeping(flag){if(flag===this.m_allowSleep){return;}this.m_allowSleep=flag;if(!this.m_allowSleep){for(var b=this.m_bodyList;b;b=b.m_next){b.SetAwake(true);}}};_proto107.GetAllowSleeping=function GetAllowSleeping(){return this.m_allowSleep;};_proto107.SetWarmStarting=function SetWarmStarting(flag){this.m_warmStarting=flag;};_proto107.GetWarmStarting=function GetWarmStarting(){return this.m_warmStarting;};_proto107.SetContinuousPhysics=function SetContinuousPhysics(flag){this.m_continuousPhysics=flag;};_proto107.GetContinuousPhysics=function GetContinuousPhysics(){return this.m_continuousPhysics;};_proto107.SetSubStepping=function SetSubStepping(flag){this.m_subStepping=flag;};_proto107.GetSubStepping=function GetSubStepping(){return this.m_subStepping;};_proto107.GetProxyCount=function GetProxyCount(){return this.m_contactManager.m_broadPhase.GetProxyCount();};_proto107.GetBodyCount=function GetBodyCount(){return this.m_bodyCount;};_proto107.GetJointCount=function GetJointCount(){return this.m_jointCount;};_proto107.GetContactCount=function GetContactCount(){return this.m_contactManager.m_contactCount;};_proto107.GetTreeHeight=function GetTreeHeight(){return this.m_contactManager.m_broadPhase.GetTreeHeight();};_proto107.GetTreeBalance=function GetTreeBalance(){return this.m_contactManager.m_broadPhase.GetTreeBalance();};_proto107.GetTreeQuality=function GetTreeQuality(){return this.m_contactManager.m_broadPhase.GetTreeQuality();};_proto107.SetGravity=function SetGravity(gravity,wake){if(wake===void 0){wake=true;}if(!b2Vec2.IsEqualToV(this.m_gravity,gravity)){this.m_gravity.Copy(gravity);if(wake){for(var b=this.m_bodyList;b;b=b.m_next){b.SetAwake(true);}}}};_proto107.GetGravity=function GetGravity(){return this.m_gravity;};_proto107.IsLocked=function IsLocked(){return this.m_locked;};_proto107.SetAutoClearForces=function SetAutoClearForces(flag){this.m_clearForces=flag;};_proto107.GetAutoClearForces=function GetAutoClearForces(){return this.m_clearForces;};_proto107.ShiftOrigin=function ShiftOrigin(newOrigin){if(this.IsLocked()){throw new Error();}for(var b=this.m_bodyList;b;b=b.m_next){b.m_xf.p.SelfSub(newOrigin);b.m_sweep.c0.SelfSub(newOrigin);b.m_sweep.c.SelfSub(newOrigin);}for(var j=this.m_jointList;j;j=j.m_next){j.ShiftOrigin(newOrigin);}this.m_contactManager.m_broadPhase.ShiftOrigin(newOrigin);};_proto107.GetContactManager=function GetContactManager(){return this.m_contactManager;};_proto107.GetProfile=function GetProfile(){return this.m_profile;};_proto107.Dump=function Dump(log){if(this.m_locked){return;}log("const g: b2Vec2 = new b2Vec2(%.15f, %.15f);\n",this.m_gravity.x,this.m_gravity.y);log("this.m_world.SetGravity(g);\n");log("const bodies: b2Body[] = [];\n");log("const joints: b2Joint[] = [];\n");var i=0;for(var b=this.m_bodyList;b;b=b.m_next){b.m_islandIndex=i;b.Dump(log);++i;}i=0;for(var j=this.m_jointList;j;j=j.m_next){j.m_index=i;++i;}for(var _j5=this.m_jointList;_j5;_j5=_j5.m_next){if(_j5.m_type===exports$1.b2JointType.e_gearJoint){continue;}log("{\n");_j5.Dump(log);log("}\n");}for(var _j6=this.m_jointList;_j6;_j6=_j6.m_next){if(_j6.m_type!==exports$1.b2JointType.e_gearJoint){continue;}log("{\n");_j6.Dump(log);log("}\n");}};_proto107.DrawJoint=function DrawJoint(joint){if(this.m_debugDraw===null){return;}var bodyA=joint.GetBodyA();var bodyB=joint.GetBodyB();var xf1=bodyA.m_xf;var xf2=bodyB.m_xf;var x1=xf1.p;var x2=xf2.p;var p1=joint.GetAnchorA(b2World.DrawJoint_s_p1);var p2=joint.GetAnchorB(b2World.DrawJoint_s_p2);var color=b2World.DrawJoint_s_color.SetRGB(0.5,0.8,0.8);switch(joint.m_type){case exports$1.b2JointType.e_distanceJoint:this.m_debugDraw.DrawSegment(p1,p2,color);break;case exports$1.b2JointType.e_pulleyJoint:{var pulley=joint;var s1=pulley.GetGroundAnchorA();var s2=pulley.GetGroundAnchorB();this.m_debugDraw.DrawSegment(s1,p1,color);this.m_debugDraw.DrawSegment(s2,p2,color);this.m_debugDraw.DrawSegment(s1,s2,color);break;}case exports$1.b2JointType.e_mouseJoint:{var c=b2World.DrawJoint_s_c;c.Set(0.0,1.0,0.0);this.m_debugDraw.DrawPoint(p1,4.0,c);this.m_debugDraw.DrawPoint(p2,4.0,c);c.Set(0.8,0.8,0.8);this.m_debugDraw.DrawSegment(p1,p2,c);break;}default:this.m_debugDraw.DrawSegment(x1,p1,color);this.m_debugDraw.DrawSegment(p1,p2,color);this.m_debugDraw.DrawSegment(x2,p2,color);}};_proto107.DrawShape=function DrawShape(fixture,color){if(this.m_debugDraw===null){return;}var shape=fixture.GetShape();switch(shape.m_type){case exports$1.b2ShapeType.e_circleShape:{var circle=shape;var center=circle.m_p;var radius=circle.m_radius;var axis=b2Vec2.UNITX;this.m_debugDraw.DrawSolidCircle(center,radius,axis,color);break;}case exports$1.b2ShapeType.e_edgeShape:{var edge=shape;var v1=edge.m_vertex1;var v2=edge.m_vertex2;this.m_debugDraw.DrawSegment(v1,v2,color);break;}case exports$1.b2ShapeType.e_chainShape:{var chain=shape;var count=chain.m_count;var vertices=chain.m_vertices;var ghostColor=b2World.DrawShape_s_ghostColor.SetRGBA(0.75*color.r,0.75*color.g,0.75*color.b,color.a);var _v7=vertices[0];this.m_debugDraw.DrawPoint(_v7,4.0,color);if(chain.m_hasPrevVertex){var vp=chain.m_prevVertex;this.m_debugDraw.DrawSegment(vp,_v7,ghostColor);this.m_debugDraw.DrawCircle(vp,0.1,ghostColor);}for(var i=1;i<count;++i){var _v8=vertices[i];this.m_debugDraw.DrawSegment(_v7,_v8,color);this.m_debugDraw.DrawPoint(_v8,4.0,color);_v7=_v8;}if(chain.m_hasNextVertex){var vn=chain.m_nextVertex;this.m_debugDraw.DrawSegment(vn,_v7,ghostColor);this.m_debugDraw.DrawCircle(vn,0.1,ghostColor);}break;}case exports$1.b2ShapeType.e_polygonShape:{var poly=shape;var vertexCount=poly.m_count;var _vertices4=poly.m_vertices;this.m_debugDraw.DrawSolidPolygon(_vertices4,vertexCount,color);break;}}};_proto107.Solve=function Solve(step){for(var b=this.m_bodyList;b;b=b.m_next){b.m_xf0.Copy(b.m_xf);}for(var controller=this.m_controllerList;controller;controller=controller.m_next){controller.Step(step);}this.m_profile.solveInit=0;this.m_profile.solveVelocity=0;this.m_profile.solvePosition=0;var island=this.m_island;island.Initialize(this.m_bodyCount,this.m_contactManager.m_contactCount,this.m_jointCount,this.m_contactManager.m_contactListener);for(var _b17=this.m_bodyList;_b17;_b17=_b17.m_next){_b17.m_islandFlag=false;}for(var c=this.m_contactManager.m_contactList;c;c=c.m_next){c.m_islandFlag=false;}for(var j=this.m_jointList;j;j=j.m_next){j.m_islandFlag=false;}var stack=this.s_stack;for(var seed=this.m_bodyList;seed;seed=seed.m_next){if(seed.m_islandFlag){continue;}if(!seed.IsAwake()||!seed.IsActive()){continue;}if(seed.GetType()===exports$1.b2BodyType.b2_staticBody){continue;}island.Clear();var stackCount=0;stack[stackCount++]=seed;seed.m_islandFlag=true;while(stackCount>0){var _b18=stack[--stackCount];if(!_b18){throw new Error();}island.AddBody(_b18);_b18.m_awakeFlag=true;if(_b18.GetType()===exports$1.b2BodyType.b2_staticBody){continue;}for(var ce=_b18.m_contactList;ce;ce=ce.next){var contact=ce.contact;if(contact.m_islandFlag){continue;}if(!contact.IsEnabled()||!contact.IsTouching()){continue;}var sensorA=contact.m_fixtureA.m_isSensor;var sensorB=contact.m_fixtureB.m_isSensor;if(sensorA||sensorB){continue;}island.AddContact(contact);contact.m_islandFlag=true;var other=ce.other;if(other.m_islandFlag){continue;}stack[stackCount++]=other;other.m_islandFlag=true;}for(var je=_b18.m_jointList;je;je=je.next){if(je.joint.m_islandFlag){continue;}var _other=je.other;if(!_other.IsActive()){continue;}island.AddJoint(je.joint);je.joint.m_islandFlag=true;if(_other.m_islandFlag){continue;}stack[stackCount++]=_other;_other.m_islandFlag=true;}}var profile=new b2Profile();island.Solve(profile,step,this.m_gravity,this.m_allowSleep);this.m_profile.solveInit+=profile.solveInit;this.m_profile.solveVelocity+=profile.solveVelocity;this.m_profile.solvePosition+=profile.solvePosition;for(var i=0;i<island.m_bodyCount;++i){var _b19=island.m_bodies[i];if(_b19.GetType()===exports$1.b2BodyType.b2_staticBody){_b19.m_islandFlag=false;}}}for(var _i41=0;_i41<stack.length;++_i41){if(!stack[_i41]){break;}stack[_i41]=null;}var timer=new b2Timer();for(var _b20=this.m_bodyList;_b20;_b20=_b20.m_next){if(!_b20.m_islandFlag){continue;}if(_b20.GetType()===exports$1.b2BodyType.b2_staticBody){continue;}_b20.SynchronizeFixtures();}this.m_contactManager.FindNewContacts();this.m_profile.broadphase=timer.GetMilliseconds();};_proto107.SolveTOI=function SolveTOI(step){var island=this.m_island;island.Initialize(2*b2_maxTOIContacts,b2_maxTOIContacts,0,this.m_contactManager.m_contactListener);if(this.m_stepComplete){for(var b=this.m_bodyList;b;b=b.m_next){b.m_islandFlag=false;b.m_sweep.alpha0=0;}for(var c=this.m_contactManager.m_contactList;c;c=c.m_next){c.m_toiFlag=false;c.m_islandFlag=false;c.m_toiCount=0;c.m_toi=1;}}for(;;){var minContact=null;var minAlpha=1;for(var _c=this.m_contactManager.m_contactList;_c;_c=_c.m_next){if(!_c.IsEnabled()){continue;}if(_c.m_toiCount>b2_maxSubSteps){continue;}var alpha=1;if(_c.m_toiFlag){alpha=_c.m_toi;}else {var _fA=_c.GetFixtureA();var _fB=_c.GetFixtureB();if(_fA.IsSensor()||_fB.IsSensor()){continue;}var _bA=_fA.GetBody();var _bB=_fB.GetBody();var typeA=_bA.m_type;var typeB=_bB.m_type;var activeA=_bA.IsAwake()&&typeA!==exports$1.b2BodyType.b2_staticBody;var activeB=_bB.IsAwake()&&typeB!==exports$1.b2BodyType.b2_staticBody;if(!activeA&&!activeB){continue;}var collideA=_bA.IsBullet()||typeA!==exports$1.b2BodyType.b2_dynamicBody;var collideB=_bB.IsBullet()||typeB!==exports$1.b2BodyType.b2_dynamicBody;if(!collideA&&!collideB){continue;}var alpha0=_bA.m_sweep.alpha0;if(_bA.m_sweep.alpha0<_bB.m_sweep.alpha0){alpha0=_bB.m_sweep.alpha0;_bA.m_sweep.Advance(alpha0);}else if(_bB.m_sweep.alpha0<_bA.m_sweep.alpha0){alpha0=_bA.m_sweep.alpha0;_bB.m_sweep.Advance(alpha0);}var indexA=_c.GetChildIndexA();var indexB=_c.GetChildIndexB();var input=b2World.SolveTOI_s_toi_input;input.proxyA.SetShape(_fA.GetShape(),indexA);input.proxyB.SetShape(_fB.GetShape(),indexB);input.sweepA.Copy(_bA.m_sweep);input.sweepB.Copy(_bB.m_sweep);input.tMax=1;var output=b2World.SolveTOI_s_toi_output;b2TimeOfImpact(output,input);var beta=output.t;if(output.state===exports$1.b2TOIOutputState.e_touching){alpha=b2Min(alpha0+(1-alpha0)*beta,1);}else {alpha=1;}_c.m_toi=alpha;_c.m_toiFlag=true;}if(alpha<minAlpha){minContact=_c;minAlpha=alpha;}}if(minContact===null||1-10*b2_epsilon<minAlpha){this.m_stepComplete=true;break;}var fA=minContact.GetFixtureA();var fB=minContact.GetFixtureB();var bA=fA.GetBody();var bB=fB.GetBody();var backup1=b2World.SolveTOI_s_backup1.Copy(bA.m_sweep);var backup2=b2World.SolveTOI_s_backup2.Copy(bB.m_sweep);bA.Advance(minAlpha);bB.Advance(minAlpha);minContact.Update(this.m_contactManager.m_contactListener);minContact.m_toiFlag=false;++minContact.m_toiCount;if(!minContact.IsEnabled()||!minContact.IsTouching()){minContact.SetEnabled(false);bA.m_sweep.Copy(backup1);bB.m_sweep.Copy(backup2);bA.SynchronizeTransform();bB.SynchronizeTransform();continue;}bA.SetAwake(true);bB.SetAwake(true);island.Clear();island.AddBody(bA);island.AddBody(bB);island.AddContact(minContact);bA.m_islandFlag=true;bB.m_islandFlag=true;minContact.m_islandFlag=true;for(var i=0;i<2;++i){var body=i===0?bA:bB;if(body.m_type===exports$1.b2BodyType.b2_dynamicBody){for(var ce=body.m_contactList;ce;ce=ce.next){if(island.m_bodyCount===island.m_bodyCapacity){break;}if(island.m_contactCount===island.m_contactCapacity){break;}var contact=ce.contact;if(contact.m_islandFlag){continue;}var other=ce.other;if(other.m_type===exports$1.b2BodyType.b2_dynamicBody&&!body.IsBullet()&&!other.IsBullet()){continue;}var sensorA=contact.m_fixtureA.m_isSensor;var sensorB=contact.m_fixtureB.m_isSensor;if(sensorA||sensorB){continue;}var backup=b2World.SolveTOI_s_backup.Copy(other.m_sweep);if(!other.m_islandFlag){other.Advance(minAlpha);}contact.Update(this.m_contactManager.m_contactListener);if(!contact.IsEnabled()){other.m_sweep.Copy(backup);other.SynchronizeTransform();continue;}if(!contact.IsTouching()){other.m_sweep.Copy(backup);other.SynchronizeTransform();continue;}contact.m_islandFlag=true;island.AddContact(contact);if(other.m_islandFlag){continue;}other.m_islandFlag=true;if(other.m_type!==exports$1.b2BodyType.b2_staticBody){other.SetAwake(true);}island.AddBody(other);}}}var subStep=b2World.SolveTOI_s_subStep;subStep.dt=(1-minAlpha)*step.dt;subStep.inv_dt=1/subStep.dt;subStep.dtRatio=1;subStep.positionIterations=20;subStep.velocityIterations=step.velocityIterations;subStep.particleIterations=step.particleIterations;subStep.warmStarting=false;island.SolveTOI(subStep,bA.m_islandIndex,bB.m_islandIndex);for(var _i42=0;_i42<island.m_bodyCount;++_i42){var _body3=island.m_bodies[_i42];_body3.m_islandFlag=false;if(_body3.m_type!==exports$1.b2BodyType.b2_dynamicBody){continue;}_body3.SynchronizeFixtures();for(var _ce=_body3.m_contactList;_ce;_ce=_ce.next){_ce.contact.m_toiFlag=false;_ce.contact.m_islandFlag=false;}}this.m_contactManager.FindNewContacts();if(this.m_subStepping){this.m_stepComplete=false;break;}}};_proto107.AddController=function AddController(controller){controller.m_next=this.m_controllerList;controller.m_prev=null;if(this.m_controllerList){this.m_controllerList.m_prev=controller;}this.m_controllerList=controller;++this.m_controllerCount;return controller;};_proto107.RemoveController=function RemoveController(controller){if(controller.m_prev){controller.m_prev.m_next=controller.m_next;}if(controller.m_next){controller.m_next.m_prev=controller.m_prev;}if(this.m_controllerList===controller){this.m_controllerList=controller.m_next;}--this.m_controllerCount;controller.m_prev=null;controller.m_next=null;return controller;};return b2World;}();b2World.Step_s_step=new b2TimeStep();b2World.Step_s_stepTimer=new b2Timer();b2World.Step_s_timer=new b2Timer();b2World.DrawDebugData_s_color=new b2Color(0,0,0);b2World.DrawDebugData_s_vs=b2Vec2.MakeArray(4);b2World.DrawDebugData_s_xf=new b2Transform();b2World.QueryFixtureShape_s_aabb=new b2AABB();b2World.RayCast_s_input=new b2RayCastInput();b2World.RayCast_s_output=new b2RayCastOutput();b2World.RayCast_s_point=new b2Vec2();b2World.DrawJoint_s_p1=new b2Vec2();b2World.DrawJoint_s_p2=new b2Vec2();b2World.DrawJoint_s_color=new b2Color(0.5,0.8,0.8);b2World.DrawJoint_s_c=new b2Color();b2World.DrawShape_s_ghostColor=new b2Color();b2World.SolveTOI_s_subStep=new b2TimeStep();b2World.SolveTOI_s_backup=new b2Sweep();b2World.SolveTOI_s_backup1=new b2Sweep();b2World.SolveTOI_s_backup2=new b2Sweep();b2World.SolveTOI_s_toi_input=new b2TOIInput();b2World.SolveTOI_s_toi_output=new b2TOIOutput();var b2ControllerEdge=function b2ControllerEdge(controller,body){this.prevBody=null;this.nextBody=null;this.prevController=null;this.nextController=null;this.controller=controller;this.body=body;};var b2Controller=function(){function b2Controller(){this.m_bodyList=null;this.m_bodyCount=0;this.m_prev=null;this.m_next=null;}var _proto108=b2Controller.prototype;_proto108.GetNext=function GetNext(){return this.m_next;};_proto108.GetPrev=function GetPrev(){return this.m_prev;};_proto108.GetBodyList=function GetBodyList(){return this.m_bodyList;};_proto108.AddBody=function AddBody(body){var edge=new b2ControllerEdge(this,body);edge.nextBody=this.m_bodyList;edge.prevBody=null;if(this.m_bodyList){this.m_bodyList.prevBody=edge;}this.m_bodyList=edge;++this.m_bodyCount;edge.nextController=body.m_controllerList;edge.prevController=null;if(body.m_controllerList){body.m_controllerList.prevController=edge;}body.m_controllerList=edge;++body.m_controllerCount;};_proto108.RemoveBody=function RemoveBody(body){if(this.m_bodyCount<=0){throw new Error();}var edge=this.m_bodyList;while(edge&&edge.body!==body){edge=edge.nextBody;}if(edge===null){throw new Error();}if(edge.prevBody){edge.prevBody.nextBody=edge.nextBody;}if(edge.nextBody){edge.nextBody.prevBody=edge.prevBody;}if(this.m_bodyList===edge){this.m_bodyList=edge.nextBody;}--this.m_bodyCount;if(edge.nextController){edge.nextController.prevController=edge.prevController;}if(edge.prevController){edge.prevController.nextController=edge.nextController;}if(body.m_controllerList===edge){body.m_controllerList=edge.nextController;}--body.m_controllerCount;};_proto108.Clear=function Clear(){while(this.m_bodyList){this.RemoveBody(this.m_bodyList.body);}this.m_bodyCount=0;};return b2Controller;}();var b2BuoyancyController=function(_b2Controller){_inheritsLoose(b2BuoyancyController,_b2Controller);function b2BuoyancyController(){var _this38;_this38=_b2Controller.apply(this,arguments)||this;_this38.normal=new b2Vec2(0,1);_this38.offset=0;_this38.density=0;_this38.velocity=new b2Vec2(0,0);_this38.linearDrag=0;_this38.angularDrag=0;_this38.useDensity=false;_this38.useWorldGravity=true;_this38.gravity=new b2Vec2(0,0);return _this38;}var _proto109=b2BuoyancyController.prototype;_proto109.Step=function Step(step){if(!this.m_bodyList){return;}if(this.useWorldGravity){this.gravity.Copy(this.m_bodyList.body.GetWorld().GetGravity());}for(var i=this.m_bodyList;i;i=i.nextBody){var body=i.body;if(!body.IsAwake()){continue;}var areac=new b2Vec2();var massc=new b2Vec2();var area=0;var mass=0;for(var fixture=body.GetFixtureList();fixture;fixture=fixture.m_next){var sc=new b2Vec2();var sarea=fixture.GetShape().ComputeSubmergedArea(this.normal,this.offset,body.GetTransform(),sc);area+=sarea;areac.x+=sarea*sc.x;areac.y+=sarea*sc.y;var shapeDensity=0;if(this.useDensity){shapeDensity=fixture.GetDensity();}else {shapeDensity=1;}mass+=sarea*shapeDensity;massc.x+=sarea*sc.x*shapeDensity;massc.y+=sarea*sc.y*shapeDensity;}areac.x/=area;areac.y/=area;massc.x/=mass;massc.y/=mass;if(area<b2_epsilon){continue;}var buoyancyForce=this.gravity.Clone().SelfNeg();buoyancyForce.SelfMul(this.density*area);body.ApplyForce(buoyancyForce,massc);var dragForce=body.GetLinearVelocityFromWorldPoint(areac,new b2Vec2());dragForce.SelfSub(this.velocity);dragForce.SelfMul(-this.linearDrag*area);body.ApplyForce(dragForce,areac);body.ApplyTorque(-body.GetInertia()/body.GetMass()*area*body.GetAngularVelocity()*this.angularDrag);}};_proto109.Draw=function Draw(debugDraw){var r=100;var p1=new b2Vec2();var p2=new b2Vec2();p1.x=this.normal.x*this.offset+this.normal.y*r;p1.y=this.normal.y*this.offset-this.normal.x*r;p2.x=this.normal.x*this.offset-this.normal.y*r;p2.y=this.normal.y*this.offset+this.normal.x*r;var color=new b2Color(0,0,0.8);debugDraw.DrawSegment(p1,p2,color);};return b2BuoyancyController;}(b2Controller);var b2ConstantAccelController=function(_b2Controller2){_inheritsLoose(b2ConstantAccelController,_b2Controller2);function b2ConstantAccelController(){var _this39;_this39=_b2Controller2.apply(this,arguments)||this;_this39.A=new b2Vec2(0,0);return _this39;}var _proto110=b2ConstantAccelController.prototype;_proto110.Step=function Step(step){var dtA=b2Vec2.MulSV(step.dt,this.A,b2ConstantAccelController.Step_s_dtA);for(var i=this.m_bodyList;i;i=i.nextBody){var body=i.body;if(!body.IsAwake()){continue;}body.SetLinearVelocity(b2Vec2.AddVV(body.GetLinearVelocity(),dtA,b2Vec2.s_t0));}};_proto110.Draw=function Draw(draw){};return b2ConstantAccelController;}(b2Controller);b2ConstantAccelController.Step_s_dtA=new b2Vec2();var b2ConstantForceController=function(_b2Controller3){_inheritsLoose(b2ConstantForceController,_b2Controller3);function b2ConstantForceController(){var _this40;_this40=_b2Controller3.apply(this,arguments)||this;_this40.F=new b2Vec2(0,0);return _this40;}var _proto111=b2ConstantForceController.prototype;_proto111.Step=function Step(step){for(var i=this.m_bodyList;i;i=i.nextBody){var body=i.body;if(!body.IsAwake()){continue;}body.ApplyForce(this.F,body.GetWorldCenter());}};_proto111.Draw=function Draw(draw){};return b2ConstantForceController;}(b2Controller);var b2GravityController=function(_b2Controller4){_inheritsLoose(b2GravityController,_b2Controller4);function b2GravityController(){var _this41;_this41=_b2Controller4.apply(this,arguments)||this;_this41.G=1;_this41.invSqr=true;return _this41;}var _proto112=b2GravityController.prototype;_proto112.Step=function Step(step){if(this.invSqr){for(var i=this.m_bodyList;i;i=i.nextBody){var body1=i.body;var p1=body1.GetWorldCenter();var mass1=body1.GetMass();for(var j=this.m_bodyList;j&&j!==i;j=j.nextBody){var body2=j.body;var p2=body2.GetWorldCenter();var mass2=body2.GetMass();var dx=p2.x-p1.x;var dy=p2.y-p1.y;var r2=dx*dx+dy*dy;if(r2<b2_epsilon){continue;}var f=b2GravityController.Step_s_f.Set(dx,dy);f.SelfMul(this.G/r2/b2Sqrt(r2)*mass1*mass2);if(body1.IsAwake()){body1.ApplyForce(f,p1);}if(body2.IsAwake()){body2.ApplyForce(f.SelfMul(-1),p2);}}}}else {for(var _i43=this.m_bodyList;_i43;_i43=_i43.nextBody){var _body4=_i43.body;var _p2=_body4.GetWorldCenter();var _mass2=_body4.GetMass();for(var _j7=this.m_bodyList;_j7&&_j7!==_i43;_j7=_j7.nextBody){var _body5=_j7.body;var _p3=_body5.GetWorldCenter();var _mass3=_body5.GetMass();var _dx=_p3.x-_p2.x;var _dy=_p3.y-_p2.y;var _r=_dx*_dx+_dy*_dy;if(_r<b2_epsilon){continue;}var _f8=b2GravityController.Step_s_f.Set(_dx,_dy);_f8.SelfMul(this.G/_r*_mass2*_mass3);if(_body4.IsAwake()){_body4.ApplyForce(_f8,_p2);}if(_body5.IsAwake()){_body5.ApplyForce(_f8.SelfMul(-1),_p3);}}}}};_proto112.Draw=function Draw(draw){};return b2GravityController;}(b2Controller);b2GravityController.Step_s_f=new b2Vec2();var b2TensorDampingController=function(_b2Controller5){_inheritsLoose(b2TensorDampingController,_b2Controller5);function b2TensorDampingController(){var _this42;_this42=_b2Controller5.apply(this,arguments)||this;_this42.T=new b2Mat22();_this42.maxTimestep=0;return _this42;}var _proto113=b2TensorDampingController.prototype;_proto113.Step=function Step(step){var timestep=step.dt;if(timestep<=b2_epsilon){return;}if(timestep>this.maxTimestep&&this.maxTimestep>0){timestep=this.maxTimestep;}for(var i=this.m_bodyList;i;i=i.nextBody){var body=i.body;if(!body.IsAwake()){continue;}var damping=body.GetWorldVector(b2Mat22.MulMV(this.T,body.GetLocalVector(body.GetLinearVelocity(),b2Vec2.s_t0),b2Vec2.s_t1),b2TensorDampingController.Step_s_damping);body.SetLinearVelocity(b2Vec2.AddVV(body.GetLinearVelocity(),b2Vec2.MulSV(timestep,damping,b2Vec2.s_t0),b2Vec2.s_t1));}};_proto113.Draw=function Draw(draw){};_proto113.SetAxisAligned=function SetAxisAligned(xDamping,yDamping){this.T.ex.x=-xDamping;this.T.ex.y=0;this.T.ey.x=0;this.T.ey.y=-yDamping;if(xDamping>0||yDamping>0){this.maxTimestep=1/b2Max(xDamping,yDamping);}else {this.maxTimestep=0;}};return b2TensorDampingController;}(b2Controller);b2TensorDampingController.Step_s_damping=new b2Vec2();var b2RopeDef=function b2RopeDef(){this.vertices=[];this.count=0;this.masses=[];this.gravity=new b2Vec2(0,0);this.damping=0.1;this.k2=0.9;this.k3=0.1;};var b2Rope=function(){function b2Rope(){this.m_count=0;this.m_ps=[];this.m_p0s=[];this.m_vs=[];this.m_ims=[];this.m_Ls=[];this.m_as=[];this.m_gravity=new b2Vec2();this.m_damping=0;this.m_k2=1;this.m_k3=0.1;}var _proto114=b2Rope.prototype;_proto114.GetVertexCount=function GetVertexCount(){return this.m_count;};_proto114.GetVertices=function GetVertices(){return this.m_ps;};_proto114.Initialize=function Initialize(def){this.m_count=def.count;this.m_ps=b2Vec2.MakeArray(this.m_count);this.m_p0s=b2Vec2.MakeArray(this.m_count);this.m_vs=b2Vec2.MakeArray(this.m_count);this.m_ims=b2MakeNumberArray(this.m_count);for(var i=0;i<this.m_count;++i){this.m_ps[i].Copy(def.vertices[i]);this.m_p0s[i].Copy(def.vertices[i]);this.m_vs[i].SetZero();var m=def.masses[i];if(m>0){this.m_ims[i]=1/m;}else {this.m_ims[i]=0;}}var count2=this.m_count-1;var count3=this.m_count-2;this.m_Ls=b2MakeNumberArray(count2);this.m_as=b2MakeNumberArray(count3);for(var _i44=0;_i44<count2;++_i44){var p1=this.m_ps[_i44];var p2=this.m_ps[_i44+1];this.m_Ls[_i44]=b2Vec2.DistanceVV(p1,p2);}for(var _i45=0;_i45<count3;++_i45){var _p4=this.m_ps[_i45];var _p5=this.m_ps[_i45+1];var p3=this.m_ps[_i45+2];var d1=b2Vec2.SubVV(_p5,_p4,b2Vec2.s_t0);var d2=b2Vec2.SubVV(p3,_p5,b2Vec2.s_t1);var a=b2Vec2.CrossVV(d1,d2);var b=b2Vec2.DotVV(d1,d2);this.m_as[_i45]=b2Atan2(a,b);}this.m_gravity.Copy(def.gravity);this.m_damping=def.damping;this.m_k2=def.k2;this.m_k3=def.k3;};_proto114.Step=function Step(h,iterations){if(h===0){return;}var d=Math.exp(-h*this.m_damping);for(var i=0;i<this.m_count;++i){this.m_p0s[i].Copy(this.m_ps[i]);if(this.m_ims[i]>0){this.m_vs[i].SelfMulAdd(h,this.m_gravity);}this.m_vs[i].SelfMul(d);this.m_ps[i].SelfMulAdd(h,this.m_vs[i]);}for(var _i46=0;_i46<iterations;++_i46){this.SolveC2();this.SolveC3();this.SolveC2();}var inv_h=1/h;for(var _i47=0;_i47<this.m_count;++_i47){b2Vec2.MulSV(inv_h,b2Vec2.SubVV(this.m_ps[_i47],this.m_p0s[_i47],b2Vec2.s_t0),this.m_vs[_i47]);}};_proto114.SolveC2=function SolveC2(){var count2=this.m_count-1;for(var i=0;i<count2;++i){var p1=this.m_ps[i];var p2=this.m_ps[i+1];var d=b2Vec2.SubVV(p2,p1,b2Rope.s_d);var L=d.Normalize();var im1=this.m_ims[i];var im2=this.m_ims[i+1];if(im1+im2===0){continue;}var s1=im1/(im1+im2);var s2=im2/(im1+im2);p1.SelfMulSub(this.m_k2*s1*(this.m_Ls[i]-L),d);p2.SelfMulAdd(this.m_k2*s2*(this.m_Ls[i]-L),d);}};_proto114.SetAngle=function SetAngle(angle){var count3=this.m_count-2;for(var i=0;i<count3;++i){this.m_as[i]=angle;}};_proto114.SolveC3=function SolveC3(){var count3=this.m_count-2;for(var i=0;i<count3;++i){var p1=this.m_ps[i];var p2=this.m_ps[i+1];var p3=this.m_ps[i+2];var m1=this.m_ims[i];var m2=this.m_ims[i+1];var m3=this.m_ims[i+2];var d1=b2Vec2.SubVV(p2,p1,b2Rope.s_d1);var d2=b2Vec2.SubVV(p3,p2,b2Rope.s_d2);var L1sqr=d1.LengthSquared();var L2sqr=d2.LengthSquared();if(L1sqr*L2sqr===0){continue;}var a=b2Vec2.CrossVV(d1,d2);var b=b2Vec2.DotVV(d1,d2);var angle=b2Atan2(a,b);var Jd1=b2Vec2.MulSV(-1/L1sqr,d1.SelfSkew(),b2Rope.s_Jd1);var Jd2=b2Vec2.MulSV(1/L2sqr,d2.SelfSkew(),b2Rope.s_Jd2);var J1=b2Vec2.NegV(Jd1,b2Rope.s_J1);var J2=b2Vec2.SubVV(Jd1,Jd2,b2Rope.s_J2);var J3=Jd2;var mass=m1*b2Vec2.DotVV(J1,J1)+m2*b2Vec2.DotVV(J2,J2)+m3*b2Vec2.DotVV(J3,J3);if(mass===0){continue;}mass=1/mass;var C=angle-this.m_as[i];while(C>b2_pi){angle-=2*b2_pi;C=angle-this.m_as[i];}while(C<-b2_pi){angle+=2*b2_pi;C=angle-this.m_as[i];}var impulse=-this.m_k3*mass*C;p1.SelfMulAdd(m1*impulse,J1);p2.SelfMulAdd(m2*impulse,J2);p3.SelfMulAdd(m3*impulse,J3);}};_proto114.Draw=function Draw(draw){var c=new b2Color(0.4,0.5,0.7);for(var i=0;i<this.m_count-1;++i){draw.DrawSegment(this.m_ps[i],this.m_ps[i+1],c);}};return b2Rope;}();b2Rope.s_d=new b2Vec2();b2Rope.s_d1=new b2Vec2();b2Rope.s_d2=new b2Vec2();b2Rope.s_Jd1=new b2Vec2();b2Rope.s_Jd2=new b2Vec2();b2Rope.s_J1=new b2Vec2();b2Rope.s_J2=new b2Vec2();exports$1.b2AABB=b2AABB;exports$1.b2Abs=b2Abs;exports$1.b2Acos=b2Acos;exports$1.b2Alloc=b2Alloc;exports$1.b2AreaJoint=b2AreaJoint;exports$1.b2AreaJointDef=b2AreaJointDef;exports$1.b2Asin=b2Asin;exports$1.b2Assert=b2Assert;exports$1.b2Atan2=b2Atan2;exports$1.b2BlockAllocator=b2BlockAllocator;exports$1.b2Body=b2Body;exports$1.b2BodyDef=b2BodyDef;exports$1.b2BroadPhase=b2BroadPhase;exports$1.b2BuoyancyController=b2BuoyancyController;exports$1.b2CalculateParticleIterations=b2CalculateParticleIterations;exports$1.b2ChainAndCircleContact=b2ChainAndCircleContact;exports$1.b2ChainAndPolygonContact=b2ChainAndPolygonContact;exports$1.b2ChainShape=b2ChainShape;exports$1.b2CircleContact=b2CircleContact;exports$1.b2CircleShape=b2CircleShape;exports$1.b2Clamp=b2Clamp;exports$1.b2ClipSegmentToLine=b2ClipSegmentToLine;exports$1.b2ClipVertex=b2ClipVertex;exports$1.b2CollideCircles=b2CollideCircles;exports$1.b2CollideEdgeAndCircle=b2CollideEdgeAndCircle;exports$1.b2CollideEdgeAndPolygon=b2CollideEdgeAndPolygon;exports$1.b2CollidePolygonAndCircle=b2CollidePolygonAndCircle;exports$1.b2CollidePolygons=b2CollidePolygons;exports$1.b2Color=b2Color;exports$1.b2ConstantAccelController=b2ConstantAccelController;exports$1.b2ConstantForceController=b2ConstantForceController;exports$1.b2Contact=b2Contact;exports$1.b2ContactEdge=b2ContactEdge;exports$1.b2ContactFactory=b2ContactFactory;exports$1.b2ContactFeature=b2ContactFeature;exports$1.b2ContactFilter=b2ContactFilter;exports$1.b2ContactID=b2ContactID;exports$1.b2ContactImpulse=b2ContactImpulse;exports$1.b2ContactListener=b2ContactListener;exports$1.b2ContactManager=b2ContactManager;exports$1.b2ContactPositionConstraint=b2ContactPositionConstraint;exports$1.b2ContactRegister=b2ContactRegister;exports$1.b2ContactSolver=b2ContactSolver;exports$1.b2ContactSolverDef=b2ContactSolverDef;exports$1.b2ContactVelocityConstraint=b2ContactVelocityConstraint;exports$1.b2Controller=b2Controller;exports$1.b2ControllerEdge=b2ControllerEdge;exports$1.b2Cos=b2Cos;exports$1.b2Counter=b2Counter;exports$1.b2DegToRad=b2DegToRad;exports$1.b2DestructionListener=b2DestructionListener;exports$1.b2Distance=b2Distance;exports$1.b2DistanceInput=b2DistanceInput;exports$1.b2DistanceJoint=b2DistanceJoint;exports$1.b2DistanceJointDef=b2DistanceJointDef;exports$1.b2DistanceOutput=b2DistanceOutput;exports$1.b2DistanceProxy=b2DistanceProxy;exports$1.b2Draw=b2Draw;exports$1.b2DynamicTree=b2DynamicTree;exports$1.b2EdgeAndCircleContact=b2EdgeAndCircleContact;exports$1.b2EdgeAndPolygonContact=b2EdgeAndPolygonContact;exports$1.b2EdgeShape=b2EdgeShape;exports$1.b2Filter=b2Filter;exports$1.b2Fixture=b2Fixture;exports$1.b2FixtureDef=b2FixtureDef;exports$1.b2FixtureParticleQueryCallback=b2FixtureParticleQueryCallback;exports$1.b2FixtureProxy=b2FixtureProxy;exports$1.b2Free=b2Free;exports$1.b2FrictionJoint=b2FrictionJoint;exports$1.b2FrictionJointDef=b2FrictionJointDef;exports$1.b2GearJoint=b2GearJoint;exports$1.b2GearJointDef=b2GearJointDef;exports$1.b2GetPointStates=b2GetPointStates;exports$1.b2GravityController=b2GravityController;exports$1.b2GrowableBuffer=b2GrowableBuffer;exports$1.b2GrowableStack=b2GrowableStack;exports$1.b2InvSqrt=b2InvSqrt;exports$1.b2IsPowerOfTwo=b2IsPowerOfTwo;exports$1.b2IsValid=b2IsValid;exports$1.b2Island=b2Island;exports$1.b2Jacobian=b2Jacobian;exports$1.b2Joint=b2Joint;exports$1.b2JointDef=b2JointDef;exports$1.b2JointEdge=b2JointEdge;exports$1.b2Log=b2Log;exports$1.b2MakeArray=b2MakeArray;exports$1.b2MakeNullArray=b2MakeNullArray;exports$1.b2MakeNumberArray=b2MakeNumberArray;exports$1.b2Manifold=b2Manifold;exports$1.b2ManifoldPoint=b2ManifoldPoint;exports$1.b2MassData=b2MassData;exports$1.b2Mat22=b2Mat22;exports$1.b2Mat33=b2Mat33;exports$1.b2Max=b2Max;exports$1.b2Maybe=b2Maybe;exports$1.b2Min=b2Min;exports$1.b2MixFriction=b2MixFriction;exports$1.b2MixRestitution=b2MixRestitution;exports$1.b2MotorJoint=b2MotorJoint;exports$1.b2MotorJointDef=b2MotorJointDef;exports$1.b2MouseJoint=b2MouseJoint;exports$1.b2MouseJointDef=b2MouseJointDef;exports$1.b2NextPowerOfTwo=b2NextPowerOfTwo;exports$1.b2Pair=b2Pair;exports$1.b2PairLessThan=b2PairLessThan;exports$1.b2ParseInt=b2ParseInt;exports$1.b2ParseUInt=b2ParseUInt;exports$1.b2ParticleBodyContact=b2ParticleBodyContact;exports$1.b2ParticleContact=b2ParticleContact;exports$1.b2ParticleDef=b2ParticleDef;exports$1.b2ParticleGroup=b2ParticleGroup;exports$1.b2ParticleGroupDef=b2ParticleGroupDef;exports$1.b2ParticleHandle=b2ParticleHandle;exports$1.b2ParticlePair=b2ParticlePair;exports$1.b2ParticlePairSet=b2ParticlePairSet;exports$1.b2ParticleSystem=b2ParticleSystem;exports$1.b2ParticleSystemDef=b2ParticleSystemDef;exports$1.b2ParticleSystem_CompositeShape=b2ParticleSystem_CompositeShape;exports$1.b2ParticleSystem_ConnectionFilter=b2ParticleSystem_ConnectionFilter;exports$1.b2ParticleSystem_DestroyParticlesInShapeCallback=b2ParticleSystem_DestroyParticlesInShapeCallback;exports$1.b2ParticleSystem_FixedSetAllocator=b2ParticleSystem_FixedSetAllocator;exports$1.b2ParticleSystem_FixtureParticle=b2ParticleSystem_FixtureParticle;exports$1.b2ParticleSystem_FixtureParticleSet=b2ParticleSystem_FixtureParticleSet;exports$1.b2ParticleSystem_InsideBoundsEnumerator=b2ParticleSystem_InsideBoundsEnumerator;exports$1.b2ParticleSystem_JoinParticleGroupsFilter=b2ParticleSystem_JoinParticleGroupsFilter;exports$1.b2ParticleSystem_ParticleListNode=b2ParticleSystem_ParticleListNode;exports$1.b2ParticleSystem_ParticlePair=b2ParticleSystem_ParticlePair;exports$1.b2ParticleSystem_Proxy=b2ParticleSystem_Proxy;exports$1.b2ParticleSystem_ReactiveFilter=b2ParticleSystem_ReactiveFilter;exports$1.b2ParticleSystem_SolveCollisionCallback=b2ParticleSystem_SolveCollisionCallback;exports$1.b2ParticleSystem_UpdateBodyContactsCallback=b2ParticleSystem_UpdateBodyContactsCallback;exports$1.b2ParticleSystem_UserOverridableBuffer=b2ParticleSystem_UserOverridableBuffer;exports$1.b2ParticleTriad=b2ParticleTriad;exports$1.b2PolygonAndCircleContact=b2PolygonAndCircleContact;exports$1.b2PolygonContact=b2PolygonContact;exports$1.b2PolygonShape=b2PolygonShape;exports$1.b2Position=b2Position;exports$1.b2PositionSolverManifold=b2PositionSolverManifold;exports$1.b2Pow=b2Pow;exports$1.b2PrismaticJoint=b2PrismaticJoint;exports$1.b2PrismaticJointDef=b2PrismaticJointDef;exports$1.b2Profile=b2Profile;exports$1.b2PulleyJoint=b2PulleyJoint;exports$1.b2PulleyJointDef=b2PulleyJointDef;exports$1.b2QueryCallback=b2QueryCallback;exports$1.b2RadToDeg=b2RadToDeg;exports$1.b2Random=b2Random;exports$1.b2RandomRange=b2RandomRange;exports$1.b2RayCastCallback=b2RayCastCallback;exports$1.b2RayCastInput=b2RayCastInput;exports$1.b2RayCastOutput=b2RayCastOutput;exports$1.b2RevoluteJoint=b2RevoluteJoint;exports$1.b2RevoluteJointDef=b2RevoluteJointDef;exports$1.b2Rope=b2Rope;exports$1.b2RopeDef=b2RopeDef;exports$1.b2RopeJoint=b2RopeJoint;exports$1.b2RopeJointDef=b2RopeJointDef;exports$1.b2Rot=b2Rot;exports$1.b2SeparationFunction=b2SeparationFunction;exports$1.b2Shape=b2Shape;exports$1.b2ShapeCast=b2ShapeCast;exports$1.b2ShapeCastInput=b2ShapeCastInput;exports$1.b2ShapeCastOutput=b2ShapeCastOutput;exports$1.b2Simplex=b2Simplex;exports$1.b2SimplexCache=b2SimplexCache;exports$1.b2SimplexVertex=b2SimplexVertex;exports$1.b2Sin=b2Sin;exports$1.b2SolverData=b2SolverData;exports$1.b2Sq=b2Sq;exports$1.b2Sqrt=b2Sqrt;exports$1.b2StackAllocator=b2StackAllocator;exports$1.b2Swap=b2Swap;exports$1.b2Sweep=b2Sweep;exports$1.b2TOIInput=b2TOIInput;exports$1.b2TOIOutput=b2TOIOutput;exports$1.b2TensorDampingController=b2TensorDampingController;exports$1.b2TestOverlapAABB=b2TestOverlapAABB;exports$1.b2TestOverlapShape=b2TestOverlapShape;exports$1.b2TimeOfImpact=b2TimeOfImpact;exports$1.b2TimeStep=b2TimeStep;exports$1.b2Timer=b2Timer;exports$1.b2Transform=b2Transform;exports$1.b2TreeNode=b2TreeNode;exports$1.b2Vec2=b2Vec2;exports$1.b2Vec2_zero=b2Vec2_zero;exports$1.b2Vec3=b2Vec3;exports$1.b2Velocity=b2Velocity;exports$1.b2VelocityConstraintPoint=b2VelocityConstraintPoint;exports$1.b2Version=b2Version;exports$1.b2WeldJoint=b2WeldJoint;exports$1.b2WeldJointDef=b2WeldJointDef;exports$1.b2WheelJoint=b2WheelJoint;exports$1.b2WheelJointDef=b2WheelJointDef;exports$1.b2World=b2World;exports$1.b2WorldManifold=b2WorldManifold;exports$1.b2_180_over_pi=b2_180_over_pi;exports$1.b2_aabbExtension=b2_aabbExtension;exports$1.b2_aabbMultiplier=b2_aabbMultiplier;exports$1.b2_angularSleepTolerance=b2_angularSleepTolerance;exports$1.b2_angularSlop=b2_angularSlop;exports$1.b2_barrierCollisionTime=b2_barrierCollisionTime;exports$1.b2_baumgarte=b2_baumgarte;exports$1.b2_branch=b2_branch;exports$1.b2_commit=b2_commit;exports$1.b2_epsilon=b2_epsilon;exports$1.b2_epsilon_sq=b2_epsilon_sq;exports$1.b2_gjk_reset=b2_gjk_reset;exports$1.b2_invalidParticleIndex=b2_invalidParticleIndex;exports$1.b2_linearSleepTolerance=b2_linearSleepTolerance;exports$1.b2_linearSlop=b2_linearSlop;exports$1.b2_maxAngularCorrection=b2_maxAngularCorrection;exports$1.b2_maxFloat=b2_maxFloat;exports$1.b2_maxLinearCorrection=b2_maxLinearCorrection;exports$1.b2_maxManifoldPoints=b2_maxManifoldPoints;exports$1.b2_maxParticleForce=b2_maxParticleForce;exports$1.b2_maxParticleIndex=b2_maxParticleIndex;exports$1.b2_maxParticlePressure=b2_maxParticlePressure;exports$1.b2_maxPolygonVertices=b2_maxPolygonVertices;exports$1.b2_maxRotation=b2_maxRotation;exports$1.b2_maxRotationSquared=b2_maxRotationSquared;exports$1.b2_maxSubSteps=b2_maxSubSteps;exports$1.b2_maxTOIContacts=b2_maxTOIContacts;exports$1.b2_maxTranslation=b2_maxTranslation;exports$1.b2_maxTranslationSquared=b2_maxTranslationSquared;exports$1.b2_maxTriadDistance=b2_maxTriadDistance;exports$1.b2_maxTriadDistanceSquared=b2_maxTriadDistanceSquared;exports$1.b2_minParticleSystemBufferCapacity=b2_minParticleSystemBufferCapacity;exports$1.b2_minParticleWeight=b2_minParticleWeight;exports$1.b2_minPulleyLength=b2_minPulleyLength;exports$1.b2_particleStride=b2_particleStride;exports$1.b2_pi=b2_pi;exports$1.b2_pi_over_180=b2_pi_over_180;exports$1.b2_polygonRadius=b2_polygonRadius;exports$1.b2_timeToSleep=b2_timeToSleep;exports$1.b2_toiBaumgarte=b2_toiBaumgarte;exports$1.b2_toi_reset=b2_toi_reset;exports$1.b2_two_pi=b2_two_pi;exports$1.b2_velocityThreshold=b2_velocityThreshold;exports$1.b2_version=b2_version;exports$1.g_blockSolve=g_blockSolve;Object.defineProperty(exports$1,'__esModule',{value:true});});});unwrapExports(box2d_umd);

      var b2={};for(var key in box2d_umd){if(key.indexOf('b2_')!==-1){continue;}var newKey=key.replace('b2','');b2[newKey]=box2d_umd[key];}var box2d_1=b2;

      var PhysicsContactListener = function (_b2$ContactListener) {
        _inheritsLoose(PhysicsContactListener, _b2$ContactListener);
        function PhysicsContactListener() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _b2$ContactListener.call.apply(_b2$ContactListener, [this].concat(args)) || this;
          _this._contactFixtures = [];
          _this._BeginContact = null;
          _this._EndContact = null;
          _this._PreSolve = null;
          _this._PostSolve = null;
          return _this;
        }
        var _proto = PhysicsContactListener.prototype;
        _proto.setBeginContact = function setBeginContact(cb) {
          this._BeginContact = cb;
        };
        _proto.setEndContact = function setEndContact(cb) {
          this._EndContact = cb;
        };
        _proto.setPreSolve = function setPreSolve(cb) {
          this._PreSolve = cb;
        };
        _proto.setPostSolve = function setPostSolve(cb) {
          this._PostSolve = cb;
        };
        _proto.BeginContact = function BeginContact(contact) {
          if (!this._BeginContact) return;
          var fixtureA = contact.GetFixtureA();
          var fixtureB = contact.GetFixtureB();
          var fixtures = this._contactFixtures;
          contact._shouldReport = false;
          if (fixtures.indexOf(fixtureA) !== -1 || fixtures.indexOf(fixtureB) !== -1) {
            contact._shouldReport = true;
            this._BeginContact(contact);
          }
        };
        _proto.EndContact = function EndContact(contact) {
          if (this._EndContact && contact._shouldReport) {
            contact._shouldReport = false;
            this._EndContact(contact);
          }
        };
        _proto.PreSolve = function PreSolve(contact, oldManifold) {
          if (this._PreSolve && contact._shouldReport) {
            this._PreSolve(contact, oldManifold);
          }
        };
        _proto.PostSolve = function PostSolve(contact, impulse) {
          if (this._PostSolve && contact._shouldReport) {
            this._PostSolve(contact, impulse);
          }
        };
        _proto.registerContactFixture = function registerContactFixture(fixture) {
          this._contactFixtures.push(fixture);
        };
        _proto.unregisterContactFixture = function unregisterContactFixture(fixture) {
          remove(this._contactFixtures, fixture);
        };
        return PhysicsContactListener;
      }(box2d_1.ContactListener);

      var PhysicsAABBQueryCallback = function (_b2$QueryCallback) {
        _inheritsLoose(PhysicsAABBQueryCallback, _b2$QueryCallback);
        function PhysicsAABBQueryCallback() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _b2$QueryCallback.call.apply(_b2$QueryCallback, [this].concat(args)) || this;
          _this._point = new box2d_1.Vec2();
          _this._isPoint = false;
          _this._fixtures = [];
          return _this;
        }
        var _proto = PhysicsAABBQueryCallback.prototype;
        _proto.init = function init(point) {
          if (point) {
            this._isPoint = true;
            this._point.x = point.x;
            this._point.y = point.y;
          } else {
            this._isPoint = false;
          }
          this._fixtures.length = 0;
        };
        _proto.ReportFixture = function ReportFixture(fixture) {
          if (this._isPoint) {
            if (fixture.TestPoint(this._point)) {
              this._fixtures.push(fixture);
            }
          } else {
            this._fixtures.push(fixture);
          }
          return true;
        };
        _proto.getFixture = function getFixture() {
          return this._fixtures[0];
        };
        _proto.getFixtures = function getFixtures() {
          return this._fixtures;
        };
        return PhysicsAABBQueryCallback;
      }(box2d_1.QueryCallback);

      function At(i, vertices) {
        var s = vertices.length;
        return vertices[i < 0 ? s - -i % s : i % s];
      }
      function Copy(i, j, vertices) {
        var p = [];
        while (j < i) j += vertices.length;
        for (; i <= j; ++i) {
          p.push(At(i, vertices));
        }
        return p;
      }
      function ConvexPartition$1(vertices) {
        ForceCounterClockWise$1(vertices);
        var list = [];
        var d;
        var lowerDist;
        var upperDist;
        var p;
        var lowerInt = new Vec2();
        var upperInt = new Vec2();
        var lowerIndex = 0;
        var upperIndex = 0;
        var lowerPoly;
        var upperPoly;
        for (var i = 0; i < vertices.length; ++i) {
          if (Reflex(i, vertices)) {
            lowerDist = upperDist = 10e7;
            for (var j = 0; j < vertices.length; ++j) {
              if (Left(At(i - 1, vertices), At(i, vertices), At(j, vertices)) && RightOn(At(i - 1, vertices), At(i, vertices), At(j - 1, vertices))) {
                p = LineIntersect(At(i - 1, vertices), At(i, vertices), At(j, vertices), At(j - 1, vertices));
                if (Right(At(i + 1, vertices), At(i, vertices), p)) {
                  d = SquareDist(At(i, vertices), p);
                  if (d < lowerDist) {
                    lowerDist = d;
                    lowerInt = p;
                    lowerIndex = j;
                  }
                }
              }
              if (Left(At(i + 1, vertices), At(i, vertices), At(j + 1, vertices)) && RightOn(At(i + 1, vertices), At(i, vertices), At(j, vertices))) {
                p = LineIntersect(At(i + 1, vertices), At(i, vertices), At(j, vertices), At(j + 1, vertices));
                if (Left(At(i - 1, vertices), At(i, vertices), p)) {
                  d = SquareDist(At(i, vertices), p);
                  if (d < upperDist) {
                    upperDist = d;
                    upperIndex = j;
                    upperInt = p;
                  }
                }
              }
            }
            if (lowerIndex == (upperIndex + 1) % vertices.length) {
              var sp = lowerInt.add(upperInt).multiplyScalar(1 / 2);
              lowerPoly = Copy(i, upperIndex, vertices);
              lowerPoly.push(sp);
              upperPoly = Copy(lowerIndex, i, vertices);
              upperPoly.push(sp);
            } else {
              var highestScore = 0;
              var bestIndex = lowerIndex;
              while (upperIndex < lowerIndex) {
                upperIndex += vertices.length;
              }
              for (var _j = lowerIndex; _j <= upperIndex; ++_j) {
                if (CanSee(i, _j, vertices)) {
                  var score = 1 / (SquareDist(At(i, vertices), At(_j, vertices)) + 1);
                  if (Reflex(_j, vertices)) {
                    if (RightOn(At(_j - 1, vertices), At(_j, vertices), At(i, vertices)) && LeftOn(At(_j + 1, vertices), At(_j, vertices), At(i, vertices))) {
                      score += 3;
                    } else {
                      score += 2;
                    }
                  } else {
                    score += 1;
                  }
                  if (score > highestScore) {
                    bestIndex = _j;
                    highestScore = score;
                  }
                }
              }
              lowerPoly = Copy(i, bestIndex, vertices);
              upperPoly = Copy(bestIndex, i, vertices);
            }
            list = list.concat(ConvexPartition$1(lowerPoly));
            list = list.concat(ConvexPartition$1(upperPoly));
            return list;
          }
        }
        list.push(vertices);
        for (var _i = list.length - 1; _i >= 0; _i--) {
          if (list[_i].length == 0) list.splice(_i, 0);
        }
        return list;
      }
      function CanSee(i, j, vertices) {
        if (Reflex(i, vertices)) {
          if (LeftOn(At(i, vertices), At(i - 1, vertices), At(j, vertices)) && RightOn(At(i, vertices), At(i + 1, vertices), At(j, vertices))) return false;
        } else if (RightOn(At(i, vertices), At(i + 1, vertices), At(j, vertices)) || LeftOn(At(i, vertices), At(i - 1, vertices), At(j, vertices))) return false;
        if (Reflex(j, vertices)) {
          if (LeftOn(At(j, vertices), At(j - 1, vertices), At(i, vertices)) && RightOn(At(j, vertices), At(j + 1, vertices), At(i, vertices))) return false;
        } else if (RightOn(At(j, vertices), At(j + 1, vertices), At(i, vertices)) || LeftOn(At(j, vertices), At(j - 1, vertices), At(i, vertices))) return false;
        for (var k = 0; k < vertices.length; ++k) {
          if ((k + 1) % vertices.length == i || k == i || (k + 1) % vertices.length == j || k == j) {
            continue;
          }
          var intersectionPoint = new Vec2();
          if (LineIntersect2(At(i, vertices), At(j, vertices), At(k, vertices), At(k + 1, vertices), intersectionPoint)) {
            return false;
          }
        }
        return true;
      }
      function Reflex(i, vertices) {
        return Right(i, vertices);
      }
      function Right(a, b, c) {
        if (typeof c === 'undefined') {
          var i = a;
          var vertices = b;
          a = At(i - 1, vertices);
          b = At(i, vertices);
          c = At(i + 1, vertices);
          if (typeof a === 'undefined') {
            a = b;
          }
          if (typeof c === 'undefined') {
            c = b;
          }
        }
        return Area(a, b, c) < 0;
      }
      function Left(a, b, c) {
        return Area(a, b, c) > 0;
      }
      function LeftOn(a, b, c) {
        return Area(a, b, c) >= 0;
      }
      function RightOn(a, b, c) {
        return Area(a, b, c) <= 0;
      }
      function SquareDist(a, b) {
        var dx = b.x - a.x;
        var dy = b.y - a.y;
        return dx * dx + dy * dy;
      }
      function ForceCounterClockWise$1(vertices) {
        if (!IsCounterClockWise(vertices)) {
          vertices.reverse();
        }
      }
      function IsCounterClockWise(vertices) {
        if (vertices.length < 3) return true;
        return GetSignedArea(vertices) > 0;
      }
      function GetSignedArea(vertices) {
        var i;
        var area = 0;
        for (i = 0; i < vertices.length; i++) {
          var j = (i + 1) % vertices.length;
          area += vertices[i].x * vertices[j].y;
          area -= vertices[i].y * vertices[j].x;
        }
        area /= 2;
        return area;
      }
      function LineIntersect(p1, p2, q1, q2) {
        var i = new Vec2();
        var a1 = p2.y - p1.y;
        var b1 = p1.x - p2.x;
        var c1 = a1 * p1.x + b1 * p1.y;
        var a2 = q2.y - q1.y;
        var b2 = q1.x - q2.x;
        var c2 = a2 * q1.x + b2 * q1.y;
        var det = a1 * b2 - a2 * b1;
        if (!FloatEquals(det, 0)) {
          i.x = (b2 * c1 - b1 * c2) / det;
          i.y = (a1 * c2 - a2 * c1) / det;
        }
        return i;
      }
      function LineIntersect2(a0, a1, b0, b1, intersectionPoint) {
        if (a0 == b0 || a0 == b1 || a1 == b0 || a1 == b1) return false;
        var x1 = a0.x;
        var y1 = a0.y;
        var x2 = a1.x;
        var y2 = a1.y;
        var x3 = b0.x;
        var y3 = b0.y;
        var x4 = b1.x;
        var y4 = b1.y;
        if (Math.max(x1, x2) < Math.min(x3, x4) || Math.max(x3, x4) < Math.min(x1, x2)) return false;
        if (Math.max(y1, y2) < Math.min(y3, y4) || Math.max(y3, y4) < Math.min(y1, y2)) return false;
        var ua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);
        var ub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3);
        var denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
        if (Math.abs(denom) < 10e-7) {
          return false;
        }
        ua /= denom;
        ub /= denom;
        if (ua > 0 && ua < 1 && ub > 0 && ub < 1) {
          intersectionPoint.x = x1 + ua * (x2 - x1);
          intersectionPoint.y = y1 + ua * (y2 - y1);
          return true;
        }
        return false;
      }
      function FloatEquals(value1, value2) {
        return Math.abs(value1 - value2) <= 10e-7;
      }
      function Area(a, b, c) {
        return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y);
      }

      var PolygonSeparator = /*#__PURE__*/Object.freeze({
        __proto__: null,
        ConvexPartition: ConvexPartition$1,
        ForceCounterClockWise: ForceCounterClockWise$1,
        IsCounterClockWise: IsCounterClockWise
      });

      function ConvexPartition(polygon) {
        ForceCounterClockWise(polygon);
        var convex = true;
        for (var i = 0, len = polygon.length; i < len; ++i) {
          if (!isConvex(polygon[(i + len - 1) % len], polygon[i], polygon[(i + 1) % len])) {
            convex = false;
            break;
          }
        }
        if (convex) {
          return [polygon];
        }
        var ret = [];
        var triangles = Triangulate(polygon);
        if (!triangles) return null;
        for (; triangles.length;) {
          var poly = triangles.splice(0, 1)[0];
          for (var iPoly = 0, polyLen = poly.length; iPoly < polyLen; ++iPoly) {
            var diag1 = poly[iPoly];
            var diag2 = poly[(iPoly + 1) % polyLen];
            var tri3 = null;
            var iTri2 = 0;
            for (; iTri2 < triangles.length; ++iTri2) {
              var triangle = triangles[iTri2];
              for (var _i = 0; _i < 3; ++_i) {
                var tri1 = triangle[_i];
                var tri2 = triangle[(_i + 1) % 3];
                if (equals(diag1, tri2) && equals(diag2, tri1)) {
                  tri3 = triangle[(_i + 2) % 3];
                  break;
                }
              }
              if (tri3) {
                break;
              }
            }
            if (!tri3) {
              continue;
            }
            if (area(poly[(iPoly + polyLen - 1) % polyLen], diag1, tri3) > 0) {
              continue;
            }
            if (area(tri3, diag2, poly[(iPoly + 2) % polyLen]) > 0) {
              continue;
            }
            var newPoly = [];
            for (var _i2 = (iPoly + 1) % polyLen; _i2 !== iPoly; _i2 = (_i2 + 1) % polyLen) {
              newPoly.push(poly[_i2]);
            }
            newPoly.push(diag1, tri3);
            poly = newPoly;
            polyLen = newPoly.length;
            iPoly = -1;
            triangles.splice(iTri2, 1);
          }
          ret.push(poly);
        }
        return ret;
      }
      var Vertex = function Vertex() {
        this.isActive = false;
        this.isConvex = false;
        this.isEar = false;
        this.point = null;
        this.angleCos = 0;
        this.shouldUpdate = false;
        this.index = 0;
        this.prev = null;
        this.next = null;
      };
      function area(a, b, c) {
        return (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y);
      }
      function isConvex(p1, p2, p3) {
        return area(p1, p2, p3) < 0;
      }
      function equals(a, b) {
        return a.x === b.x && a.y === b.y;
      }
      function isClockwise(polygon) {
        var sum = 0;
        for (var i = 0, len = polygon.length; i < len; ++i) {
          var p1 = polygon[i];
          var p2 = polygon[(i + 1) % len];
          sum += (p2.x - p1.x) * (p2.y + p1.y);
        }
        return sum > 0;
      }
      function ForceCounterClockWise(vertices) {
        if (isClockwise(vertices)) {
          vertices.reverse();
        }
      }
      function updateVertex(vertex, vertices) {
        if (!vertex.shouldUpdate) {
          return;
        }
        vertex.shouldUpdate = false;
        var v1 = vertex.prev.point;
        var v2 = vertex.point;
        var v3 = vertex.next.point;
        vertex.isConvex = isConvex(v1, v2, v3);
        var v1x = v1.x - v2.x;
        var v1y = v1.y - v2.y;
        var v1Len = Math.sqrt(v1x * v1x + v1y * v1y);
        v1x /= v1Len;
        v1y /= v1Len;
        var v3x = v3.x - v2.x;
        var v3y = v3.y - v2.y;
        var v3Len = Math.sqrt(v3x * v3x + v3y * v3y);
        v3x /= v3Len;
        v3y /= v3Len;
        vertex.angleCos = v1x * v3x + v1y * v3y;
        if (vertex.isConvex) {
          vertex.isEar = true;
          for (var i = 0, len = vertices.length; i < len; ++i) {
            var curr = vertices[i];
            if (!curr.isActive || curr === vertex) {
              continue;
            }
            var currentPoint = curr.point;
            if (equals(v1, currentPoint) || equals(v2, currentPoint) || equals(v3, currentPoint)) {
              continue;
            }
            var areaA = area(v1, currentPoint, v2);
            var areaB = area(v2, currentPoint, v3);
            var areaC = area(v3, currentPoint, v1);
            if (areaA > 0 && areaB > 0 && areaC > 0) {
              vertex.isEar = false;
              break;
            }
            if (areaA === 0 && areaB >= 0 && areaC >= 0) {
              if (area(v1, curr.prev.point, v2) > 0 || area(v1, curr.next.point, v2) > 0) {
                vertex.isEar = false;
                break;
              }
            }
            if (areaB === 0 && areaA >= 0 && areaC >= 0) {
              if (area(v2, curr.prev.point, v3) > 0 || area(v2, curr.next.point, v3) > 0) {
                vertex.isEar = false;
                break;
              }
            }
            if (areaC === 0 && areaA >= 0 && areaB >= 0) {
              if (area(v3, curr.prev.point, v1) > 0 || area(v3, curr.next.point, v1) > 0) {
                vertex.isEar = false;
                break;
              }
            }
          }
        } else {
          vertex.isEar = false;
        }
      }
      function removeCollinearOrDuplicate(start) {
        for (var curr = start, end = start;;) {
          if (equals(curr.point, curr.next.point) || area(curr.prev.point, curr.point, curr.next.point) === 0) {
            curr.prev.next = curr.next;
            curr.next.prev = curr.prev;
            curr.prev.shouldUpdate = true;
            curr.next.shouldUpdate = true;
            if (curr === curr.next) {
              break;
            }
            end = curr.prev;
            curr = curr.next;
            continue;
          }
          curr = curr.next;
          if (curr === end) {
            break;
          }
        }
      }
      function Triangulate(polygon) {
        ForceCounterClockWise(polygon);
        if (polygon.length < 4) {
          return [polygon];
        }
        var len = polygon.length;
        var vertices = [];
        var triangles = [];
        for (var i = 0; i < len; ++i) {
          var v = new Vertex();
          v.isActive = true;
          v.isConvex = false;
          v.isEar = false;
          v.point = polygon[i];
          v.angleCos = 0;
          v.shouldUpdate = true;
          v.index = i;
          vertices.push(v);
        }
        for (var _i3 = 0; _i3 < len; ++_i3) {
          var vertex = vertices[_i3];
          vertex.prev = vertices[(_i3 + len - 1) % len];
          vertex.next = vertices[(_i3 + 1) % len];
        }
        vertices.forEach(function (vertex) {
          return updateVertex(vertex, vertices);
        });
        for (var _i4 = 0; _i4 < len - 3; ++_i4) {
          var ear = void 0;
          for (var j = 0; j < len; ++j) {
            var _vertex = vertices[j];
            if (!_vertex.isActive || !_vertex.isEar) {
              continue;
            }
            if (!ear) {
              ear = _vertex;
            } else if (_vertex.angleCos > ear.angleCos) {
              ear = _vertex;
            }
          }
          if (!ear) {
            for (var i_1 = 0; i_1 < len; ++i_1) {
              var _vertex2 = vertices[i_1];
              if (_vertex2.isActive) {
                var p1 = _vertex2.prev.point;
                var p2 = _vertex2.point;
                var p3 = _vertex2.next.point;
                if (Math.abs(area(p1, p2, p3)) > 1e-5) {
                  console.log('Failed to find ear. There might be self-intersection in the polygon.');
                  return null;
                }
              }
            }
            break;
          }
          triangles.push([ear.prev.point, ear.point, ear.next.point]);
          ear.isActive = false;
          ear.prev.next = ear.next;
          ear.next.prev = ear.prev;
          ear.prev.shouldUpdate = true;
          ear.next.shouldUpdate = true;
          removeCollinearOrDuplicate(ear.next);
          if (_i4 === len - 4) {
            break;
          }
          for (var i_2 = 0; i_2 < len; ++i_2) {
            updateVertex(vertices[i_2], vertices);
          }
        }
        for (var _i5 = 0; _i5 < len; ++_i5) {
          var _vertex3 = vertices[_i5];
          if (_vertex3.isActive) {
            _vertex3.prev.isActive = false;
            _vertex3.next.isActive = false;
            var _p = _vertex3.prev.point;
            var _p2 = _vertex3.point;
            var _p3 = _vertex3.next.point;
            if (Math.abs(area(_p, _p2, _p3)) > 1e-5) {
              triangles.push([_p, _p2, _p3]);
            }
          }
        }
        return triangles;
      }

      var PolygonPartition = /*#__PURE__*/Object.freeze({
        __proto__: null,
        ConvexPartition: ConvexPartition
      });

      var ERigidBodyType; exports('g4', ERigidBodyType);
      (function (ERigidBodyType) {
        ERigidBodyType[ERigidBodyType["DYNAMIC"] = 1] = "DYNAMIC";
        ERigidBodyType[ERigidBodyType["STATIC"] = 2] = "STATIC";
        ERigidBodyType[ERigidBodyType["KINEMATIC"] = 4] = "KINEMATIC";
      })(ERigidBodyType || (exports('g4', ERigidBodyType = {})));
      Enum(ERigidBodyType);
      var EAxisDirection; exports('g3', EAxisDirection);
      (function (EAxisDirection) {
        EAxisDirection[EAxisDirection["X_AXIS"] = 0] = "X_AXIS";
        EAxisDirection[EAxisDirection["Y_AXIS"] = 1] = "Y_AXIS";
        EAxisDirection[EAxisDirection["Z_AXIS"] = 2] = "Z_AXIS";
      })(EAxisDirection || (exports('g3', EAxisDirection = {})));
      Enum(EAxisDirection);
      var ED6Axis;
      (function (ED6Axis) {
        ED6Axis[ED6Axis["X"] = 0] = "X";
        ED6Axis[ED6Axis["Y"] = 1] = "Y";
        ED6Axis[ED6Axis["Z"] = 2] = "Z";
        ED6Axis[ED6Axis["SWING1"] = 3] = "SWING1";
        ED6Axis[ED6Axis["SWING2"] = 4] = "SWING2";
        ED6Axis[ED6Axis["TWIST"] = 5] = "TWIST";
      })(ED6Axis || (ED6Axis = {}));
      Enum(ED6Axis);
      var ESimplexType;
      (function (ESimplexType) {
        ESimplexType[ESimplexType["VERTEX"] = 1] = "VERTEX";
        ESimplexType[ESimplexType["LINE"] = 2] = "LINE";
        ESimplexType[ESimplexType["TRIANGLE"] = 3] = "TRIANGLE";
        ESimplexType[ESimplexType["TETRAHEDRON"] = 4] = "TETRAHEDRON";
      })(ESimplexType || (ESimplexType = {}));
      Enum(ESimplexType);
      var EColliderType; exports('g5', EColliderType);
      (function (EColliderType) {
        EColliderType[EColliderType["BOX"] = 0] = "BOX";
        EColliderType[EColliderType["SPHERE"] = 1] = "SPHERE";
        EColliderType[EColliderType["CAPSULE"] = 2] = "CAPSULE";
        EColliderType[EColliderType["CYLINDER"] = 3] = "CYLINDER";
        EColliderType[EColliderType["CONE"] = 4] = "CONE";
        EColliderType[EColliderType["MESH"] = 5] = "MESH";
        EColliderType[EColliderType["PLANE"] = 6] = "PLANE";
        EColliderType[EColliderType["SIMPLEX"] = 7] = "SIMPLEX";
        EColliderType[EColliderType["TERRAIN"] = 8] = "TERRAIN";
      })(EColliderType || (exports('g5', EColliderType = {})));
      Enum(EColliderType);
      var EConstraintType;
      (function (EConstraintType) {
        EConstraintType[EConstraintType["POINT_TO_POINT"] = 0] = "POINT_TO_POINT";
        EConstraintType[EConstraintType["HINGE"] = 1] = "HINGE";
        EConstraintType[EConstraintType["FIXED"] = 2] = "FIXED";
        EConstraintType[EConstraintType["CONFIGURABLE"] = 3] = "CONFIGURABLE";
      })(EConstraintType || (EConstraintType = {}));
      Enum(EConstraintType);
      var EConstraintMode;
      (function (EConstraintMode) {
        EConstraintMode[EConstraintMode["FREE"] = 0] = "FREE";
        EConstraintMode[EConstraintMode["LIMITED"] = 1] = "LIMITED";
        EConstraintMode[EConstraintMode["LOCKED"] = 2] = "LOCKED";
      })(EConstraintMode || (EConstraintMode = {}));
      Enum(EConstraintMode);
      var EDriverMode;
      (function (EDriverMode) {
        EDriverMode[EDriverMode["DISABLED"] = 0] = "DISABLED";
        EDriverMode[EDriverMode["SERVO"] = 1] = "SERVO";
        EDriverMode[EDriverMode["INDUCTION"] = 2] = "INDUCTION";
      })(EDriverMode || (EDriverMode = {}));
      Enum(EDriverMode);
      var ECharacterControllerType;
      (function (ECharacterControllerType) {
        ECharacterControllerType[ECharacterControllerType["BOX"] = 0] = "BOX";
        ECharacterControllerType[ECharacterControllerType["CAPSULE"] = 1] = "CAPSULE";
      })(ECharacterControllerType || (ECharacterControllerType = {}));
      Enum(ECharacterControllerType);
      var PhysicsGroup;
      (function (PhysicsGroup) {
        PhysicsGroup[PhysicsGroup["DEFAULT"] = 1] = "DEFAULT";
      })(PhysicsGroup || (PhysicsGroup = {}));
      Enum(PhysicsGroup);
      var EPhysicsDrawFlags; exports('g6', EPhysicsDrawFlags);
      (function (EPhysicsDrawFlags) {
        EPhysicsDrawFlags[EPhysicsDrawFlags["NONE"] = 0] = "NONE";
        EPhysicsDrawFlags[EPhysicsDrawFlags["WIRE_FRAME"] = 1] = "WIRE_FRAME";
        EPhysicsDrawFlags[EPhysicsDrawFlags["CONSTRAINT"] = 2] = "CONSTRAINT";
        EPhysicsDrawFlags[EPhysicsDrawFlags["AABB"] = 4] = "AABB";
      })(EPhysicsDrawFlags || (exports('g6', EPhysicsDrawFlags = {})));
      Enum(EPhysicsDrawFlags);

      var CollisionMatrix = function CollisionMatrix(strategy) {
        if (strategy === 1) {
          var self = this;
          var _loop = function _loop(i) {
            var key = "_" + (1 << i);
            self[key] = 0;
            self.updateArray = [];
            Object.defineProperty(self, 1 << i, {
              get: function get() {
                return this[key];
              },
              set: function set(v) {
                if (this[key] !== v) {
                  this[key] = v;
                  if (this.updateArray.indexOf(i) < 0) {
                    this.updateArray.push(i);
                  }
                }
              }
            });
          };
          for (var i = 0; i < 32; i++) {
            _loop(i);
          }
          this['_1'] = PhysicsGroup.DEFAULT;
        } else {
          for (var _i = 0; _i < 32; _i++) {
            var key = 1 << _i;
            this["" + key] = 0;
          }
          this['1'] = PhysicsGroup.DEFAULT;
        }
      };

      var instance = null;
      legacyCC.internal.PhysicsGroup2D = PhysicsGroup$1;
      var PhysicsSystem2D = exports('fq', function (_Eventify) {
        _inheritsLoose(PhysicsSystem2D, _Eventify);
        function PhysicsSystem2D() {
          var _settings$querySettin, _settings$querySettin2, _settings$querySettin3, _settings$querySettin4;
          var _this;
          _this = _Eventify.call(this) || this;
          _this.velocityIterations = 10;
          _this.positionIterations = 10;
          _this.collisionMatrix = new CollisionMatrix();
          _this._enable = true;
          _this._allowSleep = true;
          _this._maxSubSteps = 1;
          _this._fixedTimeStep = 1.0 / 60.0;
          _this._autoSimulation = true;
          _this._accumulator = 0;
          _this._steping = false;
          _this._gravity = new Vec2(0, -10 * PHYSICS_2D_PTM_RATIO);
          _this._delayEvents = [];
          var gravity = settings.querySettings(Settings.Category.PHYSICS, 'gravity');
          if (gravity) {
            Vec2.copy(_this._gravity, gravity);
            _this._gravity.multiplyScalar(PHYSICS_2D_PTM_RATIO);
          }
          _this._allowSleep = (_settings$querySettin = settings.querySettings(Settings.Category.PHYSICS, 'allowSleep')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : _this._allowSleep;
          _this._fixedTimeStep = (_settings$querySettin2 = settings.querySettings(Settings.Category.PHYSICS, 'fixedTimeStep')) !== null && _settings$querySettin2 !== void 0 ? _settings$querySettin2 : _this._fixedTimeStep;
          _this._maxSubSteps = (_settings$querySettin3 = settings.querySettings(Settings.Category.PHYSICS, 'maxSubSteps')) !== null && _settings$querySettin3 !== void 0 ? _settings$querySettin3 : _this._maxSubSteps;
          _this._autoSimulation = (_settings$querySettin4 = settings.querySettings(Settings.Category.PHYSICS, 'autoSimulation')) !== null && _settings$querySettin4 !== void 0 ? _settings$querySettin4 : _this._autoSimulation;
          var collisionMatrix = settings.querySettings(Settings.Category.PHYSICS, 'collisionMatrix');
          if (collisionMatrix) {
            for (var i in collisionMatrix) {
              var bit = parseInt(i);
              var value = 1 << parseInt(i);
              _this.collisionMatrix["" + value] = collisionMatrix[bit];
            }
          }
          var collisionGroups = settings.querySettings(Settings.Category.PHYSICS, 'collisionGroups');
          if (collisionGroups) {
            var cg = collisionGroups;
            if (cg instanceof Array) {
              cg.forEach(function (v) {
                PhysicsGroup$1[v.name] = 1 << v.index;
              });
              Enum.update(PhysicsGroup$1);
            }
          }
          var mutableSelector = selector$1;
          mutableSelector.physicsWorld = createPhysicsWorld$1();
          _this.gravity = _this._gravity;
          _this.allowSleep = _this._allowSleep;
          return _this;
        }
        var _proto = PhysicsSystem2D.prototype;
        _proto.postUpdate = function postUpdate(deltaTime) {
          if (!this._enable) {
            return;
          }
          if (!this._autoSimulation) {
            return;
          }
          director.emit(Director.EVENT_BEFORE_PHYSICS);
          this.physicsWorld.syncSceneToPhysics();
          this._steping = true;
          var fixedTimeStep = this._fixedTimeStep;
          var velocityIterations = this.velocityIterations;
          var positionIterations = this.positionIterations;
          this._accumulator += deltaTime;
          var substepIndex = 0;
          while (substepIndex++ < this._maxSubSteps && this._accumulator > fixedTimeStep) {
            this.physicsWorld.step(fixedTimeStep, velocityIterations, positionIterations);
            this._accumulator -= fixedTimeStep;
          }
          var events = this._delayEvents;
          for (var i = 0, l = events.length; i < l; i++) {
            var event = events[i];
            event.func.call(event.target);
          }
          events.length = 0;
          this.physicsWorld.syncPhysicsToScene();
          if (this.debugDrawFlags) {
            this.physicsWorld.drawDebug();
          }
          this._steping = false;
          director.emit(Director.EVENT_AFTER_PHYSICS);
        };
        _proto._callAfterStep = function _callAfterStep(target, func) {
          if (this._steping) {
            this._delayEvents.push({
              target: target,
              func: func
            });
          } else {
            func.call(target);
          }
        };
        _proto.resetAccumulator = function resetAccumulator(time) {
          if (time === void 0) {
            time = 0;
          }
          this._accumulator = time;
        };
        _proto.step = function step(fixedTimeStep) {
          this.physicsWorld.step(fixedTimeStep, this.velocityIterations, this.positionIterations);
        };
        _proto.raycast = function raycast(p1, p2, type, mask) {
          if (type === void 0) {
            type = ERaycast2DType.Closest;
          }
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          return this.physicsWorld.raycast(p1, p2, type, mask);
        };
        _proto.testPoint = function testPoint(p) {
          return this.physicsWorld.testPoint(p);
        };
        _proto.testAABB = function testAABB(rect) {
          return this.physicsWorld.testAABB(rect);
        };
        PhysicsSystem2D.constructAndRegister = function constructAndRegister() {
          director.registerSystem(PhysicsSystem2D.ID, PhysicsSystem2D.instance, System.Priority.LOW);
        };
        _createClass(PhysicsSystem2D, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(value) {
            this._enable = value;
          }
        }, {
          key: "allowSleep",
          get: function get() {
            return this._allowSleep;
          },
          set: function set(v) {
            this._allowSleep = v;
            {
              this.physicsWorld.setAllowSleep(v);
            }
          }
        }, {
          key: "gravity",
          get: function get() {
            return this._gravity;
          },
          set: function set(gravity) {
            this._gravity.set(gravity);
            {
              this.physicsWorld.setGravity(new Vec2(gravity.x / PHYSICS_2D_PTM_RATIO, gravity.y / PHYSICS_2D_PTM_RATIO));
            }
          }
        }, {
          key: "maxSubSteps",
          get: function get() {
            return this._maxSubSteps;
          },
          set: function set(value) {
            this._maxSubSteps = value;
          }
        }, {
          key: "fixedTimeStep",
          get: function get() {
            return this._fixedTimeStep;
          },
          set: function set(value) {
            this._fixedTimeStep = value;
          }
        }, {
          key: "autoSimulation",
          get: function get() {
            return this._autoSimulation;
          },
          set: function set(value) {
            this._autoSimulation = value;
          }
        }, {
          key: "debugDrawFlags",
          get: function get() {
            return this.physicsWorld.debugDrawFlags;
          },
          set: function set(v) {
            this.physicsWorld.debugDrawFlags = v;
          }
        }, {
          key: "physicsWorld",
          get: function get() {
            return selector$1.physicsWorld;
          }
        }, {
          key: "stepping",
          get: function get() {
            return this._steping;
          }
        }], [{
          key: "PHYSICS_NONE",
          get: function get() {
            return !selector$1.id;
          }
        }, {
          key: "PHYSICS_BUILTIN",
          get: function get() {
            return selector$1.id === 'builtin';
          }
        }, {
          key: "PHYSICS_BOX2D",
          get: function get() {
            return selector$1.id === 'box2d';
          }
        }, {
          key: "PHYSICS_BOX2D_WASM",
          get: function get() {
            return selector$1.id === 'box2d-wasm';
          }
        }, {
          key: "PhysicsGroup",
          get: function get() {
            return PhysicsGroup$1;
          }
        }, {
          key: "instance",
          get: function get() {
            if (!instance) {
              instance = new PhysicsSystem2D();
            }
            return instance;
          }
        }]);
        return PhysicsSystem2D;
      }(Eventify(System)));
      PhysicsSystem2D.ID = 'PHYSICS_2D';
      director.once(Director.EVENT_INIT, function () {
        PhysicsSystem2D.constructAndRegister();
      });

      var Physics2DManifoldType; exports('fr', Physics2DManifoldType);
      (function (Physics2DManifoldType) {
        Physics2DManifoldType[Physics2DManifoldType["Circles"] = 0] = "Circles";
        Physics2DManifoldType[Physics2DManifoldType["FaceA"] = 1] = "FaceA";
        Physics2DManifoldType[Physics2DManifoldType["FaceB"] = 2] = "FaceB";
      })(Physics2DManifoldType || (exports('fr', Physics2DManifoldType = {})));

      var _dec$13, _dec2$_, _dec3$L, _dec4$z, _dec5$w, _dec6$k, _dec7$h, _dec8$b, _dec9$9, _dec10$5, _class$12, _class2$_, _initializer$Y, _initializer2$S, _initializer3$D, _initializer4$v, _initializer5$o, _initializer6$k, _initializer7$g, _initializer8$e, _initializer9$c, _initializer10$b, _initializer11$b, _initializer12$9;
      var type$2 = type$d,
        ccclass$d = ccclass$M;
      var RigidBody2D = exports('fs', (_dec$13 = ccclass$d('cc.RigidBody2D'), _dec2$_ = type$2(PhysicsGroup), _dec3$L = type$2(ERigidBody2DType), _dec4$z = type$2(CCBoolean), _dec5$w = type$2(CCFloat), _dec6$k = type$2(CCFloat), _dec7$h = type$2(CCFloat), _dec8$b = type$2(Vec2), _dec9$9 = type$2(CCFloat), _dec10$5 = type$2(CCBoolean), _dec$13(_class$12 = (_class2$_ = function (_Component) {
        _inheritsLoose(RigidBody2D, _Component);
        function RigidBody2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.enabledContactListener = _initializer$Y && _initializer$Y();
          _this.bullet = _initializer2$S && _initializer2$S();
          _this.awakeOnLoad = _initializer3$D && _initializer3$D();
          _this._body = null;
          _this._group = _initializer4$v && _initializer4$v();
          _this._type = _initializer5$o && _initializer5$o();
          _this._allowSleep = _initializer6$k && _initializer6$k();
          _this._gravityScale = _initializer7$g && _initializer7$g();
          _this._linearDamping = _initializer8$e && _initializer8$e();
          _this._angularDamping = _initializer9$c && _initializer9$c();
          _this._linearVelocity = _initializer10$b && _initializer10$b();
          _this._angularVelocity = _initializer11$b && _initializer11$b();
          _this._fixedRotation = _initializer12$9 && _initializer12$9();
          return _this;
        }
        var _proto = RigidBody2D.prototype;
        _proto.isAwake = function isAwake() {
          if (this._body) {
            return this._body.isAwake;
          }
          return false;
        };
        _proto.wakeUp = function wakeUp() {
          if (this._body) {
            this._body.wakeUp();
          }
        };
        _proto.sleep = function sleep() {
          if (this._body) {
            this._body.sleep();
          }
        };
        _proto.getMass = function getMass() {
          if (this._body) {
            return this._body.getMass();
          }
          return 0;
        };
        _proto.applyForce = function applyForce(force, point, wake) {
          if (this._body) {
            this._body.applyForce(force, point, wake);
          }
        };
        _proto.applyForceToCenter = function applyForceToCenter(force, wake) {
          if (this._body) {
            this._body.applyForceToCenter(force, wake);
          }
        };
        _proto.applyTorque = function applyTorque(torque, wake) {
          if (this._body) {
            this._body.applyTorque(torque, wake);
          }
        };
        _proto.applyLinearImpulse = function applyLinearImpulse(impulse, point, wake) {
          if (this._body) {
            this._body.applyLinearImpulse(impulse, point, wake);
          }
        };
        _proto.applyLinearImpulseToCenter = function applyLinearImpulseToCenter(impulse, wake) {
          if (this._body) {
            this._body.applyLinearImpulseToCenter(impulse, wake);
          }
        };
        _proto.applyAngularImpulse = function applyAngularImpulse(impulse, wake) {
          if (this._body) {
            this._body.applyAngularImpulse(impulse, wake);
          }
        };
        _proto.getLinearVelocityFromWorldPoint = function getLinearVelocityFromWorldPoint(worldPoint, out) {
          if (this._body) {
            return this._body.getLinearVelocityFromWorldPoint(worldPoint, out);
          }
          return out;
        };
        _proto.getLocalVector = function getLocalVector(worldVector, out) {
          if (this._body) {
            return this._body.getLocalVector(worldVector, out);
          }
          return out;
        };
        _proto.getWorldVector = function getWorldVector(localVector, out) {
          if (this._body) {
            return this._body.getWorldVector(localVector, out);
          }
          return out;
        };
        _proto.getLocalPoint = function getLocalPoint(worldPoint, out) {
          if (this._body) {
            return this._body.getLocalPoint(worldPoint, out);
          }
          return out;
        };
        _proto.getWorldPoint = function getWorldPoint(localPoint, out) {
          if (this._body) {
            return this._body.getWorldPoint(localPoint, out);
          }
          return out;
        };
        _proto.getLocalCenter = function getLocalCenter(out) {
          if (this._body) {
            return this._body.getLocalCenter(out);
          }
          return out;
        };
        _proto.getWorldCenter = function getWorldCenter(out) {
          if (this._body) {
            return this._body.getWorldCenter(out);
          }
          return out;
        };
        _proto.getInertia = function getInertia() {
          if (this._body) {
            return this._body.getInertia();
          }
          return 0;
        };
        _proto.onLoad = function onLoad() {
          {
            this._body = createRigidBody$1();
            this._body.initialize(this);
          }
        };
        _proto.onEnable = function onEnable() {
          if (this._body) {
            this._body.onEnable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._body) {
            this._body.onDisable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._body) {
            this._body.onDestroy();
          }
        };
        _createClass(RigidBody2D, [{
          key: "group",
          get: function get() {
            return this._group;
          },
          set: function set(v) {
            this._group = v;
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(v) {
            this._type = v;
            if (this._body) {
              if (v === ERigidBody2DType.Animated) {
                this._body.setType(ERigidBody2DType.Kinematic);
              } else {
                this._body.setType(v);
              }
            }
          }
        }, {
          key: "allowSleep",
          get: function get() {
            return this._allowSleep;
          },
          set: function set(v) {
            this._allowSleep = v;
            if (this._body) {
              this._body.setAllowSleep(v);
            }
          }
        }, {
          key: "gravityScale",
          get: function get() {
            return this._gravityScale;
          },
          set: function set(v) {
            this._gravityScale = v;
            if (this._body) {
              this._body.setGravityScale(v);
            }
          }
        }, {
          key: "linearDamping",
          get: function get() {
            return this._linearDamping;
          },
          set: function set(v) {
            this._linearDamping = v;
            if (this._body) {
              this._body.setLinearDamping(v);
            }
          }
        }, {
          key: "angularDamping",
          get: function get() {
            return this._angularDamping;
          },
          set: function set(v) {
            this._angularDamping = v;
            if (this._body) {
              this._body.setAngularDamping(v);
            }
          }
        }, {
          key: "linearVelocity",
          get: function get() {
            if (this._body) {
              this._body.getLinearVelocity(this._linearVelocity);
            }
            return this._linearVelocity;
          },
          set: function set(v) {
            this._linearVelocity = v;
            if (this._body) {
              this._body.setLinearVelocity(v);
            }
          }
        }, {
          key: "angularVelocity",
          get: function get() {
            if (this._body) {
              this._angularVelocity = this._body.getAngularVelocity();
            }
            return this._angularVelocity;
          },
          set: function set(v) {
            this._angularVelocity = v;
            if (this._body) {
              this._body.setAngularVelocity(v);
            }
          }
        }, {
          key: "fixedRotation",
          get: function get() {
            return this._fixedRotation;
          },
          set: function set(v) {
            this._fixedRotation = v;
            if (this._body) {
              this._body.setFixedRotation(v);
            }
          }
        }, {
          key: "impl",
          get: function get() {
            return this._body;
          }
        }]);
        return RigidBody2D;
      }(Component), (_applyDecoratedDescriptor(_class2$_.prototype, "group", [_dec2$_], Object.getOwnPropertyDescriptor(_class2$_.prototype, "group"), _class2$_.prototype), _initializer$Y = applyDecoratedInitializer(_class2$_.prototype, "enabledContactListener", [serializable$p], function () {
        return false;
      }), _initializer2$S = applyDecoratedInitializer(_class2$_.prototype, "bullet", [serializable$p], function () {
        return false;
      }), _applyDecoratedDescriptor(_class2$_.prototype, "type", [_dec3$L], Object.getOwnPropertyDescriptor(_class2$_.prototype, "type"), _class2$_.prototype), _applyDecoratedDescriptor(_class2$_.prototype, "allowSleep", [_dec4$z], Object.getOwnPropertyDescriptor(_class2$_.prototype, "allowSleep"), _class2$_.prototype), _applyDecoratedDescriptor(_class2$_.prototype, "gravityScale", [_dec5$w], Object.getOwnPropertyDescriptor(_class2$_.prototype, "gravityScale"), _class2$_.prototype), _applyDecoratedDescriptor(_class2$_.prototype, "linearDamping", [_dec6$k], Object.getOwnPropertyDescriptor(_class2$_.prototype, "linearDamping"), _class2$_.prototype), _applyDecoratedDescriptor(_class2$_.prototype, "angularDamping", [_dec7$h], Object.getOwnPropertyDescriptor(_class2$_.prototype, "angularDamping"), _class2$_.prototype), _applyDecoratedDescriptor(_class2$_.prototype, "linearVelocity", [_dec8$b], Object.getOwnPropertyDescriptor(_class2$_.prototype, "linearVelocity"), _class2$_.prototype), _applyDecoratedDescriptor(_class2$_.prototype, "angularVelocity", [_dec9$9], Object.getOwnPropertyDescriptor(_class2$_.prototype, "angularVelocity"), _class2$_.prototype), _applyDecoratedDescriptor(_class2$_.prototype, "fixedRotation", [_dec10$5], Object.getOwnPropertyDescriptor(_class2$_.prototype, "fixedRotation"), _class2$_.prototype), _initializer3$D = applyDecoratedInitializer(_class2$_.prototype, "awakeOnLoad", [serializable$p], function () {
        return true;
      }), _initializer4$v = applyDecoratedInitializer(_class2$_.prototype, "_group", [serializable$p], function () {
        return PhysicsGroup.DEFAULT;
      }), _initializer5$o = applyDecoratedInitializer(_class2$_.prototype, "_type", [serializable$p], function () {
        return ERigidBody2DType.Dynamic;
      }), _initializer6$k = applyDecoratedInitializer(_class2$_.prototype, "_allowSleep", [serializable$p], function () {
        return true;
      }), _initializer7$g = applyDecoratedInitializer(_class2$_.prototype, "_gravityScale", [serializable$p], function () {
        return 1;
      }), _initializer8$e = applyDecoratedInitializer(_class2$_.prototype, "_linearDamping", [serializable$p], function () {
        return 0;
      }), _initializer9$c = applyDecoratedInitializer(_class2$_.prototype, "_angularDamping", [serializable$p], function () {
        return 0;
      }), _initializer10$b = applyDecoratedInitializer(_class2$_.prototype, "_linearVelocity", [serializable$p], function () {
        return new Vec2();
      }), _initializer11$b = applyDecoratedInitializer(_class2$_.prototype, "_angularVelocity", [serializable$p], function () {
        return 0;
      }), _initializer12$9 = applyDecoratedInitializer(_class2$_.prototype, "_fixedRotation", [serializable$p], function () {
        return false;
      })), _class2$_)) || _class$12));

      var _dec$12, _dec2$Z, _dec3$K, _dec4$y, _dec5$v, _dec6$j, _dec7$g, _dec8$a, _class$11, _class2$Z, _initializer$X, _initializer2$R, _initializer3$C, _initializer4$u, _initializer5$n, _initializer6$j, _initializer7$f;
      var ccclass$c = ccclass$M,
        type$1 = type$d;
      var Collider2D = exports('ft', (_dec$12 = ccclass$c('cc.Collider2D'), _dec2$Z = type$1(CCFloat), _dec3$K = type$1(PhysicsGroup), _dec4$y = type$1(CCFloat), _dec5$v = type$1(CCBoolean), _dec6$j = type$1(CCFloat), _dec7$g = type$1(CCFloat), _dec8$a = type$1(Vec2), _dec$12(_class$11 = (_class2$Z = function (_Eventify) {
        _inheritsLoose(Collider2D, _Eventify);
        function Collider2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Eventify.call.apply(_Eventify, [this].concat(args)) || this;
          _this.editing = false;
          _this.tag = _initializer$X && _initializer$X();
          _this.TYPE = ECollider2DType.None;
          _this._shape = null;
          _this._body = null;
          _this._group = _initializer2$R && _initializer2$R();
          _this._density = _initializer3$C && _initializer3$C();
          _this._sensor = _initializer4$u && _initializer4$u();
          _this._friction = _initializer5$n && _initializer5$n();
          _this._restitution = _initializer6$j && _initializer6$j();
          _this._offset = _initializer7$f && _initializer7$f();
          return _this;
        }
        var _proto = Collider2D.prototype;
        _proto.onLoad = function onLoad() {
          {
            this._shape = createShape$1(this.TYPE);
            this._shape.initialize(this);
            if (this._shape.onLoad) {
              this._shape.onLoad();
            }
            this._body = this.getComponent(RigidBody2D);
          }
        };
        _proto.onEnable = function onEnable() {
          if (this._shape) {
            this._shape.onEnable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._shape && this._shape.onDisable) {
            this._shape.onDisable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._shape && this._shape.onDestroy) {
            this._shape.onDestroy();
          }
        };
        _proto.apply = function apply() {
          if (this._shape && this._shape.apply) {
            this._shape.apply();
          }
        };
        _createClass(Collider2D, [{
          key: "group",
          get: function get() {
            return this._group;
          },
          set: function set(v) {
            this._group = v;
            if (this._shape && this._shape.onGroupChanged) {
              this._shape.onGroupChanged();
            }
          }
        }, {
          key: "density",
          get: function get() {
            return this._density;
          },
          set: function set(v) {
            this._density = v;
          }
        }, {
          key: "sensor",
          get: function get() {
            return this._sensor;
          },
          set: function set(v) {
            this._sensor = v;
          }
        }, {
          key: "friction",
          get: function get() {
            return this._friction;
          },
          set: function set(v) {
            this._friction = v;
          }
        }, {
          key: "restitution",
          get: function get() {
            return this._restitution;
          },
          set: function set(v) {
            this._restitution = v;
          }
        }, {
          key: "offset",
          get: function get() {
            return this._offset;
          },
          set: function set(v) {
            this._offset = v;
          }
        }, {
          key: "body",
          get: function get() {
            return this._body;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._shape;
          }
        }, {
          key: "worldAABB",
          get: function get() {
            if (this._shape) {
              return this._shape.worldAABB;
            }
            return new Rect$1();
          }
        }]);
        return Collider2D;
      }(Eventify(Component)), (_initializer$X = applyDecoratedInitializer(_class2$Z.prototype, "tag", [_dec2$Z, serializable$p], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$Z.prototype, "group", [_dec3$K], Object.getOwnPropertyDescriptor(_class2$Z.prototype, "group"), _class2$Z.prototype), _applyDecoratedDescriptor(_class2$Z.prototype, "density", [_dec4$y], Object.getOwnPropertyDescriptor(_class2$Z.prototype, "density"), _class2$Z.prototype), _applyDecoratedDescriptor(_class2$Z.prototype, "sensor", [_dec5$v], Object.getOwnPropertyDescriptor(_class2$Z.prototype, "sensor"), _class2$Z.prototype), _applyDecoratedDescriptor(_class2$Z.prototype, "friction", [_dec6$j], Object.getOwnPropertyDescriptor(_class2$Z.prototype, "friction"), _class2$Z.prototype), _applyDecoratedDescriptor(_class2$Z.prototype, "restitution", [_dec7$g], Object.getOwnPropertyDescriptor(_class2$Z.prototype, "restitution"), _class2$Z.prototype), _applyDecoratedDescriptor(_class2$Z.prototype, "offset", [_dec8$a], Object.getOwnPropertyDescriptor(_class2$Z.prototype, "offset"), _class2$Z.prototype), _initializer2$R = applyDecoratedInitializer(_class2$Z.prototype, "_group", [serializable$p], function () {
        return PhysicsGroup.DEFAULT;
      }), _initializer3$C = applyDecoratedInitializer(_class2$Z.prototype, "_density", [serializable$p], function () {
        return 1.0;
      }), _initializer4$u = applyDecoratedInitializer(_class2$Z.prototype, "_sensor", [serializable$p], function () {
        return false;
      }), _initializer5$n = applyDecoratedInitializer(_class2$Z.prototype, "_friction", [serializable$p], function () {
        return 0.2;
      }), _initializer6$j = applyDecoratedInitializer(_class2$Z.prototype, "_restitution", [serializable$p], function () {
        return 0;
      }), _initializer7$f = applyDecoratedInitializer(_class2$Z.prototype, "_offset", [serializable$p], function () {
        return new Vec2();
      })), _class2$Z)) || _class$11));

      var _dec$11, _dec2$Y, _class$10, _class2$Y, _initializer$W;
      var ccclass$b = ccclass$M;
      var BoxCollider2D = exports('fu', (_dec$11 = ccclass$b('cc.BoxCollider2D'), _dec2$Y = type$d(Size$1), _dec$11(_class$10 = (_class2$Y = function (_Collider2D) {
        _inheritsLoose(BoxCollider2D, _Collider2D);
        function BoxCollider2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Collider2D.call.apply(_Collider2D, [this].concat(args)) || this;
          _this._size = _initializer$W && _initializer$W();
          _this.TYPE = ECollider2DType.BOX;
          return _this;
        }
        _createClass(BoxCollider2D, [{
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(v) {
            this._size = v;
          }
        }, {
          key: "worldPoints",
          get: function get() {
            if (this._shape) {
              return this._shape.worldPoints;
            }
            return [];
          }
        }]);
        return BoxCollider2D;
      }(Collider2D), (_initializer$W = applyDecoratedInitializer(_class2$Y.prototype, "_size", [serializable$p], function () {
        return new Size$1(1, 1);
      }), _applyDecoratedDescriptor(_class2$Y.prototype, "size", [_dec2$Y], Object.getOwnPropertyDescriptor(_class2$Y.prototype, "size"), _class2$Y.prototype)), _class2$Y)) || _class$10));

      var _dec$10, _dec2$X, _class$$, _class2$X, _initializer$V;
      var ccclass$a = ccclass$M;
      var CircleCollider2D = exports('fv', (_dec$10 = ccclass$a('cc.CircleCollider2D'), _dec2$X = type$d(CCFloat), _dec$10(_class$$ = (_class2$X = function (_Collider2D) {
        _inheritsLoose(CircleCollider2D, _Collider2D);
        function CircleCollider2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Collider2D.call.apply(_Collider2D, [this].concat(args)) || this;
          _this._radius = _initializer$V && _initializer$V();
          _this.TYPE = ECollider2DType.CIRCLE;
          return _this;
        }
        _createClass(CircleCollider2D, [{
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(v) {
            this._radius = v < 0 ? 0 : v;
          }
        }, {
          key: "worldPosition",
          get: function get() {
            if (this._shape) {
              return this._shape.worldPosition;
            }
            return new Vec2();
          }
        }, {
          key: "worldRadius",
          get: function get() {
            if (this._shape) {
              return this._shape.worldRadius;
            }
            return 0;
          }
        }]);
        return CircleCollider2D;
      }(Collider2D), (_initializer$V = applyDecoratedInitializer(_class2$X.prototype, "_radius", [serializable$p], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$X.prototype, "radius", [_dec2$X], Object.getOwnPropertyDescriptor(_class2$X.prototype, "radius"), _class2$X.prototype)), _class2$X)) || _class$$));

      var _dec$$, _dec2$W, _dec3$J, _class$_, _class2$W, _initializer$U, _initializer2$Q;
      var ccclass$9 = ccclass$M;
      var PolygonCollider2D = exports('fw', (_dec$$ = ccclass$9('cc.PolygonCollider2D'), _dec2$W = type$d(CCFloat), _dec3$J = type$d([Vec2]), _dec$$(_class$_ = (_class2$W = function (_Collider2D) {
        _inheritsLoose(PolygonCollider2D, _Collider2D);
        function PolygonCollider2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Collider2D.call.apply(_Collider2D, [this].concat(args)) || this;
          _this.threshold = _initializer$U && _initializer$U();
          _this._points = _initializer2$Q && _initializer2$Q();
          _this.TYPE = ECollider2DType.POLYGON;
          return _this;
        }
        _createClass(PolygonCollider2D, [{
          key: "points",
          get: function get() {
            return this._points;
          },
          set: function set(v) {
            this._points = v;
          }
        }, {
          key: "worldPoints",
          get: function get() {
            if (this._shape) {
              return this._shape.worldPoints;
            }
            return [];
          }
        }]);
        return PolygonCollider2D;
      }(Collider2D), (_initializer$U = applyDecoratedInitializer(_class2$W.prototype, "threshold", [_dec2$W], function () {
        return 1;
      }), _initializer2$Q = applyDecoratedInitializer(_class2$W.prototype, "_points", [serializable$p], function () {
        return [new Vec2(-1, -1), new Vec2(1, -1), new Vec2(1, 1), new Vec2(-1, 1)];
      }), _applyDecoratedDescriptor(_class2$W.prototype, "points", [_dec3$J], Object.getOwnPropertyDescriptor(_class2$W.prototype, "points"), _class2$W.prototype)), _class2$W)) || _class$_));

      var _dec$_, _dec2$V, _class$Z, _class2$V, _initializer$T, _initializer2$P, _initializer3$B, _initializer4$t;
      var ccclass$8 = ccclass$M,
        type = type$d;
      var Joint2D = exports('fx', (_dec$_ = ccclass$8('cc.Joint2D'), _dec2$V = type(RigidBody2D), _dec$_(_class$Z = (_class2$V = function (_Component) {
        _inheritsLoose(Joint2D, _Component);
        function Joint2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.anchor = _initializer$T && _initializer$T();
          _this.connectedAnchor = _initializer2$P && _initializer2$P();
          _this.collideConnected = _initializer3$B && _initializer3$B();
          _this.connectedBody = _initializer4$t && _initializer4$t();
          _this._body = null;
          _this._joint = null;
          _this.TYPE = EJoint2DType.None;
          return _this;
        }
        var _proto = Joint2D.prototype;
        _proto.onLoad = function onLoad() {
          {
            this._joint = createJoint(this.TYPE);
            this._joint.initialize(this);
            this._body = this.getComponent(RigidBody2D);
          }
        };
        _proto.onEnable = function onEnable() {
          if (this._joint && this._joint.onEnable) {
            this._joint.onEnable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._joint && this._joint.onDisable) {
            this._joint.onDisable();
          }
        };
        _proto.start = function start() {
          if (this._joint && this._joint.start) {
            this._joint.start();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._joint && this._joint.onDestroy) {
            this._joint.onDestroy();
          }
        };
        _proto.apply = function apply() {
          if (this._joint && this._joint.apply) {
            this._joint.apply();
          }
        };
        _createClass(Joint2D, [{
          key: "body",
          get: function get() {
            return this._body;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._joint;
          }
        }]);
        return Joint2D;
      }(Component), (_initializer$T = applyDecoratedInitializer(_class2$V.prototype, "anchor", [serializable$p], function () {
        return new Vec2();
      }), _initializer2$P = applyDecoratedInitializer(_class2$V.prototype, "connectedAnchor", [serializable$p], function () {
        return new Vec2();
      }), _initializer3$B = applyDecoratedInitializer(_class2$V.prototype, "collideConnected", [serializable$p], function () {
        return false;
      }), _initializer4$t = applyDecoratedInitializer(_class2$V.prototype, "connectedBody", [_dec2$V, serializable$p], function () {
        return null;
      })), _class2$V)) || _class$Z));

      var _dec$Z, _dec2$U, _dec3$I, _class$Y, _class2$U, _initializer$S, _initializer2$O;
      var ccclass$7 = ccclass$M;
      var DistanceJoint2D = exports('fy', (_dec$Z = ccclass$7('cc.DistanceJoint2D'), _dec2$U = type$d(CCFloat), _dec3$I = type$d(CCBoolean), _dec$Z(_class$Y = (_class2$U = function (_Joint2D) {
        _inheritsLoose(DistanceJoint2D, _Joint2D);
        function DistanceJoint2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
          _this.TYPE = EJoint2DType.DISTANCE;
          _this._maxLength = _initializer$S && _initializer$S();
          _this._autoCalcDistance = _initializer2$O && _initializer2$O();
          return _this;
        }
        _createClass(DistanceJoint2D, [{
          key: "maxLength",
          get: function get() {
            if (this._autoCalcDistance) {
              if (this.connectedBody) {
                return Vec3.distance(this.node.worldPosition, this.connectedBody.node.worldPosition);
              } else {
                return Vec3.len(this.node.worldPosition);
              }
            }
            return this._maxLength;
          },
          set: function set(v) {
            this._maxLength = v;
            if (this._joint) {
              this._joint.setMaxLength(v);
            }
          }
        }, {
          key: "autoCalcDistance",
          get: function get() {
            return this._autoCalcDistance;
          },
          set: function set(v) {
            this._autoCalcDistance = v;
          }
        }]);
        return DistanceJoint2D;
      }(Joint2D), (_applyDecoratedDescriptor(_class2$U.prototype, "maxLength", [_dec2$U], Object.getOwnPropertyDescriptor(_class2$U.prototype, "maxLength"), _class2$U.prototype), _applyDecoratedDescriptor(_class2$U.prototype, "autoCalcDistance", [_dec3$I], Object.getOwnPropertyDescriptor(_class2$U.prototype, "autoCalcDistance"), _class2$U.prototype), _initializer$S = applyDecoratedInitializer(_class2$U.prototype, "_maxLength", [serializable$p], function () {
        return 5;
      }), _initializer2$O = applyDecoratedInitializer(_class2$U.prototype, "_autoCalcDistance", [serializable$p], function () {
        return true;
      })), _class2$U)) || _class$Y));

      var _dec$Y, _dec2$T, _dec3$H, _dec4$x, _dec5$u, _class$X, _class2$T, _initializer$R, _initializer2$N, _initializer3$A, _initializer4$s;
      var ccclass$6 = ccclass$M;
      var SpringJoint2D = exports('fz', (_dec$Y = ccclass$6('cc.SpringJoint2D'), _dec2$T = type$d(CCFloat), _dec3$H = type$d(CCFloat), _dec4$x = type$d(CCFloat), _dec5$u = type$d(CCBoolean), _dec$Y(_class$X = (_class2$T = function (_Joint2D) {
        _inheritsLoose(SpringJoint2D, _Joint2D);
        function SpringJoint2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
          _this.TYPE = EJoint2DType.SPRING;
          _this._frequency = _initializer$R && _initializer$R();
          _this._dampingRatio = _initializer2$N && _initializer2$N();
          _this._distance = _initializer3$A && _initializer3$A();
          _this._autoCalcDistance = _initializer4$s && _initializer4$s();
          return _this;
        }
        _createClass(SpringJoint2D, [{
          key: "frequency",
          get: function get() {
            return this._frequency;
          },
          set: function set(v) {
            this._frequency = v;
            if (this._joint) {
              this._joint.setFrequency(v);
            }
          }
        }, {
          key: "dampingRatio",
          get: function get() {
            return this._dampingRatio;
          },
          set: function set(v) {
            this._dampingRatio = v;
            if (this._joint) {
              this._joint.setDampingRatio(v);
            }
          }
        }, {
          key: "distance",
          get: function get() {
            if (this._autoCalcDistance) {
              if (this.connectedBody) {
                return Vec3.distance(this.node.worldPosition, this.connectedBody.node.worldPosition);
              } else {
                return Vec3.len(this.node.worldPosition);
              }
            }
            return this._distance;
          },
          set: function set(v) {
            this._distance = v;
            if (this._joint) {
              this._joint.setDistance(v);
            }
          }
        }, {
          key: "autoCalcDistance",
          get: function get() {
            return this._autoCalcDistance;
          },
          set: function set(v) {
            this._autoCalcDistance = v;
          }
        }]);
        return SpringJoint2D;
      }(Joint2D), (_applyDecoratedDescriptor(_class2$T.prototype, "frequency", [_dec2$T], Object.getOwnPropertyDescriptor(_class2$T.prototype, "frequency"), _class2$T.prototype), _applyDecoratedDescriptor(_class2$T.prototype, "dampingRatio", [_dec3$H], Object.getOwnPropertyDescriptor(_class2$T.prototype, "dampingRatio"), _class2$T.prototype), _applyDecoratedDescriptor(_class2$T.prototype, "distance", [_dec4$x], Object.getOwnPropertyDescriptor(_class2$T.prototype, "distance"), _class2$T.prototype), _applyDecoratedDescriptor(_class2$T.prototype, "autoCalcDistance", [_dec5$u], Object.getOwnPropertyDescriptor(_class2$T.prototype, "autoCalcDistance"), _class2$T.prototype), _initializer$R = applyDecoratedInitializer(_class2$T.prototype, "_frequency", [serializable$p], function () {
        return 5;
      }), _initializer2$N = applyDecoratedInitializer(_class2$T.prototype, "_dampingRatio", [serializable$p], function () {
        return 0.7;
      }), _initializer3$A = applyDecoratedInitializer(_class2$T.prototype, "_distance", [serializable$p], function () {
        return 10;
      }), _initializer4$s = applyDecoratedInitializer(_class2$T.prototype, "_autoCalcDistance", [serializable$p], function () {
        return true;
      })), _class2$T)) || _class$X));

      var _dec$X, _dec2$S, _dec3$G, _dec4$w, _class$W, _class2$S, _initializer$Q, _initializer2$M, _initializer3$z;
      var ccclass$5 = ccclass$M;
      var MouseJoint2D = exports('fA', (_dec$X = ccclass$5('cc.MouseJoint2D'), _dec2$S = type$d(CCFloat), _dec3$G = type$d(CCFloat), _dec4$w = type$d(CCFloat), _dec$X(_class$W = (_class2$S = function (_Joint2D) {
        _inheritsLoose(MouseJoint2D, _Joint2D);
        function MouseJoint2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
          _this.TYPE = EJoint2DType.MOUSE;
          _this._maxForce = _initializer$Q && _initializer$Q();
          _this._dampingRatio = _initializer2$M && _initializer2$M();
          _this._frequency = _initializer3$z && _initializer3$z();
          _this._target = new Vec2();
          return _this;
        }
        var _proto = MouseJoint2D.prototype;
        _proto.update = function update(dt) {
          this._joint.update(dt);
        };
        _createClass(MouseJoint2D, [{
          key: "target",
          get: function get() {
            return this._target;
          },
          set: function set(v) {
            this._target = v;
            if (this._joint) {
              this._joint.setTarget(v);
            }
          }
        }, {
          key: "frequency",
          get: function get() {
            return this._frequency;
          },
          set: function set(v) {
            this._frequency = v;
            if (this._joint) {
              this._joint.setFrequency(v);
            }
          }
        }, {
          key: "dampingRatio",
          get: function get() {
            return this._dampingRatio;
          },
          set: function set(v) {
            this._dampingRatio = v;
            if (this._joint) {
              this._joint.setDampingRatio(v);
            }
          }
        }, {
          key: "maxForce",
          get: function get() {
            return this._maxForce;
          },
          set: function set(v) {
            this._maxForce = v;
            if (this._joint) {
              this._joint.setMaxForce(v);
            }
          }
        }]);
        return MouseJoint2D;
      }(Joint2D), (_applyDecoratedDescriptor(_class2$S.prototype, "frequency", [_dec2$S], Object.getOwnPropertyDescriptor(_class2$S.prototype, "frequency"), _class2$S.prototype), _applyDecoratedDescriptor(_class2$S.prototype, "dampingRatio", [_dec3$G], Object.getOwnPropertyDescriptor(_class2$S.prototype, "dampingRatio"), _class2$S.prototype), _applyDecoratedDescriptor(_class2$S.prototype, "maxForce", [_dec4$w], Object.getOwnPropertyDescriptor(_class2$S.prototype, "maxForce"), _class2$S.prototype), _initializer$Q = applyDecoratedInitializer(_class2$S.prototype, "_maxForce", [serializable$p], function () {
        return 1000;
      }), _initializer2$M = applyDecoratedInitializer(_class2$S.prototype, "_dampingRatio", [serializable$p], function () {
        return 0.7;
      }), _initializer3$z = applyDecoratedInitializer(_class2$S.prototype, "_frequency", [serializable$p], function () {
        return 5;
      })), _class2$S)) || _class$W));

      var _dec$W, _dec2$R, _dec3$F, _dec4$v, _dec5$t, _dec6$i, _dec7$f, _class$V, _class2$R, _initializer$P, _initializer2$L, _initializer3$y, _initializer4$r, _initializer5$m, _initializer6$i;
      var tempVec3_1 = new Vec3();
      var tempVec3_2 = new Vec3();
      var ccclass$4 = ccclass$M;
      var RelativeJoint2D = exports('fB', (_dec$W = ccclass$4('cc.RelativeJoint2D'), _dec2$R = type$d(CCFloat), _dec3$F = type$d(CCFloat), _dec4$v = type$d(CCFloat), _dec5$t = type$d(Vec2), _dec6$i = type$d(CCFloat), _dec7$f = type$d(CCBoolean), _dec$W(_class$V = (_class2$R = function (_Joint2D) {
        _inheritsLoose(RelativeJoint2D, _Joint2D);
        function RelativeJoint2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
          _this.TYPE = EJoint2DType.RELATIVE;
          _this._maxForce = _initializer$P && _initializer$P();
          _this._maxTorque = _initializer2$L && _initializer2$L();
          _this._correctionFactor = _initializer3$y && _initializer3$y();
          _this._angularOffset = _initializer4$r && _initializer4$r();
          _this._linearOffset = _initializer5$m && _initializer5$m();
          _this._autoCalcOffset = _initializer6$i && _initializer6$i();
          return _this;
        }
        _createClass(RelativeJoint2D, [{
          key: "maxForce",
          get: function get() {
            return this._maxForce;
          },
          set: function set(v) {
            this._maxForce = v;
            if (this._joint) {
              this._joint.setMaxForce(v);
            }
          }
        }, {
          key: "maxTorque",
          get: function get() {
            return this._maxTorque;
          },
          set: function set(v) {
            this._maxTorque = v;
            if (this._joint) {
              this._joint.setMaxTorque(v);
            }
          }
        }, {
          key: "correctionFactor",
          get: function get() {
            return this._correctionFactor;
          },
          set: function set(v) {
            this._correctionFactor = v;
            if (this._joint) {
              this._joint.setCorrectionFactor(v);
            }
          }
        }, {
          key: "linearOffset",
          get: function get() {
            if (this._autoCalcOffset) {
              if (this.connectedBody) {
                return Vec2.subtract(this._linearOffset, this.connectedBody.node.worldPosition, this.node.worldPosition);
              } else {
                return Vec2.subtract(this._linearOffset, new Vec2(0, 0), this.node.worldPosition);
              }
            }
            return this._linearOffset;
          },
          set: function set(v) {
            this._linearOffset.set(v);
            if (this._joint) {
              this._joint.setLinearOffset(v);
            }
          }
        }, {
          key: "angularOffset",
          get: function get() {
            if (this._autoCalcOffset) {
              Quat.toEuler(tempVec3_1, this.node.worldRotation);
              if (this.connectedBody) {
                Quat.toEuler(tempVec3_2, this.connectedBody.node.worldRotation);
              } else {
                Quat.toEuler(tempVec3_2, new Quat());
              }
              this._angularOffset = tempVec3_2.z - tempVec3_1.z;
            }
            return this._angularOffset;
          },
          set: function set(v) {
            this._angularOffset = v;
            if (this._joint) {
              this._joint.setAngularOffset(v);
            }
          }
        }, {
          key: "autoCalcOffset",
          get: function get() {
            return this._autoCalcOffset;
          },
          set: function set(v) {
            this._autoCalcOffset = v;
          }
        }]);
        return RelativeJoint2D;
      }(Joint2D), (_applyDecoratedDescriptor(_class2$R.prototype, "maxForce", [_dec2$R], Object.getOwnPropertyDescriptor(_class2$R.prototype, "maxForce"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "maxTorque", [_dec3$F], Object.getOwnPropertyDescriptor(_class2$R.prototype, "maxTorque"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "correctionFactor", [_dec4$v], Object.getOwnPropertyDescriptor(_class2$R.prototype, "correctionFactor"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "linearOffset", [_dec5$t], Object.getOwnPropertyDescriptor(_class2$R.prototype, "linearOffset"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "angularOffset", [_dec6$i], Object.getOwnPropertyDescriptor(_class2$R.prototype, "angularOffset"), _class2$R.prototype), _applyDecoratedDescriptor(_class2$R.prototype, "autoCalcOffset", [_dec7$f], Object.getOwnPropertyDescriptor(_class2$R.prototype, "autoCalcOffset"), _class2$R.prototype), _initializer$P = applyDecoratedInitializer(_class2$R.prototype, "_maxForce", [serializable$p], function () {
        return 5;
      }), _initializer2$L = applyDecoratedInitializer(_class2$R.prototype, "_maxTorque", [serializable$p], function () {
        return 0.7;
      }), _initializer3$y = applyDecoratedInitializer(_class2$R.prototype, "_correctionFactor", [serializable$p], function () {
        return 0.3;
      }), _initializer4$r = applyDecoratedInitializer(_class2$R.prototype, "_angularOffset", [serializable$p], function () {
        return 0;
      }), _initializer5$m = applyDecoratedInitializer(_class2$R.prototype, "_linearOffset", [serializable$p], function () {
        return new Vec2();
      }), _initializer6$i = applyDecoratedInitializer(_class2$R.prototype, "_autoCalcOffset", [serializable$p], function () {
        return true;
      })), _class2$R)) || _class$V));

      var _dec$V, _dec2$Q, _dec3$E, _dec4$u, _dec5$s, _dec6$h, _dec7$e, _dec8$9, _dec9$8, _class$U, _class2$Q, _initializer$O, _initializer2$K, _initializer3$x, _initializer4$q, _initializer5$l, _initializer6$h, _initializer7$e, _initializer8$d;
      var tempVec2 = new Vec2();
      var ccclass$3 = ccclass$M;
      var SliderJoint2D = exports('fC', (_dec$V = ccclass$3('cc.SliderJoint2D'), _dec2$Q = type$d(CCFloat), _dec3$E = type$d(CCBoolean), _dec4$u = type$d(CCBoolean), _dec5$s = type$d(CCFloat), _dec6$h = type$d(CCFloat), _dec7$e = type$d(CCBoolean), _dec8$9 = type$d(CCFloat), _dec9$8 = type$d(CCFloat), _dec$V(_class$U = (_class2$Q = function (_Joint2D) {
        _inheritsLoose(SliderJoint2D, _Joint2D);
        function SliderJoint2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
          _this.TYPE = EJoint2DType.SLIDER;
          _this._angle = _initializer$O && _initializer$O();
          _this._autoCalcAngle = _initializer2$K && _initializer2$K();
          _this._enableMotor = _initializer3$x && _initializer3$x();
          _this._maxMotorForce = _initializer4$q && _initializer4$q();
          _this._motorSpeed = _initializer5$l && _initializer5$l();
          _this._enableLimit = _initializer6$h && _initializer6$h();
          _this._lowerLimit = _initializer7$e && _initializer7$e();
          _this._upperLimit = _initializer8$d && _initializer8$d();
          return _this;
        }
        _createClass(SliderJoint2D, [{
          key: "angle",
          get: function get() {
            if (this._autoCalcAngle) {
              if (this.connectedBody) {
                Vec2.subtract(tempVec2, this.connectedBody.node.worldPosition, this.node.worldPosition);
              } else {
                Vec2.subtract(tempVec2, new Vec2(0, 0), this.node.worldPosition);
              }
              this._angle = toDegree(Math.atan2(tempVec2.y, tempVec2.x));
            }
            return this._angle;
          },
          set: function set(v) {
            this._angle = v;
          }
        }, {
          key: "autoCalcAngle",
          get: function get() {
            return this._autoCalcAngle;
          },
          set: function set(v) {
            this._autoCalcAngle = v;
          }
        }, {
          key: "enableMotor",
          get: function get() {
            return this._enableMotor;
          },
          set: function set(v) {
            this._enableMotor = v;
          }
        }, {
          key: "maxMotorForce",
          get: function get() {
            return this._maxMotorForce;
          },
          set: function set(v) {
            this._maxMotorForce = v;
            if (this._joint) {
              this._joint.setMaxMotorForce(v);
            }
          }
        }, {
          key: "motorSpeed",
          get: function get() {
            return this._motorSpeed;
          },
          set: function set(v) {
            this._motorSpeed = v;
            if (this._joint) {
              this._joint.setMotorSpeed(v);
            }
          }
        }, {
          key: "enableLimit",
          get: function get() {
            return this._enableLimit;
          },
          set: function set(v) {
            this._enableLimit = v;
          }
        }, {
          key: "lowerLimit",
          get: function get() {
            return this._lowerLimit;
          },
          set: function set(v) {
            this._lowerLimit = v;
            if (this._joint) {
              this._joint.setLowerLimit(v);
            }
          }
        }, {
          key: "upperLimit",
          get: function get() {
            return this._upperLimit;
          },
          set: function set(v) {
            this._upperLimit = v;
            if (this._joint) {
              this._joint.setUpperLimit(v);
            }
          }
        }]);
        return SliderJoint2D;
      }(Joint2D), (_applyDecoratedDescriptor(_class2$Q.prototype, "angle", [_dec2$Q], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "angle"), _class2$Q.prototype), _applyDecoratedDescriptor(_class2$Q.prototype, "autoCalcAngle", [_dec3$E], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "autoCalcAngle"), _class2$Q.prototype), _applyDecoratedDescriptor(_class2$Q.prototype, "enableMotor", [_dec4$u], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "enableMotor"), _class2$Q.prototype), _applyDecoratedDescriptor(_class2$Q.prototype, "maxMotorForce", [_dec5$s], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "maxMotorForce"), _class2$Q.prototype), _applyDecoratedDescriptor(_class2$Q.prototype, "motorSpeed", [_dec6$h], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "motorSpeed"), _class2$Q.prototype), _applyDecoratedDescriptor(_class2$Q.prototype, "enableLimit", [_dec7$e], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "enableLimit"), _class2$Q.prototype), _applyDecoratedDescriptor(_class2$Q.prototype, "lowerLimit", [_dec8$9], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "lowerLimit"), _class2$Q.prototype), _applyDecoratedDescriptor(_class2$Q.prototype, "upperLimit", [_dec9$8], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "upperLimit"), _class2$Q.prototype), _initializer$O = applyDecoratedInitializer(_class2$Q.prototype, "_angle", [serializable$p], function () {
        return 0;
      }), _initializer2$K = applyDecoratedInitializer(_class2$Q.prototype, "_autoCalcAngle", [serializable$p], function () {
        return true;
      }), _initializer3$x = applyDecoratedInitializer(_class2$Q.prototype, "_enableMotor", [serializable$p], function () {
        return false;
      }), _initializer4$q = applyDecoratedInitializer(_class2$Q.prototype, "_maxMotorForce", [serializable$p], function () {
        return 1000;
      }), _initializer5$l = applyDecoratedInitializer(_class2$Q.prototype, "_motorSpeed", [serializable$p], function () {
        return 1000;
      }), _initializer6$h = applyDecoratedInitializer(_class2$Q.prototype, "_enableLimit", [serializable$p], function () {
        return false;
      }), _initializer7$e = applyDecoratedInitializer(_class2$Q.prototype, "_lowerLimit", [serializable$p], function () {
        return 0;
      }), _initializer8$d = applyDecoratedInitializer(_class2$Q.prototype, "_upperLimit", [serializable$p], function () {
        return 0;
      })), _class2$Q)) || _class$U));

      var _dec$U, _dec2$P, _dec3$D, _class$T, _class2$P, _initializer$N, _initializer2$J;
      var ccclass$2 = ccclass$M;
      var FixedJoint2D = exports('fD', (_dec$U = ccclass$2('cc.FixedJoint2D'), _dec2$P = type$d(CCFloat), _dec3$D = type$d(CCFloat), _dec$U(_class$T = (_class2$P = function (_Joint2D) {
        _inheritsLoose(FixedJoint2D, _Joint2D);
        function FixedJoint2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
          _this.TYPE = EJoint2DType.FIXED;
          _this._frequency = _initializer$N && _initializer$N();
          _this._dampingRatio = _initializer2$J && _initializer2$J();
          return _this;
        }
        _createClass(FixedJoint2D, [{
          key: "frequency",
          get: function get() {
            return this._frequency;
          },
          set: function set(v) {
            this._frequency = v;
            if (this._joint) {
              this._joint.setFrequency(v);
            }
          }
        }, {
          key: "dampingRatio",
          get: function get() {
            return this._dampingRatio;
          },
          set: function set(v) {
            this._dampingRatio = v;
            if (this._joint) {
              this._joint.setDampingRatio(v);
            }
          }
        }]);
        return FixedJoint2D;
      }(Joint2D), (_applyDecoratedDescriptor(_class2$P.prototype, "frequency", [_dec2$P], Object.getOwnPropertyDescriptor(_class2$P.prototype, "frequency"), _class2$P.prototype), _applyDecoratedDescriptor(_class2$P.prototype, "dampingRatio", [_dec3$D], Object.getOwnPropertyDescriptor(_class2$P.prototype, "dampingRatio"), _class2$P.prototype), _initializer$N = applyDecoratedInitializer(_class2$P.prototype, "_frequency", [serializable$p], function () {
        return 0.7;
      }), _initializer2$J = applyDecoratedInitializer(_class2$P.prototype, "_dampingRatio", [serializable$p], function () {
        return 0.5;
      })), _class2$P)) || _class$T));

      var _dec$T, _dec2$O, _dec3$C, _dec4$t, _dec5$r, _dec6$g, _dec7$d, _class$S, _class2$O, _initializer$M, _initializer2$I, _initializer3$w, _initializer4$p, _initializer5$k, _initializer6$g;
      var ccclass$1 = ccclass$M;
      var WheelJoint2D = exports('fE', (_dec$T = ccclass$1('cc.WheelJoint2D'), _dec2$O = type$d(CCFloat), _dec3$C = type$d(CCBoolean), _dec4$t = type$d(CCFloat), _dec5$r = type$d(CCFloat), _dec6$g = type$d(CCFloat), _dec7$d = type$d(CCFloat), _dec$T(_class$S = (_class2$O = function (_Joint2D) {
        _inheritsLoose(WheelJoint2D, _Joint2D);
        function WheelJoint2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
          _this.TYPE = EJoint2DType.WHEEL;
          _this._angle = _initializer$M && _initializer$M();
          _this._enableMotor = _initializer2$I && _initializer2$I();
          _this._maxMotorTorque = _initializer3$w && _initializer3$w();
          _this._motorSpeed = _initializer4$p && _initializer4$p();
          _this._frequency = _initializer5$k && _initializer5$k();
          _this._dampingRatio = _initializer6$g && _initializer6$g();
          return _this;
        }
        _createClass(WheelJoint2D, [{
          key: "angle",
          get: function get() {
            return this._angle;
          },
          set: function set(v) {
            this._angle = v;
          }
        }, {
          key: "enableMotor",
          get: function get() {
            return this._enableMotor;
          },
          set: function set(v) {
            this._enableMotor = v;
            if (this._joint) {
              this._joint.enableMotor(v);
            }
          }
        }, {
          key: "maxMotorTorque",
          get: function get() {
            return this._maxMotorTorque;
          },
          set: function set(v) {
            this._maxMotorTorque = v;
            if (this._joint) {
              this._joint.setMaxMotorTorque(v);
            }
          }
        }, {
          key: "motorSpeed",
          get: function get() {
            return this._motorSpeed;
          },
          set: function set(v) {
            this._motorSpeed = v;
            if (this._joint) {
              this._joint.setMotorSpeed(v);
            }
          }
        }, {
          key: "frequency",
          get: function get() {
            return this._frequency;
          },
          set: function set(v) {
            this._frequency = v;
            if (this._joint) {
              this._joint.setFrequency(v);
            }
          }
        }, {
          key: "dampingRatio",
          get: function get() {
            return this._dampingRatio;
          },
          set: function set(v) {
            this._dampingRatio = v;
            if (this._joint) {
              this._joint.setDampingRatio(v);
            }
          }
        }]);
        return WheelJoint2D;
      }(Joint2D), (_applyDecoratedDescriptor(_class2$O.prototype, "angle", [_dec2$O], Object.getOwnPropertyDescriptor(_class2$O.prototype, "angle"), _class2$O.prototype), _applyDecoratedDescriptor(_class2$O.prototype, "enableMotor", [_dec3$C], Object.getOwnPropertyDescriptor(_class2$O.prototype, "enableMotor"), _class2$O.prototype), _applyDecoratedDescriptor(_class2$O.prototype, "maxMotorTorque", [_dec4$t], Object.getOwnPropertyDescriptor(_class2$O.prototype, "maxMotorTorque"), _class2$O.prototype), _applyDecoratedDescriptor(_class2$O.prototype, "motorSpeed", [_dec5$r], Object.getOwnPropertyDescriptor(_class2$O.prototype, "motorSpeed"), _class2$O.prototype), _applyDecoratedDescriptor(_class2$O.prototype, "frequency", [_dec6$g], Object.getOwnPropertyDescriptor(_class2$O.prototype, "frequency"), _class2$O.prototype), _applyDecoratedDescriptor(_class2$O.prototype, "dampingRatio", [_dec7$d], Object.getOwnPropertyDescriptor(_class2$O.prototype, "dampingRatio"), _class2$O.prototype), _initializer$M = applyDecoratedInitializer(_class2$O.prototype, "_angle", [serializable$p], function () {
        return 90;
      }), _initializer2$I = applyDecoratedInitializer(_class2$O.prototype, "_enableMotor", [serializable$p], function () {
        return false;
      }), _initializer3$w = applyDecoratedInitializer(_class2$O.prototype, "_maxMotorTorque", [serializable$p], function () {
        return 1000;
      }), _initializer4$p = applyDecoratedInitializer(_class2$O.prototype, "_motorSpeed", [serializable$p], function () {
        return 0;
      }), _initializer5$k = applyDecoratedInitializer(_class2$O.prototype, "_frequency", [serializable$p], function () {
        return 5;
      }), _initializer6$g = applyDecoratedInitializer(_class2$O.prototype, "_dampingRatio", [serializable$p], function () {
        return 0.7;
      })), _class2$O)) || _class$S));

      var _dec$S, _dec2$N, _dec3$B, _dec4$s, _dec5$q, _dec6$f, _dec7$c, _class$R, _class2$N, _initializer$L, _initializer2$H, _initializer3$v, _initializer4$o, _initializer5$j, _initializer6$f;
      var ccclass = ccclass$M;
      var HingeJoint2D = exports('fF', (_dec$S = ccclass('cc.HingeJoint2D'), _dec2$N = type$d(CCBoolean), _dec3$B = type$d(CCFloat), _dec4$s = type$d(CCFloat), _dec5$q = type$d(CCBoolean), _dec6$f = type$d(CCFloat), _dec7$c = type$d(CCFloat), _dec$S(_class$R = (_class2$N = function (_Joint2D) {
        _inheritsLoose(HingeJoint2D, _Joint2D);
        function HingeJoint2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Joint2D.call.apply(_Joint2D, [this].concat(args)) || this;
          _this.TYPE = EJoint2DType.HINGE;
          _this._enableLimit = _initializer$L && _initializer$L();
          _this._lowerAngle = _initializer2$H && _initializer2$H();
          _this._upperAngle = _initializer3$v && _initializer3$v();
          _this._enableMotor = _initializer4$o && _initializer4$o();
          _this._maxMotorTorque = _initializer5$j && _initializer5$j();
          _this._motorSpeed = _initializer6$f && _initializer6$f();
          return _this;
        }
        _createClass(HingeJoint2D, [{
          key: "enableLimit",
          get: function get() {
            return this._enableLimit;
          },
          set: function set(v) {
            this._enableLimit = v;
          }
        }, {
          key: "lowerAngle",
          get: function get() {
            return this._lowerAngle;
          },
          set: function set(v) {
            this._lowerAngle = v;
            if (this._joint) {
              this._joint.setLowerAngle(v);
            }
          }
        }, {
          key: "upperAngle",
          get: function get() {
            return this._upperAngle;
          },
          set: function set(v) {
            this._upperAngle = v;
            if (this._joint) {
              this._joint.setUpperAngle(v);
            }
          }
        }, {
          key: "enableMotor",
          get: function get() {
            return this._enableMotor;
          },
          set: function set(v) {
            this._enableMotor = v;
            if (this._joint) {
              this._joint.enableMotor(v);
            }
          }
        }, {
          key: "maxMotorTorque",
          get: function get() {
            return this._maxMotorTorque;
          },
          set: function set(v) {
            this._maxMotorTorque = v;
            if (this._joint) {
              this._joint.setMaxMotorTorque(v);
            }
          }
        }, {
          key: "motorSpeed",
          get: function get() {
            return this._motorSpeed;
          },
          set: function set(v) {
            this._motorSpeed = v;
            if (this._joint) {
              this._joint.setMotorSpeed(v);
            }
          }
        }]);
        return HingeJoint2D;
      }(Joint2D), (_applyDecoratedDescriptor(_class2$N.prototype, "enableLimit", [_dec2$N], Object.getOwnPropertyDescriptor(_class2$N.prototype, "enableLimit"), _class2$N.prototype), _applyDecoratedDescriptor(_class2$N.prototype, "lowerAngle", [_dec3$B], Object.getOwnPropertyDescriptor(_class2$N.prototype, "lowerAngle"), _class2$N.prototype), _applyDecoratedDescriptor(_class2$N.prototype, "upperAngle", [_dec4$s], Object.getOwnPropertyDescriptor(_class2$N.prototype, "upperAngle"), _class2$N.prototype), _applyDecoratedDescriptor(_class2$N.prototype, "enableMotor", [_dec5$q], Object.getOwnPropertyDescriptor(_class2$N.prototype, "enableMotor"), _class2$N.prototype), _applyDecoratedDescriptor(_class2$N.prototype, "maxMotorTorque", [_dec6$f], Object.getOwnPropertyDescriptor(_class2$N.prototype, "maxMotorTorque"), _class2$N.prototype), _applyDecoratedDescriptor(_class2$N.prototype, "motorSpeed", [_dec7$c], Object.getOwnPropertyDescriptor(_class2$N.prototype, "motorSpeed"), _class2$N.prototype), _initializer$L = applyDecoratedInitializer(_class2$N.prototype, "_enableLimit", [serializable$p], function () {
        return false;
      }), _initializer2$H = applyDecoratedInitializer(_class2$N.prototype, "_lowerAngle", [serializable$p], function () {
        return 0;
      }), _initializer3$v = applyDecoratedInitializer(_class2$N.prototype, "_upperAngle", [serializable$p], function () {
        return 0;
      }), _initializer4$o = applyDecoratedInitializer(_class2$N.prototype, "_enableMotor", [serializable$p], function () {
        return false;
      }), _initializer5$j = applyDecoratedInitializer(_class2$N.prototype, "_maxMotorTorque", [serializable$p], function () {
        return 1000;
      }), _initializer6$f = applyDecoratedInitializer(_class2$N.prototype, "_motorSpeed", [serializable$p], function () {
        return 0;
      })), _class2$N)) || _class$R));

      var Physics2DUtils = exports('fg', {
        PolygonSeparator: PolygonSeparator,
        PolygonPartition: PolygonPartition
      });
      legacyCC.internal.physics2d = {
        selector: selector$1
      };

      var PhysicsRayCastCallback = function (_b2$RayCastCallback) {
        _inheritsLoose(PhysicsRayCastCallback, _b2$RayCastCallback);
        function PhysicsRayCastCallback() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _b2$RayCastCallback.call.apply(_b2$RayCastCallback, [this].concat(args)) || this;
          _this._type = ERaycast2DType.Closest;
          _this._fixtures = [];
          _this._points = [];
          _this._normals = [];
          _this._fractions = [];
          _this._mask = 0xffffffff;
          return _this;
        }
        var _proto = PhysicsRayCastCallback.prototype;
        _proto.init = function init(type, mask) {
          this._type = type;
          this._mask = mask;
          this._fixtures.length = 0;
          this._points.length = 0;
          this._normals.length = 0;
          this._fractions.length = 0;
        };
        _proto.ReportFixture = function ReportFixture(fixture, point, normal, fraction) {
          if ((fixture.GetFilterData().categoryBits & this._mask) === 0) {
            return 0;
          }
          if (this._type === ERaycast2DType.Closest) {
            this._fixtures[0] = fixture;
            this._points[0] = point;
            this._normals[0] = normal;
            this._fractions[0] = fraction;
            return fraction;
          }
          this._fixtures.push(fixture);
          this._points.push(new Vec2(point.x, point.y));
          this._normals.push(new Vec2(normal.x, normal.y));
          this._fractions.push(fraction);
          if (this._type === ERaycast2DType.Any) {
            return 0;
          } else if (this._type >= ERaycast2DType.All) {
            return 1;
          }
          return fraction;
        };
        _proto.getFixtures = function getFixtures() {
          return this._fixtures;
        };
        _proto.getPoints = function getPoints() {
          return this._points;
        };
        _proto.getNormals = function getNormals() {
          return this._normals;
        };
        _proto.getFractions = function getFractions() {
          return this._fractions;
        };
        return PhysicsRayCastCallback;
      }(box2d_1.RayCastCallback);

      var pools = [];
      var pointCache = [new Vec2(), new Vec2()];
      var b2worldmanifold = new box2d_1.WorldManifold();
      var worldmanifold = {
        points: [],
        separations: [],
        normal: new Vec2()
      };
      var ManifoldPoint = function ManifoldPoint() {
        this.localPoint = new Vec2();
        this.normalImpulse = 0;
        this.tangentImpulse = 0;
      };
      var manifoldPointCache = [new ManifoldPoint(), new ManifoldPoint()];
      var manifold = {
        type: 0,
        localPoint: new Vec2(),
        localNormal: new Vec2(),
        points: []
      };
      var impulse = {
        normalImpulses: [],
        tangentImpulses: []
      };
      var PhysicsContact = function () {
        function PhysicsContact() {
          this.colliderA = null;
          this.colliderB = null;
          this.disabled = false;
          this.disabledOnce = false;
          this._impulse = null;
          this._inverted = false;
          this._b2contact = null;
        }
        PhysicsContact.get = function get(b2contact) {
          var c = pools.pop();
          if (!c) {
            c = new PhysicsContact();
          }
          c.init(b2contact);
          return c;
        };
        PhysicsContact.put = function put(b2contact) {
          var c = b2contact.m_userData;
          if (!c) return;
          pools.push(c);
          c.reset();
        };
        var _proto = PhysicsContact.prototype;
        _proto._setImpulse = function _setImpulse(impulse) {
          this._impulse = impulse;
        };
        _proto.init = function init(b2contact) {
          this.colliderA = b2contact.m_fixtureA.m_userData.collider;
          this.colliderB = b2contact.m_fixtureB.m_userData.collider;
          this.disabled = false;
          this.disabledOnce = false;
          this._impulse = null;
          this._inverted = false;
          this._b2contact = b2contact;
          b2contact.m_userData = this;
        };
        _proto.reset = function reset() {
          this.setTangentSpeed(0);
          this.resetFriction();
          this.resetRestitution();
          this.colliderA = null;
          this.colliderB = null;
          this.disabled = false;
          this._impulse = null;
          this._b2contact.m_userData = null;
          this._b2contact = null;
        };
        _proto.getWorldManifold = function getWorldManifold() {
          var points = worldmanifold.points;
          var separations = worldmanifold.separations;
          var normal = worldmanifold.normal;
          this._b2contact.GetWorldManifold(b2worldmanifold);
          var b2points = b2worldmanifold.points;
          var b2separations = b2worldmanifold.separations;
          var count = this._b2contact.GetManifold().pointCount;
          points.length = separations.length = count;
          for (var i = 0; i < count; i++) {
            var p = pointCache[i];
            p.x = b2points[i].x * PHYSICS_2D_PTM_RATIO;
            p.y = b2points[i].y * PHYSICS_2D_PTM_RATIO;
            points[i] = p;
            separations[i] = b2separations[i] * PHYSICS_2D_PTM_RATIO;
          }
          normal.x = b2worldmanifold.normal.x;
          normal.y = b2worldmanifold.normal.y;
          if (this._inverted) {
            normal.x *= -1;
            normal.y *= -1;
          }
          return worldmanifold;
        };
        _proto.getManifold = function getManifold() {
          var points = manifold.points;
          var localNormal = manifold.localNormal;
          var localPoint = manifold.localPoint;
          var b2manifold = this._b2contact.GetManifold();
          var b2points = b2manifold.points;
          var count = points.length = b2manifold.pointCount;
          for (var i = 0; i < count; i++) {
            var p = manifoldPointCache[i];
            var b2p = b2points[i];
            p.localPoint.x = b2p.localPoint.x * PHYSICS_2D_PTM_RATIO;
            p.localPoint.y = b2p.localPoint.y * PHYSICS_2D_PTM_RATIO;
            p.normalImpulse = b2p.normalImpulse * PHYSICS_2D_PTM_RATIO;
            p.tangentImpulse = b2p.tangentImpulse;
            points[i] = p;
          }
          localPoint.x = b2manifold.localPoint.x * PHYSICS_2D_PTM_RATIO;
          localPoint.y = b2manifold.localPoint.y * PHYSICS_2D_PTM_RATIO;
          localNormal.x = b2manifold.localNormal.x;
          localNormal.y = b2manifold.localNormal.y;
          manifold.type = b2manifold.type;
          if (this._inverted) {
            localNormal.x *= -1;
            localNormal.y *= -1;
          }
          return manifold;
        };
        _proto.getImpulse = function getImpulse() {
          var b2impulse = this._impulse;
          if (!b2impulse) return null;
          var normalImpulses = impulse.normalImpulses;
          var tangentImpulses = impulse.tangentImpulses;
          var count = b2impulse.count;
          for (var i = 0; i < count; i++) {
            normalImpulses[i] = b2impulse.normalImpulses[i] * PHYSICS_2D_PTM_RATIO;
            tangentImpulses[i] = b2impulse.tangentImpulses[i];
          }
          tangentImpulses.length = normalImpulses.length = count;
          return impulse;
        };
        _proto.emit = function emit(contactType) {
          switch (contactType) {
            case Contact2DType.BEGIN_CONTACT:
              break;
            case Contact2DType.END_CONTACT:
              break;
            case Contact2DType.PRE_SOLVE:
              break;
            case Contact2DType.POST_SOLVE:
              break;
          }
          var colliderA = this.colliderA;
          var colliderB = this.colliderB;
          var bodyA = colliderA.body;
          var bodyB = colliderB.body;
          if (bodyA.enabledContactListener) {
            colliderA === null || colliderA === void 0 ? void 0 : colliderA.emit(contactType, colliderA, colliderB, this);
          }
          if (bodyB.enabledContactListener) {
            colliderB === null || colliderB === void 0 ? void 0 : colliderB.emit(contactType, colliderB, colliderA, this);
          }
          if (bodyA.enabledContactListener || bodyB.enabledContactListener) {
            PhysicsSystem2D.instance.emit(contactType, colliderA, colliderB, this);
          }
          if (this.disabled || this.disabledOnce) {
            this.setEnabled(false);
            this.disabledOnce = false;
          }
        };
        _proto.setEnabled = function setEnabled(value) {
          this._b2contact.SetEnabled(value);
        };
        _proto.isTouching = function isTouching() {
          return this._b2contact.IsTouching();
        };
        _proto.setTangentSpeed = function setTangentSpeed(value) {
          this._b2contact.SetTangentSpeed(value);
        };
        _proto.getTangentSpeed = function getTangentSpeed() {
          return this._b2contact.GetTangentSpeed();
        };
        _proto.setFriction = function setFriction(value) {
          this._b2contact.SetFriction(value);
        };
        _proto.getFriction = function getFriction() {
          return this._b2contact.GetFriction();
        };
        _proto.resetFriction = function resetFriction() {
          return this._b2contact.ResetFriction();
        };
        _proto.setRestitution = function setRestitution(value) {
          this._b2contact.SetRestitution(value);
        };
        _proto.getRestitution = function getRestitution() {
          return this._b2contact.GetRestitution();
        };
        _proto.resetRestitution = function resetRestitution() {
          return this._b2contact.ResetRestitution();
        };
        return PhysicsContact;
      }();

      var _tmp_vec2 = new box2d_1.Vec2();
      var _tmp_color = new Color$1();
      var GREEN_COLOR = Color$1.GREEN;
      var RED_COLOR = Color$1.RED;
      var PhysicsDebugDraw = function (_b2$Draw) {
        _inheritsLoose(PhysicsDebugDraw, _b2$Draw);
        function PhysicsDebugDraw(drawer) {
          var _this;
          _this = _b2$Draw.call(this) || this;
          _this._drawer = null;
          _this._xf = new box2d_1.Transform();
          _this._dxf = new box2d_1.Transform();
          _this._drawer = drawer;
          return _this;
        }
        var _proto = PhysicsDebugDraw.prototype;
        _proto._DrawPolygon = function _DrawPolygon(vertices, vertexCount) {
          var drawer = this._drawer;
          for (var i = 0; i < vertexCount; i++) {
            box2d_1.Transform.MulXV(this._xf, vertices[i], _tmp_vec2);
            var x = _tmp_vec2.x * PHYSICS_2D_PTM_RATIO;
            var y = _tmp_vec2.y * PHYSICS_2D_PTM_RATIO;
            if (i === 0) drawer.moveTo(x, y);else {
              drawer.lineTo(x, y);
            }
          }
          drawer.close();
        };
        _proto.DrawPolygon = function DrawPolygon(vertices, vertexCount, color) {
          this._applyStrokeColor(color);
          this._DrawPolygon(vertices, vertexCount);
          this._drawer.stroke();
        };
        _proto.DrawSolidPolygon = function DrawSolidPolygon(vertices, vertexCount, color) {
          this._applyFillColor(color);
          this._DrawPolygon(vertices, vertexCount);
          this._drawer.fill();
          this._drawer.stroke();
        };
        _proto._DrawCircle = function _DrawCircle(center, radius) {
          box2d_1.Transform.MulXV(this._xf, center, _tmp_vec2);
          this._drawer.circle(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO, radius * PHYSICS_2D_PTM_RATIO);
        };
        _proto.DrawCircle = function DrawCircle(center, radius, color) {
          this._applyStrokeColor(color);
          this._DrawCircle(center, radius);
          this._drawer.stroke();
        };
        _proto.DrawSolidCircle = function DrawSolidCircle(center, radius, axis, color) {
          this._applyFillColor(color);
          this._DrawCircle(center, radius);
          this._drawer.fill();
        };
        _proto.DrawSegment = function DrawSegment(p1, p2, color) {
          var drawer = this._drawer;
          if (p1.x === p2.x && p1.y === p2.y) {
            this._applyFillColor(color);
            this._DrawCircle(p1, 2 / PHYSICS_2D_PTM_RATIO);
            drawer.fill();
            return;
          }
          this._applyStrokeColor(color);
          box2d_1.Transform.MulXV(this._xf, p1, _tmp_vec2);
          drawer.moveTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          box2d_1.Transform.MulXV(this._xf, p2, _tmp_vec2);
          drawer.lineTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          drawer.stroke();
        };
        _proto.DrawTransform = function DrawTransform(xf) {
          var drawer = this._drawer;
          drawer.strokeColor = RED_COLOR;
          _tmp_vec2.x = _tmp_vec2.y = 0;
          box2d_1.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
          drawer.moveTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          _tmp_vec2.x = 1;
          _tmp_vec2.y = 0;
          box2d_1.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
          drawer.lineTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          drawer.stroke();
          drawer.strokeColor = GREEN_COLOR;
          _tmp_vec2.x = _tmp_vec2.y = 0;
          box2d_1.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
          drawer.moveTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          _tmp_vec2.x = 0;
          _tmp_vec2.y = 1;
          box2d_1.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
          drawer.lineTo(_tmp_vec2.x * PHYSICS_2D_PTM_RATIO, _tmp_vec2.y * PHYSICS_2D_PTM_RATIO);
          drawer.stroke();
        };
        _proto.DrawPoint = function DrawPoint(center, radius, color) {};
        _proto.DrawParticles = function DrawParticles() {};
        _proto._applyStrokeColor = function _applyStrokeColor(color) {
          this._drawer.strokeColor = _tmp_color.set(color.r * 255, color.g * 255, color.b * 255, 150);
        };
        _proto._applyFillColor = function _applyFillColor(color) {
          this._drawer.fillColor = _tmp_color.set(color.r * 255, color.g * 255, color.b * 255, 150);
        };
        _proto.PushTransform = function PushTransform(xf) {
          this._xf = xf;
        };
        _proto.PopTransform = function PopTransform() {
          this._xf = this._dxf;
        };
        return PhysicsDebugDraw;
      }(box2d_1.Draw);

      var tempVec3$1 = new Vec3();
      var tempVec2_1$1 = new Vec2();
      var tempVec2_2 = new Vec2();
      var temoBodyDef = new box2d_1.BodyDef();
      var tempB2AABB = new box2d_1.AABB();
      var testResults = [];
      var b2PhysicsWorld = function () {
        function b2PhysicsWorld() {
          this._world = void 0;
          this._bodies = [];
          this._animatedBodies = [];
          this._rotationAxis = new Vec3();
          this._physicsGroundBody = void 0;
          this._contactListener = void 0;
          this._aabbQueryCallback = void 0;
          this._raycastQueryCallback = void 0;
          this._debugGraphics = null;
          this._b2DebugDrawer = null;
          this._debugDrawFlags = 0;
          this._world = new box2d_1.World(new box2d_1.Vec2(0, -10));
          var tempBodyDef = new box2d_1.BodyDef();
          this._physicsGroundBody = this._world.CreateBody(tempBodyDef);
          var listener = new PhysicsContactListener();
          listener.setBeginContact(this._onBeginContact);
          listener.setEndContact(this._onEndContact);
          listener.setPreSolve(this._onPreSolve);
          listener.setPostSolve(this._onPostSolve);
          this._world.SetContactListener(listener);
          this._contactListener = listener;
          this._aabbQueryCallback = new PhysicsAABBQueryCallback();
          this._raycastQueryCallback = new PhysicsRayCastCallback();
        }
        var _proto = b2PhysicsWorld.prototype;
        _proto._checkDebugDrawValid = function _checkDebugDrawValid() {
          if (!this._debugGraphics || !this._debugGraphics.isValid) {
            var canvas = find('Canvas');
            if (!canvas) {
              var scene = director.getScene();
              if (!scene) {
                return;
              }
              canvas = new Node$1('Canvas');
              canvas.addComponent('cc.Canvas');
              canvas.parent = scene;
            }
            var node = new Node$1('PHYSICS_2D_DEBUG_DRAW');
            node.hideFlags |= CCObject.Flags.DontSave;
            node.parent = canvas;
            node.worldPosition = Vec3.ZERO;
            node.layer = Layers.Enum.UI_2D;
            this._debugGraphics = node.addComponent('cc.Graphics');
            this._debugGraphics.lineWidth = 3;
            var debugDraw = new PhysicsDebugDraw(this._debugGraphics);
            this._b2DebugDrawer = debugDraw;
            this._world.SetDebugDraw(debugDraw);
          }
          var parent = this._debugGraphics.node.parent;
          this._debugGraphics.node.setSiblingIndex(parent.children.length - 1);
          if (this._b2DebugDrawer) {
            this._b2DebugDrawer.SetFlags(this.debugDrawFlags);
          }
        };
        _proto.setGravity = function setGravity(v) {
          this._world.SetGravity(v);
        };
        _proto.setAllowSleep = function setAllowSleep(v) {
          this._world.SetAllowSleeping(true);
        };
        _proto.step = function step(deltaTime, velocityIterations, positionIterations) {
          if (velocityIterations === void 0) {
            velocityIterations = 10;
          }
          if (positionIterations === void 0) {
            positionIterations = 10;
          }
          var animatedBodies = this._animatedBodies;
          for (var i = 0, l = animatedBodies.length; i < l; i++) {
            animatedBodies[i].animate(deltaTime);
          }
          this._world.Step(deltaTime, velocityIterations, positionIterations);
        };
        _proto.raycast = function raycast(p1, p2, type, mask) {
          if (p1.equals(p2)) {
            return [];
          }
          type = type || ERaycast2DType.Closest;
          tempVec2_1$1.x = p1.x / PHYSICS_2D_PTM_RATIO;
          tempVec2_1$1.y = p1.y / PHYSICS_2D_PTM_RATIO;
          tempVec2_2.x = p2.x / PHYSICS_2D_PTM_RATIO;
          tempVec2_2.y = p2.y / PHYSICS_2D_PTM_RATIO;
          var callback = this._raycastQueryCallback;
          callback.init(type, mask);
          this._world.RayCast(callback, tempVec2_1$1, tempVec2_2);
          var fixtures = callback.getFixtures();
          if (fixtures.length > 0) {
            var points = callback.getPoints();
            var normals = callback.getNormals();
            var fractions = callback.getFractions();
            var results = [];
            for (var i = 0, l = fixtures.length; i < l; i++) {
              var fixture = fixtures[i];
              var shape = fixture.m_userData;
              var collider = shape.collider;
              if (type === ERaycast2DType.AllClosest) {
                var result = void 0;
                for (var j = 0; j < results.length; j++) {
                  if (results[j].collider === collider) {
                    result = results[j];
                  }
                }
                if (result) {
                  if (fractions[i] < result.fraction) {
                    result.fixtureIndex = shape.getFixtureIndex(fixture);
                    result.point.x = points[i].x * PHYSICS_2D_PTM_RATIO;
                    result.point.y = points[i].y * PHYSICS_2D_PTM_RATIO;
                    result.normal.x = normals[i].x;
                    result.normal.y = normals[i].y;
                    result.fraction = fractions[i];
                  }
                  continue;
                }
              }
              results.push({
                collider: collider,
                fixtureIndex: shape.getFixtureIndex(fixture),
                point: new Vec2(points[i].x * PHYSICS_2D_PTM_RATIO, points[i].y * PHYSICS_2D_PTM_RATIO),
                normal: new Vec2(normals[i].x, normals[i].y),
                fraction: fractions[i]
              });
            }
            return results;
          }
          return [];
        };
        _proto.syncPhysicsToScene = function syncPhysicsToScene() {
          var bodies = this._bodies;
          for (var i = 0, l = bodies.length; i < l; i++) {
            var body = bodies[i];
            var bodyComp = body.rigidBody;
            if (bodyComp.type === ERigidBody2DType.Animated) {
              body.resetVelocity();
              continue;
            }
            var node = bodyComp.node;
            var b2body = body.impl;
            var pos = b2body.GetPosition();
            tempVec3$1.x = pos.x * PHYSICS_2D_PTM_RATIO;
            tempVec3$1.y = pos.y * PHYSICS_2D_PTM_RATIO;
            tempVec3$1.z = 0;
            node.worldPosition = tempVec3$1;
            var angle = toDegree(b2body.GetAngle());
            node.setWorldRotationFromEuler(0, 0, angle);
          }
        };
        _proto.syncSceneToPhysics = function syncSceneToPhysics() {
          var bodies = this._bodies;
          for (var i = 0; i < bodies.length; i++) {
            bodies[i].syncSceneToPhysics();
          }
        };
        _proto.addBody = function addBody(body) {
          var bodies = this._bodies;
          if (bodies.includes(body)) {
            return;
          }
          var bodyDef = temoBodyDef;
          var comp = body.rigidBody;
          bodyDef.allowSleep = comp.allowSleep;
          bodyDef.gravityScale = comp.gravityScale;
          bodyDef.linearDamping = comp.linearDamping;
          bodyDef.angularDamping = comp.angularDamping;
          bodyDef.fixedRotation = comp.fixedRotation;
          bodyDef.bullet = comp.bullet;
          var node = comp.node;
          var pos = node.worldPosition;
          bodyDef.position.Set(pos.x / PHYSICS_2D_PTM_RATIO, pos.y / PHYSICS_2D_PTM_RATIO);
          tempVec3$1.z = Quat.getAxisAngle(this._rotationAxis, node.worldRotation);
          if (this._rotationAxis.z < 0.0) {
            tempVec3$1.z = Math.PI * 2 - tempVec3$1.z;
          }
          bodyDef.angle = tempVec3$1.z;
          bodyDef.awake = comp.awakeOnLoad;
          if (comp.type === ERigidBody2DType.Animated) {
            bodyDef.type = ERigidBody2DType.Kinematic;
            this._animatedBodies.push(body);
            body._animatedPos.set(bodyDef.position.x, bodyDef.position.y);
            body._animatedAngle = bodyDef.angle;
          } else {
            bodyDef.type = comp.type;
          }
          var compPrivate = comp;
          var linearVelocity = compPrivate._linearVelocity;
          bodyDef.linearVelocity.Set(linearVelocity.x, linearVelocity.y);
          bodyDef.angularVelocity = compPrivate._angularVelocity;
          var b2Body = this._world.CreateBody(bodyDef);
          b2Body.m_userData = body;
          body._imp = b2Body;
          this._bodies.push(body);
        };
        _proto.removeBody = function removeBody(body) {
          if (!this._bodies.includes(body)) {
            return;
          }
          if (body.impl) {
            body.impl.m_userData = null;
            this._world.DestroyBody(body.impl);
            body._imp = null;
          }
          remove(this._bodies, body);
          var comp = body.rigidBody;
          if (comp.type === ERigidBody2DType.Animated) {
            remove(this._animatedBodies, body);
          }
        };
        _proto.registerContactFixture = function registerContactFixture(fixture) {
          this._contactListener.registerContactFixture(fixture);
        };
        _proto.unregisterContactFixture = function unregisterContactFixture(fixture) {
          this._contactListener.unregisterContactFixture(fixture);
        };
        _proto.testPoint = function testPoint(point) {
          var x = tempVec2_1$1.x = point.x / PHYSICS_2D_PTM_RATIO;
          var y = tempVec2_1$1.y = point.y / PHYSICS_2D_PTM_RATIO;
          var d = 0.2 / PHYSICS_2D_PTM_RATIO;
          tempB2AABB.lowerBound.x = x - d;
          tempB2AABB.lowerBound.y = y - d;
          tempB2AABB.upperBound.x = x + d;
          tempB2AABB.upperBound.y = y + d;
          var callback = this._aabbQueryCallback;
          callback.init(tempVec2_1$1);
          this._world.QueryAABB(callback, tempB2AABB);
          var fixtures = callback.getFixtures();
          testResults.length = 0;
          for (var i = 0; i < fixtures.length; i++) {
            var collider = fixtures[i].m_userData.collider;
            if (!testResults.includes(collider)) {
              testResults.push(collider);
            }
          }
          return testResults;
        };
        _proto.testAABB = function testAABB(rect) {
          tempB2AABB.lowerBound.x = rect.xMin / PHYSICS_2D_PTM_RATIO;
          tempB2AABB.lowerBound.y = rect.yMin / PHYSICS_2D_PTM_RATIO;
          tempB2AABB.upperBound.x = rect.xMax / PHYSICS_2D_PTM_RATIO;
          tempB2AABB.upperBound.y = rect.yMax / PHYSICS_2D_PTM_RATIO;
          var callback = this._aabbQueryCallback;
          callback.init();
          this._world.QueryAABB(callback, tempB2AABB);
          var fixtures = callback.getFixtures();
          testResults.length = 0;
          for (var i = 0; i < fixtures.length; i++) {
            var collider = fixtures[i].m_userData.collider;
            if (!testResults.includes(collider)) {
              testResults.push(collider);
            }
          }
          return testResults;
        };
        _proto.drawDebug = function drawDebug() {
          this._checkDebugDrawValid();
          if (!this._debugGraphics) {
            return;
          }
          this._debugGraphics.clear();
          this._world.DrawDebugData();
        };
        _proto._onBeginContact = function _onBeginContact(b2contact) {
          var c = PhysicsContact.get(b2contact);
          c.emit(Contact2DType.BEGIN_CONTACT);
        };
        _proto._onEndContact = function _onEndContact(b2contact) {
          var c = b2contact.m_userData;
          if (!c) {
            return;
          }
          c.emit(Contact2DType.END_CONTACT);
          PhysicsContact.put(b2contact);
        };
        _proto._onPreSolve = function _onPreSolve(b2contact) {
          var c = b2contact.m_userData;
          if (!c) {
            return;
          }
          c.emit(Contact2DType.PRE_SOLVE);
        };
        _proto._onPostSolve = function _onPostSolve(b2contact, impulse) {
          var c = b2contact.m_userData;
          if (!c) {
            return;
          }
          c._setImpulse(impulse);
          c.emit(Contact2DType.POST_SOLVE);
          c._setImpulse(null);
        };
        _createClass(b2PhysicsWorld, [{
          key: "impl",
          get: function get() {
            return this._world;
          }
        }, {
          key: "groundBodyImpl",
          get: function get() {
            return this._physicsGroundBody;
          }
        }, {
          key: "debugDrawFlags",
          get: function get() {
            return this._debugDrawFlags;
          },
          set: function set(v) {
            if (!v) {
              if (this._debugGraphics) {
                this._debugGraphics.node.parent = null;
              }
            }
            this._debugDrawFlags = v;
          }
        }]);
        return b2PhysicsWorld;
      }();

      var tempVec3 = new Vec3();
      var tempVec2_1 = new box2d_1.Vec2();
      var b2RigidBody2D = function () {
        function b2RigidBody2D() {
          this._animatedPos = new Vec2();
          this._animatedAngle = 0;
          this._body = null;
          this._rigidBody = void 0;
          this._inited = false;
        }
        var _proto = b2RigidBody2D.prototype;
        _proto.initialize = function initialize(com) {
          this._rigidBody = com;
          PhysicsSystem2D.instance._callAfterStep(this, this._init);
        };
        _proto.onDestroy = function onDestroy() {
          PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
        };
        _proto.onEnable = function onEnable() {
          this.setActive(true);
        };
        _proto.onDisable = function onDisable() {
          this.setActive(false);
        };
        _proto.nodeTransformChanged = function nodeTransformChanged(type) {
          if (PhysicsSystem2D.instance.stepping) {
            return;
          }
          if (type & Node$1.TransformBit.SCALE) {
            var colliders = this.rigidBody.getComponents(Collider2D);
            for (var i = 0; i < colliders.length; i++) {
              colliders[i].apply();
            }
          }
          if (type & Node$1.TransformBit.POSITION) {
            this.syncPositionToPhysics(true);
          }
          if (type & Node$1.TransformBit.ROTATION) {
            this.syncRotationToPhysics(true);
          }
        };
        _proto._init = function _init() {
          if (this._inited) {
            return;
          }
          PhysicsSystem2D.instance.physicsWorld.addBody(this);
          this.setActive(false);
          this._inited = true;
        };
        _proto._destroy = function _destroy() {
          if (!this._inited) return;
          PhysicsSystem2D.instance.physicsWorld.removeBody(this);
          this._inited = false;
        };
        _proto.animate = function animate(dt) {
          var b2body = this._body;
          if (!b2body) return;
          var b2Pos = b2body.GetPosition();
          b2body.SetAwake(true);
          var timeStep = 1 / dt;
          tempVec2_1.x = (this._animatedPos.x - b2Pos.x) * timeStep;
          tempVec2_1.y = (this._animatedPos.y - b2Pos.y) * timeStep;
          b2body.SetLinearVelocity(tempVec2_1);
          var b2Rotation = b2body.GetAngle() % TWO_PI;
          if (b2Rotation > Math.PI) {
            b2Rotation -= TWO_PI;
          }
          var angularVelocity = (this._animatedAngle - b2Rotation) * timeStep;
          if (this._animatedAngle < -HALF_PI && b2Rotation > HALF_PI) {
            angularVelocity = (this._animatedAngle + TWO_PI - b2Rotation) * timeStep;
          }
          if (this._animatedAngle > HALF_PI && b2Rotation < -HALF_PI) {
            angularVelocity = (this._animatedAngle - TWO_PI - b2Rotation) * timeStep;
          }
          b2body.SetAngularVelocity(angularVelocity);
        };
        _proto.syncSceneToPhysics = function syncSceneToPhysics() {
          var dirty = this._rigidBody.node.hasChangedFlags;
          if (dirty) {
            this.nodeTransformChanged(dirty);
          }
        };
        _proto.syncPositionToPhysics = function syncPositionToPhysics(enableAnimated) {
          if (enableAnimated === void 0) {
            enableAnimated = false;
          }
          var b2body = this._body;
          if (!b2body) return;
          var pos = this._rigidBody.node.worldPosition;
          var temp;
          var bodyType = this._rigidBody.type;
          if (bodyType === ERigidBody2DType.Animated) {
            temp = b2body.GetLinearVelocity();
          } else {
            temp = b2body.GetPosition();
          }
          temp.x = pos.x / PHYSICS_2D_PTM_RATIO;
          temp.y = pos.y / PHYSICS_2D_PTM_RATIO;
          if (bodyType === ERigidBody2DType.Animated && enableAnimated) {
            this._animatedPos.set(temp.x, temp.y);
          } else {
            b2body.SetTransformVec(temp, b2body.GetAngle());
          }
        };
        _proto.syncRotationToPhysics = function syncRotationToPhysics(enableAnimated) {
          if (enableAnimated === void 0) {
            enableAnimated = false;
          }
          var b2body = this._body;
          if (!b2body) return;
          var rot = this._rigidBody.node.worldRotation;
          var euler = tempVec3;
          Quat.toEulerInYXZOrder(euler, rot);
          var rotation = toRadian(euler.z);
          var bodyType = this._rigidBody.type;
          if (bodyType === ERigidBody2DType.Animated && enableAnimated) {
            this._animatedAngle = rotation;
          } else {
            b2body.SetTransformVec(b2body.GetPosition(), rotation);
          }
        };
        _proto.resetVelocity = function resetVelocity() {
          var b2body = this._body;
          if (!b2body) return;
          var temp = b2body.m_linearVelocity;
          temp.Set(0, 0);
          b2body.SetLinearVelocity(temp);
          b2body.SetAngularVelocity(0);
        };
        _proto.setType = function setType(v) {
          this._body.SetType(v);
        };
        _proto.setLinearDamping = function setLinearDamping(v) {
          this._body.SetLinearDamping(v);
        };
        _proto.setAngularDamping = function setAngularDamping(v) {
          this._body.SetAngularDamping(v);
        };
        _proto.setGravityScale = function setGravityScale(v) {
          this._body.SetGravityScale(v);
        };
        _proto.setFixedRotation = function setFixedRotation(v) {
          this._body.SetFixedRotation(v);
        };
        _proto.setAllowSleep = function setAllowSleep(v) {
          this._body.SetSleepingAllowed(v);
        };
        _proto.isActive = function isActive() {
          return this._body.IsActive();
        };
        _proto.setActive = function setActive(v) {
          this._body.SetActive(v);
        };
        _proto.wakeUp = function wakeUp() {
          this._body.SetAwake(true);
        };
        _proto.sleep = function sleep() {
          this._body.SetAwake(false);
        };
        _proto.getMass = function getMass() {
          return this._body.GetMass();
        };
        _proto.setLinearVelocity = function setLinearVelocity(v) {
          this._body.SetLinearVelocity(v);
        };
        _proto.getLinearVelocity = function getLinearVelocity(out) {
          var velocity = this._body.GetLinearVelocity();
          out.x = velocity.x;
          out.y = velocity.y;
          return out;
        };
        _proto.getLinearVelocityFromWorldPoint = function getLinearVelocityFromWorldPoint(worldPoint, out) {
          tempVec2_1.Set(worldPoint.x / PHYSICS_2D_PTM_RATIO, worldPoint.y / PHYSICS_2D_PTM_RATIO);
          this._body.GetLinearVelocityFromWorldPoint(tempVec2_1, out);
          out.x *= PHYSICS_2D_PTM_RATIO;
          out.y *= PHYSICS_2D_PTM_RATIO;
          return out;
        };
        _proto.setAngularVelocity = function setAngularVelocity(v) {
          this._body.SetAngularVelocity(v);
        };
        _proto.getAngularVelocity = function getAngularVelocity() {
          return this._body.GetAngularVelocity();
        };
        _proto.getLocalVector = function getLocalVector(worldVector, out) {
          out = out || new Vec2();
          tempVec2_1.Set(worldVector.x / PHYSICS_2D_PTM_RATIO, worldVector.y / PHYSICS_2D_PTM_RATIO);
          this._body.GetLocalVector(tempVec2_1, out);
          out.x *= PHYSICS_2D_PTM_RATIO;
          out.y *= PHYSICS_2D_PTM_RATIO;
          return out;
        };
        _proto.getWorldVector = function getWorldVector(localVector, out) {
          tempVec2_1.Set(localVector.x / PHYSICS_2D_PTM_RATIO, localVector.y / PHYSICS_2D_PTM_RATIO);
          this._body.GetWorldVector(tempVec2_1, out);
          out.x *= PHYSICS_2D_PTM_RATIO;
          out.y *= PHYSICS_2D_PTM_RATIO;
          return out;
        };
        _proto.getLocalPoint = function getLocalPoint(worldPoint, out) {
          out = out || new Vec2();
          tempVec2_1.Set(worldPoint.x / PHYSICS_2D_PTM_RATIO, worldPoint.y / PHYSICS_2D_PTM_RATIO);
          this._body.GetLocalPoint(tempVec2_1, out);
          out.x *= PHYSICS_2D_PTM_RATIO;
          out.y *= PHYSICS_2D_PTM_RATIO;
          return out;
        };
        _proto.getWorldPoint = function getWorldPoint(localPoint, out) {
          out = out || new Vec2();
          tempVec2_1.Set(localPoint.x / PHYSICS_2D_PTM_RATIO, localPoint.y / PHYSICS_2D_PTM_RATIO);
          this._body.GetWorldPoint(tempVec2_1, out);
          out.x *= PHYSICS_2D_PTM_RATIO;
          out.y *= PHYSICS_2D_PTM_RATIO;
          return out;
        };
        _proto.getLocalCenter = function getLocalCenter(out) {
          out = out || new Vec2();
          var pos = this._body.GetLocalCenter();
          out.x = pos.x * PHYSICS_2D_PTM_RATIO;
          out.y = pos.y * PHYSICS_2D_PTM_RATIO;
          return out;
        };
        _proto.getWorldCenter = function getWorldCenter(out) {
          out = out || new Vec2();
          var pos = this._body.GetWorldCenter();
          out.x = pos.x * PHYSICS_2D_PTM_RATIO;
          out.y = pos.y * PHYSICS_2D_PTM_RATIO;
          return out;
        };
        _proto.getInertia = function getInertia() {
          return this._body.GetInertia();
        };
        _proto.applyForce = function applyForce(force, point, wake) {
          if (this._body) {
            tempVec2_1.Set(point.x / PHYSICS_2D_PTM_RATIO, point.y / PHYSICS_2D_PTM_RATIO);
            this._body.ApplyForce(force, tempVec2_1, wake);
          }
        };
        _proto.applyForceToCenter = function applyForceToCenter(force, wake) {
          if (this._body) {
            this._body.ApplyForceToCenter(force, wake);
          }
        };
        _proto.applyTorque = function applyTorque(torque, wake) {
          if (this._body) {
            this._body.ApplyTorque(torque, wake);
          }
        };
        _proto.applyLinearImpulse = function applyLinearImpulse(impulse, point, wake) {
          if (this._body) {
            tempVec2_1.Set(point.x / PHYSICS_2D_PTM_RATIO, point.y / PHYSICS_2D_PTM_RATIO);
            this._body.ApplyLinearImpulse(impulse, tempVec2_1, wake);
          }
        };
        _proto.applyLinearImpulseToCenter = function applyLinearImpulseToCenter(impulse, wake) {
          if (this._body) {
            this._body.ApplyLinearImpulse(impulse, this._body.GetPosition(), wake);
          }
        };
        _proto.applyAngularImpulse = function applyAngularImpulse(impulse, wake) {
          if (this._body) {
            this._body.ApplyAngularImpulse(impulse, wake);
          }
        };
        _createClass(b2RigidBody2D, [{
          key: "impl",
          get: function get() {
            return this._body;
          }
        }, {
          key: "_imp",
          set: function set(v) {
            this._body = v;
          }
        }, {
          key: "rigidBody",
          get: function get() {
            return this._rigidBody;
          }
        }, {
          key: "isAwake",
          get: function get() {
            return this._body.IsAwake();
          }
        }, {
          key: "isSleeping",
          get: function get() {
            return !this._body.IsAwake();
          }
        }]);
        return b2RigidBody2D;
      }();

      var tempFilter = new box2d_1.Filter();
      var lowerBound = new box2d_1.Vec2();
      var upperBound = new box2d_1.Vec2();
      function getFilter(shape) {
        var comp = shape.collider;
        if (comp.body) {
          tempFilter.categoryBits = comp.group === PhysicsGroup.DEFAULT ? comp.body.group : comp.group;
        } else {
          tempFilter.categoryBits = comp.group;
        }
        tempFilter.maskBits = PhysicsSystem2D.instance.collisionMatrix[tempFilter.categoryBits];
        return tempFilter;
      }
      var b2Shape2D = function () {
        function b2Shape2D() {
          this._shapes = [];
          this._fixtures = [];
          this._collider = null;
          this._body = null;
          this._inited = false;
          this._rect = new Rect$1();
        }
        var _proto = b2Shape2D.prototype;
        _proto.initialize = function initialize(comp) {
          this._collider = comp;
        };
        _proto.onLoad = function onLoad() {};
        _proto.onEnable = function onEnable() {
          PhysicsSystem2D.instance._callAfterStep(this, this._init);
        };
        _proto.onDisable = function onDisable() {
          PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
        };
        _proto.start = function start() {};
        _proto.onGroupChanged = function onGroupChanged() {
          var filter = getFilter(this);
          this._fixtures.forEach(function (f) {
            f.SetFilterData(filter);
          });
        };
        _proto.apply = function apply() {
          this._destroy();
          if (this.collider.enabledInHierarchy) {
            this._init();
          }
        };
        _proto.getFixtureIndex = function getFixtureIndex(fixture) {
          return this._fixtures.indexOf(fixture);
        };
        _proto._createShapes = function _createShapes(scaleX, scaleY, relativePositionX, relativePositionY) {
          return [];
        };
        _proto._init = function _init() {
          if (this._inited) return;
          var comp = this.collider;
          var scale = comp.node.worldScale;
          var relativePosition = Vec3.ZERO;
          var body = comp.getComponent(RigidBody2D);
          if (body && body.impl && body.impl.impl) {
            this._body = body.impl.impl;
          } else {
            this._body = PhysicsSystem2D.instance.physicsWorld.groundBodyImpl;
            relativePosition = comp.node.worldPosition;
          }
          var shapes = scale.x === 0 && scale.y === 0 ? [] : this._createShapes(scale.x, scale.y, relativePosition.x, relativePosition.y);
          var filter = getFilter(this);
          for (var i = 0; i < shapes.length; i++) {
            var shape = shapes[i];
            var fixDef = {
              density: comp.density,
              isSensor: comp.sensor,
              friction: comp.friction,
              restitution: comp.restitution,
              shape: shape,
              filter: filter
            };
            var fixture = this._body.CreateFixture(fixDef);
            fixture.m_userData = this;
            if (body !== null && body !== void 0 && body.enabledContactListener) {
              PhysicsSystem2D.instance.physicsWorld.registerContactFixture(fixture);
            }
            this._shapes.push(shape);
            this._fixtures.push(fixture);
          }
          this._inited = true;
        };
        _proto._destroy = function _destroy() {
          if (!this._inited) return;
          var fixtures = this._fixtures;
          var body = this._body;
          for (var i = fixtures.length - 1; i >= 0; i--) {
            var fixture = fixtures[i];
            fixture.m_userData = null;
            PhysicsSystem2D.instance.physicsWorld.unregisterContactFixture(fixture);
            if (body) {
              body.DestroyFixture(fixture);
            }
          }
          this._body = null;
          this._fixtures.length = 0;
          this._shapes.length = 0;
          this._inited = false;
        };
        _createClass(b2Shape2D, [{
          key: "impl",
          get: function get() {
            return this._shapes;
          }
        }, {
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "worldAABB",
          get: function get() {
            var MAX = 10e6;
            var minX = MAX;
            var minY = MAX;
            var maxX = -MAX;
            var maxY = -MAX;
            var fixtures = this._fixtures;
            for (var i = 0; i < fixtures.length; i++) {
              var fixture = fixtures[i];
              var count = fixture.GetShape().GetChildCount();
              for (var j = 0; j < count; j++) {
                lowerBound.Copy(fixture.GetAABB(j).lowerBound);
                upperBound.Copy(fixture.GetAABB(j).upperBound);
                if (fixture.GetShape().m_type === 2) {
                  var skinWidth = fixture.GetShape().m_radius;
                  lowerBound.SelfAddXY(skinWidth, skinWidth);
                  upperBound.SelfSubXY(skinWidth, skinWidth);
                }
                if (lowerBound.x < minX) minX = lowerBound.x;
                if (lowerBound.y < minY) minY = lowerBound.y;
                if (upperBound.x > maxX) maxX = upperBound.x;
                if (upperBound.y > maxY) maxY = upperBound.y;
              }
            }
            minX *= PHYSICS_2D_PTM_RATIO;
            minY *= PHYSICS_2D_PTM_RATIO;
            maxX *= PHYSICS_2D_PTM_RATIO;
            maxY *= PHYSICS_2D_PTM_RATIO;
            var r = this._rect;
            r.x = minX;
            r.y = minY;
            r.width = maxX - minX;
            r.height = maxY - minY;
            return r;
          }
        }]);
        return b2Shape2D;
      }();

      var tempAabb = new Rect$1();
      var b2BoxShape = function (_b2Shape2D) {
        _inheritsLoose(b2BoxShape, _b2Shape2D);
        function b2BoxShape() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _b2Shape2D.call.apply(_b2Shape2D, [this].concat(args)) || this;
          _this._worldPoints = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
          return _this;
        }
        var _proto = b2BoxShape.prototype;
        _proto._createShapes = function _createShapes(scaleX, scaleY, relativePositionX, relativePositionY) {
          scaleX = Math.abs(scaleX);
          scaleY = Math.abs(scaleY);
          var comp = this.collider;
          var width = comp.size.width / 2 / PHYSICS_2D_PTM_RATIO * scaleX;
          var height = comp.size.height / 2 / PHYSICS_2D_PTM_RATIO * scaleY;
          var offsetX = (relativePositionX + comp.offset.x * scaleX) / PHYSICS_2D_PTM_RATIO;
          var offsetY = (relativePositionY + comp.offset.y * scaleY) / PHYSICS_2D_PTM_RATIO;
          var shape = new box2d_1.PolygonShape();
          shape.SetAsBox(width, height, new box2d_1.Vec2(offsetX, offsetY), 0);
          return [shape];
        };
        _createClass(b2BoxShape, [{
          key: "worldPoints",
          get: function get() {
            var aabb = tempAabb;
            var collider = this.collider;
            var size = collider.size;
            var offset = collider.offset;
            aabb.x = offset.x - size.width / 2;
            aabb.y = offset.y - size.height / 2;
            aabb.width = size.width;
            aabb.height = size.height;
            var wps = this._worldPoints;
            var wp0 = wps[0];
            var wp1 = wps[1];
            var wp2 = wps[2];
            var wp3 = wps[3];
            aabb.transformMat4ToPoints(collider.node.worldMatrix, wp0, wp1, wp2, wp3);
            return wps;
          }
        }]);
        return b2BoxShape;
      }(b2Shape2D);

      var b2CircleShape = function (_b2Shape2D) {
        _inheritsLoose(b2CircleShape, _b2Shape2D);
        function b2CircleShape() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _b2Shape2D.call.apply(_b2Shape2D, [this].concat(args)) || this;
          _this._worldPosition = new Vec2();
          return _this;
        }
        var _proto = b2CircleShape.prototype;
        _proto._createShapes = function _createShapes(scaleX, scaleY, relativePositionX, relativePositionY) {
          scaleX = Math.abs(scaleX);
          scaleY = Math.abs(scaleY);
          var comp = this.collider;
          var offsetX = (relativePositionX + comp.offset.x * scaleX) / PHYSICS_2D_PTM_RATIO;
          var offsetY = (relativePositionY + comp.offset.y * scaleY) / PHYSICS_2D_PTM_RATIO;
          var shape = new box2d_1.CircleShape();
          shape.m_radius = comp.radius / PHYSICS_2D_PTM_RATIO * scaleX;
          shape.m_p.Set(offsetX, offsetY);
          return [shape];
        };
        _createClass(b2CircleShape, [{
          key: "worldRadius",
          get: function get() {
            return this._shapes[0].m_radius * PHYSICS_2D_PTM_RATIO;
          }
        }, {
          key: "worldPosition",
          get: function get() {
            var p = this._shapes[0].m_p;
            return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
          }
        }]);
        return b2CircleShape;
      }(b2Shape2D);

      var b2PolygonShape = function (_b2Shape2D) {
        _inheritsLoose(b2PolygonShape, _b2Shape2D);
        function b2PolygonShape() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _b2Shape2D.call.apply(_b2Shape2D, [this].concat(args)) || this;
          _this._worldPoints = [];
          return _this;
        }
        var _proto = b2PolygonShape.prototype;
        _proto._createShapes = function _createShapes(scaleX, scaleY, relativePositionX, relativePositionY) {
          var shapes = [];
          var comp = this.collider;
          var points = comp.points;
          if (points.length > 0 && points[0].equals(points[points.length - 1])) {
            points.length -= 1;
          }
          var polys = ConvexPartition(points);
          if (!polys) {
            console.log('[Physics2D] b2PolygonShape failed to decompose polygon into convex polygons, node name: ', comp.node.name);
            return shapes;
          }
          var offset = comp.offset;
          for (var i = 0; i < polys.length; i++) {
            var poly = polys[i];
            var shape = null;
            var vertices = [];
            var firstVertice = null;
            for (var j = 0, l = poly.length; j < l; j++) {
              if (!shape) {
                shape = new box2d_1.PolygonShape();
              }
              var p = poly[j];
              var x = (relativePositionX + (p.x + offset.x) * scaleX) / PHYSICS_2D_PTM_RATIO;
              var y = (relativePositionY + (p.y + offset.y) * scaleY) / PHYSICS_2D_PTM_RATIO;
              var v = new box2d_1.Vec2(x, y);
              vertices.push(v);
              if (!firstVertice) {
                firstVertice = v;
              }
              if (vertices.length === box2d_1.maxPolygonVertices) {
                shape.Set(vertices, vertices.length);
                shapes.push(shape);
                shape = null;
                if (j < l - 1) {
                  vertices = [firstVertice, vertices[vertices.length - 1]];
                }
              }
            }
            if (shape) {
              shape.Set(vertices, vertices.length);
              shapes.push(shape);
            }
          }
          return shapes;
        };
        _createClass(b2PolygonShape, [{
          key: "worldPoints",
          get: function get() {
            var comp = this.collider;
            var points = comp.points;
            var worldPoints = this._worldPoints;
            var m = comp.node.worldMatrix;
            for (var i = 0; i < points.length; i++) {
              if (!worldPoints[i]) {
                worldPoints[i] = new Vec2();
              }
              Vec2.transformMat4(worldPoints[i], points[i], m);
            }
            worldPoints.length = points.length;
            return this._worldPoints;
          }
        }]);
        return b2PolygonShape;
      }(b2Shape2D);

      var b2Joint = function () {
        function b2Joint() {
          this._b2joint = null;
          this._jointComp = null;
          this._body = null;
          this._inited = false;
        }
        var _proto = b2Joint.prototype;
        _proto.initialize = function initialize(comp) {
          this._jointComp = comp;
        };
        _proto.onEnable = function onEnable() {
          PhysicsSystem2D.instance._callAfterStep(this, this._init);
        };
        _proto.onDisable = function onDisable() {
          PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
        };
        _proto.start = function start() {
          PhysicsSystem2D.instance._callAfterStep(this, this._init);
        };
        _proto.apply = function apply() {
          PhysicsSystem2D.instance._callAfterStep(this, this._destroy);
          if (this.comp.enabledInHierarchy) {
            PhysicsSystem2D.instance._callAfterStep(this, this._init);
          }
        };
        _proto._init = function _init() {
          if (this._inited) return;
          var comp = this._jointComp;
          if (!comp.isValid) {
            return;
          }
          this._body = comp.getComponent(RigidBody2D);
          var def = this._createJointDef();
          if (!def) {
            return;
          }
          def.bodyA = this._body.impl.impl;
          var connectedBody = comp.connectedBody;
          if (connectedBody && !connectedBody.enabledInHierarchy) {
            return;
          }
          if (!connectedBody) {
            def.bodyB = PhysicsSystem2D.instance.physicsWorld.groundBodyImpl;
          } else {
            def.bodyB = connectedBody.impl.impl;
          }
          def.collideConnected = comp.collideConnected;
          this._b2joint = PhysicsSystem2D.instance.physicsWorld.impl.CreateJoint(def);
          this._inited = true;
        };
        _proto._destroy = function _destroy() {
          if (!this._inited) return;
          PhysicsSystem2D.instance.physicsWorld.impl.DestroyJoint(this._b2joint);
          this._b2joint = null;
          this._inited = false;
        };
        _proto._createJointDef = function _createJointDef() {
          return null;
        };
        _proto.isValid = function isValid() {
          return this._b2joint && this._body && this._body.impl && this._jointComp;
        };
        _createClass(b2Joint, [{
          key: "impl",
          get: function get() {
            return this._b2joint;
          }
        }, {
          key: "comp",
          get: function get() {
            return this._jointComp;
          }
        }, {
          key: "body",
          get: function get() {
            return this._body;
          }
        }]);
        return b2Joint;
      }();

      var tempB2Vec2 = new box2d_1.Vec2();
      var b2MouseJoint = function (_b2Joint) {
        _inheritsLoose(b2MouseJoint, _b2Joint);
        function b2MouseJoint() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _b2Joint.call.apply(_b2Joint, [this].concat(args)) || this;
          _this._touchPoint = new Vec2();
          _this._isTouched = false;
          return _this;
        }
        var _proto = b2MouseJoint.prototype;
        _proto.setTarget = function setTarget(v) {
          if (this._b2joint) {
            tempB2Vec2.x = v.x / PHYSICS_2D_PTM_RATIO;
            tempB2Vec2.y = v.y / PHYSICS_2D_PTM_RATIO;
            this._b2joint.SetTarget(tempB2Vec2);
          }
        };
        _proto.setDampingRatio = function setDampingRatio(v) {
          if (this._b2joint) {
            this._b2joint.SetDampingRatio(v);
          }
        };
        _proto.setFrequency = function setFrequency(v) {
          if (this._b2joint) {
            this._b2joint.SetFrequency(v);
          }
        };
        _proto.setMaxForce = function setMaxForce(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxForce(v);
          }
        };
        _proto._createJointDef = function _createJointDef() {
          var def = new box2d_1.MouseJointDef();
          var comp = this._jointComp;
          def.target.Set(this._touchPoint.x / PHYSICS_2D_PTM_RATIO, this._touchPoint.y / PHYSICS_2D_PTM_RATIO);
          def.maxForce = comp.maxForce;
          def.dampingRatio = comp.dampingRatio;
          def.frequencyHz = comp.frequency;
          return def;
        };
        _proto.initialize = function initialize(comp) {
          _b2Joint.prototype.initialize.call(this, comp);
          var canvas = find('Canvas');
          if (canvas) {
            canvas.on(NodeEventType.TOUCH_START, this.onTouchBegan, this);
            canvas.on(NodeEventType.TOUCH_MOVE, this.onTouchMove, this);
            canvas.on(NodeEventType.TOUCH_END, this.onTouchEnd, this);
            canvas.on(NodeEventType.TOUCH_CANCEL, this.onTouchEnd, this);
          }
        };
        _proto.onEnable = function onEnable() {};
        _proto.start = function start() {};
        _proto.onTouchBegan = function onTouchBegan(event) {
          this._isTouched = true;
          var target = this._touchPoint.set(event.getUILocation());
          var world = PhysicsSystem2D.instance.physicsWorld;
          var colliders = world.testPoint(target);
          if (colliders.length <= 0) return;
          var body = colliders[0].body;
          body.wakeUp();
          var comp = this._jointComp;
          comp.connectedBody = body;
          this._init();
          this.setMaxForce(comp.maxForce * body.getMass());
          this.setTarget(target);
        };
        _proto.onTouchMove = function onTouchMove(event) {
          this._touchPoint = event.getUILocation();
        };
        _proto.onTouchEnd = function onTouchEnd(event) {
          this._destroy();
          this._isTouched = false;
        };
        _proto.update = function update() {
          if (!this._isTouched || !this.isValid()) {
            return;
          }
          this.setTarget(this._touchPoint);
        };
        return b2MouseJoint;
      }(b2Joint);

      var b2DistanceJoint = function (_b2Joint) {
        _inheritsLoose(b2DistanceJoint, _b2Joint);
        function b2DistanceJoint() {
          return _b2Joint.apply(this, arguments) || this;
        }
        var _proto = b2DistanceJoint.prototype;
        _proto.setMaxLength = function setMaxLength(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxLength(v);
          }
        };
        _proto._createJointDef = function _createJointDef() {
          var comp = this._jointComp;
          var def = new box2d_1.RopeJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          def.maxLength = comp.maxLength / PHYSICS_2D_PTM_RATIO;
          return def;
        };
        return b2DistanceJoint;
      }(b2Joint);

      var b2SpringJoint = function (_b2Joint) {
        _inheritsLoose(b2SpringJoint, _b2Joint);
        function b2SpringJoint() {
          return _b2Joint.apply(this, arguments) || this;
        }
        var _proto = b2SpringJoint.prototype;
        _proto.setDampingRatio = function setDampingRatio(v) {
          if (this._b2joint) {
            this._b2joint.SetDampingRatio(v);
          }
        };
        _proto.setFrequency = function setFrequency(v) {
          if (this._b2joint) {
            this._b2joint.SetFrequency(v);
          }
        };
        _proto.setDistance = function setDistance(v) {
          if (this._b2joint) {
            this._b2joint.SetLength(v);
          }
        };
        _proto._createJointDef = function _createJointDef() {
          var comp = this._jointComp;
          var def = new box2d_1.DistanceJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          def.length = comp.distance / PHYSICS_2D_PTM_RATIO;
          def.dampingRatio = comp.dampingRatio;
          def.frequencyHz = comp.frequency;
          return def;
        };
        return b2SpringJoint;
      }(b2Joint);

      var b2RelativeJoint = function (_b2Joint) {
        _inheritsLoose(b2RelativeJoint, _b2Joint);
        function b2RelativeJoint() {
          return _b2Joint.apply(this, arguments) || this;
        }
        var _proto = b2RelativeJoint.prototype;
        _proto.setMaxForce = function setMaxForce(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxForce(v);
          }
        };
        _proto.setAngularOffset = function setAngularOffset(v) {
          if (this._b2joint) {
            this._b2joint.SetAngularOffset(toRadian(v));
          }
        };
        _proto.setLinearOffset = function setLinearOffset(v) {
          if (this._b2joint) {
            this._b2joint.SetLinearOffset(new box2d_1.Vec2(v.x / PHYSICS_2D_PTM_RATIO, v.y / PHYSICS_2D_PTM_RATIO));
          }
        };
        _proto.setCorrectionFactor = function setCorrectionFactor(v) {
          if (this._b2joint) {
            this._b2joint.m_correctionFactor = v;
          }
        };
        _proto.setMaxTorque = function setMaxTorque(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxTorque(v);
          }
        };
        _proto._createJointDef = function _createJointDef() {
          var comp = this._jointComp;
          var def = new box2d_1.MotorJointDef();
          def.linearOffset.Set(comp.linearOffset.x / PHYSICS_2D_PTM_RATIO, comp.linearOffset.y / PHYSICS_2D_PTM_RATIO);
          def.angularOffset = toRadian(comp.angularOffset);
          def.maxForce = comp.maxForce;
          def.maxTorque = comp.maxTorque;
          def.correctionFactor = comp.correctionFactor;
          return def;
        };
        return b2RelativeJoint;
      }(b2Joint);

      var b2SliderJoint = function (_b2Joint) {
        _inheritsLoose(b2SliderJoint, _b2Joint);
        function b2SliderJoint() {
          return _b2Joint.apply(this, arguments) || this;
        }
        var _proto = b2SliderJoint.prototype;
        _proto.enableLimit = function enableLimit(v) {
          if (this._b2joint) {
            this._b2joint.EnableLimit(v);
          }
        };
        _proto.setLowerLimit = function setLowerLimit(v) {
          this.updateLimits();
        };
        _proto.setUpperLimit = function setUpperLimit(v) {
          this.updateLimits();
        };
        _proto.updateLimits = function updateLimits() {
          if (this._b2joint) {
            var comp = this._jointComp;
            this._b2joint.SetLimits(comp.lowerLimit / PHYSICS_2D_PTM_RATIO, comp.upperLimit / PHYSICS_2D_PTM_RATIO);
          }
        };
        _proto.enableMotor = function enableMotor(v) {
          if (this._b2joint) {
            this._b2joint.EnableMotor(v);
          }
        };
        _proto.setMaxMotorForce = function setMaxMotorForce(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxMotorForce(v);
          }
        };
        _proto.setMotorSpeed = function setMotorSpeed(v) {
          if (this._b2joint) {
            this._b2joint.SetMotorSpeed(v);
          }
        };
        _proto._createJointDef = function _createJointDef() {
          var comp = this._jointComp;
          var def = new box2d_1.PrismaticJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          var angle = toRadian(comp.angle);
          def.localAxisA.Set(Math.cos(angle), Math.sin(angle));
          def.referenceAngle = 0;
          def.enableLimit = comp.enableLimit;
          def.lowerTranslation = comp.lowerLimit / PHYSICS_2D_PTM_RATIO;
          def.upperTranslation = comp.upperLimit / PHYSICS_2D_PTM_RATIO;
          def.enableMotor = comp.enableMotor;
          def.maxMotorForce = comp.maxMotorForce;
          def.motorSpeed = comp.motorSpeed;
          return def;
        };
        return b2SliderJoint;
      }(b2Joint);

      var b2FixedJoint = function (_b2Joint) {
        _inheritsLoose(b2FixedJoint, _b2Joint);
        function b2FixedJoint() {
          return _b2Joint.apply(this, arguments) || this;
        }
        var _proto = b2FixedJoint.prototype;
        _proto.setFrequency = function setFrequency(v) {
          if (this._b2joint) {
            this._b2joint.SetFrequency(v);
          }
        };
        _proto.setDampingRatio = function setDampingRatio(v) {
          if (this._b2joint) {
            this._b2joint.SetDampingRatio(v);
          }
        };
        _proto._createJointDef = function _createJointDef() {
          var comp = this._jointComp;
          var def = new box2d_1.WeldJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          def.referenceAngle = 0;
          def.frequencyHz = comp.frequency;
          def.dampingRatio = comp.dampingRatio;
          return def;
        };
        return b2FixedJoint;
      }(b2Joint);

      var b2WheelJoint = function (_b2Joint) {
        _inheritsLoose(b2WheelJoint, _b2Joint);
        function b2WheelJoint() {
          return _b2Joint.apply(this, arguments) || this;
        }
        var _proto = b2WheelJoint.prototype;
        _proto.setDampingRatio = function setDampingRatio(v) {
          if (this._b2joint) {
            this._b2joint.SetSpringDampingRatio(v);
          }
        };
        _proto.setFrequency = function setFrequency(v) {
          if (this._b2joint) {
            this._b2joint.SetSpringFrequencyHz(v);
          }
        };
        _proto.enableMotor = function enableMotor(v) {
          if (this._b2joint) {
            this._b2joint.EnableMotor(v);
          }
        };
        _proto.setMaxMotorTorque = function setMaxMotorTorque(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxMotorTorque(v);
          }
        };
        _proto.setMotorSpeed = function setMotorSpeed(v) {
          if (this._b2joint) {
            this._b2joint.SetMotorSpeed(v);
          }
        };
        _proto._createJointDef = function _createJointDef() {
          var comp = this._jointComp;
          var def = new box2d_1.WheelJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          var angle = toRadian(comp.angle);
          def.localAxisA.Set(Math.cos(angle), Math.sin(angle));
          def.maxMotorTorque = comp.maxMotorTorque;
          def.motorSpeed = toRadian(comp.motorSpeed);
          def.enableMotor = comp.enableMotor;
          def.dampingRatio = comp.dampingRatio;
          def.frequencyHz = comp.frequency;
          return def;
        };
        return b2WheelJoint;
      }(b2Joint);

      var b2HingeJoint = function (_b2Joint) {
        _inheritsLoose(b2HingeJoint, _b2Joint);
        function b2HingeJoint() {
          return _b2Joint.apply(this, arguments) || this;
        }
        var _proto = b2HingeJoint.prototype;
        _proto.enableLimit = function enableLimit(v) {
          if (this._b2joint) {
            this._b2joint.EnableLimit(v);
          }
        };
        _proto.setLowerAngle = function setLowerAngle(v) {
          this.updateLimits();
        };
        _proto.setUpperAngle = function setUpperAngle(v) {
          this.updateLimits();
        };
        _proto.updateLimits = function updateLimits() {
          if (this._b2joint) {
            var comp = this._jointComp;
            this._b2joint.SetLimits(toRadian(comp.lowerAngle), toRadian(comp.upperAngle));
          }
        };
        _proto.enableMotor = function enableMotor(v) {
          if (this._b2joint) {
            this._b2joint.EnableMotor(v);
          }
        };
        _proto.setMaxMotorTorque = function setMaxMotorTorque(v) {
          if (this._b2joint) {
            this._b2joint.SetMaxMotorTorque(v);
          }
        };
        _proto.setMotorSpeed = function setMotorSpeed(v) {
          if (this._b2joint) {
            this._b2joint.SetMotorSpeed(v);
          }
        };
        _proto._createJointDef = function _createJointDef() {
          var comp = this._jointComp;
          var def = new box2d_1.RevoluteJointDef();
          def.localAnchorA.Set(comp.anchor.x / PHYSICS_2D_PTM_RATIO, comp.anchor.y / PHYSICS_2D_PTM_RATIO);
          def.localAnchorB.Set(comp.connectedAnchor.x / PHYSICS_2D_PTM_RATIO, comp.connectedAnchor.y / PHYSICS_2D_PTM_RATIO);
          def.enableMotor = comp.enableMotor;
          def.maxMotorTorque = comp.maxMotorTorque;
          def.motorSpeed = toRadian(comp.motorSpeed);
          def.enableLimit = comp.enableLimit;
          def.lowerAngle = toRadian(comp.lowerAngle);
          def.upperAngle = toRadian(comp.upperAngle);
          return def;
        };
        return b2HingeJoint;
      }(b2Joint);

      game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, function () {
        selector$1.register('box2d', {
          PhysicsWorld: b2PhysicsWorld,
          RigidBody: b2RigidBody2D,
          BoxShape: b2BoxShape,
          CircleShape: b2CircleShape,
          PolygonShape: b2PolygonShape,
          MouseJoint: b2MouseJoint,
          DistanceJoint: b2DistanceJoint,
          SpringJoint: b2SpringJoint,
          RelativeJoint: b2RelativeJoint,
          SliderJoint: b2SliderJoint,
          FixedJoint: b2FixedJoint,
          WheelJoint: b2WheelJoint,
          HingeJoint: b2HingeJoint
        });
      });

      function updateLegacyMacro(id) {
        legacyCC._global.CC_PHYSICS_BUILTIN = id === 'builtin';
        legacyCC._global.CC_PHYSICS_CANNON = id === 'cannon.js';
        legacyCC._global.CC_PHYSICS_AMMO = id === 'bullet';
      }
      function register(id, wrapper) {
        log("[PHYSICS]: register " + id + ".");
        selector.backend[id] = wrapper;
        if (!selector.physicsWorld || selector.id === id) {
          updateLegacyMacro(id);
          var mutableSelector = selector;
          mutableSelector.id = id;
          mutableSelector.wrapper = wrapper;
        }
      }
      var worldInitData;
      function switchTo(id) {
        if (!selector.runInEditor) return;
        var mutableSelector = selector;
        if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
          selector.physicsWorld.destroy();
          log("[PHYSICS]: switch from " + selector.id + " to " + id + ".");
          updateLegacyMacro(id);
          mutableSelector.id = id;
          mutableSelector.wrapper = selector.backend[id];
          mutableSelector.physicsWorld = createPhysicsWorld();
        } else {
          log("[PHYSICS]: using " + id + ".");
          mutableSelector.physicsWorld = createPhysicsWorld();
        }
        if (worldInitData) {
          var world = mutableSelector.physicsWorld;
          world.setGravity(worldInitData.gravity);
          world.setAllowSleep(worldInitData.allowSleep);
        }
      }
      var selector = {
        id: '',
        switchTo: switchTo,
        register: register,
        wrapper: {},
        backend: {},
        physicsWorld: null,
        runInEditor: !EDITOR
      };
      function constructDefaultWorld(data) {
        if (!worldInitData) worldInitData = data;
        if (!selector.runInEditor) return;
        if (!selector.physicsWorld) {
          log("[PHYSICS]: using " + selector.id + ".");
          var mutableSelector = selector;
          var world = mutableSelector.physicsWorld = createPhysicsWorld();
          world.setGravity(worldInitData.gravity);
          world.setAllowSleep(worldInitData.allowSleep);
        }
      }
      var FUNC = function FUNC() {
        return 0;
      };
      var ENTIRE_WORLD = {
        impl: null,
        debugDrawFlags: 0,
        debugDrawConstraintSize: 0,
        setGravity: FUNC,
        setAllowSleep: FUNC,
        setDefaultMaterial: FUNC,
        step: FUNC,
        syncAfterEvents: FUNC,
        syncSceneToPhysics: FUNC,
        raycast: FUNC,
        raycastClosest: FUNC,
        sweepBox: FUNC,
        sweepBoxClosest: FUNC,
        sweepSphere: FUNC,
        sweepSphereClosest: FUNC,
        sweepCapsule: FUNC,
        sweepCapsuleClosest: FUNC,
        emitEvents: FUNC,
        destroy: FUNC
      };
      var ECheckType;
      (function (ECheckType) {
        ECheckType[ECheckType["World"] = 0] = "World";
        ECheckType[ECheckType["RigidBody"] = 1] = "RigidBody";
        ECheckType[ECheckType["BoxCollider"] = 2] = "BoxCollider";
        ECheckType[ECheckType["SphereCollider"] = 3] = "SphereCollider";
        ECheckType[ECheckType["CapsuleCollider"] = 4] = "CapsuleCollider";
        ECheckType[ECheckType["MeshCollider"] = 5] = "MeshCollider";
        ECheckType[ECheckType["CylinderCollider"] = 6] = "CylinderCollider";
        ECheckType[ECheckType["ConeCollider"] = 7] = "ConeCollider";
        ECheckType[ECheckType["TerrainCollider"] = 8] = "TerrainCollider";
        ECheckType[ECheckType["SimplexCollider"] = 9] = "SimplexCollider";
        ECheckType[ECheckType["PlaneCollider"] = 10] = "PlaneCollider";
        ECheckType[ECheckType["PointToPointConstraint"] = 11] = "PointToPointConstraint";
        ECheckType[ECheckType["HingeConstraint"] = 12] = "HingeConstraint";
        ECheckType[ECheckType["FixedConstraint"] = 13] = "FixedConstraint";
        ECheckType[ECheckType["ConfigurableConstraint"] = 14] = "ConfigurableConstraint";
        ECheckType[ECheckType["BoxCharacterController"] = 15] = "BoxCharacterController";
        ECheckType[ECheckType["CapsuleCharacterController"] = 16] = "CapsuleCharacterController";
      })(ECheckType || (ECheckType = {}));
      function check(obj, type) {
        if (obj == null) {
          if (selector.id) {
            warn(selector.id + " physics does not support " + ECheckType[type]);
          } else {
            errorID(9600);
          }
          return true;
        }
        return false;
      }
      function createPhysicsWorld() {
        if (check(selector.wrapper.PhysicsWorld, ECheckType.World)) {
          return ENTIRE_WORLD;
        }
        return new selector.wrapper.PhysicsWorld();
      }
      var ENTIRE_RIGID_BODY = {
        impl: null,
        rigidBody: null,
        isAwake: false,
        isSleepy: false,
        isSleeping: false,
        initialize: FUNC,
        onEnable: FUNC,
        onDisable: FUNC,
        onDestroy: FUNC,
        setType: FUNC,
        setMass: FUNC,
        setLinearDamping: FUNC,
        setAngularDamping: FUNC,
        useGravity: FUNC,
        setLinearFactor: FUNC,
        setAngularFactor: FUNC,
        setAllowSleep: FUNC,
        wakeUp: FUNC,
        sleep: FUNC,
        clearState: FUNC,
        clearForces: FUNC,
        clearVelocity: FUNC,
        setSleepThreshold: FUNC,
        getSleepThreshold: FUNC,
        getLinearVelocity: FUNC,
        setLinearVelocity: FUNC,
        getAngularVelocity: FUNC,
        setAngularVelocity: FUNC,
        applyForce: FUNC,
        applyLocalForce: FUNC,
        applyImpulse: FUNC,
        applyLocalImpulse: FUNC,
        applyTorque: FUNC,
        applyLocalTorque: FUNC,
        setGroup: FUNC,
        getGroup: FUNC,
        addGroup: FUNC,
        removeGroup: FUNC,
        setMask: FUNC,
        getMask: FUNC,
        addMask: FUNC,
        removeMask: FUNC,
        isUsingCCD: FUNC,
        useCCD: FUNC
      };
      function createRigidBody() {
        if (check(selector.wrapper.RigidBody, ECheckType.RigidBody)) {
          return ENTIRE_RIGID_BODY;
        }
        return new selector.wrapper.RigidBody();
      }
      var CREATE_COLLIDER_PROXY = {
        INITED: false
      };
      var ENTIRE_SHAPE = {
        impl: null,
        collider: null,
        attachedRigidBody: null,
        initialize: FUNC,
        onLoad: FUNC,
        onEnable: FUNC,
        onDisable: FUNC,
        onDestroy: FUNC,
        setGroup: FUNC,
        getGroup: FUNC,
        addGroup: FUNC,
        removeGroup: FUNC,
        setMask: FUNC,
        getMask: FUNC,
        addMask: FUNC,
        removeMask: FUNC,
        setMaterial: FUNC,
        setAsTrigger: FUNC,
        setCenter: FUNC,
        getAABB: FUNC,
        getBoundingSphere: FUNC,
        updateSize: FUNC,
        updateRadius: FUNC,
        setRadius: FUNC,
        setCylinderHeight: FUNC,
        setDirection: FUNC,
        setHeight: FUNC,
        setShapeType: FUNC,
        setVertices: FUNC,
        setMesh: FUNC,
        setTerrain: FUNC,
        setNormal: FUNC,
        setConstant: FUNC,
        updateEventListener: FUNC
      };
      function createShape(type) {
        initColliderProxy();
        return CREATE_COLLIDER_PROXY[type]();
      }
      function initColliderProxy() {
        if (CREATE_COLLIDER_PROXY.INITED) return;
        CREATE_COLLIDER_PROXY.INITED = true;
        CREATE_COLLIDER_PROXY[EColliderType.BOX] = function createBoxShape() {
          if (check(selector.wrapper.BoxShape, ECheckType.BoxCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.BoxShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.SPHERE] = function createSphereShape() {
          if (check(selector.wrapper.SphereShape, ECheckType.SphereCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.SphereShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.CAPSULE] = function createCapsuleShape() {
          if (check(selector.wrapper.CapsuleShape, ECheckType.CapsuleCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.CapsuleShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.CYLINDER] = function createCylinderShape() {
          if (check(selector.wrapper.CylinderShape, ECheckType.CylinderCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.CylinderShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.CONE] = function createConeShape() {
          if (check(selector.wrapper.ConeShape, ECheckType.ConeCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.ConeShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.MESH] = function createTrimeshShape() {
          if (check(selector.wrapper.TrimeshShape, ECheckType.MeshCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.TrimeshShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.TERRAIN] = function createTerrainShape() {
          if (check(selector.wrapper.TerrainShape, ECheckType.TerrainCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.TerrainShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.SIMPLEX] = function createSimplexShape() {
          if (check(selector.wrapper.SimplexShape, ECheckType.SimplexCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.SimplexShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.PLANE] = function createPlaneShape() {
          if (check(selector.wrapper.PlaneShape, ECheckType.PlaneCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.PlaneShape();
        };
      }
      var CREATE_CONSTRAINT_PROXY = {
        INITED: false
      };
      var ENTIRE_CONSTRAINT = {
        impl: null,
        initialize: FUNC,
        onLoad: FUNC,
        onEnable: FUNC,
        onDisable: FUNC,
        onDestroy: FUNC,
        setEnableCollision: FUNC,
        setConnectedBody: FUNC,
        setPivotA: FUNC,
        setPivotB: FUNC,
        setAxis: FUNC,
        setSecondaryAxis: FUNC,
        setBreakForce: FUNC,
        setBreakTorque: FUNC,
        setConstraintMode: FUNC,
        setLinearLimit: FUNC,
        setAngularExtent: FUNC,
        setLinearSoftConstraint: FUNC,
        setLinearStiffness: FUNC,
        setLinearDamping: FUNC,
        setLinearRestitution: FUNC,
        setSwingSoftConstraint: FUNC,
        setTwistSoftConstraint: FUNC,
        setSwingStiffness: FUNC,
        setSwingDamping: FUNC,
        setSwingRestitution: FUNC,
        setTwistStiffness: FUNC,
        setTwistDamping: FUNC,
        setTwistRestitution: FUNC,
        setDriverMode: FUNC,
        setLinearMotorTarget: FUNC,
        setLinearMotorVelocity: FUNC,
        setLinearMotorForceLimit: FUNC,
        setAngularMotorTarget: FUNC,
        setAngularMotorVelocity: FUNC,
        setAngularMotorForceLimit: FUNC,
        setAutoPivotB: FUNC,
        setLimitEnabled: FUNC,
        setLowerLimit: FUNC,
        setUpperLimit: FUNC,
        setMotorEnabled: FUNC,
        setMotorVelocity: FUNC,
        setMotorForceLimit: FUNC
      };
      function createConstraint(type) {
        initConstraintProxy();
        return CREATE_CONSTRAINT_PROXY[type]();
      }
      function initConstraintProxy() {
        if (CREATE_CONSTRAINT_PROXY.INITED) return;
        CREATE_CONSTRAINT_PROXY.INITED = true;
        CREATE_CONSTRAINT_PROXY[EConstraintType.POINT_TO_POINT] = function createPointToPointConstraint() {
          if (check(selector.wrapper.PointToPointConstraint, ECheckType.PointToPointConstraint)) {
            return ENTIRE_CONSTRAINT;
          }
          return new selector.wrapper.PointToPointConstraint();
        };
        CREATE_CONSTRAINT_PROXY[EConstraintType.HINGE] = function createHingeConstraint() {
          if (check(selector.wrapper.HingeConstraint, ECheckType.HingeConstraint)) {
            return ENTIRE_CONSTRAINT;
          }
          return new selector.wrapper.HingeConstraint();
        };
        CREATE_CONSTRAINT_PROXY[EConstraintType.FIXED] = function createFixedConstraint() {
          if (check(selector.wrapper.FixedConstraint, ECheckType.FixedConstraint)) {
            return ENTIRE_CONSTRAINT;
          }
          return new selector.wrapper.FixedConstraint();
        };
        CREATE_CONSTRAINT_PROXY[EConstraintType.CONFIGURABLE] = function createConfigurableConstraint() {
          if (check(selector.wrapper.ConfigurableConstraint, ECheckType.ConfigurableConstraint)) {
            return ENTIRE_CONSTRAINT;
          }
          return new selector.wrapper.ConfigurableConstraint();
        };
      }
      var CREATE_CHARACTER_CONTROLLER_PROXY = {
        INITED: false
      };
      var ENTIRE_CHARACTER_CONTROLLER = {
        initialize: FUNC,
        onLoad: FUNC,
        onEnable: FUNC,
        onDisable: FUNC,
        onDestroy: FUNC,
        onGround: FUNC,
        getPosition: FUNC,
        setPosition: FUNC,
        setStepOffset: FUNC,
        setSlopeLimit: FUNC,
        setContactOffset: FUNC,
        setDetectCollisions: FUNC,
        setOverlapRecovery: FUNC,
        setGroup: FUNC,
        getGroup: FUNC,
        addGroup: FUNC,
        removeGroup: FUNC,
        setMask: FUNC,
        getMask: FUNC,
        addMask: FUNC,
        removeMask: FUNC,
        move: FUNC,
        syncPhysicsToScene: FUNC,
        updateEventListener: FUNC,
        setHalfHeight: FUNC,
        setHalfSideExtent: FUNC,
        setHalfForwardExtent: FUNC,
        setRadius: FUNC,
        setHeight: FUNC
      };
      function createCharacterController(type) {
        initCharacterControllerProxy();
        return CREATE_CHARACTER_CONTROLLER_PROXY[type]();
      }
      function initCharacterControllerProxy() {
        if (CREATE_CHARACTER_CONTROLLER_PROXY.INITED) return;
        CREATE_CHARACTER_CONTROLLER_PROXY.INITED = true;
        CREATE_CHARACTER_CONTROLLER_PROXY[ECharacterControllerType.BOX] = function createBoxCharacterController() {
          if (check(selector.wrapper.BoxCharacterController, ECheckType.BoxCharacterController)) {
            return ENTIRE_CHARACTER_CONTROLLER;
          }
          return new selector.wrapper.BoxCharacterController();
        };
        CREATE_CHARACTER_CONTROLLER_PROXY[ECharacterControllerType.CAPSULE] = function createCapsuleCharacterController() {
          if (check(selector.wrapper.CapsuleCharacterController, ECheckType.CapsuleCharacterController)) {
            return ENTIRE_CHARACTER_CONTROLLER;
          }
          return new selector.wrapper.CapsuleCharacterController();
        };
      }

      var EBulletType;
      (function (EBulletType) {
        EBulletType[EBulletType["EBulletTypeVec3"] = 0] = "EBulletTypeVec3";
        EBulletType[EBulletType["EBulletTypeQuat"] = 1] = "EBulletTypeQuat";
        EBulletType[EBulletType["EBulletTypeTransform"] = 2] = "EBulletTypeTransform";
        EBulletType[EBulletType["EBulletTypeMotionState"] = 3] = "EBulletTypeMotionState";
        EBulletType[EBulletType["EBulletTypeCollisionObject"] = 4] = "EBulletTypeCollisionObject";
        EBulletType[EBulletType["EBulletTypeCollisionShape"] = 5] = "EBulletTypeCollisionShape";
        EBulletType[EBulletType["EBulletTypeCharacterController"] = 6] = "EBulletTypeCharacterController";
        EBulletType[EBulletType["EBulletTypeStridingMeshInterface"] = 7] = "EBulletTypeStridingMeshInterface";
        EBulletType[EBulletType["EBulletTypeTriangleMesh"] = 8] = "EBulletTypeTriangleMesh";
        EBulletType[EBulletType["EBulletTypeCollisionDispatcher"] = 9] = "EBulletTypeCollisionDispatcher";
        EBulletType[EBulletType["EBulletTypeDbvtBroadPhase"] = 10] = "EBulletTypeDbvtBroadPhase";
        EBulletType[EBulletType["EBulletTypeSequentialImpulseConstraintSolver"] = 11] = "EBulletTypeSequentialImpulseConstraintSolver";
        EBulletType[EBulletType["EBulletTypeCollisionWorld"] = 12] = "EBulletTypeCollisionWorld";
        EBulletType[EBulletType["EBulletTypeTypedConstraint"] = 13] = "EBulletTypeTypedConstraint";
        EBulletType[EBulletType["EBulletTypeDebugDraw"] = 14] = "EBulletTypeDebugDraw";
      })(EBulletType || (EBulletType = {}));
      var EBulletTriangleRaycastFlag;
      (function (EBulletTriangleRaycastFlag) {
        EBulletTriangleRaycastFlag[EBulletTriangleRaycastFlag["NONE"] = 0] = "NONE";
        EBulletTriangleRaycastFlag[EBulletTriangleRaycastFlag["FilterBackfaces"] = 1] = "FilterBackfaces";
        EBulletTriangleRaycastFlag[EBulletTriangleRaycastFlag["KeepUnflippedNormal"] = 2] = "KeepUnflippedNormal";
        EBulletTriangleRaycastFlag[EBulletTriangleRaycastFlag["UseSubSimplexConvexCastRaytest"] = 4] = "UseSubSimplexConvexCastRaytest";
        EBulletTriangleRaycastFlag[EBulletTriangleRaycastFlag["UseGjkConvexCastRaytest"] = 8] = "UseGjkConvexCastRaytest";
      })(EBulletTriangleRaycastFlag || (EBulletTriangleRaycastFlag = {}));
      var EBulletDebugDrawModes;
      (function (EBulletDebugDrawModes) {
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_NoDebug"] = 0] = "DBG_NoDebug";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_DrawWireframe"] = 1] = "DBG_DrawWireframe";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_DrawAabb"] = 2] = "DBG_DrawAabb";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_DrawFeaturesText"] = 4] = "DBG_DrawFeaturesText";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_DrawContactPoints"] = 8] = "DBG_DrawContactPoints";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_NoDeactivation"] = 16] = "DBG_NoDeactivation";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_NoHelpText"] = 32] = "DBG_NoHelpText";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_DrawText"] = 64] = "DBG_DrawText";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_ProfileTimings"] = 128] = "DBG_ProfileTimings";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_EnableSatComparison"] = 256] = "DBG_EnableSatComparison";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_DisableBulletLCP"] = 512] = "DBG_DisableBulletLCP";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_EnableCCD"] = 1024] = "DBG_EnableCCD";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_DrawConstraints"] = 2048] = "DBG_DrawConstraints";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_DrawConstraintLimits"] = 4096] = "DBG_DrawConstraintLimits";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_FastWireframe"] = 8192] = "DBG_FastWireframe";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_DrawNormals"] = 16384] = "DBG_DrawNormals";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_DrawFrames"] = 32768] = "DBG_DrawFrames";
        EBulletDebugDrawModes[EBulletDebugDrawModes["DBG_MAX_DEBUG_DRAW_MODE"] = 32769] = "DBG_MAX_DEBUG_DRAW_MODE";
      })(EBulletDebugDrawModes || (EBulletDebugDrawModes = {}));
      var bt = {};
      var btCache = {};
      btCache.BODY_CACHE_NAME = 'body';
      btCache.CCT_CACHE_NAME = 'cct';
      function initWASM(wasmFactory, wasmUrl) {
        return new Promise(function (resolve, reject) {
          var errorMessage = function errorMessage(err) {
            return "[bullet]: bullet wasm lib load failed: " + err;
          };
          wasmFactory({
            instantiateWasm: function instantiateWasm$1(importObject, receiveInstance) {
              instantiateWasm(wasmUrl, importObject).then(function (result) {
                receiveInstance(result.instance, result.module);
              })["catch"](function (err) {
                return reject(errorMessage(err));
              });
            }
          }).then(function (instance) {
            log('[bullet]:bullet wasm lib loaded.');
            bt = instance;
          }).then(resolve)["catch"](function (err) {
            return reject(errorMessage(err));
          });
        });
      }
      function initASM(asmFactory) {
        if (asmFactory != null) {
          return asmFactory().then(function (instance) {
            log('[bullet]:bullet asm lib loaded.');
            bt = instance;
          });
        } else {
          return new Promise(function (resolve, reject) {
            resolve();
          });
        }
      }
      function shouldUseWasmModule$1() {
        {
          return sys.hasFeature(sys.Feature.WASM);
        }
      }
      function waitForAmmoInstantiation() {
        var errorReport = function errorReport(msg) {
          error(msg);
        };
        return ensureWasmModuleReady().then(function () {
          if (shouldUseWasmModule$1()) {
            return Promise.all([module.import('./bullet.release.wasm-2a6098be.js'), module.import('./bullet.release.wasm-e702f478.js')]).then(function (_ref) {
              var bulletWasmFactory = _ref[0]["default"],
                bulletWasmUrl = _ref[1]["default"];
              return initWASM(bulletWasmFactory, bulletWasmUrl);
            });
          } else {
            return module.import('./bullet.release.asm-8c1fefd7.js').then(function (_ref2) {
              var bulletAsmFactory = _ref2["default"];
              return initASM(bulletAsmFactory);
            });
          }
        })["catch"](errorReport);
      }
      game.onPostInfrastructureInitDelegate.add(waitForAmmoInstantiation);

      var TriggerEventObject = {
        type: 'onTriggerEnter',
        selfCollider: null,
        otherCollider: null,
        impl: null
      };
      var CollisionEventObject = {
        type: 'onCollisionEnter',
        selfCollider: null,
        otherCollider: null,
        contacts: [],
        impl: null
      };
      var CharacterTriggerEventObject = {
        type: 'onControllerTriggerEnter',
        collider: null,
        characterController: null,
        impl: null
      };
      var BulletCache = function () {
        function BulletCache() {
          this.BT_TRANSFORM_0 = bt.Transform_new();
          this.BT_TRANSFORM_1 = bt.Transform_new();
          this.BT_V3_0 = bt.Vec3_new(0, 0, 0);
          this.BT_V3_1 = bt.Vec3_new(0, 0, 0);
          this.BT_V3_2 = bt.Vec3_new(0, 0, 0);
          this.BT_QUAT_0 = bt.Quat_new(0, 0, 0, 1);
        }
        BulletCache.setWrapper = function setWrapper(impl, type, wrap) {
          if (!this.ROOT[type]) this.ROOT[type] = {};
          this.ROOT[type][impl] = wrap;
        };
        BulletCache.delWrapper = function delWrapper(impl, type) {
          delete this.ROOT[type][impl];
        };
        BulletCache.getWrapper = function getWrapper(ptr, type) {
          return this.ROOT[type][ptr];
        };
        BulletCache.isNotEmptyShape = function isNotEmptyShape(ptr) {
          return ptr !== bt.EmptyShape_static();
        };
        _createClass(BulletCache, null, [{
          key: "instance",
          get: function get() {
            if (BulletCache._instance == null) BulletCache._instance = new BulletCache();
            return BulletCache._instance;
          }
        }]);
        return BulletCache;
      }();
      BulletCache._instance = void 0;
      BulletCache.ROOT = {};
      var CC_V3_0 = new Vec3();
      var CC_V3_1 = new Vec3();
      var CC_V3_2 = new Vec3();
      var CC_QUAT_0 = new Quat();
      var CC_QUAT_1 = new Quat();
      var CC_MAT4_0 = new Mat4();
      new Mat4();
      var CC_COLOR_0 = new Color$1();
      btCache.CACHE = BulletCache;

      function cocos2BulletVec3(out, v) {
        bt.Vec3_set(out, v.x, v.y, v.z);
        return out;
      }
      function bullet2CocosVec3(out, v) {
        var rawVertexBuffer = bt.HEAPF32.subarray(v / 4, v / 4 + 3);
        out.x = rawVertexBuffer[0];
        out.y = rawVertexBuffer[1];
        out.z = rawVertexBuffer[2];
        return out;
      }
      function cocos2BulletQuat(out, q) {
        bt.Quat_set(out, q.x, q.y, q.z, q.w);
        return out;
      }
      function bullet2CocosQuat(out, q) {
        var rawVertexBuffer = bt.HEAPF32.subarray(q / 4, q / 4 + 4);
        out.x = rawVertexBuffer[0];
        out.y = rawVertexBuffer[1];
        out.z = rawVertexBuffer[2];
        out.w = rawVertexBuffer[3];
        return out;
      }
      function cocos2BulletTriMesh(out, mesh) {
        var len = mesh.renderingSubMeshes.length;
        for (var i = 0; i < len; i++) {
          var subMesh = mesh.renderingSubMeshes[i];
          var geoInfo = subMesh.geometricInfo;
          if (geoInfo) {
            var primitiveMode = subMesh.primitiveMode;
            var vb = geoInfo.positions;
            var ib = geoInfo.indices;
            var v0 = BulletCache.instance.BT_V3_0;
            var v1 = BulletCache.instance.BT_V3_1;
            var v2 = BulletCache.instance.BT_V3_2;
            if (primitiveMode === PrimitiveMode.TRIANGLE_LIST) {
              var cnt = ib.length;
              for (var j = 0; j < cnt; j += 3) {
                var i0 = ib[j] * 3;
                var i1 = ib[j + 1] * 3;
                var i2 = ib[j + 2] * 3;
                bt.Vec3_set(v0, vb[i0], vb[i0 + 1], vb[i0 + 2]);
                bt.Vec3_set(v1, vb[i1], vb[i1 + 1], vb[i1 + 2]);
                bt.Vec3_set(v2, vb[i2], vb[i2 + 1], vb[i2 + 2]);
                bt.TriangleMesh_addTriangle(out, v0, v1, v2, false);
              }
            } else if (primitiveMode === PrimitiveMode.TRIANGLE_STRIP) {
              var _cnt = ib.length - 2;
              var rev = 0;
              for (var _j = 0; _j < _cnt; _j += 1) {
                var _i = ib[_j - rev] * 3;
                var _i2 = ib[_j + rev + 1] * 3;
                var _i3 = ib[_j + 2] * 3;
                rev = ~rev;
                bt.Vec3_set(v0, vb[_i], vb[_i + 1], vb[_i + 2]);
                bt.Vec3_set(v1, vb[_i2], vb[_i2 + 1], vb[_i2 + 2]);
                bt.Vec3_set(v2, vb[_i3], vb[_i3 + 1], vb[_i3 + 2]);
                bt.TriangleMesh_addTriangle(out, v0, v1, v2, false);
              }
            } else if (primitiveMode === PrimitiveMode.TRIANGLE_FAN) {
              var _cnt2 = ib.length - 1;
              var _i4 = ib[0] * 3;
              bt.Vec3_set(v0, vb[_i4], vb[_i4 + 1], vb[_i4 + 2]);
              for (var _j2 = 1; _j2 < _cnt2; _j2 += 1) {
                var _i5 = ib[_j2] * 3;
                var _i6 = ib[_j2 + 1] * 3;
                bt.Vec3_set(v1, vb[_i5], vb[_i5 + 1], vb[_i5 + 2]);
                bt.Vec3_set(v2, vb[_i6], vb[_i6 + 1], vb[_i6 + 2]);
                bt.TriangleMesh_addTriangle(out, v0, v1, v2, false);
              }
            }
          }
        }
        return out;
      }
      function force2Impulse(force, dt) {
        return force * dt;
      }

      var _dec$R, _dec2$M, _dec3$A, _dec4$r, _dec5$p, _class$Q, _class2$M, _initializer$K, _initializer2$G, _initializer3$u, _initializer4$n, _class3$l;
      var PhysicsMaterial = exports('fL', (_dec$R = ccclass$M('cc.PhysicsMaterial'), _dec2$M = type$d(CCFloat), _dec3$A = type$d(CCFloat), _dec4$r = type$d(CCFloat), _dec5$p = type$d(CCFloat), _dec$R(_class$Q = (_class2$M = (_class3$l = function (_Asset) {
        _inheritsLoose(PhysicsMaterial, _Asset);
        function PhysicsMaterial() {
          var _this;
          _this = _Asset.call(this) || this;
          _this.id = void 0;
          _this._friction = _initializer$K && _initializer$K();
          _this._rollingFriction = _initializer2$G && _initializer2$G();
          _this._spinningFriction = _initializer3$u && _initializer3$u();
          _this._restitution = _initializer4$n && _initializer4$n();
          PhysicsMaterial.allMaterials.push(_assertThisInitialized(_this));
          _this.id = PhysicsMaterial._idCounter++;
          if (!_this._uuid) _this._uuid = "pm_" + _this.id;
          return _this;
        }
        var _proto = PhysicsMaterial.prototype;
        _proto.clone = function clone() {
          var c = new PhysicsMaterial();
          c._friction = this._friction;
          c._restitution = this._restitution;
          c._rollingFriction = this._rollingFriction;
          c._spinningFriction = this._spinningFriction;
          return c;
        };
        _proto.destroy = function destroy() {
          if (_Asset.prototype.destroy.call(this)) {
            var idx = PhysicsMaterial.allMaterials.indexOf(this);
            if (idx >= 0) {
              PhysicsMaterial.allMaterials.splice(idx, 1);
            }
            return true;
          }
          return false;
        };
        _proto.setValues = function setValues(friction, rollingFriction, spinningFriction, restitution) {
          var emitUpdate = this._friction !== friction || this._rollingFriction !== rollingFriction || this._spinningFriction !== spinningFriction || this._restitution !== restitution;
          this._friction = friction;
          this._rollingFriction = rollingFriction;
          this._spinningFriction = spinningFriction;
          this._restitution = restitution;
          if (emitUpdate) this.emit(PhysicsMaterial.EVENT_UPDATE);
        };
        _createClass(PhysicsMaterial, [{
          key: "friction",
          get: function get() {
            return this._friction;
          },
          set: function set(value) {
            if (!equals$2(this._friction, value)) {
              this._friction = value;
              this.emit(PhysicsMaterial.EVENT_UPDATE);
            }
          }
        }, {
          key: "rollingFriction",
          get: function get() {
            return this._rollingFriction;
          },
          set: function set(value) {
            if (!equals$2(this._rollingFriction, value)) {
              this._rollingFriction = value;
              this.emit(PhysicsMaterial.EVENT_UPDATE);
            }
          }
        }, {
          key: "spinningFriction",
          get: function get() {
            return this._spinningFriction;
          },
          set: function set(value) {
            if (!equals$2(this._spinningFriction, value)) {
              this._spinningFriction = value;
              this.emit(PhysicsMaterial.EVENT_UPDATE);
            }
          }
        }, {
          key: "restitution",
          get: function get() {
            return this._restitution;
          },
          set: function set(value) {
            if (!equals$2(this._restitution, value)) {
              this._restitution = value;
              this.emit(PhysicsMaterial.EVENT_UPDATE);
            }
          }
        }]);
        return PhysicsMaterial;
      }(Asset), _class3$l.allMaterials = [], _class3$l.EVENT_UPDATE = 'event_update', _class3$l._idCounter = 0, _class3$l), (_applyDecoratedDescriptor(_class2$M.prototype, "friction", [_dec2$M], Object.getOwnPropertyDescriptor(_class2$M.prototype, "friction"), _class2$M.prototype), _applyDecoratedDescriptor(_class2$M.prototype, "rollingFriction", [_dec3$A], Object.getOwnPropertyDescriptor(_class2$M.prototype, "rollingFriction"), _class2$M.prototype), _applyDecoratedDescriptor(_class2$M.prototype, "spinningFriction", [_dec4$r], Object.getOwnPropertyDescriptor(_class2$M.prototype, "spinningFriction"), _class2$M.prototype), _applyDecoratedDescriptor(_class2$M.prototype, "restitution", [_dec5$p], Object.getOwnPropertyDescriptor(_class2$M.prototype, "restitution"), _class2$M.prototype), _initializer$K = applyDecoratedInitializer(_class2$M.prototype, "_friction", [serializable$p], function () {
        return 0.6;
      }), _initializer2$G = applyDecoratedInitializer(_class2$M.prototype, "_rollingFriction", [serializable$p], function () {
        return 0.0;
      }), _initializer3$u = applyDecoratedInitializer(_class2$M.prototype, "_spinningFriction", [serializable$p], function () {
        return 0.0;
      }), _initializer4$n = applyDecoratedInitializer(_class2$M.prototype, "_restitution", [serializable$p], function () {
        return 0.0;
      })), _class2$M)) || _class$Q));

      var PhysicsRayResult = exports('fM', function () {
        function PhysicsRayResult() {
          this._hitPoint = new Vec3();
          this._hitNormal = new Vec3();
          this._distance = 0;
          this._collider = null;
        }
        var _proto = PhysicsRayResult.prototype;
        _proto._assign = function _assign(hitPoint, distance, collider, hitNormal) {
          Vec3.copy(this._hitPoint, hitPoint);
          Vec3.copy(this._hitNormal, hitNormal);
          this._distance = distance;
          this._collider = collider;
        };
        _proto.clone = function clone() {
          var c = new PhysicsRayResult();
          Vec3.copy(c._hitPoint, this._hitPoint);
          Vec3.copy(c._hitNormal, this._hitNormal);
          c._distance = this._distance;
          c._collider = this._collider;
          return c;
        };
        _createClass(PhysicsRayResult, [{
          key: "hitPoint",
          get: function get() {
            return this._hitPoint;
          }
        }, {
          key: "distance",
          get: function get() {
            return this._distance;
          }
        }, {
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "hitNormal",
          get: function get() {
            return this._hitNormal;
          }
        }]);
        return PhysicsRayResult;
      }());
      var PhysicsLineStripCastResult = exports('fN', function (_PhysicsRayResult) {
        _inheritsLoose(PhysicsLineStripCastResult, _PhysicsRayResult);
        function PhysicsLineStripCastResult() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PhysicsRayResult.call.apply(_PhysicsRayResult, [this].concat(args)) || this;
          _this._id = 0;
          return _this;
        }
        var _proto2 = PhysicsLineStripCastResult.prototype;
        _proto2._assign = function _assign(hitPoint, distance, collider, hitNormal, id) {
          if (id === void 0) {
            id = 0;
          }
          _PhysicsRayResult.prototype._assign.call(this, hitPoint, distance, collider, hitNormal);
          this._id = id;
        };
        _proto2.clone = function clone() {
          var c = new PhysicsLineStripCastResult();
          Vec3.copy(c._hitPoint, this._hitPoint);
          Vec3.copy(c._hitNormal, this._hitNormal);
          c._distance = this._distance;
          c._collider = this._collider;
          c._id = this._id;
          return c;
        };
        _createClass(PhysicsLineStripCastResult, [{
          key: "id",
          get: function get() {
            return this._id;
          }
        }]);
        return PhysicsLineStripCastResult;
      }(PhysicsRayResult));

      legacyCC.internal.PhysicsGroup = PhysicsGroup;
      var PhysicsSystem = exports('fH', function (_System) {
        _inheritsLoose(PhysicsSystem, _System);
        var _proto = PhysicsSystem.prototype;
        _proto.setDefaultPhysicsMaterial = function setDefaultPhysicsMaterial(material) {
          this._material = material;
          this.physicsWorld.setDefaultMaterial(this._material);
          this._material.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
        };
        _proto.initDefaultMaterial = function initDefaultMaterial() {
          var _this2 = this;
          if (this._material != null) return Promise.resolve();
          var builtinMaterial = builtinResMgr.get('default-physics-material');
          if (!builtinMaterial) {
            console.error('PhysicsSystem initDefaultMaterial() Failed to load builtinMaterial');
            return Promise.resolve();
          }
          var userMaterial = settings.querySettings(Settings.Category.PHYSICS, 'defaultMaterial');
          if (!userMaterial) {
            this.setDefaultPhysicsMaterial(builtinMaterial);
            return Promise.resolve();
          } else {
            return new Promise(function (resolve, reject) {
              assetManager.loadAny(userMaterial, function (err, asset) {
                return err || !(asset instanceof PhysicsMaterial) ? reject(err) : resolve(asset);
              });
            }).then(function (asset) {
              _this2.setDefaultPhysicsMaterial(asset);
            })["catch"](function (reason) {
              warn(reason);
              warn("Failed to load user customized default physics material: " + userMaterial + ", will fallback to built-in default physics material");
              _this2.setDefaultPhysicsMaterial(builtinMaterial);
            });
          }
        };
        function PhysicsSystem() {
          var _this;
          _this = _System.call(this) || this;
          _this.raycastClosestResult = new PhysicsRayResult();
          _this.raycastResults = [];
          _this.lineStripCastClosestResult = new PhysicsLineStripCastResult();
          _this.lineStripCastResults = [];
          _this.sweepCastClosestResult = new PhysicsRayResult();
          _this.sweepCastResults = [];
          _this.collisionMatrix = new CollisionMatrix(1);
          _this.minVolumeSize = 1e-5;
          _this.useNodeChains = false;
          _this._enable = true;
          _this._allowSleep = true;
          _this._maxSubSteps = 1;
          _this._subStepCount = 0;
          _this._fixedTimeStep = 1.0 / 60.0;
          _this._autoSimulation = true;
          _this._accumulator = 0;
          _this._sleepThreshold = 0.1;
          _this._gravity = new Vec3(0, -10, 0);
          _this._material = void 0;
          _this.raycastOptions = {
            group: -1,
            mask: -1,
            queryTrigger: true,
            maxDistance: 10000000
          };
          _this.raycastResultPool = new RecyclePool(function () {
            return new PhysicsRayResult();
          }, 1);
          _this.sweepResultPool = new RecyclePool(function () {
            return new PhysicsRayResult();
          }, 1);
          return _this;
        }
        _proto.postUpdate = function postUpdate(deltaTime) {
          if (!this.physicsWorld) return;
          if (!this._enable) {
            this.physicsWorld.syncSceneToPhysics();
            return;
          }
          if (this._autoSimulation) {
            this._subStepCount = 0;
            this._accumulator += deltaTime;
            director.emit(Director.EVENT_BEFORE_PHYSICS);
            while (this._subStepCount < this._maxSubSteps) {
              if (this._accumulator >= this._fixedTimeStep) {
                this.physicsWorld.syncSceneToPhysics();
                this.physicsWorld.step(this._fixedTimeStep);
                this.physicsWorld.emitEvents();
                this.physicsWorld.syncAfterEvents();
                this._accumulator -= this._fixedTimeStep;
                this._subStepCount++;
              } else {
                this.physicsWorld.syncSceneToPhysics();
                break;
              }
            }
            director.emit(Director.EVENT_AFTER_PHYSICS);
          }
        };
        _proto.resetConfiguration = function resetConfiguration(config) {
          var allowSleep = config ? config.allowSleep : settings.querySettings(Settings.Category.PHYSICS, 'allowSleep');
          if (typeof allowSleep === 'boolean') this._allowSleep = allowSleep;
          var fixedTimeStep = config ? config.fixedTimeStep : settings.querySettings(Settings.Category.PHYSICS, 'fixedTimeStep');
          if (typeof fixedTimeStep === 'number') this._fixedTimeStep = fixedTimeStep;
          var maxSubSteps = config ? config.maxSubSteps : settings.querySettings(Settings.Category.PHYSICS, 'maxSubSteps');
          if (typeof maxSubSteps === 'number') this._maxSubSteps = maxSubSteps;
          var sleepThreshold = config ? config.sleepThreshold : settings.querySettings(Settings.Category.PHYSICS, 'sleepThreshold');
          if (typeof sleepThreshold === 'number') this._sleepThreshold = sleepThreshold;
          var autoSimulation = config ? config.autoSimulation : settings.querySettings(Settings.Category.PHYSICS, 'autoSimulation');
          if (typeof autoSimulation === 'boolean') this.autoSimulation = autoSimulation;
          var gravity = config ? config.gravity : settings.querySettings(Settings.Category.PHYSICS, 'gravity');
          if (gravity) Vec3.copy(this._gravity, gravity);
          var collisionMatrix = config ? config.collisionMatrix : settings.querySettings(Settings.Category.PHYSICS, 'collisionMatrix');
          if (collisionMatrix) {
            for (var i in collisionMatrix) {
              this.collisionMatrix["" + (1 << parseInt(i))] = collisionMatrix[i];
            }
          }
          var collisionGroups = config ? config.collisionGroups : settings.querySettings(Settings.Category.PHYSICS, 'collisionGroups');
          if (collisionGroups) {
            var cg = collisionGroups;
            if (cg instanceof Array) {
              cg.forEach(function (v) {
                PhysicsGroup[v.name] = 1 << v.index;
              });
              Enum.update(PhysicsGroup);
            }
          }
          if (this.physicsWorld) {
            this.physicsWorld.setGravity(this._gravity);
            this.physicsWorld.setAllowSleep(this._allowSleep);
          }
        };
        _proto.resetAccumulator = function resetAccumulator(time) {
          if (time === void 0) {
            time = 0;
          }
          this._accumulator = time;
        };
        _proto.step = function step(fixedTimeStep, deltaTime, maxSubSteps) {
          if (this.physicsWorld) this.physicsWorld.step(fixedTimeStep, deltaTime, maxSubSteps);
        };
        _proto.syncSceneToPhysics = function syncSceneToPhysics() {
          if (this.physicsWorld) this.physicsWorld.syncSceneToPhysics();
        };
        _proto.emitEvents = function emitEvents() {
          if (this.physicsWorld) this.physicsWorld.emitEvents();
        };
        _proto.raycast = function raycast(worldRay, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.raycastResultPool.reset();
          this.raycastResults.length = 0;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.raycast(worldRay, this.raycastOptions, this.raycastResultPool, this.raycastResults);
        };
        _proto.raycastClosest = function raycastClosest(worldRay, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.raycastClosest(worldRay, this.raycastOptions, this.raycastClosestResult);
        };
        _proto.lineStripCast = function lineStripCast(samplePointsWorldSpace, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (samplePointsWorldSpace.length < 2) return false;
          this.lineStripCastResults = [];
          var distance = 0;
          var worldRay = new Ray();
          for (var i = 1; i < samplePointsWorldSpace.length; ++i) {
            if (distance > maxDistance) break;
            var fromPoint = samplePointsWorldSpace[i - 1];
            var toPoint = samplePointsWorldSpace[i];
            var direction = new Vec3();
            Vec3.subtract(direction, toPoint, fromPoint);
            var stepLength = Vec3.len(direction);
            distance += stepLength;
            Vec3.multiplyScalar(direction, direction, 1.0 / stepLength);
            worldRay.d = direction;
            worldRay.o = fromPoint;
            var hit = this.raycast(worldRay, mask, stepLength, queryTrigger);
            if (hit) {
              for (var re = 0; re < this.raycastResults.length; re++) {
                var result = this.raycastResults[re];
                if (re === 0 && Vec3.equals(fromPoint, result.hitPoint)) {
                  continue;
                }
                var copiedResult = new PhysicsLineStripCastResult();
                copiedResult._assign(result.hitPoint, result.distance, result.collider, result.hitNormal, i - 1);
                this.lineStripCastResults.push(copiedResult);
              }
            }
          }
          return this.lineStripCastResults.length > 0;
        };
        _proto.lineStripCastClosest = function lineStripCastClosest(samplePointsWorldSpace, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (samplePointsWorldSpace.length < 2) {
            return false;
          }
          var distance = 0;
          var worldRay = new Ray();
          var hit = false;
          for (var i = 1; i < samplePointsWorldSpace.length; ++i) {
            if (distance > maxDistance) break;
            var fromPoint = samplePointsWorldSpace[i - 1];
            var toPoint = samplePointsWorldSpace[i];
            var direction = new Vec3();
            Vec3.subtract(direction, toPoint, fromPoint);
            var stepLength = Vec3.len(direction);
            distance += stepLength;
            Vec3.multiplyScalar(direction, direction, 1.0 / stepLength);
            worldRay.d = direction;
            worldRay.o = fromPoint;
            hit = this.raycastClosest(worldRay, mask, stepLength, queryTrigger);
            if (hit) {
              var result = this.raycastClosestResult;
              var copiedResult = new PhysicsLineStripCastResult();
              copiedResult._assign(result.hitPoint, result.distance, result.collider, result.hitNormal, i - 1);
              this.lineStripCastClosestResult = copiedResult;
              break;
            }
          }
          return hit;
        };
        _proto.sweepBox = function sweepBox(worldRay, halfExtent, orientation, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.sweepResultPool.reset();
          this.sweepCastResults.length = 0;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepBox(worldRay, halfExtent, orientation, this.raycastOptions, this.sweepResultPool, this.sweepCastResults);
        };
        _proto.sweepBoxClosest = function sweepBoxClosest(worldRay, halfExtent, orientation, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepBoxClosest(worldRay, halfExtent, orientation, this.raycastOptions, this.sweepCastClosestResult);
        };
        _proto.sweepSphere = function sweepSphere(worldRay, radius, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.sweepResultPool.reset();
          this.sweepCastResults.length = 0;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepSphere(worldRay, radius, this.raycastOptions, this.sweepResultPool, this.sweepCastResults);
        };
        _proto.sweepSphereClosest = function sweepSphereClosest(worldRay, radius, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepSphereClosest(worldRay, radius, this.raycastOptions, this.sweepCastClosestResult);
        };
        _proto.sweepCapsule = function sweepCapsule(worldRay, radius, height, orientation, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.sweepResultPool.reset();
          this.sweepCastResults.length = 0;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepCapsule(worldRay, radius, height, orientation, this.raycastOptions, this.sweepResultPool, this.sweepCastResults);
        };
        _proto.sweepCapsuleClosest = function sweepCapsuleClosest(worldRay, radius, height, orientation, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepCapsuleClosest(worldRay, radius, height, orientation, this.raycastOptions, this.sweepCastClosestResult);
        };
        _proto._updateMaterial = function _updateMaterial() {
          if (this.physicsWorld) this.physicsWorld.setDefaultMaterial(this._material);
        };
        PhysicsSystem.constructAndRegister = function constructAndRegister() {
          var _settings$querySettin;
          var enabled = (_settings$querySettin = settings.querySettings(Settings.Category.PHYSICS, 'enabled')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : true;
          if (!enabled) {
            return;
          }
          if (!PhysicsSystem._instance) {
            var sys = new PhysicsSystem();
            PhysicsSystem._instance = sys;
            sys.resetConfiguration();
            constructDefaultWorld(sys);
            director.registerSystem(PhysicsSystem.ID, sys, sys.priority);
            game.onPostProjectInitDelegate.add(sys.initDefaultMaterial.bind(sys));
          }
        };
        _createClass(PhysicsSystem, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(value) {
            this._enable = value;
          }
        }, {
          key: "allowSleep",
          get: function get() {
            return this._allowSleep;
          },
          set: function set(v) {
            this._allowSleep = v;
            if (this.physicsWorld) {
              this.physicsWorld.setAllowSleep(v);
            }
          }
        }, {
          key: "maxSubSteps",
          get: function get() {
            return this._maxSubSteps;
          },
          set: function set(value) {
            this._maxSubSteps = value;
          }
        }, {
          key: "fixedTimeStep",
          get: function get() {
            return this._fixedTimeStep;
          },
          set: function set(value) {
            this._fixedTimeStep = value;
          }
        }, {
          key: "gravity",
          get: function get() {
            return this._gravity;
          },
          set: function set(gravity) {
            this._gravity.set(gravity);
            if (this.physicsWorld) {
              this.physicsWorld.setGravity(gravity);
            }
          }
        }, {
          key: "sleepThreshold",
          get: function get() {
            return this._sleepThreshold;
          },
          set: function set(v) {
            this._sleepThreshold = v;
          }
        }, {
          key: "autoSimulation",
          get: function get() {
            return this._autoSimulation;
          },
          set: function set(value) {
            this._autoSimulation = value;
          }
        }, {
          key: "defaultMaterial",
          get: function get() {
            return this._material;
          }
        }, {
          key: "physicsWorld",
          get: function get() {
            return selector.physicsWorld;
          }
        }, {
          key: "debugDrawFlags",
          get: function get() {
            return this.physicsWorld.debugDrawFlags;
          },
          set: function set(v) {
            this.physicsWorld.debugDrawFlags = v;
          }
        }, {
          key: "debugDrawConstraintSize",
          get: function get() {
            return this.physicsWorld.debugDrawConstraintSize;
          },
          set: function set(v) {
            this.physicsWorld.debugDrawConstraintSize = v;
          }
        }], [{
          key: "PHYSICS_NONE",
          get: function get() {
            return !selector.id;
          }
        }, {
          key: "PHYSICS_BUILTIN",
          get: function get() {
            return selector.id === 'builtin';
          }
        }, {
          key: "PHYSICS_CANNON",
          get: function get() {
            return selector.id === 'cannon.js';
          }
        }, {
          key: "PHYSICS_BULLET",
          get: function get() {
            return selector.id === 'bullet';
          }
        }, {
          key: "PHYSICS_PHYSX",
          get: function get() {
            return selector.id === 'physx';
          }
        }, {
          key: "PhysicsGroup",
          get: function get() {
            return PhysicsGroup;
          }
        }, {
          key: "instance",
          get: function get() {
            return PhysicsSystem._instance;
          }
        }]);
        return PhysicsSystem;
      }(System));
      PhysicsSystem.ID = 'PHYSICS';
      PhysicsSystem._instance = null;
      director.once(Director.EVENT_INIT, function () {
        PhysicsSystem.constructAndRegister();
      });

      var _dec$Q, _dec2$L, _dec3$z, _dec4$q, _class$P, _class2$L, _initializer$J, _initializer2$F, _initializer3$t, _initializer4$m, _initializer5$i, _initializer6$e, _initializer7$d, _initializer8$c, _initializer9$b, _class3$k;
      var RigidBody = exports('fI', (_dec$Q = ccclass$M('cc.RigidBody'), _dec2$L = executionOrder$1(-1), _dec3$z = type$d(PhysicsSystem.PhysicsGroup), _dec4$q = type$d(ERigidBodyType), _dec$Q(_class$P = disallowMultiple$1(_class$P = _dec2$L(_class$P = (_class2$L = (_class3$k = function (_Component) {
        _inheritsLoose(RigidBody, _Component);
        function RigidBody() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._body = null;
          _this._group = _initializer$J && _initializer$J();
          _this._type = _initializer2$F && _initializer2$F();
          _this._mass = _initializer3$t && _initializer3$t();
          _this._allowSleep = _initializer4$m && _initializer4$m();
          _this._linearDamping = _initializer5$i && _initializer5$i();
          _this._angularDamping = _initializer6$e && _initializer6$e();
          _this._useGravity = _initializer7$d && _initializer7$d();
          _this._linearFactor = _initializer8$c && _initializer8$c();
          _this._angularFactor = _initializer9$b && _initializer9$b();
          return _this;
        }
        var _proto = RigidBody.prototype;
        _proto.onLoad = function onLoad() {
          if (!selector.runInEditor) return;
          this._body = createRigidBody();
          this._body.initialize(this);
        };
        _proto.onEnable = function onEnable() {
          if (this._body) this._body.onEnable();
        };
        _proto.onDisable = function onDisable() {
          if (this._body) this._body.onDisable();
        };
        _proto.onDestroy = function onDestroy() {
          if (this._body) this._body.onDestroy();
        };
        _proto.applyForce = function applyForce(force, relativePoint) {
          if (this._isInitialized) this._body.applyForce(force, relativePoint);
        };
        _proto.applyLocalForce = function applyLocalForce(force, localPoint) {
          if (this._isInitialized) this._body.applyLocalForce(force, localPoint);
        };
        _proto.applyImpulse = function applyImpulse(impulse, relativePoint) {
          if (this._isInitialized) this._body.applyImpulse(impulse, relativePoint);
        };
        _proto.applyLocalImpulse = function applyLocalImpulse(impulse, localPoint) {
          if (this._isInitialized) this._body.applyLocalImpulse(impulse, localPoint);
        };
        _proto.applyTorque = function applyTorque(torque) {
          if (this._isInitialized) this._body.applyTorque(torque);
        };
        _proto.applyLocalTorque = function applyLocalTorque(torque) {
          if (this._isInitialized) this._body.applyLocalTorque(torque);
        };
        _proto.wakeUp = function wakeUp() {
          if (this._isInitialized) this._body.wakeUp();
        };
        _proto.sleep = function sleep() {
          if (this._isInitialized) this._body.sleep();
        };
        _proto.clearState = function clearState() {
          if (this._isInitialized) this._body.clearState();
        };
        _proto.clearForces = function clearForces() {
          if (this._isInitialized) this._body.clearForces();
        };
        _proto.clearVelocity = function clearVelocity() {
          if (this._isInitialized) this._body.clearVelocity();
        };
        _proto.getLinearVelocity = function getLinearVelocity(out) {
          if (this._isInitialized) this._body.getLinearVelocity(out);
        };
        _proto.setLinearVelocity = function setLinearVelocity(value) {
          if (this._isInitialized) this._body.setLinearVelocity(value);
        };
        _proto.getAngularVelocity = function getAngularVelocity(out) {
          if (this._isInitialized) this._body.getAngularVelocity(out);
        };
        _proto.setAngularVelocity = function setAngularVelocity(value) {
          if (this._isInitialized) this._body.setAngularVelocity(value);
        };
        _proto.getGroup = function getGroup() {
          if (this._isInitialized) return this._body.getGroup();
          return 0;
        };
        _proto.setGroup = function setGroup(v) {
          if (this._isInitialized) this._body.setGroup(v);
        };
        _proto.addGroup = function addGroup(v) {
          if (this._isInitialized) this._body.addGroup(v);
        };
        _proto.removeGroup = function removeGroup(v) {
          if (this._isInitialized) this._body.removeGroup(v);
        };
        _proto.getMask = function getMask() {
          if (this._isInitialized) return this._body.getMask();
          return 0;
        };
        _proto.setMask = function setMask(v) {
          if (this._isInitialized) this._body.setMask(v);
        };
        _proto.addMask = function addMask(v) {
          if (this._isInitialized) this._body.addMask(v);
        };
        _proto.removeMask = function removeMask(v) {
          if (this._isInitialized) this._body.removeMask(v);
        };
        _createClass(RigidBody, [{
          key: "group",
          get: function get() {
            return this._group;
          },
          set: function set(v) {
            if (!Number.isInteger(Math.log2(v >>> 0))) warn('[Physics]: The group should only have one bit.');
            this._group = v;
            if (this._body) {
              if (this._body.getGroup() !== v) this._body.setGroup(v);
            }
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(v) {
            if (this._type === v) return;
            this._type = v;
            if (this._body) this._body.setType(v);
          }
        }, {
          key: "mass",
          get: function get() {
            return this._mass;
          },
          set: function set(value) {
            if (value <= 0) warn('[Physics]: The mass should be greater than zero.');
            if (this._mass === value) return;
            value = value <= 0 ? 0.0001 : value;
            this._mass = value;
            if (this._body) this._body.setMass(value);
          }
        }, {
          key: "allowSleep",
          get: function get() {
            return this._allowSleep;
          },
          set: function set(v) {
            this._allowSleep = v;
            if (this._body) this._body.setAllowSleep(v);
          }
        }, {
          key: "linearDamping",
          get: function get() {
            return this._linearDamping;
          },
          set: function set(value) {
            if ((value < 0 || value > 1)) warn('[Physics]: The damping should be between zero to one.');
            this._linearDamping = value;
            if (this._body) this._body.setLinearDamping(value);
          }
        }, {
          key: "angularDamping",
          get: function get() {
            return this._angularDamping;
          },
          set: function set(value) {
            if ((value < 0 || value > 1)) warn('[Physics]: The damping should be between zero to one.');
            this._angularDamping = value;
            if (this._body) this._body.setAngularDamping(value);
          }
        }, {
          key: "useGravity",
          get: function get() {
            return this._useGravity;
          },
          set: function set(value) {
            this._useGravity = value;
            if (this._body) this._body.useGravity(value);
          }
        }, {
          key: "linearFactor",
          get: function get() {
            return this._linearFactor;
          },
          set: function set(value) {
            Vec3.copy(this._linearFactor, value);
            if (this._body) {
              this._body.setLinearFactor(this._linearFactor);
            }
          }
        }, {
          key: "angularFactor",
          get: function get() {
            return this._angularFactor;
          },
          set: function set(value) {
            Vec3.copy(this._angularFactor, value);
            if (this._body) {
              this._body.setAngularFactor(this._angularFactor);
            }
          }
        }, {
          key: "sleepThreshold",
          get: function get() {
            if (this._isInitialized) {
              return this._body.getSleepThreshold();
            }
            return 0.1;
          },
          set: function set(v) {
            if (this._isInitialized) {
              this._body.setSleepThreshold(v);
            }
          }
        }, {
          key: "useCCD",
          get: function get() {
            if (this._isInitialized) {
              return this._body.isUsingCCD();
            }
            return false;
          },
          set: function set(v) {
            if (this._isInitialized) {
              this._body.useCCD(v);
            }
          }
        }, {
          key: "isAwake",
          get: function get() {
            if (this._isInitialized) return this._body.isAwake;
            return false;
          }
        }, {
          key: "isSleepy",
          get: function get() {
            if (this._isInitialized) return this._body.isSleepy;
            return false;
          }
        }, {
          key: "isSleeping",
          get: function get() {
            if (this._isInitialized) return this._body.isSleeping;
            return false;
          }
        }, {
          key: "isStatic",
          get: function get() {
            return this._type === ERigidBodyType.STATIC;
          },
          set: function set(v) {
            if (v && this.isStatic || !v && !this.isStatic) return;
            this.type = v ? ERigidBodyType.STATIC : ERigidBodyType.DYNAMIC;
          }
        }, {
          key: "isDynamic",
          get: function get() {
            return this._type === ERigidBodyType.DYNAMIC;
          },
          set: function set(v) {
            if (v && this.isDynamic || !v && !this.isDynamic) return;
            this.type = v ? ERigidBodyType.DYNAMIC : ERigidBodyType.KINEMATIC;
          }
        }, {
          key: "isKinematic",
          get: function get() {
            return this._type === ERigidBodyType.KINEMATIC;
          },
          set: function set(v) {
            if (v && this.isKinematic || !v && !this.isKinematic) return;
            this.type = v ? ERigidBodyType.KINEMATIC : ERigidBodyType.DYNAMIC;
          }
        }, {
          key: "body",
          get: function get() {
            return this._body;
          }
        }, {
          key: "_isInitialized",
          get: function get() {
            var r = this._body === null;
            if (r) {
              error('[Physics]: This component has not been call onLoad yet, please make sure the node has been added to the scene.');
            }
            return !r;
          }
        }]);
        return RigidBody;
      }(Component), _class3$k.Type = ERigidBodyType, _class3$k), (_applyDecoratedDescriptor(_class2$L.prototype, "group", [_dec3$z], Object.getOwnPropertyDescriptor(_class2$L.prototype, "group"), _class2$L.prototype), _applyDecoratedDescriptor(_class2$L.prototype, "type", [_dec4$q], Object.getOwnPropertyDescriptor(_class2$L.prototype, "type"), _class2$L.prototype), _initializer$J = applyDecoratedInitializer(_class2$L.prototype, "_group", [serializable$p], function () {
        return PhysicsSystem.PhysicsGroup.DEFAULT;
      }), _initializer2$F = applyDecoratedInitializer(_class2$L.prototype, "_type", [serializable$p], function () {
        return ERigidBodyType.DYNAMIC;
      }), _initializer3$t = applyDecoratedInitializer(_class2$L.prototype, "_mass", [serializable$p], function () {
        return 1;
      }), _initializer4$m = applyDecoratedInitializer(_class2$L.prototype, "_allowSleep", [serializable$p], function () {
        return true;
      }), _initializer5$i = applyDecoratedInitializer(_class2$L.prototype, "_linearDamping", [serializable$p], function () {
        return 0.1;
      }), _initializer6$e = applyDecoratedInitializer(_class2$L.prototype, "_angularDamping", [serializable$p], function () {
        return 0.1;
      }), _initializer7$d = applyDecoratedInitializer(_class2$L.prototype, "_useGravity", [serializable$p], function () {
        return true;
      }), _initializer8$c = applyDecoratedInitializer(_class2$L.prototype, "_linearFactor", [serializable$p], function () {
        return new Vec3(1, 1, 1);
      }), _initializer9$b = applyDecoratedInitializer(_class2$L.prototype, "_angularFactor", [serializable$p], function () {
        return new Vec3(1, 1, 1);
      })), _class2$L)) || _class$P) || _class$P) || _class$P));
      (function (_RigidBody) {})(RigidBody || (exports('fI', RigidBody = {})));

      var _dec$P, _dec2$K, _dec3$y, _dec4$p, _dec5$o, _class$O, _class2$K, _initializer$I, _initializer2$E, _initializer3$s, _class3$j;
      var Collider = exports('fO', (_dec$P = ccclass$M('cc.Collider'), _dec2$K = type$d(RigidBody), _dec3$y = type$d(PhysicsMaterial), _dec4$p = type$d(Vec3), _dec5$o = type$d(PhysicsMaterial), _dec$P(_class$O = (_class2$K = (_class3$j = function (_Eventify) {
        _inheritsLoose(Collider, _Eventify);
        function Collider(type) {
          var _this;
          _this = _Eventify.call(this) || this;
          _this.type = void 0;
          _this._shape = null;
          _this._aabb = null;
          _this._boundingSphere = null;
          _this._isSharedMaterial = true;
          _this._needTriggerEvent = false;
          _this._needCollisionEvent = false;
          _this._material = _initializer$I && _initializer$I();
          _this._isTrigger = _initializer2$E && _initializer2$E();
          _this._center = _initializer3$s && _initializer3$s();
          _this.type = type;
          return _this;
        }
        var _proto = Collider.prototype;
        _proto.on = function on(type, callback, target, once) {
          var ret = _Eventify.prototype.on.call(this, type, callback, target, once);
          this._updateNeedEvent(type);
          return ret;
        };
        _proto.off = function off(type, callback, target) {
          _Eventify.prototype.off.call(this, type, callback, target);
          this._updateNeedEvent();
        };
        _proto.once = function once(type, callback, target) {
          var ret = _Eventify.prototype.once.call(this, type, callback, target);
          this._updateNeedEvent(type);
          return ret;
        };
        _proto.removeAll = function removeAll(typeOrTarget) {
          _Eventify.prototype.removeAll.call(this, typeOrTarget);
          this._updateNeedEvent();
        };
        _proto.getGroup = function getGroup() {
          if (this._isInitialized) {
            return this._shape.getGroup();
          }
          return 0;
        };
        _proto.setGroup = function setGroup(v) {
          if (this._isInitialized) {
            this._shape.setGroup(v);
          }
        };
        _proto.addGroup = function addGroup(v) {
          if (this._isInitialized) {
            this._shape.addGroup(v);
          }
        };
        _proto.removeGroup = function removeGroup(v) {
          if (this._isInitialized) {
            this._shape.removeGroup(v);
          }
        };
        _proto.getMask = function getMask() {
          if (this._isInitialized) {
            return this._shape.getMask();
          }
          return 0;
        };
        _proto.setMask = function setMask(v) {
          if (this._isInitialized) {
            this._shape.setMask(v);
          }
        };
        _proto.addMask = function addMask(v) {
          if (this._isInitialized) {
            this._shape.addMask(v);
          }
        };
        _proto.removeMask = function removeMask(v) {
          if (this._isInitialized) {
            this._shape.removeMask(v);
          }
        };
        _proto.onLoad = function onLoad() {
          if (!selector.runInEditor) return;
          this.sharedMaterial = this._material;
          this._shape = createShape(this.type);
          this._shape.initialize(this);
          this._shape.onLoad();
        };
        _proto.onEnable = function onEnable() {
          if (this._shape) {
            this._shape.onEnable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._shape) {
            this._shape.onDisable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._shape) {
            this._needTriggerEvent = false;
            this._needCollisionEvent = false;
            this._shape.updateEventListener();
            if (this._material) this._material.off(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
            this._shape.onDestroy();
          }
          if (this._boundingSphere) this._boundingSphere.destroy();
        };
        _proto._updateMaterial = function _updateMaterial() {
          if (this._shape) this._shape.setMaterial(this._material);
        };
        _proto._updateNeedEvent = function _updateNeedEvent(type) {
          if (this.isValid) {
            if (type !== undefined) {
              if (type === 'onCollisionEnter' || type === 'onCollisionStay' || type === 'onCollisionExit') {
                this._needCollisionEvent = true;
              }
              if (type === 'onTriggerEnter' || type === 'onTriggerStay' || type === 'onTriggerExit' || type === 'onControllerTriggerEnter' || type === 'onControllerTriggerStay' || type === 'onControllerTriggerExit') {
                this._needTriggerEvent = true;
              }
            } else {
              if (!(this.hasEventListener('onTriggerEnter') || this.hasEventListener('onTriggerStay') || this.hasEventListener('onTriggerExit') || this.hasEventListener('onControllerTriggerEnter') || this.hasEventListener('onControllerTriggerStay') || this.hasEventListener('onControllerTriggerExit'))) {
                this._needTriggerEvent = false;
              }
              if (!(this.hasEventListener('onCollisionEnter') || this.hasEventListener('onCollisionStay') || this.hasEventListener('onCollisionExit'))) {
                this._needCollisionEvent = false;
              }
            }
            if (this._shape) this._shape.updateEventListener();
          }
        };
        _createClass(Collider, [{
          key: "attachedRigidBody",
          get: function get() {
            return findAttachedBody(this.node);
          }
        }, {
          key: "sharedMaterial",
          get: function get() {
            return this._material;
          },
          set: function set(value) {
            {
              this.material = value;
            }
          }
        }, {
          key: "material",
          get: function get() {
            if (this._isSharedMaterial && this._material) {
              this._material.off(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
              this._material = this._material.clone();
              this._material.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
              this._isSharedMaterial = false;
            }
            return this._material;
          },
          set: function set(value) {
            if (this._shape) {
              if (value && this._material) {
                if (this._material.id !== value.id) {
                  this._material.off(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
                  value.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
                  this._isSharedMaterial = false;
                  this._material = value;
                }
              } else if (value && !this._material) {
                value.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
                this._material = value;
              } else if (!value && this._material) {
                this._material.off(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
                this._material = value;
              }
              this._updateMaterial();
            } else {
              this._material = value;
            }
          }
        }, {
          key: "isTrigger",
          get: function get() {
            return this._isTrigger;
          },
          set: function set(value) {
            this._isTrigger = value;
            if (this._shape) {
              this._shape.setAsTrigger(this._isTrigger);
            }
          }
        }, {
          key: "center",
          get: function get() {
            return this._center;
          },
          set: function set(value) {
            Vec3.copy(this._center, value);
            if (this._shape) {
              this._shape.setCenter(this._center);
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }, {
          key: "worldBounds",
          get: function get() {
            if (this._aabb == null) this._aabb = new AABB();
            if (this._shape) this._shape.getAABB(this._aabb);
            return this._aabb;
          }
        }, {
          key: "boundingSphere",
          get: function get() {
            if (this._boundingSphere == null) this._boundingSphere = new Sphere();
            if (this._shape) this._shape.getBoundingSphere(this._boundingSphere);
            return this._boundingSphere;
          }
        }, {
          key: "needTriggerEvent",
          get: function get() {
            return this._needTriggerEvent;
          }
        }, {
          key: "needCollisionEvent",
          get: function get() {
            return this._needCollisionEvent;
          }
        }, {
          key: "_isInitialized",
          get: function get() {
            var r = this._shape === null;
            if (r) {
              error('[Physics]: This component has not been call onLoad yet, please make sure the node has been added to the scene.');
            }
            return !r;
          }
        }]);
        return Collider;
      }(Eventify(Component)), _class3$j.Type = EColliderType, _class3$j.Axis = EAxisDirection, _class3$j), (_applyDecoratedDescriptor(_class2$K.prototype, "attachedRigidBody", [_dec2$K], Object.getOwnPropertyDescriptor(_class2$K.prototype, "attachedRigidBody"), _class2$K.prototype), _applyDecoratedDescriptor(_class2$K.prototype, "sharedMaterial", [_dec3$y], Object.getOwnPropertyDescriptor(_class2$K.prototype, "sharedMaterial"), _class2$K.prototype), _applyDecoratedDescriptor(_class2$K.prototype, "center", [_dec4$p], Object.getOwnPropertyDescriptor(_class2$K.prototype, "center"), _class2$K.prototype), _initializer$I = applyDecoratedInitializer(_class2$K.prototype, "_material", [_dec5$o], function () {
        return null;
      }), _initializer2$E = applyDecoratedInitializer(_class2$K.prototype, "_isTrigger", [serializable$p], function () {
        return false;
      }), _initializer3$s = applyDecoratedInitializer(_class2$K.prototype, "_center", [serializable$p], function () {
        return new Vec3();
      })), _class2$K)) || _class$O));
      (function (_Collider) {})(Collider || (exports('fO', Collider = {})));
      function findAttachedBody(node) {
        var rb = node.getComponent(RigidBody);
        if (rb && rb.isValid) {
          return rb;
        }
        return null;
      }

      var _dec$O, _dec2$J, _class$N, _class2$J, _initializer$H;
      var BoxCollider = exports('fP', (_dec$O = ccclass$M('cc.BoxCollider'), _dec2$J = type$d(Vec3), _dec$O(_class$N = (_class2$J = function (_Collider) {
        _inheritsLoose(BoxCollider, _Collider);
        function BoxCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.BOX) || this;
          _this._size = _initializer$H && _initializer$H();
          return _this;
        }
        _createClass(BoxCollider, [{
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(value) {
            if (Vec3.strictEquals(this._size, value)) return;
            Vec3.copy(this._size, value);
            absolute(this._size);
            if (this._shape) {
              this.shape.updateSize();
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return BoxCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$J.prototype, "size", [_dec2$J], Object.getOwnPropertyDescriptor(_class2$J.prototype, "size"), _class2$J.prototype), _initializer$H = applyDecoratedInitializer(_class2$J.prototype, "_size", [serializable$p], function () {
        return new Vec3(1, 1, 1);
      })), _class2$J)) || _class$N));

      var _dec$N, _class$M, _class2$I, _initializer$G;
      var SphereCollider = exports('fQ', (_dec$N = ccclass$M('cc.SphereCollider'), _dec$N(_class$M = (_class2$I = function (_Collider) {
        _inheritsLoose(SphereCollider, _Collider);
        function SphereCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.SPHERE) || this;
          _this._radius = _initializer$G && _initializer$G();
          return _this;
        }
        _createClass(SphereCollider, [{
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(value) {
            if (this._radius === value) return;
            this._radius = Math.abs(value);
            if (this._shape) {
              this.shape.updateRadius();
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return SphereCollider;
      }(Collider), (_initializer$G = applyDecoratedInitializer(_class2$I.prototype, "_radius", [serializable$p], function () {
        return 0.5;
      })), _class2$I)) || _class$M));

      var _dec$M, _dec2$I, _class$L, _class2$H, _initializer$F, _initializer2$D, _initializer3$r;
      var CapsuleCollider = exports('fR', (_dec$M = ccclass$M('cc.CapsuleCollider'), _dec2$I = type$d(EAxisDirection), _dec$M(_class$L = (_class2$H = function (_Collider) {
        _inheritsLoose(CapsuleCollider, _Collider);
        function CapsuleCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.CAPSULE) || this;
          _this._radius = _initializer$F && _initializer$F();
          _this._cylinderHeight = _initializer2$D && _initializer2$D();
          _this._direction = _initializer3$r && _initializer3$r();
          return _this;
        }
        var _proto = CapsuleCollider.prototype;
        _proto._getRadiusScale = function _getRadiusScale() {
          if (this.node == null) return 1;
          var ws = this.node.worldScale;
          if (this._direction === EAxisDirection.Y_AXIS) return Math.abs(absMax(ws.x, ws.z));
          if (this._direction === EAxisDirection.X_AXIS) return Math.abs(absMax(ws.y, ws.z));
          return Math.abs(absMax(ws.x, ws.y));
        };
        _proto._getHeightScale = function _getHeightScale() {
          if (this.node == null) return 1;
          var ws = this.node.worldScale;
          if (this._direction === EAxisDirection.Y_AXIS) return Math.abs(ws.y);
          if (this._direction === EAxisDirection.X_AXIS) return Math.abs(ws.x);
          return Math.abs(ws.z);
        };
        _createClass(CapsuleCollider, [{
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(value) {
            if (this._radius === value) return;
            this._radius = Math.abs(value);
            if (this._shape) {
              this.shape.setRadius(value);
            }
          }
        }, {
          key: "cylinderHeight",
          get: function get() {
            return this._cylinderHeight;
          },
          set: function set(value) {
            if (this._cylinderHeight === value) return;
            this._cylinderHeight = Math.abs(value);
            if (this._shape) {
              this.shape.setCylinderHeight(value);
            }
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            value = Math.floor(value);
            if (value < EAxisDirection.X_AXIS || value > EAxisDirection.Z_AXIS) return;
            if (this._direction === value) return;
            this._direction = value;
            if (this._shape) {
              this.shape.setDirection(value);
            }
          }
        }, {
          key: "height",
          get: function get() {
            return this._radius * 2 + this._cylinderHeight;
          },
          set: function set(value) {
            var ch = value - this._radius * 2;
            if (ch < 0) ch = 0;
            this.cylinderHeight = ch;
          }
        }, {
          key: "worldHeight",
          get: function get() {
            return this._radius * 2 * this._getRadiusScale() + this._cylinderHeight * this._getHeightScale();
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return CapsuleCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$H.prototype, "direction", [_dec2$I], Object.getOwnPropertyDescriptor(_class2$H.prototype, "direction"), _class2$H.prototype), _initializer$F = applyDecoratedInitializer(_class2$H.prototype, "_radius", [serializable$p], function () {
        return 0.5;
      }), _initializer2$D = applyDecoratedInitializer(_class2$H.prototype, "_cylinderHeight", [serializable$p], function () {
        return 1;
      }), _initializer3$r = applyDecoratedInitializer(_class2$H.prototype, "_direction", [serializable$p], function () {
        return EAxisDirection.Y_AXIS;
      })), _class2$H)) || _class$L));

      var _dec$L, _dec2$H, _class$K, _class2$G, _initializer$E, _initializer2$C, _initializer3$q;
      var CylinderCollider = exports('fT', (_dec$L = ccclass$M('cc.CylinderCollider'), _dec2$H = type$d(EAxisDirection), _dec$L(_class$K = (_class2$G = function (_Collider) {
        _inheritsLoose(CylinderCollider, _Collider);
        function CylinderCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.CYLINDER) || this;
          _this._radius = _initializer$E && _initializer$E();
          _this._height = _initializer2$C && _initializer2$C();
          _this._direction = _initializer3$q && _initializer3$q();
          return _this;
        }
        _createClass(CylinderCollider, [{
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(value) {
            if (this._radius === value) return;
            this._radius = Math.abs(value);
            if (this._shape) {
              this.shape.setRadius(value);
            }
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          },
          set: function set(value) {
            if (this._height === value) return;
            this._height = Math.abs(value);
            if (this._shape) {
              this.shape.setHeight(value);
            }
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) return;
            if (value < EAxisDirection.X_AXIS || value > EAxisDirection.Z_AXIS) return;
            this._direction = value;
            if (this._shape) {
              this.shape.setDirection(value);
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return CylinderCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$G.prototype, "direction", [_dec2$H], Object.getOwnPropertyDescriptor(_class2$G.prototype, "direction"), _class2$G.prototype), _initializer$E = applyDecoratedInitializer(_class2$G.prototype, "_radius", [serializable$p], function () {
        return 0.5;
      }), _initializer2$C = applyDecoratedInitializer(_class2$G.prototype, "_height", [serializable$p], function () {
        return 2;
      }), _initializer3$q = applyDecoratedInitializer(_class2$G.prototype, "_direction", [serializable$p], function () {
        return EAxisDirection.Y_AXIS;
      })), _class2$G)) || _class$K));

      var _dec$K, _dec2$G, _class$J, _class2$F, _initializer$D, _initializer2$B, _initializer3$p;
      var ConeCollider = exports('fU', (_dec$K = ccclass$M('cc.ConeCollider'), _dec2$G = type$d(EAxisDirection), _dec$K(_class$J = (_class2$F = function (_Collider) {
        _inheritsLoose(ConeCollider, _Collider);
        function ConeCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.CONE) || this;
          _this._radius = _initializer$D && _initializer$D();
          _this._height = _initializer2$B && _initializer2$B();
          _this._direction = _initializer3$p && _initializer3$p();
          return _this;
        }
        _createClass(ConeCollider, [{
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(value) {
            if (this._radius === value) return;
            this._radius = Math.abs(value);
            if (this._shape) {
              this.shape.setRadius(value);
            }
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          },
          set: function set(value) {
            if (this._height === value) return;
            if (value < 0) value = 0;
            this._height = value;
            if (this._shape) {
              this.shape.setHeight(value);
            }
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) return;
            if (value < EAxisDirection.X_AXIS || value > EAxisDirection.Z_AXIS) return;
            this._direction = value;
            if (this._shape) {
              this.shape.setDirection(value);
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return ConeCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$F.prototype, "direction", [_dec2$G], Object.getOwnPropertyDescriptor(_class2$F.prototype, "direction"), _class2$F.prototype), _initializer$D = applyDecoratedInitializer(_class2$F.prototype, "_radius", [serializable$p], function () {
        return 0.5;
      }), _initializer2$B = applyDecoratedInitializer(_class2$F.prototype, "_height", [serializable$p], function () {
        return 1;
      }), _initializer3$p = applyDecoratedInitializer(_class2$F.prototype, "_direction", [serializable$p], function () {
        return EAxisDirection.Y_AXIS;
      })), _class2$F)) || _class$J));

      var _dec$J, _dec2$F, _class$I, _class2$E, _initializer$C, _initializer2$A;
      var MeshCollider = exports('fS', (_dec$J = ccclass$M('cc.MeshCollider'), _dec2$F = type$d(Mesh), _dec$J(_class$I = (_class2$E = function (_Collider) {
        _inheritsLoose(MeshCollider, _Collider);
        var _proto = MeshCollider.prototype;
        _proto.onEnable = function onEnable() {
          _Collider.prototype.onEnable.call(this);
          if (this.node) {
            var body = this.node.getComponent(RigidBody);
            if (body && body.isValid && body.type === ERigidBodyType.DYNAMIC && !this.convex) {
              warnID(9630, this.node.name);
            }
          }
        };
        function MeshCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.MESH) || this;
          _this._mesh = _initializer$C && _initializer$C();
          _this._convex = _initializer2$A && _initializer2$A();
          return _this;
        }
        _createClass(MeshCollider, [{
          key: "mesh",
          get: function get() {
            return this._mesh;
          },
          set: function set(value) {
            if (this._mesh === value) return;
            this._mesh = value;
            if (this._shape) this.shape.setMesh(this._mesh);
          }
        }, {
          key: "convex",
          get: function get() {
            return this._convex;
          },
          set: function set(value) {
            if (this._convex === value) return;
            this._convex = value;
            if (this._shape && this._mesh) this.shape.setMesh(this._mesh);
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return MeshCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$E.prototype, "mesh", [_dec2$F], Object.getOwnPropertyDescriptor(_class2$E.prototype, "mesh"), _class2$E.prototype), _initializer$C = applyDecoratedInitializer(_class2$E.prototype, "_mesh", [serializable$p], function () {
        return null;
      }), _initializer2$A = applyDecoratedInitializer(_class2$E.prototype, "_convex", [serializable$p], function () {
        return false;
      })), _class2$E)) || _class$I));

      var _dec$I, _dec2$E, _class$H, _class2$D, _initializer$B, _initializer2$z, _initializer3$o, _initializer4$l;
      var ConstantForce = exports('fK', (_dec$I = ccclass$M('cc.ConstantForce'), _dec2$E = requireComponent(RigidBody), _dec$I(_class$H = _dec2$E(_class$H = disallowMultiple$1(_class$H = (_class2$D = function (_Component) {
        _inheritsLoose(ConstantForce, _Component);
        function ConstantForce() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._rigidBody = null;
          _this._force = _initializer$B && _initializer$B();
          _this._localForce = _initializer2$z && _initializer2$z();
          _this._torque = _initializer3$o && _initializer3$o();
          _this._localTorque = _initializer4$l && _initializer4$l();
          _this._mask = 0;
          return _this;
        }
        var _proto = ConstantForce.prototype;
        _proto.onLoad = function onLoad() {
          this._rigidBody = this.node.getComponent(RigidBody);
          this._maskUpdate(this._force, 1);
          this._maskUpdate(this._localForce, 2);
          this._maskUpdate(this._torque, 4);
          this._maskUpdate(this._localTorque, 8);
        };
        _proto.lateUpdate = function lateUpdate(dt) {
          {
            if (this._rigidBody != null && this._mask !== 0) {
              if (this._mask & 1) this._rigidBody.applyForce(this._force);
              if (this._mask & 2) this._rigidBody.applyLocalForce(this.localForce);
              if (this._mask & 4) this._rigidBody.applyTorque(this._torque);
              if (this._mask & 8) this._rigidBody.applyLocalTorque(this._localTorque);
            }
          }
        };
        _proto._maskUpdate = function _maskUpdate(t, m) {
          if (t.strictEquals(Vec3.ZERO)) {
            this._mask &= ~m;
          } else {
            this._mask |= m;
          }
        };
        _createClass(ConstantForce, [{
          key: "force",
          get: function get() {
            return this._force;
          },
          set: function set(value) {
            Vec3.copy(this._force, value);
            this._maskUpdate(this._force, 1);
          }
        }, {
          key: "localForce",
          get: function get() {
            return this._localForce;
          },
          set: function set(value) {
            Vec3.copy(this._localForce, value);
            this._maskUpdate(this.localForce, 2);
          }
        }, {
          key: "torque",
          get: function get() {
            return this._torque;
          },
          set: function set(value) {
            Vec3.copy(this._torque, value);
            this._maskUpdate(this._torque, 4);
          }
        }, {
          key: "localTorque",
          get: function get() {
            return this._localTorque;
          },
          set: function set(value) {
            Vec3.copy(this._localTorque, value);
            this._maskUpdate(this._localTorque, 8);
          }
        }]);
        return ConstantForce;
      }(Component), (_initializer$B = applyDecoratedInitializer(_class2$D.prototype, "_force", [serializable$p], function () {
        return new Vec3();
      }), _initializer2$z = applyDecoratedInitializer(_class2$D.prototype, "_localForce", [serializable$p], function () {
        return new Vec3();
      }), _initializer3$o = applyDecoratedInitializer(_class2$D.prototype, "_torque", [serializable$p], function () {
        return new Vec3();
      }), _initializer4$l = applyDecoratedInitializer(_class2$D.prototype, "_localTorque", [serializable$p], function () {
        return new Vec3();
      })), _class2$D)) || _class$H) || _class$H) || _class$H));

      var _dec$H, _class2$C, _class3$i, _initializer$A, _initializer2$y, _initializer3$n, _initializer4$k, _initializer5$h, _initializer6$d, _dec2$D, _class5$7, _dec3$x, _class7$2, _class8$3, _initializer7$c;
      var TERRAIN_MAX_LEVELS = exports('gm', 4);
      var TERRAIN_MAX_BLEND_LAYERS = exports('gn', 4);
      var TERRAIN_MAX_LAYER_COUNT = exports('go', 256);
      var TERRAIN_BLOCK_TILE_COMPLEXITY = exports('gp', 32);
      var TERRAIN_BLOCK_VERTEX_COMPLEXITY = exports('gq', 33);
      var TERRAIN_BLOCK_VERTEX_SIZE = exports('gr', 8);
      var TERRAIN_HEIGHT_BASE = exports('gs', 32768);
      var TERRAIN_HEIGHT_FACTORY = exports('gt', 1.0 / 128.0);
      var TERRAIN_HEIGHT_FACTORY_V7 = exports('gu', 1.0 / 512.0);
      var TERRAIN_HEIGHT_FMIN = exports('gv', -TERRAIN_HEIGHT_BASE * TERRAIN_HEIGHT_FACTORY);
      var TERRAIN_HEIGHT_FMAX = exports('gw', (65535 - TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY);
      var TERRAIN_NORTH_INDEX = exports('gx', 0);
      var TERRAIN_SOUTH_INDEX = exports('gy', 1);
      var TERRAIN_WEST_INDEX = exports('gz', 2);
      var TERRAIN_EAST_INDEX = exports('gA', 3);
      var TERRAIN_DATA_VERSION = exports('gB', 0x01010001);
      var TERRAIN_DATA_VERSION2 = exports('gC', 0x01010002);
      var TERRAIN_DATA_VERSION3 = exports('gD', 0x01010003);
      var TERRAIN_DATA_VERSION4 = exports('gE', 0x01010004);
      var TERRAIN_DATA_VERSION5 = exports('gF', 0x01010005);
      var TERRAIN_DATA_VERSION6 = exports('gG', 0x01010006);
      var TERRAIN_DATA_VERSION7 = exports('gH', 0x01010007);
      var TERRAIN_DATA_VERSION8 = exports('gI', 0x01010008);
      var TERRAIN_DATA_VERSION_DEFAULT = exports('gJ', 0x01010111);
      var TerrainBuffer = function () {
        function TerrainBuffer() {
          this.length = 0;
          this.buffer = new Uint8Array(2048);
          this._buffView = new DataView(this.buffer.buffer);
          this._seekPos = 0;
        }
        var _proto = TerrainBuffer.prototype;
        _proto.reserve = function reserve(size) {
          if (this.buffer.byteLength > size) {
            return;
          }
          var capacity = this.buffer.byteLength;
          while (capacity < size) {
            capacity += capacity;
          }
          var temp = new Uint8Array(capacity);
          for (var i = 0; i < this.length; ++i) {
            temp[i] = this.buffer[i];
          }
          this.buffer = temp;
          this._buffView = new DataView(this.buffer.buffer);
        };
        _proto.assign = function assign(buff) {
          this.buffer = buff;
          this.length = buff.length;
          this._seekPos = buff.byteOffset;
          this._buffView = new DataView(buff.buffer);
        };
        _proto.writeInt8 = function writeInt8(value) {
          this.reserve(this.length + 1);
          this._buffView.setInt8(this.length, value);
          this.length += 1;
        };
        _proto.writeInt16 = function writeInt16(value) {
          this.reserve(this.length + 2);
          this._buffView.setInt16(this.length, value, true);
          this.length += 2;
        };
        _proto.writeInt32 = function writeInt32(value) {
          this.reserve(this.length + 4);
          this._buffView.setInt32(this.length, value, true);
          this.length += 4;
        };
        _proto.writeIntArray = function writeIntArray(value) {
          this.reserve(this.length + 4 * value.length);
          for (var i = 0; i < value.length; ++i) {
            this._buffView.setInt32(this.length + i * 4, value[i], true);
          }
          this.length += 4 * value.length;
        };
        _proto.writeFloat = function writeFloat(value) {
          this.reserve(this.length + 4);
          this._buffView.setFloat32(this.length, value, true);
          this.length += 4;
        };
        _proto.writeFloatArray = function writeFloatArray(value) {
          this.reserve(this.length + 4 * value.length);
          for (var i = 0; i < value.length; ++i) {
            this._buffView.setFloat32(this.length + i * 4, value[i], true);
          }
          this.length += 4 * value.length;
        };
        _proto.writeDouble = function writeDouble(value) {
          this.reserve(this.length + 8);
          this._buffView.setFloat64(this.length, value, true);
          this.length += 8;
        };
        _proto.writeDoubleArray = function writeDoubleArray(value) {
          this.reserve(this.length + 8 * value.length);
          for (var i = 0; i < value.length; ++i) {
            this._buffView.setFloat64(this.length + i * 8, value[i], true);
          }
          this.length += 8 * value.length;
        };
        _proto.writeString = function writeString(value) {
          this.reserve(this.length + value.length + 4);
          this._buffView.setInt32(this.length, value.length, true);
          for (var i = 0; i < value.length; ++i) {
            this._buffView.setInt8(this.length + 4 + i, value.charCodeAt(i));
          }
          this.length += value.length + 4;
        };
        _proto.readInt8 = function readInt8() {
          var value = this._buffView.getInt8(this._seekPos);
          this._seekPos += 1;
          return value;
        };
        _proto.readInt16 = function readInt16() {
          var value = this._buffView.getInt16(this._seekPos, true);
          this._seekPos += 2;
          return value;
        };
        _proto.readInt = function readInt() {
          var value = this._buffView.getInt32(this._seekPos, true);
          this._seekPos += 4;
          return value;
        };
        _proto.readIntArray = function readIntArray(value) {
          for (var i = 0; i < value.length; ++i) {
            value[i] = this._buffView.getInt32(this._seekPos + i * 4, true);
          }
          this._seekPos += 4 * value.length;
          return value;
        };
        _proto.readFloat = function readFloat() {
          var value = this._buffView.getFloat32(this._seekPos, true);
          this._seekPos += 4;
          return value;
        };
        _proto.readFloatArray = function readFloatArray(value) {
          for (var i = 0; i < value.length; ++i) {
            value[i] = this._buffView.getFloat32(this._seekPos + i * 4, true);
          }
          this._seekPos += 4 * value.length;
          return value;
        };
        _proto.readDouble = function readDouble() {
          var value = this._buffView.getFloat64(this._seekPos, true);
          this._seekPos += 8;
          return value;
        };
        _proto.readDoubleArray = function readDoubleArray(value) {
          for (var i = 0; i < value.length; ++i) {
            value[i] = this._buffView.getFloat64(this._seekPos + i * 4, true);
          }
          this._seekPos += 8 * value.length;
          return value;
        };
        _proto.readString = function readString() {
          var length = this.readInt();
          var value = '';
          for (var i = 0; i < length; ++i) {
            value += String.fromCharCode(this.readInt8());
          }
          return value;
        };
        return TerrainBuffer;
      }();
      var TerrainLayerInfo = exports('gK', (_dec$H = ccclass$M('cc.TerrainLayerInfo'), _dec$H(_class2$C = (_class3$i = function TerrainLayerInfo() {
        this.slot = _initializer$A && _initializer$A();
        this.tileSize = _initializer2$y && _initializer2$y();
        this.detailMap = _initializer3$n && _initializer3$n();
        this.normalMap = _initializer4$k && _initializer4$k();
        this.roughness = _initializer5$h && _initializer5$h();
        this.metallic = _initializer6$d && _initializer6$d();
      }, (_initializer$A = applyDecoratedInitializer(_class3$i.prototype, "slot", [serializable$p], function () {
        return 0;
      }), _initializer2$y = applyDecoratedInitializer(_class3$i.prototype, "tileSize", [serializable$p], function () {
        return 1;
      }), _initializer3$n = applyDecoratedInitializer(_class3$i.prototype, "detailMap", [serializable$p], function () {
        return null;
      }), _initializer4$k = applyDecoratedInitializer(_class3$i.prototype, "normalMap", [serializable$p], function () {
        return null;
      }), _initializer5$h = applyDecoratedInitializer(_class3$i.prototype, "roughness", [serializable$p], function () {
        return 1;
      }), _initializer6$d = applyDecoratedInitializer(_class3$i.prototype, "metallic", [serializable$p], function () {
        return 0;
      })), _class3$i)) || _class2$C));
      var TerrainLayerBinaryInfo = exports('gL', (_dec2$D = ccclass$M('cc.TerrainLayerBinaryInfo'), _dec2$D(_class5$7 = function TerrainLayerBinaryInfo() {
        this.slot = 0;
        this.tileSize = 1;
        this.roughness = 1;
        this.metallic = 0;
        this.detailMapId = '';
        this.normalMapId = '';
      }) || _class5$7));
      var TerrainAsset = exports('gM', (_dec3$x = ccclass$M('cc.TerrainAsset'), _dec3$x(_class7$2 = (_class8$3 = function (_Asset) {
        _inheritsLoose(TerrainAsset, _Asset);
        function TerrainAsset() {
          var _this;
          _this = _Asset.call(this) || this;
          _this._version = 0;
          _this._data = null;
          _this._tileSize = 1;
          _this._blockCount = [1, 1];
          _this._weightMapSize = 128;
          _this._lightMapSize = 128;
          _this._heights = new Uint16Array();
          _this._normals = new Float32Array();
          _this._weights = new Uint8Array();
          _this._layerBuffer = [-1, -1, -1, -1];
          _this._layerBinaryInfos = [];
          _this._layerInfos = _initializer7$c && _initializer7$c();
          return _this;
        }
        var _proto2 = TerrainAsset.prototype;
        _proto2.getLayer = function getLayer(xBlock, yBlock, layerId) {
          var blockId = yBlock * this.blockCount[0] + xBlock;
          var index = blockId * 4 + layerId;
          if (xBlock < this.blockCount[0] && yBlock < this.blockCount[1] && index < this._layerBuffer.length) {
            return this._layerBuffer[index];
          }
          return -1;
        };
        _proto2.getHeight = function getHeight(i, j) {
          var vertexCountX = this._blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY + 1;
          return (this._heights[j * vertexCountX + i] - TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY;
        };
        _proto2.getVertexCountI = function getVertexCountI() {
          if (this._blockCount.length < 1) return 0;
          return this._blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY + 1;
        };
        _proto2.getVertexCountJ = function getVertexCountJ() {
          if (this._blockCount.length < 2) return 0;
          return this._blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY + 1;
        };
        _proto2._setNativeData = function _setNativeData(_nativeData) {
          this._data = _nativeData;
        };
        _proto2._loadNativeData = function _loadNativeData(_nativeData) {
          if (!_nativeData || _nativeData.length === 0) {
            return false;
          }
          var stream = new TerrainBuffer();
          stream.assign(_nativeData);
          this._version = stream.readInt();
          if (this._version === TERRAIN_DATA_VERSION_DEFAULT) {
            return true;
          }
          if (this._version !== TERRAIN_DATA_VERSION && this._version !== TERRAIN_DATA_VERSION2 && this._version !== TERRAIN_DATA_VERSION3 && this._version !== TERRAIN_DATA_VERSION4 && this._version !== TERRAIN_DATA_VERSION5 && this._version !== TERRAIN_DATA_VERSION6 && this._version !== TERRAIN_DATA_VERSION7 && this._version !== TERRAIN_DATA_VERSION8) {
            return false;
          }
          if (this._version >= TERRAIN_DATA_VERSION7) {
            this.tileSize = stream.readDouble();
          } else {
            this.tileSize = stream.readFloat();
          }
          this.tileSize = Math.floor(this.tileSize * 100) / 100.0;
          stream.readIntArray(this._blockCount);
          this.weightMapSize = stream.readInt16();
          this.lightMapSize = stream.readInt16();
          var heightBufferSize = stream.readInt();
          this.heights = new Uint16Array(heightBufferSize);
          for (var i = 0; i < this.heights.length; ++i) {
            this.heights[i] = stream.readInt16();
          }
          if (this._version < TERRAIN_DATA_VERSION8) {
            for (var _i = 0; _i < this.heights.length; ++_i) {
              var h = (this._heights[_i] - TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY_V7;
              var ch = TERRAIN_HEIGHT_BASE + h / TERRAIN_HEIGHT_FACTORY;
              this.heights[_i] = ch;
            }
          }
          if (this._version >= TERRAIN_DATA_VERSION6) {
            var normalBufferSize = stream.readInt();
            this.normals = new Float32Array(normalBufferSize);
            for (var _i2 = 0; _i2 < this.normals.length; ++_i2) {
              this.normals[_i2] = stream.readFloat();
            }
          }
          var WeightBufferSize = stream.readInt();
          this.weights = new Uint8Array(WeightBufferSize);
          for (var _i3 = 0; _i3 < this.weights.length; ++_i3) {
            this.weights[_i3] = stream.readInt8();
          }
          if (this._version >= TERRAIN_DATA_VERSION2) {
            var layerBufferSize = stream.readInt();
            this.layerBuffer = new Array(layerBufferSize);
            for (var _i4 = 0; _i4 < this.layerBuffer.length; ++_i4) {
              this.layerBuffer[_i4] = stream.readInt16();
            }
          }
          if (this._version >= TERRAIN_DATA_VERSION3) {
            var layerInfoSize = stream.readInt();
            this._layerBinaryInfos = new Array(layerInfoSize);
            for (var _i5 = 0; _i5 < this._layerBinaryInfos.length; ++_i5) {
              this._layerBinaryInfos[_i5] = new TerrainLayerBinaryInfo();
              this._layerBinaryInfos[_i5].slot = stream.readInt();
              if (this._version >= TERRAIN_DATA_VERSION7) {
                this._layerBinaryInfos[_i5].tileSize = stream.readDouble();
              } else {
                this._layerBinaryInfos[_i5].tileSize = stream.readFloat();
              }
              this._layerBinaryInfos[_i5].detailMapId = stream.readString();
              if (this._version >= TERRAIN_DATA_VERSION4) {
                this._layerBinaryInfos[_i5].normalMapId = stream.readString();
                if (this._version >= TERRAIN_DATA_VERSION7) {
                  this._layerBinaryInfos[_i5].roughness = stream.readDouble();
                  this._layerBinaryInfos[_i5].metallic = stream.readDouble();
                } else {
                  this._layerBinaryInfos[_i5].roughness = stream.readFloat();
                  this._layerBinaryInfos[_i5].metallic = stream.readFloat();
                }
              }
            }
          }
          return true;
        };
        _proto2._exportNativeData = function _exportNativeData() {
          var stream = new TerrainBuffer();
          stream.writeInt32(TERRAIN_DATA_VERSION8);
          stream.writeDouble(this.tileSize);
          stream.writeIntArray(this._blockCount);
          stream.writeInt16(this.weightMapSize);
          stream.writeInt16(this.lightMapSize);
          stream.writeInt32(this.heights.length);
          for (var i = 0; i < this.heights.length; ++i) {
            stream.writeInt16(this.heights[i]);
          }
          stream.writeInt32(this.normals.length);
          for (var _i6 = 0; _i6 < this.normals.length; ++_i6) {
            stream.writeFloat(this.normals[_i6]);
          }
          stream.writeInt32(this.weights.length);
          for (var _i7 = 0; _i7 < this.weights.length; ++_i7) {
            stream.writeInt8(this.weights[_i7]);
          }
          stream.writeInt32(this.layerBuffer.length);
          for (var _i8 = 0; _i8 < this.layerBuffer.length; ++_i8) {
            stream.writeInt16(this.layerBuffer[_i8]);
          }
          var layerBinaryInfos = [];
          layerBinaryInfos.length = this.layerInfos.length;
          for (var _i9 = 0; _i9 < layerBinaryInfos.length; ++_i9) {
            var layer = this.layerInfos[_i9];
            var binaryLayer = new TerrainLayerBinaryInfo();
            binaryLayer.slot = _i9;
            binaryLayer.tileSize = layer.tileSize;
            binaryLayer.detailMapId = layer.detailMap ? layer.detailMap._uuid : '';
            binaryLayer.normalMapId = layer.normalMap ? layer.normalMap._uuid : '';
            binaryLayer.metallic = layer.metallic;
            binaryLayer.roughness = layer.roughness;
            layerBinaryInfos[_i9] = binaryLayer;
          }
          stream.writeInt32(layerBinaryInfos.length);
          for (var _i10 = 0; _i10 < layerBinaryInfos.length; ++_i10) {
            stream.writeInt32(layerBinaryInfos[_i10].slot);
            stream.writeDouble(layerBinaryInfos[_i10].tileSize);
            stream.writeString(layerBinaryInfos[_i10].detailMapId);
            stream.writeString(layerBinaryInfos[_i10].normalMapId);
            stream.writeDouble(layerBinaryInfos[_i10].roughness);
            stream.writeDouble(layerBinaryInfos[_i10].metallic);
          }
          return stream.buffer;
        };
        _proto2._exportDefaultNativeData = function _exportDefaultNativeData() {
          var stream = new TerrainBuffer();
          stream.writeInt32(TERRAIN_DATA_VERSION_DEFAULT);
          return stream.buffer;
        };
        _createClass(TerrainAsset, [{
          key: "_nativeAsset",
          get: function get() {
            return this._data.buffer;
          },
          set: function set(value) {
            if (this._data && this._data.byteLength === value.byteLength) {
              this._data.set(new Uint8Array(value));
            } else {
              this._data = new Uint8Array(value);
            }
            this._loadNativeData(this._data);
          }
        }, {
          key: "version",
          get: function get() {
            return this._version;
          }
        }, {
          key: "tileSize",
          get: function get() {
            return this._tileSize;
          },
          set: function set(value) {
            this._tileSize = value;
          }
        }, {
          key: "blockCount",
          get: function get() {
            return this._blockCount;
          },
          set: function set(value) {
            this._blockCount = value;
          }
        }, {
          key: "lightMapSize",
          get: function get() {
            return this._lightMapSize;
          },
          set: function set(value) {
            this._lightMapSize = value;
          }
        }, {
          key: "weightMapSize",
          get: function get() {
            return this._weightMapSize;
          },
          set: function set(value) {
            this._weightMapSize = value;
          }
        }, {
          key: "heights",
          get: function get() {
            return this._heights;
          },
          set: function set(value) {
            this._heights = value;
          }
        }, {
          key: "normals",
          get: function get() {
            return this._normals;
          },
          set: function set(value) {
            this._normals = value;
          }
        }, {
          key: "weights",
          get: function get() {
            return this._weights;
          },
          set: function set(value) {
            this._weights = value;
          }
        }, {
          key: "layerBuffer",
          get: function get() {
            return this._layerBuffer;
          },
          set: function set(value) {
            this._layerBuffer = value;
          }
        }, {
          key: "layerInfos",
          get: function get() {
            return this._layerInfos;
          },
          set: function set(value) {
            this._layerInfos = value;
          }
        }, {
          key: "layerBinaryInfos",
          get: function get() {
            return this._layerBinaryInfos;
          }
        }]);
        return TerrainAsset;
      }(Asset), (_initializer7$c = applyDecoratedInitializer(_class8$3.prototype, "_layerInfos", [serializable$p], function () {
        return [];
      })), _class8$3)) || _class7$2));

      var _dec$G, _dec2$C, _class$G, _class2$B, _initializer$z;
      var TerrainCollider = exports('fV', (_dec$G = ccclass$M('cc.TerrainCollider'), _dec2$C = type$d(TerrainAsset), _dec$G(_class$G = (_class2$B = function (_Collider) {
        _inheritsLoose(TerrainCollider, _Collider);
        var _proto = TerrainCollider.prototype;
        _proto.onEnable = function onEnable() {
          _Collider.prototype.onEnable.call(this);
          if (this.node) {
            var body = this.node.getComponent(RigidBody);
            if (body && body.isValid && body.type === ERigidBodyType.DYNAMIC) {
              warnID(9630, this.node.name);
            }
          }
        };
        function TerrainCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.TERRAIN) || this;
          _this._terrain = _initializer$z && _initializer$z();
          return _this;
        }
        _createClass(TerrainCollider, [{
          key: "terrain",
          get: function get() {
            return this._terrain;
          },
          set: function set(value) {
            this._terrain = value;
            if (this._shape) this.shape.setTerrain(this._terrain);
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return TerrainCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$B.prototype, "terrain", [_dec2$C], Object.getOwnPropertyDescriptor(_class2$B.prototype, "terrain"), _class2$B.prototype), _initializer$z = applyDecoratedInitializer(_class2$B.prototype, "_terrain", [serializable$p], function () {
        return null;
      })), _class2$B)) || _class$G));

      var _dec$F, _dec2$B, _class$F, _class2$A, _initializer$y, _initializer2$x, _class3$h;
      var SimplexCollider = exports('fW', (_dec$F = ccclass$M('cc.SimplexCollider'), _dec2$B = type$d(ESimplexType), _dec$F(_class$F = (_class2$A = (_class3$h = function (_Collider) {
        _inheritsLoose(SimplexCollider, _Collider);
        function SimplexCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.SIMPLEX) || this;
          _this._shapeType = _initializer$y && _initializer$y();
          _this._vertices = _initializer2$x && _initializer2$x();
          return _this;
        }
        var _proto = SimplexCollider.prototype;
        _proto.updateVertices = function updateVertices() {
          if (this._shape) {
            this.shape.setVertices(this._vertices);
          }
        };
        _createClass(SimplexCollider, [{
          key: "shapeType",
          get: function get() {
            return this._shapeType;
          },
          set: function set(v) {
            this._shapeType = v;
            if (this._shape) {
              this.shape.setShapeType(v);
            }
          }
        }, {
          key: "vertex0",
          get: function get() {
            return this._vertices[0];
          },
          set: function set(v) {
            Vec3.copy(this._vertices[0], v);
            this.updateVertices();
          }
        }, {
          key: "vertex1",
          get: function get() {
            return this._vertices[1];
          },
          set: function set(v) {
            Vec3.copy(this._vertices[1], v);
            this.updateVertices();
          }
        }, {
          key: "vertex2",
          get: function get() {
            return this._vertices[2];
          },
          set: function set(v) {
            Vec3.copy(this._vertices[2], v);
            this.updateVertices();
          }
        }, {
          key: "vertex3",
          get: function get() {
            return this._vertices[3];
          },
          set: function set(v) {
            Vec3.copy(this._vertices[3], v);
            this.updateVertices();
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }, {
          key: "vertices",
          get: function get() {
            return this._vertices;
          }
        }]);
        return SimplexCollider;
      }(Collider), _class3$h.ESimplexType = ESimplexType, _class3$h), (_applyDecoratedDescriptor(_class2$A.prototype, "shapeType", [_dec2$B], Object.getOwnPropertyDescriptor(_class2$A.prototype, "shapeType"), _class2$A.prototype), _initializer$y = applyDecoratedInitializer(_class2$A.prototype, "_shapeType", [serializable$p], function () {
        return ESimplexType.TETRAHEDRON;
      }), _initializer2$x = applyDecoratedInitializer(_class2$A.prototype, "_vertices", [serializable$p], function () {
        return [new Vec3(0, 0, 0), new Vec3(0, 0, 1), new Vec3(1, 0, 0), new Vec3(0, 1, 0)];
      })), _class2$A)) || _class$F));
      (function (_SimplexCollider) {})(SimplexCollider || (exports('fW', SimplexCollider = {})));

      var _dec$E, _dec2$A, _class$E, _class2$z, _initializer$x, _initializer2$w;
      var PlaneCollider = exports('fX', (_dec$E = ccclass$M('cc.PlaneCollider'), _dec2$A = type$d(Vec3), _dec$E(_class$E = (_class2$z = function (_Collider) {
        _inheritsLoose(PlaneCollider, _Collider);
        var _proto = PlaneCollider.prototype;
        _proto.onEnable = function onEnable() {
          _Collider.prototype.onEnable.call(this);
          if (this.node) {
            var body = this.node.getComponent(RigidBody);
            if (body && body.isValid && body.type === ERigidBodyType.DYNAMIC) {
              warnID(9630, this.node.name);
            }
          }
        };
        function PlaneCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.PLANE) || this;
          _this._normal = _initializer$x && _initializer$x();
          _this._constant = _initializer2$w && _initializer2$w();
          return _this;
        }
        _createClass(PlaneCollider, [{
          key: "normal",
          get: function get() {
            return this._normal;
          },
          set: function set(value) {
            if (Vec3.strictEquals(this._normal, value)) return;
            Vec3.copy(this._normal, value);
            if (this._shape) {
              this.shape.setNormal(this._normal);
            }
          }
        }, {
          key: "constant",
          get: function get() {
            return this._constant;
          },
          set: function set(v) {
            if (this._constant === v) return;
            this._constant = v;
            if (this._shape) {
              this.shape.setConstant(this._constant);
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return PlaneCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$z.prototype, "normal", [_dec2$A], Object.getOwnPropertyDescriptor(_class2$z.prototype, "normal"), _class2$z.prototype), _initializer$x = applyDecoratedInitializer(_class2$z.prototype, "_normal", [serializable$p], function () {
        return new Vec3(0, 1, 0);
      }), _initializer2$w = applyDecoratedInitializer(_class2$z.prototype, "_constant", [serializable$p], function () {
        return 0;
      })), _class2$z)) || _class$E));

      var _dec$D, _dec2$z, _dec3$w, _dec4$o, _dec5$n, _class$D, _class2$y, _initializer$w, _initializer2$v, _class3$g;
      var Constraint$1 = exports('fY', (_dec$D = ccclass$M('cc.Constraint'), _dec2$z = requireComponent(RigidBody), _dec3$w = type$d(RigidBody), _dec4$o = type$d(RigidBody), _dec5$n = type$d(RigidBody), _dec$D(_class$D = _dec2$z(_class$D = (_class2$y = (_class3$g = function (_Eventify) {
        _inheritsLoose(Constraint, _Eventify);
        function Constraint(type) {
          var _this;
          _this = _Eventify.call(this) || this;
          _this.TYPE = void 0;
          _this._enableCollision = _initializer$w && _initializer$w();
          _this._connectedBody = _initializer2$v && _initializer2$v();
          _this._constraint = null;
          _this.TYPE = type;
          return _this;
        }
        var _proto = Constraint.prototype;
        _proto.onLoad = function onLoad() {
          if (!selector.runInEditor) return;
          this._constraint = createConstraint(this.TYPE);
          this._constraint.initialize(this);
        };
        _proto.onEnable = function onEnable() {
          if (this._constraint) {
            this._constraint.onEnable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._constraint) {
            this._constraint.onDisable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._constraint) {
            this._constraint.onDestroy();
          }
        };
        _createClass(Constraint, [{
          key: "attachedBody",
          get: function get() {
            return this.getComponent(RigidBody);
          }
        }, {
          key: "connectedBody",
          get: function get() {
            return this._connectedBody;
          },
          set: function set(v) {
            this._connectedBody = v;
            {
              if (this._constraint) this._constraint.setConnectedBody(v);
            }
          }
        }, {
          key: "enableCollision",
          get: function get() {
            return this._enableCollision;
          },
          set: function set(v) {
            this._enableCollision = v;
            {
              if (this._constraint) this._constraint.setEnableCollision(v);
            }
          }
        }]);
        return Constraint;
      }(Eventify(Component)), _class3$g.Type = EConstraintType, _class3$g), (_applyDecoratedDescriptor(_class2$y.prototype, "attachedBody", [_dec3$w], Object.getOwnPropertyDescriptor(_class2$y.prototype, "attachedBody"), _class2$y.prototype), _applyDecoratedDescriptor(_class2$y.prototype, "connectedBody", [_dec4$o], Object.getOwnPropertyDescriptor(_class2$y.prototype, "connectedBody"), _class2$y.prototype), _initializer$w = applyDecoratedInitializer(_class2$y.prototype, "_enableCollision", [serializable$p], function () {
        return true;
      }), _initializer2$v = applyDecoratedInitializer(_class2$y.prototype, "_connectedBody", [_dec5$n], function () {
        return null;
      })), _class2$y)) || _class$D) || _class$D));
      (function (_Constraint) {})(Constraint$1 || (exports('fY', Constraint$1 = {})));

      var _dec$C, _dec2$y, _dec3$v, _dec4$n, _dec5$m, _dec6$e, _dec7$b, _class$C, _class2$x, _initializer$v, _initializer2$u, _initializer3$m, _dec8$8, _dec9$7, _dec10$4, _dec11$3, _dec12$2, _dec13$2, _dec14$1, _class4$4, _class5$6, _initializer4$j, _initializer5$g, _initializer6$c, _dec15$1, _dec16$1, _dec17$1, _dec18$1, _dec19$1, _dec20$1, _dec21$1, _dec22$1, _dec23$1, _dec24$1, _dec25$1, _dec26$1, _dec27$1, _dec28$1, _dec29$1, _class7$1, _class8$2, _initializer7$b, _initializer8$b, _initializer9$a, _initializer10$a, _initializer11$a;
      var HingeLimitData = (_dec$C = ccclass$M('cc.HingeLimitData'), _dec2$y = formerlySerializedAs$4('enabled'), _dec3$v = formerlySerializedAs$4('upperLimit'), _dec4$n = formerlySerializedAs$4('lowerLimit'), _dec5$m = type$d(CCBoolean), _dec6$e = type$d(CCFloat), _dec7$b = type$d(CCFloat), _dec$C(_class$C = (_class2$x = function () {
        function HingeLimitData() {
          this._enabled = _initializer$v && _initializer$v();
          this._upperLimit = _initializer2$u && _initializer2$u();
          this._lowerLimit = _initializer3$m && _initializer3$m();
        }
        _createClass(HingeLimitData, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(v) {
            this._enabled = v;
          }
        }, {
          key: "upperLimit",
          get: function get() {
            return this._upperLimit;
          },
          set: function set(v) {
            this._upperLimit = v;
          }
        }, {
          key: "lowerLimit",
          get: function get() {
            return this._lowerLimit;
          },
          set: function set(v) {
            this._lowerLimit = v;
          }
        }]);
        return HingeLimitData;
      }(), (_initializer$v = applyDecoratedInitializer(_class2$x.prototype, "_enabled", [serializable$p, _dec2$y], function () {
        return false;
      }), _initializer2$u = applyDecoratedInitializer(_class2$x.prototype, "_upperLimit", [serializable$p, _dec3$v], function () {
        return Number.MAX_VALUE;
      }), _initializer3$m = applyDecoratedInitializer(_class2$x.prototype, "_lowerLimit", [serializable$p, _dec4$n], function () {
        return -Number.MAX_VALUE;
      }), _applyDecoratedDescriptor(_class2$x.prototype, "enabled", [_dec5$m], Object.getOwnPropertyDescriptor(_class2$x.prototype, "enabled"), _class2$x.prototype), _applyDecoratedDescriptor(_class2$x.prototype, "upperLimit", [_dec6$e], Object.getOwnPropertyDescriptor(_class2$x.prototype, "upperLimit"), _class2$x.prototype), _applyDecoratedDescriptor(_class2$x.prototype, "lowerLimit", [_dec7$b], Object.getOwnPropertyDescriptor(_class2$x.prototype, "lowerLimit"), _class2$x.prototype)), _class2$x)) || _class$C);
      var HingeMotorData = (_dec8$8 = ccclass$M('cc.HingeMotorData'), _dec9$7 = formerlySerializedAs$4('enabled'), _dec10$4 = formerlySerializedAs$4('motorVelocity'), _dec11$3 = formerlySerializedAs$4('motorForceLimit'), _dec12$2 = type$d(CCBoolean), _dec13$2 = type$d(CCFloat), _dec14$1 = type$d(CCFloat), _dec8$8(_class4$4 = (_class5$6 = function () {
        function HingeMotorData() {
          this._enabled = _initializer4$j && _initializer4$j();
          this._motorVelocity = _initializer5$g && _initializer5$g();
          this._motorForceLimit = _initializer6$c && _initializer6$c();
        }
        _createClass(HingeMotorData, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(v) {
            this._enabled = v;
          }
        }, {
          key: "motorVelocity",
          get: function get() {
            return this._motorVelocity;
          },
          set: function set(v) {
            this._motorVelocity = v;
          }
        }, {
          key: "motorForceLimit",
          get: function get() {
            return this._motorForceLimit;
          },
          set: function set(v) {
            this._motorForceLimit = v;
          }
        }]);
        return HingeMotorData;
      }(), (_initializer4$j = applyDecoratedInitializer(_class5$6.prototype, "_enabled", [serializable$p, _dec9$7], function () {
        return false;
      }), _initializer5$g = applyDecoratedInitializer(_class5$6.prototype, "_motorVelocity", [serializable$p, _dec10$4], function () {
        return 0;
      }), _initializer6$c = applyDecoratedInitializer(_class5$6.prototype, "_motorForceLimit", [serializable$p, _dec11$3], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class5$6.prototype, "enabled", [_dec12$2], Object.getOwnPropertyDescriptor(_class5$6.prototype, "enabled"), _class5$6.prototype), _applyDecoratedDescriptor(_class5$6.prototype, "motorVelocity", [_dec13$2], Object.getOwnPropertyDescriptor(_class5$6.prototype, "motorVelocity"), _class5$6.prototype), _applyDecoratedDescriptor(_class5$6.prototype, "motorForceLimit", [_dec14$1], Object.getOwnPropertyDescriptor(_class5$6.prototype, "motorForceLimit"), _class5$6.prototype)), _class5$6)) || _class4$4);
      var HingeConstraint = exports('fZ', (_dec15$1 = ccclass$M('cc.HingeConstraint'), _dec16$1 = type$d(Vec3), _dec17$1 = type$d(Vec3), _dec18$1 = type$d(Vec3), _dec19$1 = type$d(CCBoolean), _dec20$1 = type$d(CCFloat), _dec21$1 = type$d(CCFloat), _dec22$1 = type$d(CCBoolean), _dec23$1 = type$d(CCFloat), _dec24$1 = type$d(CCFloat), _dec25$1 = formerlySerializedAs$4('axisA'), _dec26$1 = formerlySerializedAs$4('pivotA'), _dec27$1 = formerlySerializedAs$4('pivotB'), _dec28$1 = formerlySerializedAs$4('limitData'), _dec29$1 = formerlySerializedAs$4('motorData'), _dec15$1(_class7$1 = (_class8$2 = function (_Constraint) {
        _inheritsLoose(HingeConstraint, _Constraint);
        function HingeConstraint() {
          var _this;
          _this = _Constraint.call(this, EConstraintType.HINGE) || this;
          _this._axis = _initializer7$b && _initializer7$b();
          _this._pivotA = _initializer8$b && _initializer8$b();
          _this._pivotB = _initializer9$a && _initializer9$a();
          _this._limitData = _initializer10$a && _initializer10$a();
          _this._motorData = _initializer11$a && _initializer11$a();
          return _this;
        }
        _createClass(HingeConstraint, [{
          key: "pivotA",
          get: function get() {
            return this._pivotA;
          },
          set: function set(v) {
            Vec3.copy(this._pivotA, v);
            {
              this.constraint.setPivotA(this._pivotA);
            }
          }
        }, {
          key: "pivotB",
          get: function get() {
            return this._pivotB;
          },
          set: function set(v) {
            Vec3.copy(this._pivotB, v);
            {
              this.constraint.setPivotB(this._pivotB);
            }
          }
        }, {
          key: "axis",
          get: function get() {
            return this._axis;
          },
          set: function set(v) {
            Vec3.copy(this._axis, v);
            {
              this.constraint.setAxis(this._axis);
            }
          }
        }, {
          key: "limitEnabled",
          get: function get() {
            return this._limitData.enabled;
          },
          set: function set(v) {
            this._limitData.enabled = v;
            {
              this.constraint.setLimitEnabled(v);
            }
          }
        }, {
          key: "upperLimit",
          get: function get() {
            return this._limitData.upperLimit;
          },
          set: function set(v) {
            this._limitData.upperLimit = v;
            {
              this.constraint.setUpperLimit(v);
            }
          }
        }, {
          key: "lowerLimit",
          get: function get() {
            return this._limitData.lowerLimit;
          },
          set: function set(v) {
            this._limitData.lowerLimit = v;
            {
              this.constraint.setLowerLimit(v);
            }
          }
        }, {
          key: "motorEnabled",
          get: function get() {
            return this._motorData.enabled;
          },
          set: function set(v) {
            this._motorData.enabled = v;
            {
              this.constraint.setMotorEnabled(v);
            }
          }
        }, {
          key: "motorVelocity",
          get: function get() {
            return this._motorData.motorVelocity;
          },
          set: function set(v) {
            this._motorData.motorVelocity = v;
            {
              this.constraint.setMotorVelocity(v);
            }
          }
        }, {
          key: "motorForceLimit",
          get: function get() {
            return this._motorData.motorForceLimit;
          },
          set: function set(v) {
            this._motorData.motorForceLimit = v;
            {
              this.constraint.setMotorForceLimit(v);
            }
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._constraint;
          }
        }]);
        return HingeConstraint;
      }(Constraint$1), (_applyDecoratedDescriptor(_class8$2.prototype, "pivotA", [_dec16$1], Object.getOwnPropertyDescriptor(_class8$2.prototype, "pivotA"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "pivotB", [_dec17$1], Object.getOwnPropertyDescriptor(_class8$2.prototype, "pivotB"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "axis", [_dec18$1], Object.getOwnPropertyDescriptor(_class8$2.prototype, "axis"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "limitEnabled", [_dec19$1], Object.getOwnPropertyDescriptor(_class8$2.prototype, "limitEnabled"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "upperLimit", [_dec20$1], Object.getOwnPropertyDescriptor(_class8$2.prototype, "upperLimit"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "lowerLimit", [_dec21$1], Object.getOwnPropertyDescriptor(_class8$2.prototype, "lowerLimit"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "motorEnabled", [_dec22$1], Object.getOwnPropertyDescriptor(_class8$2.prototype, "motorEnabled"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "motorVelocity", [_dec23$1], Object.getOwnPropertyDescriptor(_class8$2.prototype, "motorVelocity"), _class8$2.prototype), _applyDecoratedDescriptor(_class8$2.prototype, "motorForceLimit", [_dec24$1], Object.getOwnPropertyDescriptor(_class8$2.prototype, "motorForceLimit"), _class8$2.prototype), _initializer7$b = applyDecoratedInitializer(_class8$2.prototype, "_axis", [serializable$p, _dec25$1], function () {
        return new Vec3();
      }), _initializer8$b = applyDecoratedInitializer(_class8$2.prototype, "_pivotA", [serializable$p, _dec26$1], function () {
        return new Vec3();
      }), _initializer9$a = applyDecoratedInitializer(_class8$2.prototype, "_pivotB", [serializable$p, _dec27$1], function () {
        return new Vec3();
      }), _initializer10$a = applyDecoratedInitializer(_class8$2.prototype, "_limitData", [serializable$p, _dec28$1], function () {
        return new HingeLimitData();
      }), _initializer11$a = applyDecoratedInitializer(_class8$2.prototype, "_motorData", [serializable$p, _dec29$1], function () {
        return new HingeMotorData();
      })), _class8$2)) || _class7$1));

      var _dec$B, _dec2$x, _dec3$u, _dec4$m, _dec5$l, _class$B, _class2$w, _initializer$u, _initializer2$t;
      var FixedConstraint = exports('f$', (_dec$B = ccclass$M('cc.FixedConstraint'), _dec2$x = type$d(CCFloat), _dec3$u = type$d(CCFloat), _dec4$m = formerlySerializedAs$4('breakForce'), _dec5$l = formerlySerializedAs$4('breakTorque'), _dec$B(_class$B = (_class2$w = function (_Constraint) {
        _inheritsLoose(FixedConstraint, _Constraint);
        function FixedConstraint() {
          var _this;
          _this = _Constraint.call(this, EConstraintType.FIXED) || this;
          _this._breakForce = _initializer$u && _initializer$u();
          _this._breakTorque = _initializer2$t && _initializer2$t();
          return _this;
        }
        _createClass(FixedConstraint, [{
          key: "breakForce",
          get: function get() {
            return this._breakForce;
          },
          set: function set(v) {
            this._breakForce = v;
            {
              this.constraint.setBreakForce(v);
            }
          }
        }, {
          key: "breakTorque",
          get: function get() {
            return this._breakTorque;
          },
          set: function set(v) {
            this._breakTorque = v;
            {
              this.constraint.setBreakTorque(v);
            }
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._constraint;
          }
        }]);
        return FixedConstraint;
      }(Constraint$1), (_applyDecoratedDescriptor(_class2$w.prototype, "breakForce", [_dec2$x], Object.getOwnPropertyDescriptor(_class2$w.prototype, "breakForce"), _class2$w.prototype), _applyDecoratedDescriptor(_class2$w.prototype, "breakTorque", [_dec3$u], Object.getOwnPropertyDescriptor(_class2$w.prototype, "breakTorque"), _class2$w.prototype), _initializer$u = applyDecoratedInitializer(_class2$w.prototype, "_breakForce", [serializable$p, _dec4$m], function () {
        return 1e8;
      }), _initializer2$t = applyDecoratedInitializer(_class2$w.prototype, "_breakTorque", [serializable$p, _dec5$l], function () {
        return 1e8;
      })), _class2$w)) || _class$B));

      var _dec$A, _dec2$w, _dec3$t, _dec4$l, _dec5$k, _dec6$d, _dec7$a, _dec8$7, _dec9$6, _dec10$3, _class$A, _class2$v, _initializer$t, _initializer2$s, _initializer3$l, _initializer4$i, _initializer5$f, _initializer6$b, _initializer7$a, _initializer8$a, _initializer9$9, _dec11$2, _dec12$1, _dec13$1, _dec14, _dec15, _dec16, _dec17, _dec18, _dec19, _dec20, _dec21, _dec22, _dec23, _dec24, _dec25, _class4$3, _class5$5, _initializer10$9, _initializer11$9, _initializer12$8, _initializer13$6, _initializer14$5, _initializer15$4, _initializer16$4, _initializer17$2, _initializer18$2, _initializer19$1, _initializer20$1, _initializer21$1, _initializer22$1, _initializer23, _dec26, _dec27, _dec28, _dec29, _dec30, _dec31, _dec32, _class7, _class8$1, _initializer24, _initializer25, _initializer26, _initializer27, _initializer28, _initializer29, _dec33, _dec34, _dec35, _dec36, _dec37, _dec38, _dec39, _class10, _class11, _initializer30, _initializer31, _initializer32, _initializer33, _initializer34, _initializer35, _dec40, _dec41, _dec42, _dec43, _dec44, _dec45, _dec46, _dec47, _dec48, _dec49, _dec50, _dec51, _dec52, _dec53, _dec54, _dec55, _class13$1, _class14, _initializer36, _initializer37, _initializer38, _initializer39, _initializer40, _initializer41, _initializer42, _initializer43, _initializer44, _initializer45, _initializer46;
      var LinearLimitSettings = (_dec$A = ccclass$M('cc.LinearLimitSettings'), _dec2$w = type$d(EConstraintMode), _dec3$t = type$d(EConstraintMode), _dec4$l = type$d(EConstraintMode), _dec5$k = type$d(Vec3), _dec6$d = type$d(Vec3), _dec7$a = type$d(CCFloat), _dec8$7 = type$d(CCBoolean), _dec9$6 = type$d(CCFloat), _dec10$3 = type$d(CCFloat), _dec$A(_class$A = (_class2$v = function () {
        function LinearLimitSettings(configurableConstraint) {
          this._xMotion = _initializer$t && _initializer$t();
          this._yMotion = _initializer2$s && _initializer2$s();
          this._zMotion = _initializer3$l && _initializer3$l();
          this._upper = _initializer4$i && _initializer4$i();
          this._lower = _initializer5$f && _initializer5$f();
          this._enableSoftConstraint = _initializer6$b && _initializer6$b();
          this._bounciness = _initializer7$a && _initializer7$a();
          this._stiffness = _initializer8$a && _initializer8$a();
          this._damping = _initializer9$9 && _initializer9$9();
          this._impl = void 0;
          this._impl = configurableConstraint;
        }
        _createClass(LinearLimitSettings, [{
          key: "xMotion",
          get: function get() {
            return this._xMotion;
          },
          set: function set(v) {
            this._xMotion = v;
            {
              this._impl.setConstraintMode(0, v);
            }
          }
        }, {
          key: "yMotion",
          get: function get() {
            return this._yMotion;
          },
          set: function set(v) {
            this._yMotion = v;
            {
              this._impl.setConstraintMode(1, v);
            }
          }
        }, {
          key: "zMotion",
          get: function get() {
            return this._zMotion;
          },
          set: function set(v) {
            this._zMotion = v;
            {
              this._impl.setConstraintMode(2, v);
            }
          }
        }, {
          key: "upper",
          get: function get() {
            return this._upper;
          },
          set: function set(v) {
            Vec3.copy(this._upper, v);
            {
              var lower = this.lower;
              this._impl.setLinearLimit(0, lower.x, v.x);
              this._impl.setLinearLimit(1, lower.y, v.y);
              this._impl.setLinearLimit(2, lower.z, v.z);
            }
          }
        }, {
          key: "lower",
          get: function get() {
            return this._lower;
          },
          set: function set(v) {
            Vec3.copy(this._lower, v);
            {
              var upper = this.upper;
              this._impl.setLinearLimit(0, v.x, upper.x);
              this._impl.setLinearLimit(1, v.y, upper.y);
              this._impl.setLinearLimit(2, v.z, upper.z);
            }
          }
        }, {
          key: "restitution",
          get: function get() {
            return this._bounciness;
          },
          set: function set(v) {
            this._bounciness = v;
            {
              this._impl.setLinearRestitution(v);
            }
          }
        }, {
          key: "enableSoftConstraint",
          get: function get() {
            return this._enableSoftConstraint;
          },
          set: function set(v) {
            this._enableSoftConstraint = v;
            {
              this._impl.setLinearSoftConstraint(v);
            }
          }
        }, {
          key: "stiffness",
          get: function get() {
            return this._stiffness;
          },
          set: function set(v) {
            this._stiffness = v;
            {
              this._impl.setLinearStiffness(v);
            }
          }
        }, {
          key: "damping",
          get: function get() {
            return this._damping;
          },
          set: function set(v) {
            this._damping = v;
            {
              this._impl.setLinearDamping(v);
            }
          }
        }, {
          key: "impl",
          set: function set(v) {
            this._impl = v;
          }
        }]);
        return LinearLimitSettings;
      }(), (_applyDecoratedDescriptor(_class2$v.prototype, "xMotion", [_dec2$w], Object.getOwnPropertyDescriptor(_class2$v.prototype, "xMotion"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "yMotion", [_dec3$t], Object.getOwnPropertyDescriptor(_class2$v.prototype, "yMotion"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "zMotion", [_dec4$l], Object.getOwnPropertyDescriptor(_class2$v.prototype, "zMotion"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "upper", [_dec5$k], Object.getOwnPropertyDescriptor(_class2$v.prototype, "upper"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "lower", [_dec6$d], Object.getOwnPropertyDescriptor(_class2$v.prototype, "lower"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "restitution", [_dec7$a], Object.getOwnPropertyDescriptor(_class2$v.prototype, "restitution"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "enableSoftConstraint", [_dec8$7], Object.getOwnPropertyDescriptor(_class2$v.prototype, "enableSoftConstraint"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "stiffness", [_dec9$6], Object.getOwnPropertyDescriptor(_class2$v.prototype, "stiffness"), _class2$v.prototype), _applyDecoratedDescriptor(_class2$v.prototype, "damping", [_dec10$3], Object.getOwnPropertyDescriptor(_class2$v.prototype, "damping"), _class2$v.prototype), _initializer$t = applyDecoratedInitializer(_class2$v.prototype, "_xMotion", [serializable$p], function () {
        return EConstraintMode.FREE;
      }), _initializer2$s = applyDecoratedInitializer(_class2$v.prototype, "_yMotion", [serializable$p], function () {
        return EConstraintMode.FREE;
      }), _initializer3$l = applyDecoratedInitializer(_class2$v.prototype, "_zMotion", [serializable$p], function () {
        return EConstraintMode.FREE;
      }), _initializer4$i = applyDecoratedInitializer(_class2$v.prototype, "_upper", [serializable$p], function () {
        return new Vec3();
      }), _initializer5$f = applyDecoratedInitializer(_class2$v.prototype, "_lower", [serializable$p], function () {
        return new Vec3();
      }), _initializer6$b = applyDecoratedInitializer(_class2$v.prototype, "_enableSoftConstraint", [serializable$p], function () {
        return false;
      }), _initializer7$a = applyDecoratedInitializer(_class2$v.prototype, "_bounciness", [serializable$p], function () {
        return 0;
      }), _initializer8$a = applyDecoratedInitializer(_class2$v.prototype, "_stiffness", [serializable$p], function () {
        return 0;
      }), _initializer9$9 = applyDecoratedInitializer(_class2$v.prototype, "_damping", [serializable$p], function () {
        return 0;
      })), _class2$v)) || _class$A);
      var AngularLimitSettings = (_dec11$2 = ccclass$M('cc.AngularLimitSettings'), _dec12$1 = type$d(EConstraintMode), _dec13$1 = type$d(EConstraintMode), _dec14 = type$d(EConstraintMode), _dec15 = type$d(CCFloat), _dec16 = type$d(CCFloat), _dec17 = type$d(CCFloat), _dec18 = type$d(CCFloat), _dec19 = type$d(CCFloat), _dec20 = type$d(CCBoolean), _dec21 = type$d(CCFloat), _dec22 = type$d(CCFloat), _dec23 = type$d(CCBoolean), _dec24 = type$d(CCFloat), _dec25 = type$d(CCFloat), _dec11$2(_class4$3 = (_class5$5 = function () {
        function AngularLimitSettings(configurableConstraint) {
          this._swing1Motion = _initializer10$9 && _initializer10$9();
          this._swing2Motion = _initializer11$9 && _initializer11$9();
          this._twistMotion = _initializer12$8 && _initializer12$8();
          this._twistExtent = _initializer13$6 && _initializer13$6();
          this._swingExtent1 = _initializer14$5 && _initializer14$5();
          this._swingExtent2 = _initializer15$4 && _initializer15$4();
          this._enableSoftConstraintSwing = _initializer16$4 && _initializer16$4();
          this._swingBounciness = _initializer17$2 && _initializer17$2();
          this._swingStiffness = _initializer18$2 && _initializer18$2();
          this._swingDamping = _initializer19$1 && _initializer19$1();
          this._enableSoftConstraintTwist = _initializer20$1 && _initializer20$1();
          this._twistBounciness = _initializer21$1 && _initializer21$1();
          this._twistStiffness = _initializer22$1 && _initializer22$1();
          this._twistDamping = _initializer23 && _initializer23();
          this._impl = void 0;
          this._impl = configurableConstraint;
        }
        _createClass(AngularLimitSettings, [{
          key: "twistMotion",
          get: function get() {
            return this._twistMotion;
          },
          set: function set(v) {
            this._twistMotion = v;
            {
              this._impl.setConstraintMode(3, v);
            }
          }
        }, {
          key: "swingMotion1",
          get: function get() {
            return this._swing1Motion;
          },
          set: function set(v) {
            this._swing1Motion = v;
            {
              this._impl.setConstraintMode(4, v);
            }
          }
        }, {
          key: "swingMotion2",
          get: function get() {
            return this._swing2Motion;
          },
          set: function set(v) {
            this._swing2Motion = v;
            {
              this._impl.setConstraintMode(5, v);
            }
          }
        }, {
          key: "twistExtent",
          get: function get() {
            return this._twistExtent;
          },
          set: function set(v) {
            this._twistExtent = v;
            {
              this._impl.setAngularExtent(v, this.swingExtent1, this.swingExtent2);
            }
          }
        }, {
          key: "swingExtent1",
          get: function get() {
            return this._swingExtent1;
          },
          set: function set(v) {
            this._swingExtent1 = v;
            {
              this._impl.setAngularExtent(this.twistExtent, v, this.swingExtent2);
            }
          }
        }, {
          key: "swingExtent2",
          get: function get() {
            return this._swingExtent2;
          },
          set: function set(v) {
            this._swingExtent2 = v;
            {
              this._impl.setAngularExtent(this.twistExtent, this.swingExtent1, v);
            }
          }
        }, {
          key: "twistRestitution",
          get: function get() {
            return this._twistBounciness;
          },
          set: function set(v) {
            this._twistBounciness = v;
            {
              this._impl.setTwistRestitution(v);
            }
          }
        }, {
          key: "swingRestitution",
          get: function get() {
            return this._swingBounciness;
          },
          set: function set(v) {
            this._swingBounciness = v;
            {
              this._impl.setSwingRestitution(v);
            }
          }
        }, {
          key: "enableSoftConstraintTwist",
          get: function get() {
            return this._enableSoftConstraintTwist;
          },
          set: function set(v) {
            this._enableSoftConstraintTwist = v;
            {
              this._impl.setTwistSoftConstraint(v);
            }
          }
        }, {
          key: "twistStiffness",
          get: function get() {
            return this._twistStiffness;
          },
          set: function set(v) {
            this._twistStiffness = v;
            {
              this._impl.setTwistStiffness(v);
            }
          }
        }, {
          key: "twistDamping",
          get: function get() {
            return this._twistDamping;
          },
          set: function set(v) {
            this._twistDamping = v;
            {
              this._impl.setTwistDamping(v);
            }
          }
        }, {
          key: "enableSoftConstraintSwing",
          get: function get() {
            return this._enableSoftConstraintSwing;
          },
          set: function set(v) {
            this._enableSoftConstraintSwing = v;
            {
              this._impl.setSwingSoftConstraint(v);
            }
          }
        }, {
          key: "swingStiffness",
          get: function get() {
            return this._swingStiffness;
          },
          set: function set(v) {
            this._swingStiffness = v;
            {
              this._impl.setSwingStiffness(v);
            }
          }
        }, {
          key: "swingDamping",
          get: function get() {
            return this._swingDamping;
          },
          set: function set(v) {
            this._swingDamping = v;
            {
              this._impl.setSwingDamping(v);
            }
          }
        }, {
          key: "impl",
          set: function set(v) {
            this._impl = v;
          }
        }]);
        return AngularLimitSettings;
      }(), (_applyDecoratedDescriptor(_class5$5.prototype, "twistMotion", [_dec12$1], Object.getOwnPropertyDescriptor(_class5$5.prototype, "twistMotion"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "swingMotion1", [_dec13$1], Object.getOwnPropertyDescriptor(_class5$5.prototype, "swingMotion1"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "swingMotion2", [_dec14], Object.getOwnPropertyDescriptor(_class5$5.prototype, "swingMotion2"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "twistExtent", [_dec15], Object.getOwnPropertyDescriptor(_class5$5.prototype, "twistExtent"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "swingExtent1", [_dec16], Object.getOwnPropertyDescriptor(_class5$5.prototype, "swingExtent1"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "swingExtent2", [_dec17], Object.getOwnPropertyDescriptor(_class5$5.prototype, "swingExtent2"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "twistRestitution", [_dec18], Object.getOwnPropertyDescriptor(_class5$5.prototype, "twistRestitution"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "swingRestitution", [_dec19], Object.getOwnPropertyDescriptor(_class5$5.prototype, "swingRestitution"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "enableSoftConstraintTwist", [_dec20], Object.getOwnPropertyDescriptor(_class5$5.prototype, "enableSoftConstraintTwist"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "twistStiffness", [_dec21], Object.getOwnPropertyDescriptor(_class5$5.prototype, "twistStiffness"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "twistDamping", [_dec22], Object.getOwnPropertyDescriptor(_class5$5.prototype, "twistDamping"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "enableSoftConstraintSwing", [_dec23], Object.getOwnPropertyDescriptor(_class5$5.prototype, "enableSoftConstraintSwing"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "swingStiffness", [_dec24], Object.getOwnPropertyDescriptor(_class5$5.prototype, "swingStiffness"), _class5$5.prototype), _applyDecoratedDescriptor(_class5$5.prototype, "swingDamping", [_dec25], Object.getOwnPropertyDescriptor(_class5$5.prototype, "swingDamping"), _class5$5.prototype), _initializer10$9 = applyDecoratedInitializer(_class5$5.prototype, "_swing1Motion", [serializable$p], function () {
        return EConstraintMode.FREE;
      }), _initializer11$9 = applyDecoratedInitializer(_class5$5.prototype, "_swing2Motion", [serializable$p], function () {
        return EConstraintMode.FREE;
      }), _initializer12$8 = applyDecoratedInitializer(_class5$5.prototype, "_twistMotion", [serializable$p], function () {
        return EConstraintMode.FREE;
      }), _initializer13$6 = applyDecoratedInitializer(_class5$5.prototype, "_twistExtent", [serializable$p], function () {
        return 0;
      }), _initializer14$5 = applyDecoratedInitializer(_class5$5.prototype, "_swingExtent1", [serializable$p], function () {
        return 0;
      }), _initializer15$4 = applyDecoratedInitializer(_class5$5.prototype, "_swingExtent2", [serializable$p], function () {
        return 0;
      }), _initializer16$4 = applyDecoratedInitializer(_class5$5.prototype, "_enableSoftConstraintSwing", [serializable$p], function () {
        return false;
      }), _initializer17$2 = applyDecoratedInitializer(_class5$5.prototype, "_swingBounciness", [serializable$p], function () {
        return 0;
      }), _initializer18$2 = applyDecoratedInitializer(_class5$5.prototype, "_swingStiffness", [serializable$p], function () {
        return 0;
      }), _initializer19$1 = applyDecoratedInitializer(_class5$5.prototype, "_swingDamping", [serializable$p], function () {
        return 0;
      }), _initializer20$1 = applyDecoratedInitializer(_class5$5.prototype, "_enableSoftConstraintTwist", [serializable$p], function () {
        return false;
      }), _initializer21$1 = applyDecoratedInitializer(_class5$5.prototype, "_twistBounciness", [serializable$p], function () {
        return 0;
      }), _initializer22$1 = applyDecoratedInitializer(_class5$5.prototype, "_twistStiffness", [serializable$p], function () {
        return 0;
      }), _initializer23 = applyDecoratedInitializer(_class5$5.prototype, "_twistDamping", [serializable$p], function () {
        return 0;
      })), _class5$5)) || _class4$3);
      var LinearDriverSettings = (_dec26 = ccclass$M('cc.LinearDriverSettings'), _dec27 = type$d(EDriverMode), _dec28 = type$d(EDriverMode), _dec29 = type$d(EDriverMode), _dec30 = type$d(Vec3), _dec31 = type$d(Vec3), _dec32 = type$d(CCFloat), _dec26(_class7 = (_class8$1 = function () {
        function LinearDriverSettings(configurableConstraint) {
          this._target = _initializer24 && _initializer24();
          this._velocity = _initializer25 && _initializer25();
          this._xDrive = _initializer26 && _initializer26();
          this._yDrive = _initializer27 && _initializer27();
          this._zDrive = _initializer28 && _initializer28();
          this._strength = _initializer29 && _initializer29();
          this._impl = void 0;
          this._impl = configurableConstraint;
        }
        _createClass(LinearDriverSettings, [{
          key: "xDrive",
          get: function get() {
            return this._xDrive;
          },
          set: function set(v) {
            this._xDrive = v;
            {
              this._impl.setDriverMode(0, v);
            }
          }
        }, {
          key: "yDrive",
          get: function get() {
            return this._yDrive;
          },
          set: function set(v) {
            this._yDrive = v;
            {
              this._impl.setDriverMode(1, v);
            }
          }
        }, {
          key: "zDrive",
          get: function get() {
            return this._zDrive;
          },
          set: function set(v) {
            this._zDrive = v;
            {
              this._impl.setDriverMode(2, v);
            }
          }
        }, {
          key: "targetPosition",
          get: function get() {
            return this._target;
          },
          set: function set(v) {
            Vec3.copy(this._target, v);
            {
              this._impl.setLinearMotorTarget(v);
            }
          }
        }, {
          key: "targetVelocity",
          get: function get() {
            return this._velocity;
          },
          set: function set(v) {
            Vec3.copy(this._velocity, v);
            {
              this._impl.setLinearMotorVelocity(v);
            }
          }
        }, {
          key: "strength",
          get: function get() {
            return this._strength;
          },
          set: function set(v) {
            this._strength = v;
            {
              this._impl.setLinearMotorForceLimit(v);
            }
          }
        }, {
          key: "impl",
          set: function set(v) {
            this._impl = v;
          }
        }]);
        return LinearDriverSettings;
      }(), (_applyDecoratedDescriptor(_class8$1.prototype, "xDrive", [_dec27], Object.getOwnPropertyDescriptor(_class8$1.prototype, "xDrive"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "yDrive", [_dec28], Object.getOwnPropertyDescriptor(_class8$1.prototype, "yDrive"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "zDrive", [_dec29], Object.getOwnPropertyDescriptor(_class8$1.prototype, "zDrive"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "targetPosition", [_dec30], Object.getOwnPropertyDescriptor(_class8$1.prototype, "targetPosition"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "targetVelocity", [_dec31], Object.getOwnPropertyDescriptor(_class8$1.prototype, "targetVelocity"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "strength", [_dec32], Object.getOwnPropertyDescriptor(_class8$1.prototype, "strength"), _class8$1.prototype), _initializer24 = applyDecoratedInitializer(_class8$1.prototype, "_target", [serializable$p], function () {
        return new Vec3();
      }), _initializer25 = applyDecoratedInitializer(_class8$1.prototype, "_velocity", [serializable$p], function () {
        return new Vec3();
      }), _initializer26 = applyDecoratedInitializer(_class8$1.prototype, "_xDrive", [serializable$p], function () {
        return EDriverMode.DISABLED;
      }), _initializer27 = applyDecoratedInitializer(_class8$1.prototype, "_yDrive", [serializable$p], function () {
        return EDriverMode.DISABLED;
      }), _initializer28 = applyDecoratedInitializer(_class8$1.prototype, "_zDrive", [serializable$p], function () {
        return EDriverMode.DISABLED;
      }), _initializer29 = applyDecoratedInitializer(_class8$1.prototype, "_strength", [serializable$p], function () {
        return 0;
      })), _class8$1)) || _class7);
      var AngularDriverSettings = (_dec33 = ccclass$M('cc.AngularDriverSettings'), _dec34 = type$d(EDriverMode), _dec35 = type$d(EDriverMode), _dec36 = type$d(EDriverMode), _dec37 = type$d(Vec3), _dec38 = type$d(Vec3), _dec39 = type$d(CCFloat), _dec33(_class10 = (_class11 = function () {
        function AngularDriverSettings(configurableConstraint) {
          this._swingDrive1 = _initializer30 && _initializer30();
          this._swingDrive2 = _initializer31 && _initializer31();
          this._twistDrive = _initializer32 && _initializer32();
          this._targetOrientation = _initializer33 && _initializer33();
          this._targetVelocity = _initializer34 && _initializer34();
          this._strength = _initializer35 && _initializer35();
          this._impl = void 0;
          this._impl = configurableConstraint;
        }
        _createClass(AngularDriverSettings, [{
          key: "twistDrive",
          get: function get() {
            return this._twistDrive;
          },
          set: function set(v) {
            this._twistDrive = v;
            {
              this._impl.setDriverMode(3, v);
            }
          }
        }, {
          key: "swingDrive1",
          get: function get() {
            return this._swingDrive1;
          },
          set: function set(v) {
            this._swingDrive1 = v;
            {
              this._impl.setDriverMode(4, v);
            }
          }
        }, {
          key: "swingDrive2",
          get: function get() {
            return this._swingDrive2;
          },
          set: function set(v) {
            this._swingDrive2 = v;
            {
              this._impl.setDriverMode(5, v);
            }
          }
        }, {
          key: "targetOrientation",
          get: function get() {
            return this._targetOrientation;
          },
          set: function set(v) {
            Vec3.copy(this._targetOrientation, v);
            {
              this._impl.setAngularMotorTarget(v);
            }
          }
        }, {
          key: "targetVelocity",
          get: function get() {
            return this._targetVelocity;
          },
          set: function set(v) {
            Vec3.copy(this._targetVelocity, v);
            {
              this._impl.setAngularMotorVelocity(v);
            }
          }
        }, {
          key: "strength",
          get: function get() {
            return this._strength;
          },
          set: function set(v) {
            this._strength = v;
            {
              this._impl.setAngularMotorForceLimit(v);
            }
          }
        }, {
          key: "impl",
          set: function set(v) {
            this._impl = v;
          }
        }]);
        return AngularDriverSettings;
      }(), (_applyDecoratedDescriptor(_class11.prototype, "twistDrive", [_dec34], Object.getOwnPropertyDescriptor(_class11.prototype, "twistDrive"), _class11.prototype), _applyDecoratedDescriptor(_class11.prototype, "swingDrive1", [_dec35], Object.getOwnPropertyDescriptor(_class11.prototype, "swingDrive1"), _class11.prototype), _applyDecoratedDescriptor(_class11.prototype, "swingDrive2", [_dec36], Object.getOwnPropertyDescriptor(_class11.prototype, "swingDrive2"), _class11.prototype), _applyDecoratedDescriptor(_class11.prototype, "targetOrientation", [_dec37], Object.getOwnPropertyDescriptor(_class11.prototype, "targetOrientation"), _class11.prototype), _applyDecoratedDescriptor(_class11.prototype, "targetVelocity", [_dec38], Object.getOwnPropertyDescriptor(_class11.prototype, "targetVelocity"), _class11.prototype), _applyDecoratedDescriptor(_class11.prototype, "strength", [_dec39], Object.getOwnPropertyDescriptor(_class11.prototype, "strength"), _class11.prototype), _initializer30 = applyDecoratedInitializer(_class11.prototype, "_swingDrive1", [serializable$p], function () {
        return EDriverMode.DISABLED;
      }), _initializer31 = applyDecoratedInitializer(_class11.prototype, "_swingDrive2", [serializable$p], function () {
        return EDriverMode.DISABLED;
      }), _initializer32 = applyDecoratedInitializer(_class11.prototype, "_twistDrive", [serializable$p], function () {
        return EDriverMode.DISABLED;
      }), _initializer33 = applyDecoratedInitializer(_class11.prototype, "_targetOrientation", [serializable$p], function () {
        return new Vec3();
      }), _initializer34 = applyDecoratedInitializer(_class11.prototype, "_targetVelocity", [serializable$p], function () {
        return new Vec3();
      }), _initializer35 = applyDecoratedInitializer(_class11.prototype, "_strength", [serializable$p], function () {
        return 0;
      })), _class11)) || _class10);
      var ConfigurableConstraint = exports('f_', (_dec40 = ccclass$M('cc.ConfigurableConstraint'), _dec41 = type$d(Vec3), _dec42 = type$d(Vec3), _dec43 = type$d(Vec3), _dec44 = type$d(Vec3), _dec45 = type$d(CCBoolean), _dec46 = type$d(CCFloat), _dec47 = type$d(CCFloat), _dec48 = type$d(LinearLimitSettings), _dec49 = type$d(AngularLimitSettings), _dec50 = type$d(LinearDriverSettings), _dec51 = type$d(AngularDriverSettings), _dec52 = formerlySerializedAs$4('linearLimitSettings'), _dec53 = formerlySerializedAs$4('angularLimitSettings'), _dec54 = formerlySerializedAs$4('linearDriverSettings'), _dec55 = formerlySerializedAs$4('angularDriverSettings'), _dec40(_class13$1 = (_class14 = function (_Constraint) {
        _inheritsLoose(ConfigurableConstraint, _Constraint);
        function ConfigurableConstraint() {
          var _this;
          _this = _Constraint.call(this, EConstraintType.CONFIGURABLE) || this;
          _this._breakForce = _initializer36 && _initializer36();
          _this._breakTorque = _initializer37 && _initializer37();
          _this._linearLimitSettings = _initializer38 && _initializer38();
          _this._angularLimitSettings = _initializer39 && _initializer39();
          _this._linearDriverSettings = _initializer40 && _initializer40();
          _this._angularDriverSettings = _initializer41 && _initializer41();
          _this._pivotA = _initializer42 && _initializer42();
          _this._pivotB = _initializer43 && _initializer43();
          _this._autoPivotB = _initializer44 && _initializer44();
          _this._axis = _initializer45 && _initializer45();
          _this._secondaryAxis = _initializer46 && _initializer46();
          _this._linearLimitSettings = new LinearLimitSettings(_this.constraint);
          _this._angularLimitSettings = new AngularLimitSettings(_this.constraint);
          _this._linearDriverSettings = new LinearDriverSettings(_this.constraint);
          _this._angularDriverSettings = new AngularDriverSettings(_this.constraint);
          return _this;
        }
        var _proto = ConfigurableConstraint.prototype;
        _proto.onLoad = function onLoad() {
          _Constraint.prototype.onLoad.call(this);
          {
            this.linearLimitSettings.impl = this.constraint;
            this.angularLimitSettings.impl = this.constraint;
            this.linearDriverSettings.impl = this.constraint;
            this.angularDriverSettings.impl = this.constraint;
          }
        };
        _createClass(ConfigurableConstraint, [{
          key: "axis",
          get: function get() {
            return this._axis;
          },
          set: function set(v) {
            Vec3.copy(this._axis, v);
            {
              this.constraint.setAxis(this._axis);
            }
          }
        }, {
          key: "secondaryAxis",
          get: function get() {
            return this._secondaryAxis;
          },
          set: function set(v) {
            Vec3.copy(this._secondaryAxis, v);
            {
              this.constraint.setSecondaryAxis(this._secondaryAxis);
            }
          }
        }, {
          key: "pivotA",
          get: function get() {
            return this._pivotA;
          },
          set: function set(v) {
            Vec3.copy(this._pivotA, v);
            {
              this.constraint.setPivotA(this._pivotA);
            }
          }
        }, {
          key: "pivotB",
          get: function get() {
            return this._pivotB;
          },
          set: function set(v) {
            Vec3.copy(this._pivotB, v);
            {
              this.constraint.setPivotB(this._pivotB);
            }
          }
        }, {
          key: "autoPivotB",
          get: function get() {
            return this._autoPivotB;
          },
          set: function set(v) {
            this._autoPivotB = v;
            {
              this.constraint.setAutoPivotB(this._autoPivotB);
            }
          }
        }, {
          key: "breakForce",
          get: function get() {
            return this._breakForce;
          },
          set: function set(v) {
            this._breakForce = v;
            {
              this.constraint.setBreakForce(v);
            }
          }
        }, {
          key: "breakTorque",
          get: function get() {
            return this._breakTorque;
          },
          set: function set(v) {
            this._breakTorque = v;
            {
              this.constraint.setBreakTorque(v);
            }
          }
        }, {
          key: "linearLimitSettings",
          get: function get() {
            return this._linearLimitSettings;
          },
          set: function set(v) {
            this._linearLimitSettings = v;
            {
              var constraint = this.constraint;
              constraint.setConstraintMode(0, v.xMotion);
              constraint.setConstraintMode(1, v.yMotion);
              constraint.setConstraintMode(2, v.zMotion);
              var upper = v.upper;
              var lower = v.lower;
              constraint.setLinearLimit(0, lower.x, upper.x);
              constraint.setLinearLimit(1, lower.y, upper.y);
              constraint.setLinearLimit(2, lower.z, upper.z);
              constraint.setLinearSoftConstraint(v.enableSoftConstraint);
              constraint.setLinearDamping(v.damping);
              constraint.setLinearStiffness(v.stiffness);
              constraint.setLinearRestitution(v.restitution);
            }
          }
        }, {
          key: "angularLimitSettings",
          get: function get() {
            return this._angularLimitSettings;
          },
          set: function set(v) {
            this._angularLimitSettings = v;
            {
              var constraint = this.constraint;
              constraint.setConstraintMode(3, v.twistMotion);
              constraint.setConstraintMode(4, v.swingMotion1);
              constraint.setConstraintMode(5, v.swingMotion2);
              constraint.setAngularExtent(v.twistExtent, v.swingExtent1, v.swingExtent2);
              constraint.setTwistRestitution(v.twistRestitution);
              constraint.setSwingRestitution(v.swingRestitution);
              constraint.setTwistSoftConstraint(v.enableSoftConstraintTwist);
              constraint.setSwingSoftConstraint(v.enableSoftConstraintSwing);
              constraint.setTwistDamping(v.twistDamping);
              constraint.setSwingDamping(v.swingDamping);
              constraint.setTwistStiffness(v.twistStiffness);
              constraint.setSwingStiffness(v.swingStiffness);
            }
          }
        }, {
          key: "linearDriverSettings",
          get: function get() {
            return this._linearDriverSettings;
          },
          set: function set(v) {
            this._linearDriverSettings = v;
            {
              var constraint = this.constraint;
              constraint.setDriverMode(0, v.xDrive);
              constraint.setDriverMode(1, v.yDrive);
              constraint.setDriverMode(2, v.zDrive);
              constraint.setLinearMotorTarget(v.targetPosition);
              constraint.setLinearMotorVelocity(v.targetVelocity);
              constraint.setLinearMotorForceLimit(v.strength);
            }
          }
        }, {
          key: "angularDriverSettings",
          get: function get() {
            return this._angularDriverSettings;
          },
          set: function set(v) {
            this._angularDriverSettings = v;
            {
              var constraint = this.constraint;
              constraint.setDriverMode(3, v.twistDrive);
              constraint.setDriverMode(4, v.swingDrive1);
              constraint.setDriverMode(5, v.swingDrive2);
              constraint.setAngularMotorTarget(v.targetOrientation);
              constraint.setAngularMotorVelocity(v.targetVelocity);
              constraint.setAngularMotorForceLimit(v.strength);
            }
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._constraint;
          }
        }]);
        return ConfigurableConstraint;
      }(Constraint$1), (_applyDecoratedDescriptor(_class14.prototype, "axis", [_dec41], Object.getOwnPropertyDescriptor(_class14.prototype, "axis"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "secondaryAxis", [_dec42], Object.getOwnPropertyDescriptor(_class14.prototype, "secondaryAxis"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "pivotA", [_dec43], Object.getOwnPropertyDescriptor(_class14.prototype, "pivotA"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "pivotB", [_dec44], Object.getOwnPropertyDescriptor(_class14.prototype, "pivotB"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "autoPivotB", [_dec45], Object.getOwnPropertyDescriptor(_class14.prototype, "autoPivotB"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "breakForce", [_dec46], Object.getOwnPropertyDescriptor(_class14.prototype, "breakForce"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "breakTorque", [_dec47], Object.getOwnPropertyDescriptor(_class14.prototype, "breakTorque"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "linearLimitSettings", [_dec48], Object.getOwnPropertyDescriptor(_class14.prototype, "linearLimitSettings"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "angularLimitSettings", [_dec49], Object.getOwnPropertyDescriptor(_class14.prototype, "angularLimitSettings"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "linearDriverSettings", [_dec50], Object.getOwnPropertyDescriptor(_class14.prototype, "linearDriverSettings"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "angularDriverSettings", [_dec51], Object.getOwnPropertyDescriptor(_class14.prototype, "angularDriverSettings"), _class14.prototype), _initializer36 = applyDecoratedInitializer(_class14.prototype, "_breakForce", [serializable$p], function () {
        return 1e8;
      }), _initializer37 = applyDecoratedInitializer(_class14.prototype, "_breakTorque", [serializable$p], function () {
        return 1e8;
      }), _initializer38 = applyDecoratedInitializer(_class14.prototype, "_linearLimitSettings", [serializable$p, _dec52], null), _initializer39 = applyDecoratedInitializer(_class14.prototype, "_angularLimitSettings", [serializable$p, _dec53], null), _initializer40 = applyDecoratedInitializer(_class14.prototype, "_linearDriverSettings", [serializable$p, _dec54], null), _initializer41 = applyDecoratedInitializer(_class14.prototype, "_angularDriverSettings", [serializable$p, _dec55], null), _initializer42 = applyDecoratedInitializer(_class14.prototype, "_pivotA", [serializable$p], function () {
        return new Vec3();
      }), _initializer43 = applyDecoratedInitializer(_class14.prototype, "_pivotB", [serializable$p], function () {
        return new Vec3();
      }), _initializer44 = applyDecoratedInitializer(_class14.prototype, "_autoPivotB", [serializable$p], function () {
        return false;
      }), _initializer45 = applyDecoratedInitializer(_class14.prototype, "_axis", [serializable$p], function () {
        return new Vec3(0, 1, 0);
      }), _initializer46 = applyDecoratedInitializer(_class14.prototype, "_secondaryAxis", [serializable$p], function () {
        return new Vec3(1, 0, 0);
      })), _class14)) || _class13$1));

      var _dec$z, _dec2$v, _dec3$s, _class$z, _class2$u, _initializer$s, _initializer2$r;
      var PointToPointConstraint = exports('g0', (_dec$z = ccclass$M('cc.PointToPointConstraint'), _dec2$v = type$d(Vec3), _dec3$s = type$d(Vec3), _dec$z(_class$z = (_class2$u = function (_Constraint) {
        _inheritsLoose(PointToPointConstraint, _Constraint);
        function PointToPointConstraint() {
          var _this;
          _this = _Constraint.call(this, EConstraintType.POINT_TO_POINT) || this;
          _this._pivotA = _initializer$s && _initializer$s();
          _this._pivotB = _initializer2$r && _initializer2$r();
          return _this;
        }
        _createClass(PointToPointConstraint, [{
          key: "pivotA",
          get: function get() {
            return this._pivotA;
          },
          set: function set(v) {
            Vec3.copy(this._pivotA, v);
            {
              this.constraint.setPivotA(this._pivotA);
            }
          }
        }, {
          key: "pivotB",
          get: function get() {
            return this._pivotB;
          },
          set: function set(v) {
            Vec3.copy(this._pivotB, v);
            {
              this.constraint.setPivotB(this._pivotB);
            }
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._constraint;
          }
        }]);
        return PointToPointConstraint;
      }(Constraint$1), (_applyDecoratedDescriptor(_class2$u.prototype, "pivotA", [_dec2$v], Object.getOwnPropertyDescriptor(_class2$u.prototype, "pivotA"), _class2$u.prototype), _applyDecoratedDescriptor(_class2$u.prototype, "pivotB", [_dec3$s], Object.getOwnPropertyDescriptor(_class2$u.prototype, "pivotB"), _class2$u.prototype), _initializer$s = applyDecoratedInitializer(_class2$u.prototype, "_pivotA", [serializable$p], function () {
        return new Vec3();
      }), _initializer2$r = applyDecoratedInitializer(_class2$u.prototype, "_pivotB", [serializable$p], function () {
        return new Vec3();
      })), _class2$u)) || _class$z));

      var _dec$y, _dec2$u, _dec3$r, _dec4$k, _dec5$j, _dec6$c, _dec7$9, _class$y, _class2$t, _initializer$r, _initializer2$q, _initializer3$k, _initializer4$h, _initializer5$e, _initializer6$a;
      new Vec3(0, 0, 0);
      new Vec3(0, 0, 0);
      var CharacterController = exports('fJ', (_dec$y = ccclass$M('cc.CharacterController'), _dec2$u = type$d(PhysicsSystem.PhysicsGroup), _dec3$r = type$d(CCFloat), _dec4$k = type$d(CCFloat), _dec5$j = type$d(CCFloat), _dec6$c = type$d(CCFloat), _dec7$9 = type$d(Vec3), _dec$y(_class$y = disallowMultiple$1(_class$y = (_class2$t = function (_Eventify) {
        _inheritsLoose(CharacterController, _Eventify);
        function CharacterController(type) {
          var _this;
          _this = _Eventify.call(this) || this;
          _this.type = void 0;
          _this._cct = null;
          _this._group = _initializer$r && _initializer$r();
          _this._minMoveDistance = _initializer2$q && _initializer2$q();
          _this._stepOffset = _initializer3$k && _initializer3$k();
          _this._slopeLimit = _initializer4$h && _initializer4$h();
          _this._skinWidth = _initializer5$e && _initializer5$e();
          _this._center = _initializer6$a && _initializer6$a();
          _this._initialized = false;
          _this._prevPos = new Vec3();
          _this._currentPos = new Vec3();
          _this._velocity = new Vec3();
          _this._centerWorldPosition = new Vec3();
          _this._needCollisionEvent = false;
          _this._needTriggerEvent = false;
          _this.type = type;
          return _this;
        }
        var _proto = CharacterController.prototype;
        _proto.onLoad = function onLoad() {
          if (!selector.runInEditor) return;
          this._cct = createCharacterController(this.type);
          this._initialized = this._cct.initialize(this);
          this._cct.onLoad();
        };
        _proto.onEnable = function onEnable() {
          if (this._cct) {
            this._cct.onEnable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._cct) {
            this._cct.onDisable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._cct) {
            this._needCollisionEvent = false;
            this._needTriggerEvent = false;
            this._cct.updateEventListener();
            this._cct.onDestroy();
            this._cct = null;
          }
        };
        _proto.move = function move(movement) {
          if (!this._isInitialized) {
            return;
          }
          this._prevPos.set(this.centerWorldPosition);
          var elapsedTime = PhysicsSystem.instance.fixedTimeStep;
          this._cct.move(movement, this._minMoveDistance, elapsedTime);
          this._currentPos.set(this.centerWorldPosition);
          this._velocity = this._currentPos.subtract(this._prevPos).multiplyScalar(1.0 / elapsedTime);
          this._cct.syncPhysicsToScene();
        };
        _proto.on = function on(type, callback, target, once) {
          var ret = _Eventify.prototype.on.call(this, type, callback, target, once);
          this._updateNeedEvent(type);
          return ret;
        };
        _proto.off = function off(type, callback, target) {
          _Eventify.prototype.off.call(this, type, callback, target);
          this._updateNeedEvent();
        };
        _proto.once = function once(type, callback, target) {
          var ret = _Eventify.prototype.once.call(this, type, callback, target);
          this._updateNeedEvent(type);
          return ret;
        };
        _proto.getGroup = function getGroup() {
          if (this._isInitialized) return this._cct.getGroup();
          return 0;
        };
        _proto.setGroup = function setGroup(v) {
          if (this._isInitialized) this._cct.setGroup(v);
        };
        _proto.addGroup = function addGroup(v) {
          if (this._isInitialized) this._cct.addGroup(v);
        };
        _proto.removeGroup = function removeGroup(v) {
          if (this._isInitialized) this._cct.removeGroup(v);
        };
        _proto.getMask = function getMask() {
          if (this._isInitialized) return this._cct.getMask();
          return 0;
        };
        _proto.setMask = function setMask(v) {
          if (this._isInitialized) this._cct.setMask(v);
        };
        _proto.addMask = function addMask(v) {
          if (this._isInitialized) this._cct.addMask(v);
        };
        _proto.removeMask = function removeMask(v) {
          if (this._isInitialized) this._cct.removeMask(v);
        };
        _proto._updateNeedEvent = function _updateNeedEvent(type) {
          if (this.isValid) {
            if (type !== undefined) {
              if (type === 'onControllerColliderHit') {
                this._needCollisionEvent = true;
              }
              if (type === 'onControllerTriggerEnter' || type === 'onControllerTriggerStay' || type === 'onControllerTriggerExit') {
                this._needTriggerEvent = true;
              }
            } else {
              if (!this.hasEventListener('onControllerColliderHit')) {
                this._needCollisionEvent = false;
              }
              if (!(this.hasEventListener('onControllerTriggerEnter') || this.hasEventListener('onControllerTriggerStay') || this.hasEventListener('onControllerTriggerExit'))) {
                this._needTriggerEvent = false;
              }
            }
            if (this._cct) this._cct.updateEventListener();
          }
        };
        _createClass(CharacterController, [{
          key: "group",
          get: function get() {
            return this._group;
          },
          set: function set(v) {
            if (!Number.isInteger(Math.log2(v >>> 0))) {
              warn('[Physics]: The group should only have one bit.');
            }
            this._group = v;
            if (this._cct) {
              if (this._cct.getGroup() !== v) this._cct.setGroup(v);
            }
          }
        }, {
          key: "minMoveDistance",
          get: function get() {
            return this._minMoveDistance;
          },
          set: function set(value) {
            if (this._minMoveDistance === value) return;
            this._minMoveDistance = Math.abs(value);
          }
        }, {
          key: "stepOffset",
          get: function get() {
            return this._stepOffset;
          },
          set: function set(value) {
            if (this._stepOffset === value) return;
            this._stepOffset = Math.abs(value);
            if (this._cct) {
              this._cct.setStepOffset(value);
            }
          }
        }, {
          key: "slopeLimit",
          get: function get() {
            return this._slopeLimit;
          },
          set: function set(value) {
            if (this._slopeLimit === value) return;
            this._slopeLimit = Math.abs(value);
            if (this._cct) {
              this._cct.setSlopeLimit(value);
            }
          }
        }, {
          key: "skinWidth",
          get: function get() {
            return this._skinWidth;
          },
          set: function set(value) {
            if (this._skinWidth === value) return;
            this._skinWidth = Math.abs(value);
            if (this._cct) {
              this._cct.setContactOffset(Math.max(0.0001, value));
            }
          }
        }, {
          key: "center",
          get: function get() {
            return this._center;
          },
          set: function set(value) {
            if (Vec3.equals(this._center, value)) return;
            Vec3.copy(this._center, value);
          }
        }, {
          key: "_isInitialized",
          get: function get() {
            if (this._cct === null || !this._initialized) {
              return false;
            } else {
              return true;
            }
          }
        }, {
          key: "centerWorldPosition",
          get: function get() {
            if (this._isInitialized) this._cct.getPosition(this._centerWorldPosition);
            return this._centerWorldPosition;
          },
          set: function set(value) {
            if (this._isInitialized) this._cct.setPosition(value);
          }
        }, {
          key: "velocity",
          get: function get() {
            return this._velocity;
          }
        }, {
          key: "isGrounded",
          get: function get() {
            return this._cct.onGround();
          }
        }, {
          key: "needCollisionEvent",
          get: function get() {
            return this._needCollisionEvent;
          }
        }, {
          key: "needTriggerEvent",
          get: function get() {
            return this._needTriggerEvent;
          }
        }]);
        return CharacterController;
      }(Eventify(Component)), (_applyDecoratedDescriptor(_class2$t.prototype, "group", [_dec2$u], Object.getOwnPropertyDescriptor(_class2$t.prototype, "group"), _class2$t.prototype), _applyDecoratedDescriptor(_class2$t.prototype, "minMoveDistance", [_dec3$r], Object.getOwnPropertyDescriptor(_class2$t.prototype, "minMoveDistance"), _class2$t.prototype), _applyDecoratedDescriptor(_class2$t.prototype, "stepOffset", [_dec4$k], Object.getOwnPropertyDescriptor(_class2$t.prototype, "stepOffset"), _class2$t.prototype), _applyDecoratedDescriptor(_class2$t.prototype, "slopeLimit", [_dec5$j], Object.getOwnPropertyDescriptor(_class2$t.prototype, "slopeLimit"), _class2$t.prototype), _applyDecoratedDescriptor(_class2$t.prototype, "skinWidth", [_dec6$c], Object.getOwnPropertyDescriptor(_class2$t.prototype, "skinWidth"), _class2$t.prototype), _applyDecoratedDescriptor(_class2$t.prototype, "center", [_dec7$9], Object.getOwnPropertyDescriptor(_class2$t.prototype, "center"), _class2$t.prototype), _initializer$r = applyDecoratedInitializer(_class2$t.prototype, "_group", [serializable$p], function () {
        return PhysicsSystem.PhysicsGroup.DEFAULT;
      }), _initializer2$q = applyDecoratedInitializer(_class2$t.prototype, "_minMoveDistance", [serializable$p], function () {
        return 0.001;
      }), _initializer3$k = applyDecoratedInitializer(_class2$t.prototype, "_stepOffset", [serializable$p], function () {
        return 0.5;
      }), _initializer4$h = applyDecoratedInitializer(_class2$t.prototype, "_slopeLimit", [serializable$p], function () {
        return 45.0;
      }), _initializer5$e = applyDecoratedInitializer(_class2$t.prototype, "_skinWidth", [serializable$p], function () {
        return 0.01;
      }), _initializer6$a = applyDecoratedInitializer(_class2$t.prototype, "_center", [serializable$p], function () {
        return new Vec3();
      })), _class2$t)) || _class$y) || _class$y));

      var _dec$x, _dec2$t, _dec3$q, _dec4$j, _dec5$i, _class$x, _class2$s, _initializer$q, _initializer2$p, _initializer3$j;
      new Vec3(0, 0, 0);
      var BoxCharacterController = exports('g2', (_dec$x = ccclass$M('cc.BoxCharacterController'), _dec2$t = executionOrder$1(-1), _dec3$q = type$d(CCFloat), _dec4$j = type$d(CCFloat), _dec5$i = type$d(CCFloat), _dec$x(_class$x = _dec2$t(_class$x = (_class2$s = function (_CharacterController) {
        _inheritsLoose(BoxCharacterController, _CharacterController);
        function BoxCharacterController() {
          var _this;
          _this = _CharacterController.call(this, ECharacterControllerType.BOX) || this;
          _this._halfHeight = _initializer$q && _initializer$q();
          _this._halfSideExtent = _initializer2$p && _initializer2$p();
          _this._halfForwardExtent = _initializer3$j && _initializer3$j();
          return _this;
        }
        _createClass(BoxCharacterController, [{
          key: "halfHeight",
          get: function get() {
            return this._halfHeight;
          },
          set: function set(value) {
            if (this._halfHeight === value) return;
            this._halfHeight = Math.abs(value);
            if (this._cct) {
              this._cct.setHalfHeight(value);
            }
          }
        }, {
          key: "halfSideExtent",
          get: function get() {
            return this._halfSideExtent;
          },
          set: function set(value) {
            if (this._halfSideExtent === value) return;
            this._halfSideExtent = Math.abs(value);
            if (this._cct) {
              this._cct.setHalfSideExtent(value);
            }
          }
        }, {
          key: "halfForwardExtent",
          get: function get() {
            return this._halfForwardExtent;
          },
          set: function set(value) {
            if (this._halfForwardExtent === value) return;
            this._halfForwardExtent = Math.abs(value);
            if (this._cct) {
              this._cct.setHalfForwardExtent(value);
            }
          }
        }]);
        return BoxCharacterController;
      }(CharacterController), (_applyDecoratedDescriptor(_class2$s.prototype, "halfHeight", [_dec3$q], Object.getOwnPropertyDescriptor(_class2$s.prototype, "halfHeight"), _class2$s.prototype), _applyDecoratedDescriptor(_class2$s.prototype, "halfSideExtent", [_dec4$j], Object.getOwnPropertyDescriptor(_class2$s.prototype, "halfSideExtent"), _class2$s.prototype), _applyDecoratedDescriptor(_class2$s.prototype, "halfForwardExtent", [_dec5$i], Object.getOwnPropertyDescriptor(_class2$s.prototype, "halfForwardExtent"), _class2$s.prototype), _initializer$q = applyDecoratedInitializer(_class2$s.prototype, "_halfHeight", [serializable$p], function () {
        return 0.5;
      }), _initializer2$p = applyDecoratedInitializer(_class2$s.prototype, "_halfSideExtent", [serializable$p], function () {
        return 0.5;
      }), _initializer3$j = applyDecoratedInitializer(_class2$s.prototype, "_halfForwardExtent", [serializable$p], function () {
        return 0.5;
      })), _class2$s)) || _class$x) || _class$x));

      var _dec$w, _dec2$s, _dec3$p, _dec4$i, _class$w, _class2$r, _initializer$p, _initializer2$o;
      new Vec3(0, 0, 0);
      var CapsuleCharacterController = exports('g1', (_dec$w = ccclass$M('cc.CapsuleCharacterController'), _dec2$s = executionOrder$1(-1), _dec3$p = type$d(CCFloat), _dec4$i = type$d(CCFloat), _dec$w(_class$w = _dec2$s(_class$w = (_class2$r = function (_CharacterController) {
        _inheritsLoose(CapsuleCharacterController, _CharacterController);
        function CapsuleCharacterController() {
          var _this;
          _this = _CharacterController.call(this, ECharacterControllerType.CAPSULE) || this;
          _this._radius = _initializer$p && _initializer$p();
          _this._height = _initializer2$o && _initializer2$o();
          return _this;
        }
        _createClass(CapsuleCharacterController, [{
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(value) {
            if (this._radius === value) return;
            this._radius = Math.abs(value);
            if (this._cct) {
              this._cct.setRadius(value);
            }
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          },
          set: function set(value) {
            if (this._height === value) return;
            this._height = Math.abs(value);
            if (this._cct) {
              this._cct.setHeight(value);
            }
          }
        }]);
        return CapsuleCharacterController;
      }(CharacterController), (_applyDecoratedDescriptor(_class2$r.prototype, "radius", [_dec3$p], Object.getOwnPropertyDescriptor(_class2$r.prototype, "radius"), _class2$r.prototype), _applyDecoratedDescriptor(_class2$r.prototype, "height", [_dec4$i], Object.getOwnPropertyDescriptor(_class2$r.prototype, "height"), _class2$r.prototype), _initializer$p = applyDecoratedInitializer(_class2$r.prototype, "_radius", [serializable$p], function () {
        return 0.5;
      }), _initializer2$o = applyDecoratedInitializer(_class2$r.prototype, "_height", [serializable$p], function () {
        return 1.0;
      })), _class2$r)) || _class$w) || _class$w));

      var CharacterControllerContact = function CharacterControllerContact() {
        this.worldPosition = new Vec3();
        this.worldNormal = new Vec3();
        this.motionDirection = new Vec3();
        this.motionLength = 0;
      };

      legacyCC.PhysicsSystem = PhysicsSystem;
      legacyCC.PhysicsMaterial = PhysicsMaterial;
      legacyCC.PhysicsRayResult = PhysicsRayResult;
      legacyCC.ConstantForce = ConstantForce;

      var physics = /*#__PURE__*/Object.freeze({
        __proto__: null,
        PhysicsSystem: PhysicsSystem,
        PhysicsRayResult: PhysicsRayResult,
        PhysicsLineStripCastResult: PhysicsLineStripCastResult,
        get Collider () { return Collider; },
        BoxCollider: BoxCollider,
        SphereCollider: SphereCollider,
        CapsuleCollider: CapsuleCollider,
        MeshCollider: MeshCollider,
        CylinderCollider: CylinderCollider,
        ConeCollider: ConeCollider,
        TerrainCollider: TerrainCollider,
        get SimplexCollider () { return SimplexCollider; },
        PlaneCollider: PlaneCollider,
        get Constraint () { return Constraint$1; },
        HingeConstraint: HingeConstraint,
        FixedConstraint: FixedConstraint,
        PointToPointConstraint: PointToPointConstraint,
        ConfigurableConstraint: ConfigurableConstraint,
        get RigidBody () { return RigidBody; },
        PhysicsMaterial: PhysicsMaterial,
        ConstantForce: ConstantForce,
        CharacterController: CharacterController,
        BoxCharacterController: BoxCharacterController,
        CapsuleCharacterController: CapsuleCharacterController,
        selector: selector,
        utils: util,
        CharacterControllerContact: CharacterControllerContact,
        get ERigidBodyType () { return ERigidBodyType; },
        get EAxisDirection () { return EAxisDirection; },
        get ED6Axis () { return ED6Axis; },
        get ESimplexType () { return ESimplexType; },
        get EColliderType () { return EColliderType; },
        get EConstraintType () { return EConstraintType; },
        get EConstraintMode () { return EConstraintMode; },
        get EDriverMode () { return EDriverMode; },
        get ECharacterControllerType () { return ECharacterControllerType; },
        get PhysicsGroup () { return PhysicsGroup; },
        get EPhysicsDrawFlags () { return EPhysicsDrawFlags; }
      });
      exports('fG', physics);

      replaceProperty(PhysicsSystem, 'PhysicsSystem', [{
        name: 'ins',
        newName: 'instance'
      }, {
        name: 'PHYSICS_AMMO',
        newName: 'PHYSICS_BULLET'
      }]);
      replaceProperty(PhysicsSystem.prototype, 'PhysicsSystem.prototype', [{
        name: 'deltaTime',
        newName: 'fixedTimeStep'
      }, {
        name: 'maxSubStep',
        newName: 'maxSubSteps'
      }]);
      removeProperty(PhysicsSystem.prototype, 'PhysicsSystem.prototype', [{
        name: 'useFixedTime'
      }, {
        name: 'useCollisionMatrix'
      }, {
        name: 'updateCollisionMatrix'
      }, {
        name: 'resetCollisionMatrix'
      }, {
        name: 'isCollisionGroup'
      }, {
        name: 'setCollisionGroup'
      }]);
      replaceProperty(Collider.prototype, 'Collider.prototype', [{
        name: 'attachedRigidbody',
        newName: 'attachedRigidBody'
      }, {
        name: 'TYPE',
        newName: 'type'
      }]);
      replaceProperty(Collider, 'Collider', [{
        name: 'EColliderType',
        newName: 'Type'
      }, {
        name: 'EAxisDirection',
        newName: 'Axis'
      }]);
      replaceProperty(Constraint$1, 'Constraint', [{
        name: 'EConstraintType',
        newName: 'Type'
      }]);
      replaceProperty(BoxCollider.prototype, 'BoxCollider.prototype', [{
        name: 'boxShape',
        newName: 'shape'
      }]);
      replaceProperty(SphereCollider.prototype, 'SphereCollider.prototype', [{
        name: 'sphereShape',
        newName: 'shape'
      }]);
      replaceProperty(CapsuleCollider.prototype, 'CapsuleCollider.prototype', [{
        name: 'capsuleShape',
        newName: 'shape'
      }]);
      replaceProperty(RigidBody.prototype, 'RigidBody.prototype', [{
        name: 'rigidBody',
        newName: 'body'
      }]);
      replaceProperty(RigidBody, 'RigidBody', [{
        name: 'ERigidBodyType',
        newName: 'Type'
      }]);
      removeProperty(RigidBody.prototype, 'RigidBody.prototype', [{
        name: 'fixedRotation'
      }]);
      legacyCC.RigidBodyComponent = RigidBody;
      setClassAlias(RigidBody, 'cc.RigidBodyComponent');
      legacyCC.ColliderComponent = Collider;
      setClassAlias(Collider, 'cc.ColliderComponent');
      legacyCC.BoxColliderComponent = BoxCollider;
      setClassAlias(BoxCollider, 'cc.BoxColliderComponent');
      legacyCC.SphereColliderComponent = SphereCollider;
      setClassAlias(SphereCollider, 'cc.SphereColliderComponent');
      setClassAlias(CapsuleCollider, 'cc.CapsuleColliderComponent');
      setClassAlias(MeshCollider, 'cc.MeshColliderComponent');
      setClassAlias(CylinderCollider, 'cc.CylinderColliderComponent');
      legacyCC.PhysicMaterial = PhysicsMaterial;
      setClassAlias(PhysicsMaterial, 'cc.PhysicMaterial');

      legacyCC.physics = physics;

      var EBtSharedBodyDirty;
      (function (EBtSharedBodyDirty) {
        EBtSharedBodyDirty[EBtSharedBodyDirty["BODY_RE_ADD"] = 1] = "BODY_RE_ADD";
        EBtSharedBodyDirty[EBtSharedBodyDirty["GHOST_RE_ADD"] = 2] = "GHOST_RE_ADD";
      })(EBtSharedBodyDirty || (EBtSharedBodyDirty = {}));
      var btCollisionFlags;
      (function (btCollisionFlags) {
        btCollisionFlags[btCollisionFlags["CF_STATIC_OBJECT"] = 1] = "CF_STATIC_OBJECT";
        btCollisionFlags[btCollisionFlags["CF_KINEMATIC_OBJECT"] = 2] = "CF_KINEMATIC_OBJECT";
        btCollisionFlags[btCollisionFlags["CF_NO_CONTACT_RESPONSE"] = 4] = "CF_NO_CONTACT_RESPONSE";
        btCollisionFlags[btCollisionFlags["CF_CUSTOM_MATERIAL_CALLBACK"] = 8] = "CF_CUSTOM_MATERIAL_CALLBACK";
        btCollisionFlags[btCollisionFlags["CF_CHARACTER_OBJECT"] = 16] = "CF_CHARACTER_OBJECT";
        btCollisionFlags[btCollisionFlags["CF_DISABLE_VISUALIZE_OBJECT"] = 32] = "CF_DISABLE_VISUALIZE_OBJECT";
        btCollisionFlags[btCollisionFlags["CF_DISABLE_SPU_COLLISION_PROCESSING"] = 64] = "CF_DISABLE_SPU_COLLISION_PROCESSING";
      })(btCollisionFlags || (btCollisionFlags = {}));
      var btCollisionObjectTypes;
      (function (btCollisionObjectTypes) {
        btCollisionObjectTypes[btCollisionObjectTypes["CO_COLLISION_OBJECT"] = 1] = "CO_COLLISION_OBJECT";
        btCollisionObjectTypes[btCollisionObjectTypes["CO_RIGID_BODY"] = 2] = "CO_RIGID_BODY";
        btCollisionObjectTypes[btCollisionObjectTypes["CO_GHOST_OBJECT"] = 4] = "CO_GHOST_OBJECT";
        btCollisionObjectTypes[btCollisionObjectTypes["CO_SOFT_BODY"] = 8] = "CO_SOFT_BODY";
        btCollisionObjectTypes[btCollisionObjectTypes["CO_HF_FLUID"] = 16] = "CO_HF_FLUID";
        btCollisionObjectTypes[btCollisionObjectTypes["CO_USER_TYPE"] = 32] = "CO_USER_TYPE";
        btCollisionObjectTypes[btCollisionObjectTypes["CO_FEATHERSTONE_LINK"] = 64] = "CO_FEATHERSTONE_LINK";
      })(btCollisionObjectTypes || (btCollisionObjectTypes = {}));
      var btCollisionObjectStates;
      (function (btCollisionObjectStates) {
        btCollisionObjectStates[btCollisionObjectStates["ACTIVE_TAG"] = 1] = "ACTIVE_TAG";
        btCollisionObjectStates[btCollisionObjectStates["ISLAND_SLEEPING"] = 2] = "ISLAND_SLEEPING";
        btCollisionObjectStates[btCollisionObjectStates["WANTS_DEACTIVATION"] = 3] = "WANTS_DEACTIVATION";
        btCollisionObjectStates[btCollisionObjectStates["DISABLE_DEACTIVATION"] = 4] = "DISABLE_DEACTIVATION";
        btCollisionObjectStates[btCollisionObjectStates["DISABLE_SIMULATION"] = 5] = "DISABLE_SIMULATION";
      })(btCollisionObjectStates || (btCollisionObjectStates = {}));
      var btRigidBodyFlags;
      (function (btRigidBodyFlags) {
        btRigidBodyFlags[btRigidBodyFlags["BT_DISABLE_WORLD_GRAVITY"] = 1] = "BT_DISABLE_WORLD_GRAVITY";
        btRigidBodyFlags[btRigidBodyFlags["BT_ENABLE_GYROPSCOPIC_FORCE"] = 2] = "BT_ENABLE_GYROPSCOPIC_FORCE";
      })(btRigidBodyFlags || (btRigidBodyFlags = {}));

      var v3_0$6 = CC_V3_0;
      var v3_1$2 = CC_V3_1;
      var BulletRigidBody = function () {
        var _proto = BulletRigidBody.prototype;
        _proto.setMass = function setMass(value) {
          if (!this._rigidBody.isDynamic) return;
          bt.RigidBody_setMass(this.impl, value);
          this._wakeUpIfSleep();
          this._sharedBody.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
        };
        _proto.setType = function setType(v) {
          this._sharedBody.setType(v);
        };
        _proto.setLinearDamping = function setLinearDamping(value) {
          bt.RigidBody_setDamping(this.impl, this._rigidBody.linearDamping, this._rigidBody.angularDamping);
        };
        _proto.setAngularDamping = function setAngularDamping(value) {
          bt.RigidBody_setDamping(this.impl, this._rigidBody.linearDamping, this._rigidBody.angularDamping);
        };
        _proto.useGravity = function useGravity(value) {
          if (!this._rigidBody.isDynamic) return;
          var m_rigidBodyFlag = bt.RigidBody_getFlags(this.impl);
          if (value) {
            m_rigidBodyFlag &= ~btRigidBodyFlags.BT_DISABLE_WORLD_GRAVITY;
          } else {
            bt.RigidBody_setGravity(this.impl, cocos2BulletVec3(BulletCache.instance.BT_V3_0, Vec3.ZERO));
            m_rigidBodyFlag |= btRigidBodyFlags.BT_DISABLE_WORLD_GRAVITY;
          }
          bt.RigidBody_setFlags(this.impl, m_rigidBodyFlag);
          this._wakeUpIfSleep();
          this._sharedBody.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
        };
        _proto.useCCD = function useCCD(value) {
          bt.CollisionObject_setCcdMotionThreshold(this.impl, value ? 0.01 : 0);
          bt.CollisionObject_setCcdSweptSphereRadius(this.impl, value ? 0.1 : 0);
          this._isUsingCCD = value;
        };
        _proto.isUsingCCD = function isUsingCCD() {
          return this._isUsingCCD;
        };
        _proto.setLinearFactor = function setLinearFactor(v) {
          bt.RigidBody_setLinearFactor(this.impl, cocos2BulletVec3(BulletCache.instance.BT_V3_0, v));
          this._wakeUpIfSleep();
        };
        _proto.setAngularFactor = function setAngularFactor(v) {
          bt.RigidBody_setAngularFactor(this.impl, cocos2BulletVec3(BulletCache.instance.BT_V3_0, v));
          this._wakeUpIfSleep();
        };
        _proto.setAllowSleep = function setAllowSleep(v) {
          if (!this._rigidBody.isDynamic) return;
          if (v) {
            bt.CollisionObject_forceActivationState(this.impl, btCollisionObjectStates.ACTIVE_TAG);
          } else {
            bt.CollisionObject_forceActivationState(this.impl, btCollisionObjectStates.DISABLE_DEACTIVATION);
          }
          this._wakeUpIfSleep();
        };
        function BulletRigidBody() {
          this.id = void 0;
          this._isEnabled = false;
          this._isUsingCCD = false;
          this._sharedBody = void 0;
          this._rigidBody = void 0;
          this.id = BulletRigidBody.idCounter++;
        }
        _proto.clearState = function clearState() {
          bt.RigidBody_clearState(this.impl);
        };
        _proto.clearVelocity = function clearVelocity() {
          this.setLinearVelocity(Vec3.ZERO);
          this.setAngularVelocity(Vec3.ZERO);
        };
        _proto.clearForces = function clearForces() {
          bt.RigidBody_clearForces(this.impl);
        };
        _proto.initialize = function initialize(com) {
          this._rigidBody = com;
          this._sharedBody = PhysicsSystem.instance.physicsWorld.getSharedBody(this._rigidBody.node, this);
          this._sharedBody.reference = true;
        };
        _proto.onEnable = function onEnable() {
          this._isEnabled = true;
          this.setMass(this._rigidBody.mass);
          this.setAllowSleep(this._rigidBody.allowSleep);
          this.setLinearDamping(this._rigidBody.linearDamping);
          this.setAngularDamping(this._rigidBody.angularDamping);
          this.setLinearFactor(this._rigidBody.linearFactor);
          this.setAngularFactor(this._rigidBody.angularFactor);
          this.useGravity(this._rigidBody.useGravity);
          this._sharedBody.bodyEnabled = true;
        };
        _proto.onDisable = function onDisable() {
          this._isEnabled = false;
          this._sharedBody.bodyEnabled = false;
        };
        _proto.onDestroy = function onDestroy() {
          this._sharedBody.reference = false;
          this._rigidBody = null;
          this._sharedBody = null;
        };
        _proto.wakeUp = function wakeUp(force) {
          if (force === void 0) {
            force = true;
          }
          bt.CollisionObject_activate(this.impl, force);
        };
        _proto.sleep = function sleep() {
          var state = bt.CollisionObject_getActivationState(this.impl);
          if (state !== btCollisionObjectStates.DISABLE_DEACTIVATION && state !== btCollisionObjectStates.DISABLE_SIMULATION) {
            bt.CollisionObject_forceActivationState(this.impl, btCollisionObjectStates.ISLAND_SLEEPING);
          }
        };
        _proto.setSleepThreshold = function setSleepThreshold(v) {
          this._wakeUpIfSleep();
          bt.RigidBody_setSleepingThresholds(this.impl, v, v);
        };
        _proto.getSleepThreshold = function getSleepThreshold() {
          return bt.RigidBody_getLinearSleepingThreshold(this.impl);
        };
        _proto.getLinearVelocity = function getLinearVelocity(out) {
          return bullet2CocosVec3(out, bt.RigidBody_getLinearVelocity(this.impl));
        };
        _proto.setLinearVelocity = function setLinearVelocity(value) {
          this._wakeUpIfSleep();
          cocos2BulletVec3(bt.RigidBody_getLinearVelocity(this.impl), value);
        };
        _proto.getAngularVelocity = function getAngularVelocity(out) {
          return bullet2CocosVec3(out, bt.RigidBody_getAngularVelocity(this.impl));
        };
        _proto.setAngularVelocity = function setAngularVelocity(value) {
          this._wakeUpIfSleep();
          cocos2BulletVec3(bt.RigidBody_getAngularVelocity(this.impl), value);
        };
        _proto.applyLocalForce = function applyLocalForce(force, rel_pos) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          var quat = this._sharedBody.node.worldRotation;
          var v = Vec3.transformQuat(v3_0$6, force, quat);
          var rp = rel_pos ? Vec3.transformQuat(v3_1$2, rel_pos, quat) : Vec3.ZERO;
          bt.RigidBody_applyForce(this.impl, cocos2BulletVec3(BulletCache.instance.BT_V3_0, v), cocos2BulletVec3(BulletCache.instance.BT_V3_1, rp));
        };
        _proto.applyLocalTorque = function applyLocalTorque(torque) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          Vec3.transformQuat(v3_0$6, torque, this._sharedBody.node.worldRotation);
          bt.RigidBody_applyTorque(this.impl, cocos2BulletVec3(BulletCache.instance.BT_V3_0, v3_0$6));
        };
        _proto.applyLocalImpulse = function applyLocalImpulse(impulse, rel_pos) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          var quat = this._sharedBody.node.worldRotation;
          var v = Vec3.transformQuat(v3_0$6, impulse, quat);
          var rp = rel_pos ? Vec3.transformQuat(v3_1$2, rel_pos, quat) : Vec3.ZERO;
          bt.RigidBody_applyImpulse(this.impl, cocos2BulletVec3(BulletCache.instance.BT_V3_0, v), cocos2BulletVec3(BulletCache.instance.BT_V3_1, rp));
        };
        _proto.applyForce = function applyForce(force, rel_pos) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          var rp = rel_pos || Vec3.ZERO;
          bt.RigidBody_applyForce(this.impl, cocos2BulletVec3(BulletCache.instance.BT_V3_0, force), cocos2BulletVec3(BulletCache.instance.BT_V3_1, rp));
        };
        _proto.applyTorque = function applyTorque(torque) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          bt.RigidBody_applyTorque(this.impl, cocos2BulletVec3(BulletCache.instance.BT_V3_0, torque));
        };
        _proto.applyImpulse = function applyImpulse(impulse, rel_pos) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          var rp = rel_pos || Vec3.ZERO;
          bt.RigidBody_applyImpulse(this.impl, cocos2BulletVec3(BulletCache.instance.BT_V3_0, impulse), cocos2BulletVec3(BulletCache.instance.BT_V3_1, rp));
        };
        _proto.getGroup = function getGroup() {
          return this._sharedBody.collisionFilterGroup;
        };
        _proto.setGroup = function setGroup(v) {
          this._sharedBody.collisionFilterGroup = v;
        };
        _proto.addGroup = function addGroup(v) {
          this._sharedBody.collisionFilterGroup |= v;
        };
        _proto.removeGroup = function removeGroup(v) {
          this._sharedBody.collisionFilterGroup &= ~v;
        };
        _proto.getMask = function getMask() {
          return this._sharedBody.collisionFilterMask;
        };
        _proto.setMask = function setMask(v) {
          this._sharedBody.collisionFilterMask = v;
        };
        _proto.addMask = function addMask(v) {
          this._sharedBody.collisionFilterMask |= v;
        };
        _proto.removeMask = function removeMask(v) {
          this._sharedBody.collisionFilterMask &= ~v;
        };
        _proto._wakeUpIfSleep = function _wakeUpIfSleep() {
          if (!this.isAwake) {
            bt.CollisionObject_activate(this.impl, true);
          }
        };
        _createClass(BulletRigidBody, [{
          key: "isAwake",
          get: function get() {
            var state = bt.CollisionObject_getActivationState(this.impl);
            return state === btCollisionObjectStates.ACTIVE_TAG || state === btCollisionObjectStates.DISABLE_DEACTIVATION;
          }
        }, {
          key: "isSleepy",
          get: function get() {
            var state = bt.CollisionObject_getActivationState(this.impl);
            return state === btCollisionObjectStates.WANTS_DEACTIVATION;
          }
        }, {
          key: "isSleeping",
          get: function get() {
            var state = bt.CollisionObject_getActivationState(this.impl);
            return state === btCollisionObjectStates.ISLAND_SLEEPING;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._sharedBody.body;
          }
        }, {
          key: "rigidBody",
          get: function get() {
            return this._rigidBody;
          }
        }, {
          key: "sharedBody",
          get: function get() {
            return this._sharedBody;
          }
        }, {
          key: "isEnabled",
          get: function get() {
            return this._isEnabled;
          }
        }]);
        return BulletRigidBody;
      }();
      BulletRigidBody.idCounter = 0;

      var importFunc = {
        syncPhysicsToGraphics: function syncPhysicsToGraphics(id) {
          var body = btCache.CACHE.getWrapper(id, btCache.BODY_CACHE_NAME);
          body.syncPhysicsToGraphics();
        },
        onShapeHitExt: function onShapeHitExt(hit, controller) {
          var cct = btCache.CACHE.getWrapper(controller, btCache.CCT_CACHE_NAME);
          cct.onShapeHitExt(hit);
        },
        onDebugDrawLine: function onDebugDrawLine(from, to, color) {
          var world = btCache.CACHE.world;
          if (world) {
            world.onDebugDrawLine(from, to, color);
          }
        },
        clearLines: function clearLines() {
          var world = btCache.CACHE.world;
          if (world) {
            world.onClearLines();
          }
        },
        flushLines: function flushLines() {}
      };

      var v3_0$5 = CC_V3_0;
      var quat_0 = CC_QUAT_0;
      var IDCounter = 0;
      var BulletSharedBody = function () {
        BulletSharedBody.getSharedBody = function getSharedBody(node, wrappedWorld, wrappedBody) {
          var key = node.uuid;
          var newSB;
          if (BulletSharedBody.sharedBodesMap.has(key)) {
            newSB = BulletSharedBody.sharedBodesMap.get(key);
          } else {
            newSB = new BulletSharedBody(node, wrappedWorld);
            var g = PhysicsGroup.DEFAULT;
            var m = PhysicsSystem.instance.collisionMatrix[g];
            newSB._collisionFilterGroup = g;
            newSB._collisionFilterMask = m;
            BulletSharedBody.sharedBodesMap.set(node.uuid, newSB);
          }
          if (wrappedBody) {
            newSB._wrappedBody = wrappedBody;
            var _g = wrappedBody.rigidBody.group;
            var _m = PhysicsSystem.instance.collisionMatrix[_g];
            newSB._collisionFilterGroup = _g;
            newSB._collisionFilterMask = _m;
          }
          return newSB;
        };
        function BulletSharedBody(node, wrappedWorld) {
          this.id = void 0;
          this.node = void 0;
          this.wrappedWorld = void 0;
          this.wrappedJoints0 = [];
          this.wrappedJoints1 = [];
          this.dirty = 0;
          this._collisionFilterGroup = PhysicsSystem.PhysicsGroup.DEFAULT;
          this._collisionFilterMask = -1;
          this.ref = 0;
          this.bodyIndex = -1;
          this.ghostIndex = -1;
          this._bodyStruct = void 0;
          this._ghostStruct = void 0;
          this._wrappedBody = null;
          this.id = BulletSharedBody.idCounter++;
          this.wrappedWorld = wrappedWorld;
          this.node = node;
        }
        var _proto = BulletSharedBody.prototype;
        _proto._instantiateBodyStruct = function _instantiateBodyStruct() {
          if (this._bodyStruct) return;
          var mass = 0;
          if (this._wrappedBody && this._wrappedBody.rigidBody.enabled && this._wrappedBody.rigidBody.isDynamic) {
            mass = this._wrappedBody.rigidBody.mass;
          }
          var trans = BulletCache.instance.BT_TRANSFORM_0;
          var quat = BulletCache.instance.BT_QUAT_0;
          cocos2BulletVec3(bt.Transform_getOrigin(trans), this.node.worldPosition);
          cocos2BulletQuat(quat, this.node.worldRotation);
          bt.Transform_setRotation(trans, quat);
          var motionState = bt.MotionState.implement(importFunc).$$.ptr;
          bt.ccMotionState_setup(motionState, this.id, trans);
          var body = bt.RigidBody_new(mass, motionState);
          var sleepTd = PhysicsSystem.instance.sleepThreshold;
          bt.RigidBody_setSleepingThresholds(body, sleepTd, sleepTd);
          this._bodyStruct = {
            id: IDCounter++,
            body: body,
            motionState: motionState,
            compound: bt.ccCompoundShape_new(),
            wrappedShapes: [],
            useCompound: false
          };
          BulletCache.setWrapper(this.id, btCache.BODY_CACHE_NAME, this);
          if (this._ghostStruct) bt.CollisionObject_setIgnoreCollisionCheck(this.ghost, this.body, true);
          if (this._wrappedBody) this.setBodyType(this._wrappedBody.rigidBody.type);
        };
        _proto._instantiateGhostStruct = function _instantiateGhostStruct() {
          if (this._ghostStruct) return;
          var ghost = bt.CollisionObject_new();
          var ghostShape = bt.ccCompoundShape_new();
          bt.CollisionObject_setCollisionShape(ghost, ghostShape);
          bt.CollisionObject_setCollisionFlags(ghost, btCollisionFlags.CF_STATIC_OBJECT | btCollisionFlags.CF_NO_CONTACT_RESPONSE);
          this._ghostStruct = {
            id: IDCounter++,
            ghost: ghost,
            compound: ghostShape,
            wrappedShapes: []
          };
          if (this._bodyStruct) bt.CollisionObject_setIgnoreCollisionCheck(this.body, this.ghost, true);
          if (this._wrappedBody) this.setGhostType(this._wrappedBody.rigidBody.type);
        };
        _proto.setType = function setType(v) {
          this.setBodyType(v);
          this.setGhostType(v);
        };
        _proto.setBodyType = function setBodyType(v) {
          if (this._bodyStruct && this._wrappedBody) {
            var body = this._bodyStruct.body;
            var wrap = this._wrappedBody;
            var com = wrap.rigidBody;
            var m_bcf = bt.CollisionObject_getCollisionFlags(body);
            var localInertia = BulletCache.instance.BT_V3_0;
            switch (v) {
              case ERigidBodyType.DYNAMIC:
                m_bcf &= ~btCollisionFlags.CF_KINEMATIC_OBJECT;
                m_bcf &= ~btCollisionFlags.CF_STATIC_OBJECT;
                bt.CollisionObject_setCollisionFlags(body, m_bcf);
                wrap.setMass(com.mass);
                wrap.useGravity(com.useGravity);
                wrap.setAllowSleep(com.allowSleep);
                break;
              case ERigidBodyType.KINEMATIC:
                bt.Vec3_set(localInertia, 0, 0, 0);
                bt.RigidBody_setMassProps(body, 0, localInertia);
                m_bcf |= btCollisionFlags.CF_KINEMATIC_OBJECT;
                m_bcf &= ~btCollisionFlags.CF_STATIC_OBJECT;
                bt.CollisionObject_setCollisionFlags(body, m_bcf);
                bt.CollisionObject_forceActivationState(body, btCollisionObjectStates.DISABLE_DEACTIVATION);
                break;
              case ERigidBodyType.STATIC:
              default:
                bt.Vec3_set(localInertia, 0, 0, 0);
                bt.RigidBody_setMassProps(body, 0, localInertia);
                m_bcf |= btCollisionFlags.CF_STATIC_OBJECT;
                m_bcf &= ~btCollisionFlags.CF_KINEMATIC_OBJECT;
                bt.CollisionObject_setCollisionFlags(body, m_bcf);
                bt.CollisionObject_forceActivationState(body, btCollisionObjectStates.ISLAND_SLEEPING);
                break;
            }
            this.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
          }
        };
        _proto.setGhostType = function setGhostType(v) {
          if (this._ghostStruct) {
            var ghost = this._ghostStruct.ghost;
            var m_gcf = bt.CollisionObject_getCollisionFlags(ghost);
            switch (v) {
              case ERigidBodyType.DYNAMIC:
              case ERigidBodyType.KINEMATIC:
                m_gcf &= ~btCollisionFlags.CF_STATIC_OBJECT;
                m_gcf |= btCollisionFlags.CF_KINEMATIC_OBJECT;
                bt.CollisionObject_setCollisionFlags(ghost, m_gcf);
                bt.CollisionObject_forceActivationState(ghost, btCollisionObjectStates.DISABLE_DEACTIVATION);
                break;
              case ERigidBodyType.STATIC:
              default:
                m_gcf &= ~btCollisionFlags.CF_KINEMATIC_OBJECT;
                m_gcf |= btCollisionFlags.CF_STATIC_OBJECT;
                bt.CollisionObject_setCollisionFlags(ghost, m_gcf);
                bt.CollisionObject_forceActivationState(ghost, btCollisionObjectStates.ISLAND_SLEEPING);
                break;
            }
            this.dirty |= EBtSharedBodyDirty.GHOST_RE_ADD;
          }
        };
        _proto.addShape = function addShape(v, isTrigger) {
          function switchShape(that, shape) {
            bt.CollisionObject_setCollisionShape(that.body, shape);
            that.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
            if (that._wrappedBody && that._wrappedBody.isEnabled) {
              that._wrappedBody.setMass(that._wrappedBody.rigidBody.mass);
            }
          }
          if (isTrigger) {
            var index = this.ghostStruct.wrappedShapes.indexOf(v);
            if (index < 0) {
              this.ghostStruct.wrappedShapes.push(v);
              v.setCompound(this.ghostCompoundShape);
              this.ghostEnabled = true;
            }
          } else {
            var _index = this.bodyStruct.wrappedShapes.indexOf(v);
            if (_index < 0) {
              this.bodyStruct.wrappedShapes.push(v);
              if (this.bodyStruct.useCompound) {
                v.setCompound(this.bodyCompoundShape);
              } else {
                var l = this.bodyStruct.wrappedShapes.length;
                if (l === 1 && !v.needCompound()) {
                  switchShape(this, v.impl);
                } else {
                  this.bodyStruct.useCompound = true;
                  for (var i = 0; i < l; i++) {
                    var childShape = this.bodyStruct.wrappedShapes[i];
                    childShape.setCompound(this.bodyCompoundShape);
                  }
                  switchShape(this, this.bodyStruct.compound);
                }
              }
              this.bodyEnabled = true;
            }
          }
        };
        _proto.removeShape = function removeShape(v, isTrigger) {
          if (isTrigger) {
            var index = this.ghostStruct.wrappedShapes.indexOf(v);
            if (index >= 0) {
              fastRemoveAt$2(this.ghostStruct.wrappedShapes, index);
              v.setCompound(0);
              this.ghostEnabled = false;
            }
          } else {
            var _index2 = this.bodyStruct.wrappedShapes.indexOf(v);
            if (_index2 >= 0) {
              if (this.bodyStruct.useCompound) {
                v.setCompound(0);
              } else {
                bt.CollisionObject_setCollisionShape(this.body, bt.EmptyShape_static());
              }
              bt.CollisionObject_activate(this.body, true);
              this.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
              fastRemoveAt$2(this.bodyStruct.wrappedShapes, _index2);
              this.bodyEnabled = false;
            }
          }
        };
        _proto.addJoint = function addJoint(v, type) {
          if (type) {
            var i = this.wrappedJoints1.indexOf(v);
            if (i < 0) this.wrappedJoints1.push(v);
          } else {
            var _i = this.wrappedJoints0.indexOf(v);
            if (_i < 0) this.wrappedJoints0.push(v);
          }
        };
        _proto.removeJoint = function removeJoint(v, type) {
          if (type) {
            var i = this.wrappedJoints1.indexOf(v);
            if (i >= 0) fastRemoveAt$2(this.wrappedJoints1, i);
          } else {
            var _i2 = this.wrappedJoints0.indexOf(v);
            if (_i2 >= 0) fastRemoveAt$2(this.wrappedJoints0, _i2);
          }
        };
        _proto.updateDirty = function updateDirty() {
          if (this.dirty) {
            if (this.bodyIndex >= 0 && this.dirty & EBtSharedBodyDirty.BODY_RE_ADD) this.updateBodyByReAdd();
            if (this.ghostIndex >= 0 && this.dirty & EBtSharedBodyDirty.GHOST_RE_ADD) this.updateGhostByReAdd();
            this.dirty = 0;
          }
        };
        _proto.syncSceneToPhysics = function syncSceneToPhysics() {
          if (this.node.hasChangedFlags) {
            var bt_quat = BulletCache.instance.BT_QUAT_0;
            var bt_transform = bt.CollisionObject_getWorldTransform(this.body);
            cocos2BulletQuat(bt_quat, this.node.worldRotation);
            cocos2BulletVec3(bt.Transform_getOrigin(bt_transform), this.node.worldPosition);
            bt.Transform_setRotation(bt_transform, bt_quat);
            if (this.node.hasChangedFlags & TransformBit.SCALE) {
              this.syncBodyScale();
            }
            if (bt.CollisionObject_isKinematicObject(this.body)) {
              var ms = bt.RigidBody_getMotionState(this.body);
              if (ms) bt.MotionState_setWorldTransform(ms, bt_transform);
            } else if (this.isBodySleeping()) bt.CollisionObject_activate(this.body, false);
          }
        };
        _proto.syncPhysicsToScene = function syncPhysicsToScene() {
          if (bt.CollisionObject_isStaticOrKinematicObject(this.body)) return;
          this.syncPhysicsToGraphics();
        };
        _proto.syncPhysicsToGraphics = function syncPhysicsToGraphics() {
          if (this.isBodySleeping()) return;
          var bt_quat = BulletCache.instance.BT_QUAT_0;
          var bt_transform = BulletCache.instance.BT_TRANSFORM_0;
          bt.RigidBody_getWorldTransform(this.body, bt_transform);
          var originPosPtr = bt.Transform_getRotationAndOrigin(bt_transform, bt_quat);
          this.node.worldRotation = bullet2CocosQuat(quat_0, bt_quat);
          this.node.worldPosition = bullet2CocosVec3(v3_0$5, originPosPtr);
          if (this._ghostStruct) {
            var bt_transform1 = bt.CollisionObject_getWorldTransform(this.ghost);
            cocos2BulletVec3(bt.Transform_getOrigin(bt_transform1), this.node.worldPosition);
            cocos2BulletQuat(bt_quat, this.node.worldRotation);
            bt.Transform_setRotation(bt_transform1, bt_quat);
          }
        };
        _proto.syncSceneToGhost = function syncSceneToGhost() {
          if (this.node.hasChangedFlags) {
            var bt_quat = BulletCache.instance.BT_QUAT_0;
            var bt_transform = bt.CollisionObject_getWorldTransform(this.ghost);
            cocos2BulletVec3(bt.Transform_getOrigin(bt_transform), this.node.worldPosition);
            cocos2BulletQuat(bt_quat, this.node.worldRotation);
            bt.Transform_setRotation(bt_transform, bt_quat);
            if (this.node.hasChangedFlags & TransformBit.SCALE) this.syncGhostScale();
            bt.CollisionObject_activate(this.ghost, false);
          }
        };
        _proto.syncInitialBody = function syncInitialBody() {
          var bt_quat = BulletCache.instance.BT_QUAT_0;
          var bt_transform = bt.CollisionObject_getWorldTransform(this.body);
          cocos2BulletVec3(bt.Transform_getOrigin(bt_transform), this.node.worldPosition);
          cocos2BulletQuat(bt_quat, this.node.worldRotation);
          bt.Transform_setRotation(bt_transform, bt_quat);
          this.syncBodyScale();
          bt.CollisionObject_activate(this.body, false);
        };
        _proto.syncInitialGhost = function syncInitialGhost() {
          var bt_quat = BulletCache.instance.BT_QUAT_0;
          var bt_transform = bt.CollisionObject_getWorldTransform(this.ghost);
          cocos2BulletVec3(bt.Transform_getOrigin(bt_transform), this.node.worldPosition);
          cocos2BulletQuat(bt_quat, this.node.worldRotation);
          bt.Transform_setRotation(bt_transform, bt_quat);
          this.syncGhostScale();
          bt.CollisionObject_activate(this.body, false);
        };
        _proto.syncBodyScale = function syncBodyScale() {
          for (var i = 0; i < this.bodyStruct.wrappedShapes.length; i++) {
            this.bodyStruct.wrappedShapes[i].updateScale();
          }
          for (var _i3 = 0; _i3 < this.wrappedJoints0.length; _i3++) {
            this.wrappedJoints0[_i3].updateScale0();
          }
          for (var _i4 = 0; _i4 < this.wrappedJoints1.length; _i4++) {
            this.wrappedJoints1[_i4].updateScale1();
          }
        };
        _proto.syncGhostScale = function syncGhostScale() {
          for (var i = 0; i < this.ghostStruct.wrappedShapes.length; i++) {
            this.ghostStruct.wrappedShapes[i].updateScale();
          }
        };
        _proto.updateBodyByReAdd = function updateBodyByReAdd() {
          if (this.bodyIndex >= 0) {
            this.wrappedWorld.removeSharedBody(this);
            this.bodyIndex = this.wrappedWorld.bodies.length;
            this.wrappedWorld.addSharedBody(this);
          }
        };
        _proto.updateGhostByReAdd = function updateGhostByReAdd() {
          if (this.ghostIndex >= 0) {
            this.wrappedWorld.removeGhostObject(this);
            this.ghostIndex = this.wrappedWorld.ghosts.length;
            this.wrappedWorld.addGhostObject(this);
          }
        };
        _proto.destroy = function destroy() {
          BulletSharedBody.sharedBodesMap["delete"](this.node.uuid);
          this.node = null;
          this.wrappedWorld = null;
          if (this._bodyStruct) {
            var bodyStruct = this._bodyStruct;
            BulletCache.delWrapper(bodyStruct.body, btCache.BODY_CACHE_NAME);
            bt._safe_delete(bodyStruct.motionState, EBulletType.EBulletTypeMotionState);
            bt._safe_delete(bodyStruct.compound, EBulletType.EBulletTypeCollisionShape);
            bt._safe_delete(bodyStruct.body, EBulletType.EBulletTypeCollisionObject);
            this._bodyStruct = null;
          }
          if (this._ghostStruct) {
            var ghostStruct = this._ghostStruct;
            bt._safe_delete(ghostStruct.compound, EBulletType.EBulletTypeCollisionShape);
            bt._safe_delete(ghostStruct.ghost, EBulletType.EBulletTypeCollisionObject);
            this._ghostStruct = null;
          }
        };
        _proto.isBodySleeping = function isBodySleeping() {
          return bt.CollisionObject_isSleeping(this.body);
        };
        _createClass(BulletSharedBody, [{
          key: "wrappedBody",
          get: function get() {
            return this._wrappedBody;
          }
        }, {
          key: "bodyCompoundShape",
          get: function get() {
            return this.bodyStruct.compound;
          }
        }, {
          key: "ghostCompoundShape",
          get: function get() {
            return this.ghostStruct.compound;
          }
        }, {
          key: "body",
          get: function get() {
            return this.bodyStruct.body;
          }
        }, {
          key: "ghost",
          get: function get() {
            return this.ghostStruct.ghost;
          }
        }, {
          key: "collisionFilterGroup",
          get: function get() {
            return this._collisionFilterGroup;
          },
          set: function set(v) {
            if (v !== this._collisionFilterGroup) {
              this._collisionFilterGroup = v;
              this.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
              this.dirty |= EBtSharedBodyDirty.GHOST_RE_ADD;
            }
          }
        }, {
          key: "collisionFilterMask",
          get: function get() {
            return this._collisionFilterMask;
          },
          set: function set(v) {
            if (v !== this._collisionFilterMask) {
              this._collisionFilterMask = v;
              this.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
              this.dirty |= EBtSharedBodyDirty.GHOST_RE_ADD;
            }
          }
        }, {
          key: "bodyStruct",
          get: function get() {
            this._instantiateBodyStruct();
            return this._bodyStruct;
          }
        }, {
          key: "ghostStruct",
          get: function get() {
            this._instantiateGhostStruct();
            return this._ghostStruct;
          }
        }, {
          key: "bodyEnabled",
          set: function set(v) {
            if (v) {
              if (this.bodyIndex < 0) {
                if (this.bodyStruct.wrappedShapes.length === 0) {
                  if (!this.wrappedBody) return;
                  if (!this.wrappedBody.rigidBody.isDynamic) return;
                }
                this.bodyIndex = this.wrappedWorld.bodies.length;
                this.wrappedWorld.addSharedBody(this);
                this.syncInitialBody();
              }
            } else if (this.bodyIndex >= 0) {
              var isRemoveBody = this.bodyStruct.wrappedShapes.length === 0 && this.wrappedBody == null || this.bodyStruct.wrappedShapes.length === 0 && this.wrappedBody != null && !this.wrappedBody.isEnabled || this.bodyStruct.wrappedShapes.length === 0 && this.wrappedBody != null && !this.wrappedBody.rigidBody.enabledInHierarchy;
              if (isRemoveBody) {
                bt.RigidBody_clearState(this.body);
                this.bodyIndex = -1;
                this.wrappedWorld.removeSharedBody(this);
              }
            }
          }
        }, {
          key: "ghostEnabled",
          set: function set(v) {
            if (v) {
              if (this.ghostIndex < 0 && this.ghostStruct.wrappedShapes.length > 0) {
                this.ghostIndex = 1;
                this.wrappedWorld.addGhostObject(this);
                this.syncInitialGhost();
              }
            } else if (this.ghostIndex >= 0) {
              var isRemoveGhost = this.ghostStruct.wrappedShapes.length === 0 && this.ghost;
              if (isRemoveGhost) {
                this.ghostIndex = -1;
                this.wrappedWorld.removeGhostObject(this);
              }
            }
          }
        }, {
          key: "reference",
          set: function set(v) {
            v ? this.ref++ : this.ref--;
            if (this.ref === 0) {
              this.destroy();
            }
          }
        }]);
        return BulletSharedBody;
      }();
      BulletSharedBody.idCounter = 0;
      BulletSharedBody.sharedBodesMap = new Map();

      var v3_0$4 = CC_V3_0;
      var ccMaterialBooks = {};
      var BulletShape = function () {
        function BulletShape() {
          this.id = BulletShape.idCounter++;
          this._isEnabled = false;
          this._isTrigger = false;
          this._isInitialized = false;
          this._impl = 0;
          this._compound = 0;
          this.quat = bt.Quat_new(0, 0, 0, 1);
          this.transform = bt.Transform_new();
          this._collider = void 0;
          this._sharedBody = void 0;
        }
        var _proto = BulletShape.prototype;
        _proto.updateEventListener = function updateEventListener() {
          this._sharedBody.wrappedWorld.updateNeedEmitEvents(this.collider.needCollisionEvent || this.collider.needTriggerEvent);
        };
        _proto.setMaterial = function setMaterial(v) {
          var v1 = v == null ? PhysicsSystem.instance.defaultMaterial : v;
          if (!this._isTrigger && this._isEnabled) {
            if (this._compound) {
              if (!ccMaterialBooks[v1._uuid]) ccMaterialBooks[v1._uuid] = bt.ccMaterial_new();
              var mat = ccMaterialBooks[v1._uuid];
              bt.ccMaterial_set(mat, v1.restitution, v1.friction, v1.rollingFriction, v1.spinningFriction);
              bt.CollisionShape_setMaterial(this._impl, mat);
            } else {
              bt.CollisionObject_setMaterial(this._sharedBody.body, v1.restitution, v1.friction, v1.rollingFriction, v1.spinningFriction);
            }
          }
        };
        _proto.setCenter = function setCenter(v) {
          Vec3.copy(v3_0$4, v);
          v3_0$4.multiply(this._collider.node.worldScale);
          cocos2BulletVec3(bt.Transform_getOrigin(this.transform), v3_0$4);
          this.updateCompoundTransform();
        };
        _proto.setAsTrigger = function setAsTrigger(v) {
          if (this._isTrigger === v) return;
          if (this._isEnabled) {
            this._sharedBody.removeShape(this, !v);
            this._sharedBody.addShape(this, v);
          }
          this._isTrigger = v;
        };
        _proto.getAABB = function getAABB(v) {
          var bt_transform = BulletCache.instance.BT_TRANSFORM_0;
          bt.Transform_setIdentity(bt_transform);
          bt.Transform_setRotation(bt_transform, cocos2BulletQuat(BulletCache.instance.BT_QUAT_0, this._collider.node.worldRotation));
          var MIN = BulletCache.instance.BT_V3_0;
          var MAX = BulletCache.instance.BT_V3_1;
          bt.CollisionShape_getAabb(this._impl, bt_transform, MIN, MAX);
          v.halfExtents.x = (bt.Vec3_x(MAX) - bt.Vec3_x(MIN)) / 2;
          v.halfExtents.y = (bt.Vec3_y(MAX) - bt.Vec3_y(MIN)) / 2;
          v.halfExtents.z = (bt.Vec3_z(MAX) - bt.Vec3_z(MIN)) / 2;
          Vec3.add(v.center, this._collider.node.worldPosition, this._collider.center);
        };
        _proto.getBoundingSphere = function getBoundingSphere(v) {
          v.radius = bt.CollisionShape_getLocalBoundingSphere(this._impl);
          Vec3.add(v.center, this._collider.node.worldPosition, this._collider.center);
        };
        _proto.initialize = function initialize(com) {
          this._collider = com;
          this._isInitialized = true;
          this._sharedBody = PhysicsSystem.instance.physicsWorld.getSharedBody(this._collider.node);
          this._sharedBody.reference = true;
          this.onComponentSet();
          this.setWrapper();
        };
        _proto.setWrapper = function setWrapper() {
          if (BulletCache.isNotEmptyShape(this._impl)) {
            bt.CollisionShape_setUserPointer(this._impl, this._impl);
            BulletCache.setWrapper(this._impl, BulletShape.TYPE, this);
          }
        };
        _proto.onLoad = function onLoad() {
          this.setCenter(this._collider.center);
          this.setAsTrigger(this._collider.isTrigger);
        };
        _proto.onEnable = function onEnable() {
          this._isEnabled = true;
          this._sharedBody.addShape(this, this._isTrigger);
          this.setMaterial(this.collider.sharedMaterial);
        };
        _proto.onDisable = function onDisable() {
          this._isEnabled = false;
          this._sharedBody.removeShape(this, this._isTrigger);
        };
        _proto.onDestroy = function onDestroy() {
          this._sharedBody.reference = false;
          this._collider = null;
          bt._safe_delete(this.quat, EBulletType.EBulletTypeQuat);
          bt._safe_delete(this.transform, EBulletType.EBulletTypeTransform);
          if (this._compound) bt._safe_delete(this._compound, EBulletType.EBulletTypeCollisionShape);
          if (BulletCache.isNotEmptyShape(this._impl)) {
            bt._safe_delete(this._impl, EBulletType.EBulletTypeCollisionShape);
            BulletCache.delWrapper(this._impl, BulletShape.TYPE);
          }
        };
        _proto.updateByReAdd = function updateByReAdd() {
          if (this._isEnabled) {
            this._sharedBody.removeShape(this, this._isTrigger);
            this._sharedBody.addShape(this, this._isTrigger);
          }
        };
        _proto.getGroup = function getGroup() {
          return this._sharedBody.collisionFilterGroup;
        };
        _proto.setGroup = function setGroup(v) {
          this._sharedBody.collisionFilterGroup = v;
        };
        _proto.addGroup = function addGroup(v) {
          this._sharedBody.collisionFilterGroup |= v;
        };
        _proto.removeGroup = function removeGroup(v) {
          this._sharedBody.collisionFilterGroup &= ~v;
        };
        _proto.getMask = function getMask() {
          return this._sharedBody.collisionFilterMask;
        };
        _proto.setMask = function setMask(v) {
          this._sharedBody.collisionFilterMask = v;
        };
        _proto.addMask = function addMask(v) {
          this._sharedBody.collisionFilterMask |= v;
        };
        _proto.removeMask = function removeMask(v) {
          this._sharedBody.collisionFilterMask &= ~v;
        };
        _proto.setCompound = function setCompound(compound) {
          if (this._compound) bt.CompoundShape_removeChildShape(this._compound, this._impl);
          if (compound) bt.CompoundShape_addChildShape(compound, this.transform, this._impl);
          this._compound = compound;
        };
        _proto.updateScale = function updateScale() {
          this.setCenter(this._collider.center);
        };
        _proto.updateCompoundTransform = function updateCompoundTransform() {
          if (this._compound) {
            bt.CompoundShape_updateChildTransform(this._compound, this._impl, this.transform, true);
          } else if (this._isEnabled && !this._isTrigger) {
            if (this._sharedBody && !this._sharedBody.bodyStruct.useCompound) {
              this._sharedBody.dirty |= EBtSharedBodyDirty.BODY_RE_ADD;
            }
          }
        };
        _proto.needCompound = function needCompound() {
          if (this._collider.type === EColliderType.TERRAIN) {
            return true;
          }
          if (this._collider.center.equals(Vec3.ZERO)) {
            return false;
          }
          return true;
        };
        _createClass(BulletShape, [{
          key: "attachedRigidBody",
          get: function get() {
            if (this._sharedBody.wrappedBody) return this._sharedBody.wrappedBody.rigidBody;
            return null;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._impl;
          }
        }, {
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "sharedBody",
          get: function get() {
            return this._sharedBody;
          }
        }]);
        return BulletShape;
      }();
      BulletShape.TYPE = 'shape';
      BulletShape.idCounter = 0;

      var ArrayCollisionMatrix = function () {
        function ArrayCollisionMatrix() {
          this.matrix = [];
        }
        var _proto = ArrayCollisionMatrix.prototype;
        _proto.get = function get(i, j) {
          if (j > i) {
            var temp = j;
            j = i;
            i = temp;
          }
          return this.matrix[(i * (i + 1) >> 1) + j - 1];
        };
        _proto.set = function set(i, j, value) {
          if (j > i) {
            var temp = j;
            j = i;
            i = temp;
          }
          this.matrix[(i * (i + 1) >> 1) + j - 1] = value ? 1 : 0;
        };
        _proto.reset = function reset() {
          this.matrix.length = 0;
        };
        _proto.setNumObjects = function setNumObjects(n) {
          this.matrix.length = n * (n - 1) >> 1;
        };
        return ArrayCollisionMatrix;
      }();

      var TupleDictionary = function () {
        function TupleDictionary() {
          this.data = void 0;
          this.data = {
            keys: []
          };
        }
        var _proto = TupleDictionary.prototype;
        _proto.get = function get(i, j) {
          if (i > j) {
            var temp = j;
            j = i;
            i = temp;
          }
          return this.data[i + "-" + j];
        };
        _proto.set = function set(i, j, value) {
          if (i > j) {
            var temp = j;
            j = i;
            i = temp;
          }
          var key = i + "-" + j;
          if (value == null) {
            var idx = this.data.keys.indexOf(key);
            if (idx !== -1) {
              this.data.keys.splice(idx, 1);
              delete this.data[key];
              return value;
            }
          }
          if (!this.get(i, j)) {
            this.data.keys.push(key);
          }
          this.data[key] = value;
          return this.data[key];
        };
        _proto.reset = function reset() {
          this.data = {
            keys: []
          };
        };
        _proto.getLength = function getLength() {
          return this.data.keys.length;
        };
        _proto.getKeyByIndex = function getKeyByIndex(index) {
          return this.data.keys[index];
        };
        _proto.getDataByKey = function getDataByKey(Key) {
          return this.data[Key];
        };
        return TupleDictionary;
      }();

      var BulletContactData = function () {
        function BulletContactData(event) {
          this.impl = 0;
          this.event = void 0;
          this.event = event;
        }
        var _proto = BulletContactData.prototype;
        _proto.getLocalPointOnA = function getLocalPointOnA(out) {
          if (this.impl) bullet2CocosVec3(out, bt.ManifoldPoint_get_m_localPointA(this.impl));
        };
        _proto.getLocalPointOnB = function getLocalPointOnB(out) {
          if (this.impl) bullet2CocosVec3(out, bt.ManifoldPoint_get_m_localPointB(this.impl));
        };
        _proto.getWorldPointOnA = function getWorldPointOnA(out) {
          if (this.impl) bullet2CocosVec3(out, bt.ManifoldPoint_get_m_positionWorldOnA(this.impl));
        };
        _proto.getWorldPointOnB = function getWorldPointOnB(out) {
          if (this.impl) bullet2CocosVec3(out, bt.ManifoldPoint_get_m_positionWorldOnB(this.impl));
        };
        _proto.getLocalNormalOnA = function getLocalNormalOnA(out) {
          if (this.impl) {
            var bt_rot = BulletCache.instance.BT_QUAT_0;
            var body = bt.PersistentManifold_getBody0(this.event.impl);
            var trans = bt.CollisionObject_getWorldTransform(body);
            bt.Transform_getRotation(trans, bt_rot);
            var inv_rot = CC_QUAT_0;
            bullet2CocosQuat(inv_rot, bt_rot);
            Quat.conjugate(inv_rot, inv_rot);
            bullet2CocosVec3(out, bt.ManifoldPoint_get_m_normalWorldOnB(this.impl));
            if (!this.isBodyA) Vec3.negate(out, out);
            Vec3.transformQuat(out, out, inv_rot);
          }
        };
        _proto.getLocalNormalOnB = function getLocalNormalOnB(out) {
          if (this.impl) {
            var bt_rot = BulletCache.instance.BT_QUAT_0;
            var body = bt.PersistentManifold_getBody1(this.event.impl);
            var trans = bt.CollisionObject_getWorldTransform(body);
            bt.Transform_getRotation(trans, bt_rot);
            var inv_rot = CC_QUAT_0;
            bullet2CocosQuat(inv_rot, bt_rot);
            Quat.conjugate(inv_rot, inv_rot);
            bullet2CocosVec3(out, bt.ManifoldPoint_get_m_normalWorldOnB(this.impl));
            Vec3.transformQuat(out, out, inv_rot);
          }
        };
        _proto.getWorldNormalOnA = function getWorldNormalOnA(out) {
          if (this.impl) {
            bullet2CocosVec3(out, bt.ManifoldPoint_get_m_normalWorldOnB(this.impl));
            if (!this.isBodyA) Vec3.negate(out, out);
          }
        };
        _proto.getWorldNormalOnB = function getWorldNormalOnB(out) {
          if (this.impl) bullet2CocosVec3(out, bt.ManifoldPoint_get_m_normalWorldOnB(this.impl));
        };
        _createClass(BulletContactData, [{
          key: "isBodyA",
          get: function get() {
            var sb = this.event.selfCollider.shape.sharedBody.body;
            return sb === bt.PersistentManifold_getBody0(this.event.impl);
          }
        }]);
        return BulletContactData;
      }();

      var contactsPool = [];
      var v3_0$3 = CC_V3_0;
      var v3_1$1 = CC_V3_1;
      var v3_2 = CC_V3_2;
      var c_0 = CC_COLOR_0;
      var emitHit = new CharacterControllerContact();
      var BulletWorld = function () {
        var _proto = BulletWorld.prototype;
        _proto.setDefaultMaterial = function setDefaultMaterial(v) {};
        _proto.setAllowSleep = function setAllowSleep(v) {
          bt.ccDiscreteDynamicsWorld_setAllowSleep(this._world, v);
        };
        _proto.setGravity = function setGravity(gravity) {
          bt.DynamicsWorld_setGravity(this._world, cocos2BulletVec3(BulletCache.instance.BT_V3_0, gravity));
        };
        _proto.updateNeedEmitEvents = function updateNeedEmitEvents(v) {
          if (!this.ghosts) return;
          if (v) {
            this._needEmitEvents = true;
          } else {
            this._needEmitEvents = false;
            for (var i = 0; i < this.ghosts.length; i++) {
              var ghost = this.ghosts[i];
              var shapes = ghost.ghostStruct.wrappedShapes;
              for (var j = 0; j < shapes.length; j++) {
                var collider = shapes[j].collider;
                if (collider.needCollisionEvent || collider.needTriggerEvent) {
                  this._needEmitEvents = true;
                  return;
                }
              }
            }
            for (var _i = 0; _i < this.bodies.length; _i++) {
              var body = this.bodies[_i];
              var _shapes = body.bodyStruct.wrappedShapes;
              for (var _j = 0; _j < _shapes.length; _j++) {
                var _collider = _shapes[_j].collider;
                if (_collider.needCollisionEvent || _collider.needTriggerEvent) {
                  this._needEmitEvents = true;
                  return;
                }
              }
            }
          }
        };
        _proto.updateNeedEmitCCTEvents = function updateNeedEmitCCTEvents(force) {
          if (!this.ccts) return;
          if (force) {
            this._needEmitCCTEvents = true;
          } else {
            this._needEmitCCTEvents = false;
            var ccts = this.ccts;
            var length = ccts.length;
            for (var i = 0; i < length; i++) {
              var cctCom = ccts[i].characterController;
              if (cctCom.needCollisionEvent) {
                this._needEmitCCTEvents = true;
                return;
              }
            }
          }
        };
        function BulletWorld() {
          this._world = void 0;
          this._broadphase = void 0;
          this._solver = void 0;
          this._dispatcher = void 0;
          this._debugDraw = void 0;
          this._debugLineCount = 0;
          this._MAX_DEBUG_LINE_COUNT = 16384;
          this._debugDrawFlags = EPhysicsDrawFlags.NONE;
          this._debugConstraintSize = 0.3;
          this._needEmitEvents = false;
          this._needSyncAfterEvents = false;
          this._needEmitCCTEvents = false;
          this.bodies = [];
          this.ghosts = [];
          this.ccts = [];
          this.constraints = [];
          this.triggerArrayMat = new ArrayCollisionMatrix();
          this.collisionArrayMat = new ArrayCollisionMatrix();
          this.contactsDic = new TupleDictionary();
          this.oldContactsDic = new TupleDictionary();
          this.cctShapeEventDic = new TupleDictionary();
          this.cctContactsDic = new TupleDictionary();
          this.cctOldContactsDic = new TupleDictionary();
          btCache.CACHE.world = this;
          this._broadphase = bt.DbvtBroadphase_new();
          this._dispatcher = bt.CollisionDispatcher_new();
          this._solver = bt.SequentialImpulseConstraintSolver_new();
          this._world = bt.ccDiscreteDynamicsWorld_new(this._dispatcher, this._broadphase, this._solver);
          var debugDraw = bt.DebugDraw.implement(importFunc);
          this._debugDraw = debugDraw.$$.ptr;
          bt.CollisionWorld_setDebugDrawer(this._world, this._debugDraw);
          bt.DebugDraw_setDebugMode(this._debugDraw, EBulletDebugDrawModes.DBG_NoDebug);
          bt.DebugDraw_setAABBColor(this._debugDraw, 0, 1, 1);
          bt.DebugDraw_setActiveObjectColor(this._debugDraw, 1, 0, 1);
          bt.DebugDraw_setDeactiveObjectColor(this._debugDraw, 1, 0, 1);
          bt.DebugDraw_setWantsDeactivationObjectColor(this._debugDraw, 1, 0, 1);
          bt.DebugDraw_setDisabledDeactivationObjectColor(this._debugDraw, 1, 0, 1);
          bt.DebugDraw_setDisabledSimulationObjectColor(this._debugDraw, 1, 0, 1);
          bt.DebugDraw_setConstraintLimitColor(this._debugDraw, 0.5, 0.5, 0.5);
        }
        _proto.destroy = function destroy() {
          if (this.constraints.length || this.bodies.length || this.ccts.length) error('You should destroy all physics component first.');
          bt._safe_delete(this._world, EBulletType.EBulletTypeCollisionWorld);
          bt._safe_delete(this._broadphase, EBulletType.EBulletTypeDbvtBroadPhase);
          bt._safe_delete(this._dispatcher, EBulletType.EBulletTypeCollisionDispatcher);
          bt._safe_delete(this._solver, EBulletType.EBulletTypeSequentialImpulseConstraintSolver);
          bt._safe_delete(this._debugDraw, EBulletType.EBulletTypeDebugDraw);
          this.bodies = null;
          this.ghosts = null;
          this.ccts = null;
          this.constraints = null;
          this.triggerArrayMat = null;
          this.collisionArrayMat = null;
          this.contactsDic = null;
          this.oldContactsDic = null;
          this.cctShapeEventDic = null;
          this.cctShapeEventPool = null;
          contactsPool.length = 0;
        };
        _proto.step = function step(deltaTime, timeSinceLastCalled, maxSubStep) {
          if (maxSubStep === void 0) {
            maxSubStep = 0;
          }
          if (!this.bodies.length && !this.ghosts.length) return;
          if (timeSinceLastCalled === undefined) timeSinceLastCalled = deltaTime;
          bt.DynamicsWorld_stepSimulation(this._world, timeSinceLastCalled, maxSubStep, deltaTime);
          bt.CollisionWorld_debugDrawWorld(this._world);
        };
        _proto.syncSceneToPhysics = function syncSceneToPhysics() {
          for (var i = this.ghosts.length - 1; i >= 0; i--) {
            var ghost = this.ghosts[i];
            ghost.updateDirty();
            ghost.syncSceneToGhost();
          }
          for (var _i2 = this.bodies.length - 1; _i2 >= 0; _i2--) {
            var body = this.bodies[_i2];
            body.updateDirty();
            body.syncSceneToPhysics();
          }
          var ccts = this.ccts;
          var length = ccts.length;
          for (var _i3 = length - 1; _i3 >= 0; _i3--) {
            var cct = ccts[_i3];
            cct.updateDirty();
            cct.syncSceneToPhysics();
          }
        };
        _proto.syncAfterEvents = function syncAfterEvents() {
          if (!this._needSyncAfterEvents) return;
          this.syncSceneToPhysics();
        };
        _proto.raycast = function raycast(worldRay, options, pool, results) {
          worldRay.computeHit(v3_0$3, options.maxDistance);
          var to = cocos2BulletVec3(BulletCache.instance.BT_V3_0, v3_0$3);
          var from = cocos2BulletVec3(BulletCache.instance.BT_V3_1, worldRay.o);
          var allHitsCB = bt.ccAllRayCallback_static();
          bt.ccAllRayCallback_reset(allHitsCB, from, to, options.mask >>> 0, options.queryTrigger);
          bt.ccAllRayCallback_setFlags(allHitsCB, EBulletTriangleRaycastFlag.UseSubSimplexConvexCastRaytest);
          bt.CollisionWorld_rayTest(this._world, from, to, allHitsCB);
          if (bt.RayCallback_hasHit(allHitsCB)) {
            var posArray = bt.ccAllRayCallback_getHitPointWorld(allHitsCB);
            var normalArray = bt.ccAllRayCallback_getHitNormalWorld(allHitsCB);
            var ptrArray = bt.ccAllRayCallback_getCollisionShapePtrs(allHitsCB);
            for (var i = 0, n = bt.int_array_size(ptrArray); i < n; i++) {
              bullet2CocosVec3(v3_0$3, bt.Vec3_array_at(posArray, i));
              bullet2CocosVec3(v3_1$1, bt.Vec3_array_at(normalArray, i));
              var shape = BulletCache.getWrapper(bt.int_array_at(ptrArray, i), BulletShape.TYPE);
              var r = pool.add();
              results.push(r);
              r._assign(v3_0$3, Vec3.distance(worldRay.o, v3_0$3), shape.collider, v3_1$1);
            }
            return true;
          }
          return false;
        };
        _proto.raycastClosest = function raycastClosest(worldRay, options, result) {
          worldRay.computeHit(v3_0$3, options.maxDistance);
          var to = cocos2BulletVec3(BulletCache.instance.BT_V3_0, v3_0$3);
          var from = cocos2BulletVec3(BulletCache.instance.BT_V3_1, worldRay.o);
          var closeHitCB = bt.ccClosestRayCallback_static();
          bt.ccClosestRayCallback_reset(closeHitCB, from, to, options.mask >>> 0, options.queryTrigger);
          bt.ccClosestRayCallback_setFlags(closeHitCB, EBulletTriangleRaycastFlag.UseSubSimplexConvexCastRaytest);
          bt.CollisionWorld_rayTest(this._world, from, to, closeHitCB);
          if (bt.RayCallback_hasHit(closeHitCB)) {
            bullet2CocosVec3(v3_0$3, bt.ccClosestRayCallback_getHitPointWorld(closeHitCB));
            bullet2CocosVec3(v3_1$1, bt.ccClosestRayCallback_getHitNormalWorld(closeHitCB));
            var shape = BulletCache.getWrapper(bt.ccClosestRayCallback_getCollisionShapePtr(closeHitCB), BulletShape.TYPE);
            result._assign(v3_0$3, Vec3.distance(worldRay.o, v3_0$3), shape.collider, v3_1$1);
            return true;
          }
          return false;
        };
        _proto.sweepBox = function sweepBox(worldRay, halfExtent, orientation, options, pool, results) {
          var hf = BulletCache.instance.BT_V3_0;
          cocos2BulletVec3(hf, halfExtent);
          if (!BulletWorld._sweepBoxGeometry) {
            BulletWorld._sweepBoxGeometry = bt.BoxShape_new(hf);
          }
          bt.BoxShape_setUnscaledHalfExtents(BulletWorld._sweepBoxGeometry, hf);
          return this.sweep(worldRay, BulletWorld._sweepBoxGeometry, orientation, options, pool, results);
        };
        _proto.sweepBoxClosest = function sweepBoxClosest(worldRay, halfExtent, orientation, options, result) {
          var hf = BulletCache.instance.BT_V3_0;
          cocos2BulletVec3(hf, halfExtent);
          if (!BulletWorld._sweepBoxGeometry) {
            BulletWorld._sweepBoxGeometry = bt.BoxShape_new(hf);
          }
          bt.BoxShape_setUnscaledHalfExtents(BulletWorld._sweepBoxGeometry, hf);
          return this.sweepClosest(worldRay, BulletWorld._sweepBoxGeometry, orientation, options, result);
        };
        _proto.sweepSphere = function sweepSphere(worldRay, radius, options, pool, results) {
          if (!BulletWorld._sweepSphereGeometry) {
            BulletWorld._sweepSphereGeometry = bt.SphereShape_new(radius);
          }
          bt.SphereShape_setUnscaledRadius(BulletWorld._sweepSphereGeometry, radius);
          return this.sweep(worldRay, BulletWorld._sweepSphereGeometry, Quat.IDENTITY, options, pool, results);
        };
        _proto.sweepSphereClosest = function sweepSphereClosest(worldRay, radius, options, result) {
          if (!BulletWorld._sweepSphereGeometry) {
            BulletWorld._sweepSphereGeometry = bt.SphereShape_new(radius);
          }
          bt.SphereShape_setUnscaledRadius(BulletWorld._sweepSphereGeometry, radius);
          return this.sweepClosest(worldRay, BulletWorld._sweepSphereGeometry, Quat.IDENTITY, options, result);
        };
        _proto.sweepCapsule = function sweepCapsule(worldRay, radius, height, orientation, options, pool, results) {
          if (!BulletWorld._sweepCapsuleGeometry) {
            BulletWorld._sweepCapsuleGeometry = bt.CapsuleShape_new(radius, height);
          }
          bt.CapsuleShape_updateProp(BulletWorld._sweepCapsuleGeometry, radius, height * 0.5, 1);
          return this.sweep(worldRay, BulletWorld._sweepCapsuleGeometry, orientation, options, pool, results);
        };
        _proto.sweepCapsuleClosest = function sweepCapsuleClosest(worldRay, radius, height, orientation, options, result) {
          if (!BulletWorld._sweepCapsuleGeometry) {
            BulletWorld._sweepCapsuleGeometry = bt.CapsuleShape_new(radius, height);
          }
          bt.CapsuleShape_updateProp(BulletWorld._sweepCapsuleGeometry, radius, height * 0.5, 1);
          return this.sweepClosest(worldRay, BulletWorld._sweepCapsuleGeometry, orientation, options, result);
        };
        _proto.sweep = function sweep(worldRay, btShapePtr, orientation, options, pool, results) {
          var BT_fromTransform = BulletCache.instance.BT_TRANSFORM_0;
          var BT_toTransform = BulletCache.instance.BT_TRANSFORM_1;
          var BT_orientation = BulletCache.instance.BT_QUAT_0;
          cocos2BulletVec3(bt.Transform_getOrigin(BT_fromTransform), worldRay.o);
          cocos2BulletQuat(BT_orientation, orientation);
          bt.Transform_setRotation(BT_fromTransform, BT_orientation);
          worldRay.computeHit(v3_0$3, options.maxDistance);
          cocos2BulletVec3(bt.Transform_getOrigin(BT_toTransform), v3_0$3);
          cocos2BulletQuat(BT_orientation, orientation);
          bt.Transform_setRotation(BT_toTransform, BT_orientation);
          var allHitsCB = bt.ccAllConvexCallback_static();
          bt.ccAllConvexCallback_reset(allHitsCB, BT_fromTransform, BT_toTransform, options.mask >>> 0, options.queryTrigger);
          bt.CollisionWorld_convexSweepTest(this._world, btShapePtr, BT_fromTransform, BT_toTransform, allHitsCB, 0);
          if (bt.ConvexCallback_hasHit(allHitsCB)) {
            var posArray = bt.ccAllConvexCallback_getHitPointWorld(allHitsCB);
            var normalArray = bt.ccAllConvexCallback_getHitNormalWorld(allHitsCB);
            var ptrArray = bt.ccAllConvexCallback_getCollisionShapePtrs(allHitsCB);
            for (var i = 0, n = bt.int_array_size(ptrArray); i < n; i++) {
              bullet2CocosVec3(v3_0$3, bt.Vec3_array_at(posArray, i));
              bullet2CocosVec3(v3_1$1, bt.Vec3_array_at(normalArray, i));
              var shape = BulletCache.getWrapper(bt.int_array_at(ptrArray, i), BulletShape.TYPE);
              var r = pool.add();
              results.push(r);
              r._assign(v3_0$3, Vec3.distance(worldRay.o, v3_0$3), shape.collider, v3_1$1);
            }
            return true;
          }
          return false;
        };
        _proto.sweepClosest = function sweepClosest(worldRay, btShapePtr, orientation, options, result) {
          var BT_fromTransform = BulletCache.instance.BT_TRANSFORM_0;
          var BT_toTransform = BulletCache.instance.BT_TRANSFORM_1;
          var BT_orientation = BulletCache.instance.BT_QUAT_0;
          cocos2BulletVec3(bt.Transform_getOrigin(BT_fromTransform), worldRay.o);
          cocos2BulletQuat(BT_orientation, orientation);
          bt.Transform_setRotation(BT_fromTransform, BT_orientation);
          worldRay.computeHit(v3_0$3, options.maxDistance);
          cocos2BulletVec3(bt.Transform_getOrigin(BT_toTransform), v3_0$3);
          cocos2BulletQuat(BT_orientation, orientation);
          bt.Transform_setRotation(BT_toTransform, BT_orientation);
          var closeHitCB = bt.ccClosestConvexCallback_static();
          bt.ccClosestConvexCallback_reset(closeHitCB, BT_fromTransform, BT_toTransform, options.mask >>> 0, options.queryTrigger);
          bt.CollisionWorld_convexSweepTest(this._world, btShapePtr, BT_fromTransform, BT_toTransform, closeHitCB, 0);
          if (bt.ConvexCallback_hasHit(closeHitCB)) {
            bullet2CocosVec3(v3_0$3, bt.ccClosestConvexCallback_getHitPointWorld(closeHitCB));
            bullet2CocosVec3(v3_1$1, bt.ccClosestConvexCallback_getHitNormalWorld(closeHitCB));
            var shape = BulletCache.getWrapper(bt.ccClosestConvexCallback_getCollisionShapePtr(closeHitCB), BulletShape.TYPE);
            result._assign(v3_0$3, Vec3.distance(worldRay.o, v3_0$3), shape.collider, v3_1$1);
            return true;
          }
          return false;
        };
        _proto.getSharedBody = function getSharedBody(node, wrappedBody) {
          return BulletSharedBody.getSharedBody(node, this, wrappedBody);
        };
        _proto.addSharedBody = function addSharedBody(sharedBody) {
          var i = this.bodies.indexOf(sharedBody);
          if (i < 0) {
            this.bodies.push(sharedBody);
            var group = sharedBody.collisionFilterGroup;
            var mask = sharedBody.collisionFilterMask;
            bt.DynamicsWorld_addRigidBody(this._world, sharedBody.body, group >>> 0, mask >>> 0);
          }
        };
        _proto.removeSharedBody = function removeSharedBody(sharedBody) {
          var i = this.bodies.indexOf(sharedBody);
          if (i >= 0) {
            fastRemoveAt$2(this.bodies, i);
            bt.DynamicsWorld_removeRigidBody(this._world, sharedBody.body);
          }
        };
        _proto.addGhostObject = function addGhostObject(sharedBody) {
          var i = this.ghosts.indexOf(sharedBody);
          if (i < 0) {
            this.ghosts.push(sharedBody);
            var group = sharedBody.collisionFilterGroup;
            var mask = sharedBody.collisionFilterMask;
            bt.CollisionWorld_addCollisionObject(this._world, sharedBody.ghost, group >>> 0, mask >>> 0);
          }
        };
        _proto.removeGhostObject = function removeGhostObject(sharedBody) {
          var i = this.ghosts.indexOf(sharedBody);
          if (i >= 0) {
            fastRemoveAt$2(this.ghosts, i);
            bt.CollisionWorld_removeCollisionObject(this._world, sharedBody.ghost);
          }
        };
        _proto.addCCT = function addCCT(cct) {
          var index = this.ccts.indexOf(cct);
          if (index < 0) {
            this.ccts.push(cct);
            var cctGhost = bt.CharacterController_getGhostObject(cct.impl);
            var group = cct.getGroup();
            var mask = cct.getMask();
            bt.CollisionWorld_addCollisionObject(this._world, cctGhost, group >>> 0, mask >>> 0);
            bt.DynamicsWorld_addAction(this._world, cct.impl);
          }
        };
        _proto.removeCCT = function removeCCT(cct) {
          var index = this.ccts.indexOf(cct);
          if (index >= 0) {
            fastRemoveAt$2(this.ccts, index);
            var cctGhost = bt.CharacterController_getGhostObject(cct.impl);
            bt.CollisionWorld_removeCollisionObject(this._world, cctGhost);
            bt.DynamicsWorld_removeAction(this._world, cct.impl);
          }
        };
        _proto.addConstraint = function addConstraint(constraint) {
          var i = this.constraints.indexOf(constraint);
          if (i < 0) {
            this.constraints.push(constraint);
            bt.DynamicsWorld_addConstraint(this.impl, constraint.impl, !constraint.constraint.enableCollision);
            constraint.index = i;
          }
        };
        _proto.removeConstraint = function removeConstraint(constraint) {
          var i = this.constraints.indexOf(constraint);
          if (i >= 0) {
            this.constraints.splice(i, 1);
            bt.DynamicsWorld_removeConstraint(this.impl, constraint.impl);
            constraint.index = -1;
          }
        };
        _proto.emitEvents = function emitEvents() {
          this._needSyncAfterEvents = false;
          if (this._needEmitEvents) {
            this.gatherConatactData();
            this.emitCollisionAndTriggerEvent();
            this.emitCCTTriggerEvent();
          }
          if (this._needEmitCCTEvents) {
            this.emitCCTCollisionEvent();
          }
        };
        _proto.emitCollisionAndTriggerEvent = function emitCollisionAndTriggerEvent() {
          var dicL = this.contactsDic.getLength();
          while (dicL--) {
            contactsPool.push.apply(contactsPool, CollisionEventObject.contacts);
            CollisionEventObject.contacts.length = 0;
            var key = this.contactsDic.getKeyByIndex(dicL);
            var data = this.contactsDic.getDataByKey(key);
            var shape0 = data.shape0;
            var shape1 = data.shape1;
            this.oldContactsDic.set(shape0.id, shape1.id, data);
            var collider0 = shape0.collider;
            var collider1 = shape1.collider;
            if (collider0 && collider1) {
              var isTrigger = collider0.isTrigger || collider1.isTrigger;
              if (isTrigger) {
                if (this.triggerArrayMat.get(shape0.id, shape1.id)) {
                  TriggerEventObject.type = 'onTriggerStay';
                } else {
                  TriggerEventObject.type = 'onTriggerEnter';
                  this.triggerArrayMat.set(shape0.id, shape1.id, true);
                }
                TriggerEventObject.impl = data.impl;
                TriggerEventObject.selfCollider = collider0;
                TriggerEventObject.otherCollider = collider1;
                collider0.emit(TriggerEventObject.type, TriggerEventObject);
                TriggerEventObject.selfCollider = collider1;
                TriggerEventObject.otherCollider = collider0;
                collider1.emit(TriggerEventObject.type, TriggerEventObject);
                this._needSyncAfterEvents = true;
              } else {
                var body0 = collider0.attachedRigidBody;
                var body1 = collider1.attachedRigidBody;
                if (body0 && body1) {
                  if (body0.isSleeping && body1.isSleeping) continue;
                } else if (!body0 && body1) {
                  if (body1.isSleeping) continue;
                } else if (!body1 && body0) {
                  if (body0.isSleeping) continue;
                }
                if (this.collisionArrayMat.get(shape0.id, shape1.id)) {
                  CollisionEventObject.type = 'onCollisionStay';
                } else {
                  CollisionEventObject.type = 'onCollisionEnter';
                  this.collisionArrayMat.set(shape0.id, shape1.id, true);
                }
                for (var i = 0; i < data.contacts.length; i++) {
                  var cq = data.contacts[i];
                  if (contactsPool.length > 0) {
                    var c = contactsPool.pop();
                    c.impl = cq;
                    CollisionEventObject.contacts.push(c);
                  } else {
                    var _c = new BulletContactData(CollisionEventObject);
                    _c.impl = cq;
                    CollisionEventObject.contacts.push(_c);
                  }
                }
                CollisionEventObject.impl = data.impl;
                CollisionEventObject.selfCollider = collider0;
                CollisionEventObject.otherCollider = collider1;
                collider0.emit(CollisionEventObject.type, CollisionEventObject);
                CollisionEventObject.selfCollider = collider1;
                CollisionEventObject.otherCollider = collider0;
                collider1.emit(CollisionEventObject.type, CollisionEventObject);
                this._needSyncAfterEvents = true;
              }
              if (this.oldContactsDic.get(shape0.id, shape1.id) == null) {
                this.oldContactsDic.set(shape0.id, shape1.id, data);
              }
            }
          }
          var oldDicL = this.oldContactsDic.getLength();
          while (oldDicL--) {
            var _key = this.oldContactsDic.getKeyByIndex(oldDicL);
            var _data = this.oldContactsDic.getDataByKey(_key);
            var _shape = _data.shape0;
            var _shape2 = _data.shape1;
            var _collider2 = _shape.collider;
            var _collider3 = _shape2.collider;
            if (_collider2 && _collider3) {
              var _isTrigger = _collider2.isTrigger || _collider3.isTrigger;
              if (this.contactsDic.getDataByKey(_key) == null) {
                if (_isTrigger) {
                  if (this.triggerArrayMat.get(_shape.id, _shape2.id)) {
                    TriggerEventObject.type = 'onTriggerExit';
                    TriggerEventObject.selfCollider = _collider2;
                    TriggerEventObject.otherCollider = _collider3;
                    _collider2.emit(TriggerEventObject.type, TriggerEventObject);
                    TriggerEventObject.selfCollider = _collider3;
                    TriggerEventObject.otherCollider = _collider2;
                    _collider3.emit(TriggerEventObject.type, TriggerEventObject);
                    this.triggerArrayMat.set(_shape.id, _shape2.id, false);
                    this.oldContactsDic.set(_shape.id, _shape2.id, null);
                    this._needSyncAfterEvents = true;
                  }
                } else if (this.collisionArrayMat.get(_shape.id, _shape2.id)) {
                  contactsPool.push.apply(contactsPool, CollisionEventObject.contacts);
                  CollisionEventObject.contacts.length = 0;
                  CollisionEventObject.type = 'onCollisionExit';
                  CollisionEventObject.selfCollider = _collider2;
                  CollisionEventObject.otherCollider = _collider3;
                  _collider2.emit(CollisionEventObject.type, CollisionEventObject);
                  CollisionEventObject.selfCollider = _collider3;
                  CollisionEventObject.otherCollider = _collider2;
                  _collider3.emit(CollisionEventObject.type, CollisionEventObject);
                  this.collisionArrayMat.set(_shape.id, _shape2.id, false);
                  this.oldContactsDic.set(_shape.id, _shape2.id, null);
                  this._needSyncAfterEvents = true;
                }
              }
            }
          }
          this.contactsDic.reset();
        };
        _proto.emitCCTTriggerEvent = function emitCCTTriggerEvent() {
          var dicL = this.cctContactsDic.getLength();
          while (dicL--) {
            var key = this.cctContactsDic.getKeyByIndex(dicL);
            var data = this.cctContactsDic.getDataByKey(key);
            var shape = data.shape;
            var cct = data.cct;
            this.cctOldContactsDic.set(shape.id, cct.id, data);
            var collider = shape.collider;
            var characterController = cct.characterController;
            if (collider && characterController) {
              var isTrigger = collider.isTrigger;
              if (isTrigger) {
                if (this.triggerArrayMat.get(shape.id, cct.id)) {
                  CharacterTriggerEventObject.type = 'onControllerTriggerStay';
                } else {
                  CharacterTriggerEventObject.type = 'onControllerTriggerEnter';
                  this.triggerArrayMat.set(shape.id, cct.id, true);
                }
                CharacterTriggerEventObject.impl = data.impl;
                CharacterTriggerEventObject.collider = collider;
                CharacterTriggerEventObject.characterController = characterController;
                collider.emit(CharacterTriggerEventObject.type, CharacterTriggerEventObject);
                CharacterTriggerEventObject.collider = collider;
                CharacterTriggerEventObject.characterController = characterController;
                characterController.emit(CharacterTriggerEventObject.type, CharacterTriggerEventObject);
                this._needSyncAfterEvents = true;
              }
              if (this.cctOldContactsDic.get(shape.id, cct.id) == null) {
                this.cctOldContactsDic.set(shape.id, cct.id, data);
              }
            }
          }
          var oldDicL = this.cctOldContactsDic.getLength();
          while (oldDicL--) {
            var _key2 = this.cctOldContactsDic.getKeyByIndex(oldDicL);
            var _data2 = this.cctOldContactsDic.getDataByKey(_key2);
            var _shape3 = _data2.shape;
            var _cct = _data2.cct;
            var _collider4 = _shape3.collider;
            var _characterController = _cct.characterController;
            if (_collider4 && _characterController) {
              var _isTrigger2 = _collider4.isTrigger;
              if (this.cctContactsDic.getDataByKey(_key2) == null) {
                if (_isTrigger2) {
                  if (this.triggerArrayMat.get(_shape3.id, _cct.id)) {
                    CharacterTriggerEventObject.type = 'onControllerTriggerExit';
                    CharacterTriggerEventObject.collider = _collider4;
                    CharacterTriggerEventObject.characterController = _characterController;
                    _collider4.emit(CharacterTriggerEventObject.type, CharacterTriggerEventObject);
                    CharacterTriggerEventObject.collider = _collider4;
                    CharacterTriggerEventObject.characterController = _characterController;
                    _characterController.emit(CharacterTriggerEventObject.type, CharacterTriggerEventObject);
                    this.triggerArrayMat.set(_shape3.id, _cct.id, false);
                    this.cctOldContactsDic.set(_shape3.id, _cct.id, null);
                    this._needSyncAfterEvents = true;
                  }
                }
              }
            }
          }
          this.cctContactsDic.reset();
        };
        _proto.emitCCTCollisionEvent = function emitCCTCollisionEvent() {
          var dicL = this.cctShapeEventDic.getLength();
          while (dicL--) {
            var _emitHit$controller;
            var key = this.cctShapeEventDic.getKeyByIndex(dicL);
            var data = this.cctShapeEventDic.getDataByKey(key);
            var cct = data.BulletCharacterController;
            var shape = data.BulletShape;
            var worldPos = data.worldPos;
            var worldNormal = data.worldNormal;
            var motionDir = data.motionDir;
            var motionLength = data.motionLength;
            emitHit.controller = cct.characterController;
            emitHit.collider = shape.collider;
            emitHit.worldPosition.set(worldPos.x, worldPos.y, worldPos.z);
            emitHit.worldNormal.set(worldNormal.x, worldNormal.y, worldNormal.z);
            emitHit.motionDirection.set(motionDir.x, motionDir.y, motionDir.z);
            emitHit.motionLength = motionLength;
            (_emitHit$controller = emitHit.controller) === null || _emitHit$controller === void 0 ? void 0 : _emitHit$controller.emit('onControllerColliderHit', emitHit);
            this._needSyncAfterEvents = true;
          }
          this.cctShapeEventDic.reset();
        };
        _proto.gatherConatactData = function gatherConatactData() {
          var numManifolds = bt.Dispatcher_getNumManifolds(this._dispatcher);
          for (var i = 0; i < numManifolds; i++) {
            var manifold = bt.Dispatcher_getManifoldByIndexInternal(this._dispatcher, i);
            var numContacts = bt.PersistentManifold_getNumContacts(manifold);
            for (var j = 0; j < numContacts; j++) {
              var manifoldPoint = bt.PersistentManifold_getContactPoint(manifold, j);
              var s0 = bt.ManifoldPoint_getShape0(manifoldPoint);
              var s1 = bt.ManifoldPoint_getShape1(manifoldPoint);
              var processed = false;
              if (!processed) {
                var shape0 = BulletCache.getWrapper(s0, BulletShape.TYPE);
                var shape1 = BulletCache.getWrapper(s1, BulletShape.TYPE);
                if (shape0 && shape1) {
                  processed = true;
                  if (shape0.collider.needTriggerEvent || shape1.collider.needTriggerEvent || shape0.collider.needCollisionEvent || shape1.collider.needCollisionEvent) {
                    var item = this.contactsDic.get(shape0.id, shape1.id);
                    if (!item) {
                      item = this.contactsDic.set(shape0.id, shape1.id, {
                        shape0: shape0,
                        shape1: shape1,
                        contacts: [],
                        impl: manifold
                      });
                    }
                    item.contacts.push(manifoldPoint);
                  }
                }
              }
              if (!processed) {
                var shape = BulletCache.getWrapper(s0, BulletShape.TYPE);
                var cct = BulletCache.getWrapper(s1, btCache.CCT_CACHE_NAME);
                if (shape && cct) {
                  processed = true;
                  if (shape.collider.needTriggerEvent) {
                    var _item = this.cctContactsDic.get(shape.id, cct.id);
                    if (!_item) {
                      _item = this.cctContactsDic.set(shape.id, cct.id, {
                        shape: shape,
                        cct: cct,
                        contacts: [],
                        impl: manifold
                      });
                    }
                    _item.contacts.push(manifoldPoint);
                    processed = true;
                  }
                }
              }
              if (!processed) {
                var _cct2 = BulletCache.getWrapper(s0, btCache.CCT_CACHE_NAME);
                var _shape4 = BulletCache.getWrapper(s1, BulletShape.TYPE);
                if (_shape4 && _cct2) {
                  processed = true;
                  if (_shape4.collider.needTriggerEvent) {
                    var _item2 = this.cctContactsDic.get(_shape4.id, _cct2.id);
                    if (!_item2) {
                      _item2 = this.cctContactsDic.set(_shape4.id, _cct2.id, {
                        shape: _shape4,
                        cct: _cct2,
                        contacts: [],
                        impl: manifold
                      });
                    }
                    _item2.contacts.push(manifoldPoint);
                    processed = true;
                  }
                }
              }
            }
          }
        };
        _proto._setDebugDrawMode = function _setDebugDrawMode() {
          var btDrawMode = 0;
          if (this._debugDrawFlags & EPhysicsDrawFlags.WIRE_FRAME) {
            btDrawMode |= EBulletDebugDrawModes.DBG_DrawWireframe;
          }
          if (this._debugDrawFlags & EPhysicsDrawFlags.CONSTRAINT) {
            btDrawMode |= EBulletDebugDrawModes.DBG_DrawConstraints;
            btDrawMode |= EBulletDebugDrawModes.DBG_DrawConstraintLimits;
          }
          if (this._debugDrawFlags & EPhysicsDrawFlags.AABB) {
            btDrawMode |= EBulletDebugDrawModes.DBG_DrawAabb;
          }
          bt.DebugDraw_setDebugMode(this._debugDraw, btDrawMode);
        };
        _proto._getDebugRenderer = function _getDebugRenderer() {
          var _mainWindow;
          var cameras = (_mainWindow = director.root.mainWindow) === null || _mainWindow === void 0 ? void 0 : _mainWindow.cameras;
          if (!cameras) return null;
          if (cameras.length === 0) return null;
          if (!cameras[0]) return null;
          cameras[0].initGeometryRenderer();
          return cameras[0].geometryRenderer;
        };
        _proto.onDebugDrawLine = function onDebugDrawLine(from, to, color) {
          var debugRenderer = this._getDebugRenderer();
          if (debugRenderer && this._debugLineCount < this._MAX_DEBUG_LINE_COUNT) {
            this._debugLineCount++;
            bullet2CocosVec3(v3_0$3, from);
            bullet2CocosVec3(v3_1$1, to);
            bullet2CocosVec3(v3_2, color);
            c_0.set(v3_2.x * 255, v3_2.y * 255, v3_2.z * 255, 255);
            debugRenderer.addLine(v3_0$3, v3_1$1, c_0);
          }
        };
        _proto.onClearLines = function onClearLines() {
          this._debugLineCount = 0;
        };
        _createClass(BulletWorld, [{
          key: "impl",
          get: function get() {
            return this._world;
          }
        }, {
          key: "debugDrawFlags",
          get: function get() {
            return this._debugDrawFlags;
          },
          set: function set(v) {
            this._debugDrawFlags = v;
            if (this._debugDraw) {
              this._setDebugDrawMode();
            }
          }
        }, {
          key: "debugDrawConstraintSize",
          get: function get() {
            return this._debugConstraintSize;
          },
          set: function set(v) {
            this._debugConstraintSize = v;
            for (var i = 0; i < this.constraints.length; i++) {
              this.constraints[i].updateDebugDrawSize();
            }
          }
        }]);
        return BulletWorld;
      }();
      BulletWorld._sweepBoxGeometry = void 0;
      BulletWorld._sweepSphereGeometry = void 0;
      BulletWorld._sweepCapsuleGeometry = void 0;

      var BulletBoxShape = function (_BulletShape) {
        _inheritsLoose(BulletBoxShape, _BulletShape);
        function BulletBoxShape() {
          return _BulletShape.apply(this, arguments) || this;
        }
        var _proto = BulletBoxShape.prototype;
        _proto.updateSize = function updateSize() {
          var hf = BulletCache.instance.BT_V3_0;
          cocos2BulletVec3(hf, this.getMinUnscaledHalfExtents(VEC3_0));
          bt.BoxShape_setUnscaledHalfExtents(this.impl, hf);
          this.updateCompoundTransform();
        };
        _proto.onComponentSet = function onComponentSet() {
          var hf = BulletCache.instance.BT_V3_0;
          cocos2BulletVec3(hf, this.getMinUnscaledHalfExtents(VEC3_0));
          this._impl = bt.BoxShape_new(hf);
          this.updateScale();
        };
        _proto.updateScale = function updateScale() {
          _BulletShape.prototype.updateScale.call(this);
          var bt_v3 = BulletCache.instance.BT_V3_0;
          bt.CollisionShape_setLocalScaling(this._impl, cocos2BulletVec3(bt_v3, this.getMinScale(VEC3_0)));
          this.updateCompoundTransform();
        };
        _proto.getMinUnscaledHalfExtents = function getMinUnscaledHalfExtents(out) {
          var size = this.collider.size;
          var ws = absolute(VEC3_0.set(this._collider.node.worldScale));
          var minVolumeSize = PhysicsSystem.instance.minVolumeSize;
          var halfSizeX = size.x / 2;
          var halfSizeY = size.y / 2;
          var halfSizeZ = size.z / 2;
          var halfX = halfSizeX * ws.x < minVolumeSize ? minVolumeSize / ws.x : halfSizeX;
          var halfY = halfSizeY * ws.y < minVolumeSize ? minVolumeSize / ws.y : halfSizeY;
          var halfZ = halfSizeZ * ws.z < minVolumeSize ? minVolumeSize / ws.z : halfSizeZ;
          out.set(halfX, halfY, halfZ);
          return out;
        };
        _proto.getMinScale = function getMinScale(out) {
          var size = this.collider.size;
          var ws = absolute(VEC3_0.set(this._collider.node.worldScale));
          var minVolumeSize = PhysicsSystem.instance.minVolumeSize;
          var halfSizeX = size.x / 2;
          var halfSizeY = size.y / 2;
          var halfSizeZ = size.z / 2;
          var scaleX = halfSizeX * ws.x < minVolumeSize ? minVolumeSize / halfSizeX : ws.x;
          var scaleY = halfSizeY * ws.y < minVolumeSize ? minVolumeSize / halfSizeY : ws.y;
          var scaleZ = halfSizeZ * ws.z < minVolumeSize ? minVolumeSize / halfSizeZ : ws.z;
          out.set(scaleX, scaleY, scaleZ);
          return out;
        };
        _createClass(BulletBoxShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }]);
        return BulletBoxShape;
      }(BulletShape);

      var BulletSphereShape = function (_BulletShape) {
        _inheritsLoose(BulletSphereShape, _BulletShape);
        function BulletSphereShape() {
          return _BulletShape.apply(this, arguments) || this;
        }
        var _proto = BulletSphereShape.prototype;
        _proto.updateRadius = function updateRadius() {
          bt.SphereShape_setUnscaledRadius(this.impl, this.getMinUnscaledRadius());
          this.updateCompoundTransform();
        };
        _proto.onComponentSet = function onComponentSet() {
          this._impl = bt.SphereShape_new(this.getMinUnscaledRadius());
          this.updateScale();
        };
        _proto.updateScale = function updateScale() {
          _BulletShape.prototype.updateScale.call(this);
          var scale = this.getMinScale();
          CC_V3_0.set(scale, scale, scale);
          var bt_v3 = BulletCache.instance.BT_V3_0;
          bt.CollisionShape_setLocalScaling(this._impl, cocos2BulletVec3(bt_v3, CC_V3_0));
          this.updateCompoundTransform();
        };
        _proto.getMinUnscaledRadius = function getMinUnscaledRadius() {
          var radius = this.collider.radius;
          var ws = Math.abs(absMaxComponent(this._collider.node.worldScale));
          var minVolumeSize = PhysicsSystem.instance.minVolumeSize;
          return ws * radius < minVolumeSize ? minVolumeSize / ws : radius;
        };
        _proto.getMinScale = function getMinScale() {
          var radius = this.collider.radius;
          var ws = Math.abs(absMaxComponent(this._collider.node.worldScale));
          var minVolumeSize = PhysicsSystem.instance.minVolumeSize;
          return ws * radius < minVolumeSize ? minVolumeSize / radius : ws;
        };
        _createClass(BulletSphereShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }]);
        return BulletSphereShape;
      }(BulletShape);

      var BulletCapsuleShape = function (_BulletShape) {
        _inheritsLoose(BulletCapsuleShape, _BulletShape);
        function BulletCapsuleShape() {
          return _BulletShape.apply(this, arguments) || this;
        }
        var _proto = BulletCapsuleShape.prototype;
        _proto.setCylinderHeight = function setCylinderHeight(v) {
          this.updateProperties(this.collider.radius, this.collider.cylinderHeight, this.collider.direction, this._collider.node.worldScale);
        };
        _proto.setDirection = function setDirection(v) {
          this.updateProperties(this.collider.radius, this.collider.cylinderHeight, this.collider.direction, this._collider.node.worldScale);
        };
        _proto.setRadius = function setRadius(v) {
          this.updateProperties(this.collider.radius, this.collider.cylinderHeight, this.collider.direction, this._collider.node.worldScale);
        };
        _proto.onComponentSet = function onComponentSet() {
          this._impl = bt.CapsuleShape_new(0.5, 1);
          this.setRadius(this.collider.radius);
        };
        _proto.updateScale = function updateScale() {
          _BulletShape.prototype.updateScale.call(this);
          this.setRadius(this.collider.radius);
        };
        _proto.updateProperties = function updateProperties(radius, height, direction, scale) {
          var ws = scale;
          var upAxis = direction;
          var wr;
          var halfH;
          if (upAxis === 1) {
            wr = radius * Math.abs(absMax(ws.x, ws.z));
            halfH = height / 2 * Math.abs(ws.y);
          } else if (upAxis === 0) {
            wr = radius * Math.abs(absMax(ws.y, ws.z));
            halfH = height / 2 * Math.abs(ws.x);
          } else {
            wr = radius * Math.abs(absMax(ws.x, ws.y));
            halfH = height / 2 * Math.abs(ws.z);
          }
          bt.CapsuleShape_updateProp(this._impl, wr, halfH, upAxis);
          this.updateCompoundTransform();
        };
        _createClass(BulletCapsuleShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }]);
        return BulletCapsuleShape;
      }(BulletShape);

      var BulletBvhTriangleMeshShape = function () {
        BulletBvhTriangleMeshShape.getBulletBvhTriangleMeshShape = function getBulletBvhTriangleMeshShape(key, mesh) {
          var newBulletBvhTriangleMeshShape;
          if (BulletBvhTriangleMeshShape.BulletBvhTriangleMeshShapeMap.has(key)) {
            newBulletBvhTriangleMeshShape = BulletBvhTriangleMeshShape.BulletBvhTriangleMeshShapeMap.get(key);
            newBulletBvhTriangleMeshShape.reference = true;
          } else {
            newBulletBvhTriangleMeshShape = new BulletBvhTriangleMeshShape(key, mesh);
            BulletBvhTriangleMeshShape.BulletBvhTriangleMeshShapeMap.set(key, newBulletBvhTriangleMeshShape);
          }
          return newBulletBvhTriangleMeshShape;
        };
        function BulletBvhTriangleMeshShape(key, mesh) {
          this.key = void 0;
          this.ref = 0;
          this.bulletBvhTriangleMeshShapePtr = void 0;
          this.btTriangleMeshPtr = 0;
          this.reference = true;
          this.key = key;
          this.btTriangleMeshPtr = bt.TriangleMesh_new();
          cocos2BulletTriMesh(this.btTriangleMeshPtr, mesh);
          this.bulletBvhTriangleMeshShapePtr = bt.BvhTriangleMeshShape_new(this.btTriangleMeshPtr, true, true);
        }
        var _proto = BulletBvhTriangleMeshShape.prototype;
        _proto.destroy = function destroy() {
          if (this.bulletBvhTriangleMeshShapePtr) {
            bt._safe_delete(EBulletType.EBulletTypeCollisionShape, this.bulletBvhTriangleMeshShapePtr);
          }
          if (this.btTriangleMeshPtr) {
            bt._safe_delete(EBulletType.EBulletTypeTriangleMesh, this.btTriangleMeshPtr);
          }
          BulletBvhTriangleMeshShape.BulletBvhTriangleMeshShapeMap["delete"](this.key);
        };
        _createClass(BulletBvhTriangleMeshShape, [{
          key: "reference",
          set: function set(v) {
            v ? this.ref++ : this.ref--;
            if (this.ref === 0) {
              this.destroy();
            }
          }
        }]);
        return BulletBvhTriangleMeshShape;
      }();
      BulletBvhTriangleMeshShape.BulletBvhTriangleMeshShapeMap = new Map();

      var BulletTrimeshShape = function (_BulletShape) {
        _inheritsLoose(BulletTrimeshShape, _BulletShape);
        function BulletTrimeshShape() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _BulletShape.call.apply(_BulletShape, [this].concat(args)) || this;
          _this.btBVHMeshShape = void 0;
          _this.refBtTriangleMesh = 0;
          return _this;
        }
        var _proto = BulletTrimeshShape.prototype;
        _proto.setMesh = function setMesh(v) {
          if (!this._isInitialized) return;
          if (this._impl && BulletCache.isNotEmptyShape(this._impl)) {
            if (this._compound) {
              bt.CompoundShape_removeChildShape(this._compound, this._impl);
            }
            bt._safe_delete(this._impl, EBulletType.EBulletTypeCollisionShape);
            BulletCache.delWrapper(this._impl, BulletShape.TYPE);
            this._impl = 0;
          }
          var mesh = v;
          if (mesh && mesh.renderingSubMeshes.length > 0) {
            if (this.collider.convex) {
              var btTriangleMesh = this._getBtTriangleMesh(mesh);
              this._impl = bt.ConvexTriangleMeshShape_new(btTriangleMesh);
            } else {
              this.btBVHMeshShape = BulletBvhTriangleMeshShape.getBulletBvhTriangleMeshShape(mesh.hash, mesh);
              this._impl = bt.ScaledBvhTriangleMeshShape_new(this.btBVHMeshShape.bulletBvhTriangleMeshShapePtr, 1, 1, 1);
            }
            var bt_v3 = BulletCache.instance.BT_V3_0;
            cocos2BulletVec3(bt_v3, this._collider.node.worldScale);
            bt.CollisionShape_setLocalScaling(this._impl, bt_v3);
            bt.CollisionShape_setMargin(this._impl, 0.01);
            this.setCompound(this._compound);
            this.updateByReAdd();
            this.setWrapper();
          } else {
            this._impl = bt.EmptyShape_static();
          }
        };
        _proto.onComponentSet = function onComponentSet() {
          this.setMesh(this.collider.mesh);
        };
        _proto.onDestroy = function onDestroy() {
          if (this.collider.convex) {
            if (this.refBtTriangleMesh) {
              bt._safe_delete(this.refBtTriangleMesh, EBulletType.EBulletTypeTriangleMesh);
            }
          } else if (this.btBVHMeshShape) {
            this.btBVHMeshShape.reference = false;
          }
          _BulletShape.prototype.onDestroy.call(this);
        };
        _proto.updateScale = function updateScale() {
          _BulletShape.prototype.updateScale.call(this);
          var bt_v3 = BulletCache.instance.BT_V3_0;
          cocos2BulletVec3(bt_v3, this._collider.node.worldScale);
          bt.CollisionShape_setLocalScaling(this._impl, bt_v3);
          this.updateCompoundTransform();
        };
        _proto._getBtTriangleMesh = function _getBtTriangleMesh(mesh) {
          this.refBtTriangleMesh = bt.TriangleMesh_new();
          cocos2BulletTriMesh(this.refBtTriangleMesh, mesh);
          return this.refBtTriangleMesh;
        };
        _createClass(BulletTrimeshShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }]);
        return BulletTrimeshShape;
      }(BulletShape);

      var BulletCylinderShape = function (_BulletShape) {
        _inheritsLoose(BulletCylinderShape, _BulletShape);
        function BulletCylinderShape() {
          return _BulletShape.apply(this, arguments) || this;
        }
        var _proto = BulletCylinderShape.prototype;
        _proto.setHeight = function setHeight(v) {
          this.updateProperties(this.collider.radius, this.collider.height, this.collider.direction, this._collider.node.worldScale);
        };
        _proto.setDirection = function setDirection(v) {
          this.updateProperties(this.collider.radius, this.collider.height, this.collider.direction, this._collider.node.worldScale);
        };
        _proto.setRadius = function setRadius(v) {
          this.updateProperties(this.collider.radius, this.collider.height, this.collider.direction, this._collider.node.worldScale);
        };
        _proto.onComponentSet = function onComponentSet() {
          var bt_v3 = BulletCache.instance.BT_V3_0;
          bt.Vec3_set(bt_v3, 0.5, 1, 0.5);
          this._impl = bt.CylinderShape_new(bt_v3);
          this.setRadius(this.collider.radius);
        };
        _proto.updateScale = function updateScale() {
          _BulletShape.prototype.updateScale.call(this);
          this.setRadius(this.collider.radius);
        };
        _proto.updateProperties = function updateProperties(radius, height, direction, scale) {
          var ws = scale;
          var upAxis = direction;
          var wr;
          var wh;
          if (upAxis === 1) {
            wh = height * Math.abs(ws.y);
            wr = radius * Math.abs(absMax(ws.x, ws.z));
          } else if (upAxis === 0) {
            wh = height * Math.abs(ws.x);
            wr = radius * Math.abs(absMax(ws.y, ws.z));
          } else {
            wh = height * Math.abs(ws.z);
            wr = radius * Math.abs(absMax(ws.x, ws.y));
          }
          bt.CylinderShape_updateProp(this._impl, wr, wh / 2, upAxis);
          this.updateCompoundTransform();
        };
        _createClass(BulletCylinderShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }]);
        return BulletCylinderShape;
      }(BulletShape);

      var BulletConeShape = function (_BulletShape) {
        _inheritsLoose(BulletConeShape, _BulletShape);
        function BulletConeShape() {
          return _BulletShape.apply(this, arguments) || this;
        }
        var _proto = BulletConeShape.prototype;
        _proto.setHeight = function setHeight(v) {
          this.updateProperties(this.collider.radius, this.collider.height, this.collider.direction, this._collider.node.worldScale);
        };
        _proto.setDirection = function setDirection(v) {
          this.updateProperties(this.collider.radius, this.collider.height, this.collider.direction, this._collider.node.worldScale);
        };
        _proto.setRadius = function setRadius(v) {
          this.updateProperties(this.collider.radius, this.collider.height, this.collider.direction, this._collider.node.worldScale);
        };
        _proto.onComponentSet = function onComponentSet() {
          this._impl = bt.ConeShape_new(0.5, 1);
          this.setRadius(this.collider.radius);
        };
        _proto.updateScale = function updateScale() {
          _BulletShape.prototype.updateScale.call(this);
          this.setRadius(this.collider.radius);
        };
        _proto.updateProperties = function updateProperties(radius, height, direction, scale) {
          var ws = scale;
          var upAxis = direction;
          var wr;
          var wh;
          if (upAxis === 1) {
            wh = height * Math.abs(ws.y);
            wr = radius * Math.abs(absMax(ws.x, ws.z));
          } else if (upAxis === 0) {
            wh = height * Math.abs(ws.x);
            wr = radius * Math.abs(absMax(ws.y, ws.z));
          } else {
            wh = height * Math.abs(ws.z);
            wr = radius * Math.abs(absMax(ws.x, ws.y));
          }
          bt.ConeShape_setRadius(this._impl, wr);
          bt.ConeShape_setHeight(this._impl, wh);
          bt.ConeShape_setConeUpIndex(this._impl, upAxis);
          var bt_v3 = BulletCache.instance.BT_V3_0;
          bt.Vec3_set(bt_v3, 1, 1, 1);
          bt.CollisionShape_setLocalScaling(this._impl, bt_v3);
          this.updateCompoundTransform();
        };
        _createClass(BulletConeShape, [{
          key: "impl",
          get: function get() {
            return this._impl;
          }
        }, {
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }]);
        return BulletConeShape;
      }(BulletShape);

      var BulletTerrainShape = function (_BulletShape) {
        _inheritsLoose(BulletTerrainShape, _BulletShape);
        function BulletTerrainShape() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _BulletShape.call.apply(_BulletShape, [this].concat(args)) || this;
          _this._bufPtr = 0;
          _this._tileSize = 0;
          _this._localOffset = new Vec3();
          return _this;
        }
        var _proto = BulletTerrainShape.prototype;
        _proto.setTerrain = function setTerrain(v) {
          if (!this._isInitialized) return;
          if (this._impl && BulletCache.isNotEmptyShape(this._impl)) {
            warn('[Physics][Bullet]: change the terrain asset after initialization is not support.');
          } else {
            var terrain = v;
            if (terrain) {
              this._tileSize = terrain.tileSize;
              var sizeI = terrain.getVertexCountI();
              var sizeJ = terrain.getVertexCountJ();
              this._bufPtr = bt._malloc(4 * sizeI * sizeJ);
              var offset = 0;
              var min = Number.MAX_SAFE_INTEGER;
              var max = Number.MIN_SAFE_INTEGER;
              for (var j = 0; j < sizeJ; j++) {
                for (var i = 0; i < sizeI; i++) {
                  var _v = terrain.getHeight(i, j);
                  bt._write_f32(this._bufPtr + offset, _v);
                  if (min > _v) min = _v;
                  if (_v > max) max = _v;
                  offset += 4;
                }
              }
              max += 0.01;
              min -= 0.01;
              this._localOffset.set((sizeI - 1) / 2 * this._tileSize, (max + min) / 2, (sizeJ - 1) / 2 * this._tileSize);
              this._impl = bt.TerrainShape_new(sizeI, sizeJ, this._bufPtr, 1, min, max);
              var bt_v3 = BulletCache.instance.BT_V3_0;
              bt.Vec3_set(bt_v3, this._tileSize, 1, this._tileSize);
              bt.CollisionShape_setLocalScaling(this._impl, bt_v3);
              this.setCompound(this._compound);
              this.updateByReAdd();
              this.setWrapper();
            } else {
              this._impl = bt.EmptyShape_static();
            }
          }
        };
        _proto.onComponentSet = function onComponentSet() {
          this.setTerrain(this.collider.terrain);
        };
        _proto.onDestroy = function onDestroy() {
          if (this._bufPtr) bt._free(this._bufPtr);
          _BulletShape.prototype.onDestroy.call(this);
        };
        _proto.setCenter = function setCenter(v) {
          Vec3.copy(CC_V3_0, v);
          CC_V3_0.add(this._localOffset);
          cocos2BulletVec3(bt.Transform_getOrigin(this.transform), CC_V3_0);
          this.updateCompoundTransform();
        };
        _createClass(BulletTerrainShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }]);
        return BulletTerrainShape;
      }(BulletShape);

      var BulletSimplexShape = function (_BulletShape) {
        _inheritsLoose(BulletSimplexShape, _BulletShape);
        function BulletSimplexShape() {
          return _BulletShape.apply(this, arguments) || this;
        }
        var _proto = BulletSimplexShape.prototype;
        _proto.setShapeType = function setShapeType(v) {};
        _proto.setVertices = function setVertices(v) {};
        _proto.onComponentSet = function onComponentSet() {
          this._impl = bt.SimplexShape_new();
          var length = this.collider.shapeType;
          var vertices = this.collider.vertices;
          var bt_v3 = BulletCache.instance.BT_V3_0;
          for (var i = 0; i < length; i++) {
            bt.SimplexShape_addVertex(this._impl, cocos2BulletVec3(bt_v3, vertices[i]));
          }
          bt.CollisionShape_setLocalScaling(this._impl, cocos2BulletVec3(bt_v3, this._collider.node.worldScale));
        };
        _proto.onLoad = function onLoad() {
          _BulletShape.prototype.onLoad.call(this);
          this.collider.updateVertices();
        };
        _proto.updateScale = function updateScale() {
          _BulletShape.prototype.updateScale.call(this);
          var bt_v3 = BulletCache.instance.BT_V3_0;
          bt.CollisionShape_setLocalScaling(this._impl, cocos2BulletVec3(bt_v3, this._collider.node.worldScale));
        };
        _createClass(BulletSimplexShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }]);
        return BulletSimplexShape;
      }(BulletShape);

      var BulletPlaneShape = function (_BulletShape) {
        _inheritsLoose(BulletPlaneShape, _BulletShape);
        function BulletPlaneShape() {
          return _BulletShape.apply(this, arguments) || this;
        }
        var _proto = BulletPlaneShape.prototype;
        _proto.setNormal = function setNormal(v) {
          cocos2BulletVec3(bt.StaticPlaneShape_getPlaneNormal(this.impl), v);
          this.updateCompoundTransform();
        };
        _proto.setConstant = function setConstant(v) {
          bt.StaticPlaneShape_setPlaneConstant(this.impl, v);
          this.updateCompoundTransform();
        };
        _proto.updateScale = function updateScale() {
          _BulletShape.prototype.updateScale.call(this);
          var bt_v3 = BulletCache.instance.BT_V3_0;
          cocos2BulletVec3(bt_v3, this._collider.node.worldScale);
          bt.CollisionShape_setLocalScaling(this._impl, bt_v3);
          this.updateCompoundTransform();
        };
        _proto.onComponentSet = function onComponentSet() {
          var normal = BulletCache.instance.BT_V3_0;
          cocos2BulletVec3(normal, this.collider.normal);
          this._impl = bt.StaticPlaneShape_new(normal, this.collider.constant);
          this.updateScale();
        };
        _createClass(BulletPlaneShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }]);
        return BulletPlaneShape;
      }(BulletShape);

      var BulletConstraint = function () {
        function BulletConstraint() {
          this.dirty = 0;
          this.index = -1;
          this._impl = 0;
          this._com = void 0;
          this._rigidBody = void 0;
          this._connectedBody = null;
          this._collided = false;
        }
        var _proto = BulletConstraint.prototype;
        _proto.setConnectedBody = function setConnectedBody(v) {
          if (this._connectedBody === v) return;
          var oldBody2 = this._connectedBody;
          if (oldBody2) {
            var oldSB2 = oldBody2.body.sharedBody;
            oldSB2.removeJoint(this, 1);
          }
          var sb = this._rigidBody.body.sharedBody;
          sb.removeJoint(this, 0);
          if (this._impl) {
            sb.wrappedWorld.removeConstraint(this);
            bt._safe_delete(this._impl, EBulletType.EBulletTypeTypedConstraint);
          }
          this._connectedBody = v;
          var connect = this._connectedBody;
          this.onComponentSet();
          this.setEnableCollision(this._collided);
          sb.wrappedWorld.addConstraint(this);
          sb.addJoint(this, 0);
          if (connect) {
            var sb2 = connect.body.sharedBody;
            sb2.addJoint(this, 1);
          }
        };
        _proto.setEnableCollision = function setEnableCollision(v) {
          if (this._collided !== v) {
            this._collided = v;
            this.updateByReAdd();
          }
        };
        _proto.updateByReAdd = function updateByReAdd() {
          if (this._rigidBody && this.index >= 0) {
            var sb = this._rigidBody.body.sharedBody;
            sb.wrappedWorld.removeConstraint(this);
            sb.wrappedWorld.addConstraint(this);
          }
        };
        _proto.initialize = function initialize(v) {
          this._com = v;
          this._rigidBody = v.attachedBody;
          this._connectedBody = v.connectedBody;
          this._collided = v.enableCollision;
          this.onComponentSet();
          this.setEnableCollision(this._collided);
        };
        _proto.updateDebugDrawSize = function updateDebugDrawSize() {
          if (this.impl) {
            var size = PhysicsSystem.instance.physicsWorld.debugDrawConstraintSize;
            bt.TypedConstraint_setDbgDrawSize(this.impl, size);
          }
        };
        _proto.onEnable = function onEnable() {
          var sb = this._rigidBody.body.sharedBody;
          sb.wrappedWorld.addConstraint(this);
          sb.addJoint(this, 0);
          var connect = this._connectedBody;
          if (connect) {
            var sb2 = connect.body.sharedBody;
            sb2.addJoint(this, 1);
          }
        };
        _proto.onDisable = function onDisable() {
          var sb = this._rigidBody.body.sharedBody;
          sb.wrappedWorld.removeConstraint(this);
          sb.removeJoint(this, 0);
          var connect = this._connectedBody;
          if (connect) {
            var sb2 = connect.body.sharedBody;
            sb2.removeJoint(this, 1);
          }
        };
        _proto.onDestroy = function onDestroy() {
          bt._safe_delete(this._impl, EBulletType.EBulletTypeTypedConstraint);
          this._com = null;
          this._rigidBody = null;
          this._connectedBody = null;
        };
        _createClass(BulletConstraint, [{
          key: "impl",
          get: function get() {
            return this._impl;
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._com;
          }
        }]);
        return BulletConstraint;
      }();

      var BulletP2PConstraint = function (_BulletConstraint) {
        _inheritsLoose(BulletP2PConstraint, _BulletConstraint);
        function BulletP2PConstraint() {
          return _BulletConstraint.apply(this, arguments) || this;
        }
        var _proto = BulletP2PConstraint.prototype;
        _proto.setPivotA = function setPivotA(v) {
          var cs = this.constraint;
          var pivotA = BulletCache.instance.BT_V3_0;
          Vec3.multiply(CC_V3_0, cs.node.worldScale, cs.pivotA);
          cocos2BulletVec3(pivotA, CC_V3_0);
          bt.P2PConstraint_setPivotA(this._impl, pivotA);
          if (!cs.connectedBody) this.setPivotB(cs.pivotB);
        };
        _proto.setPivotB = function setPivotB(v) {
          var cs = this.constraint;
          var node = this._rigidBody.node;
          var pivotB = BulletCache.instance.BT_V3_0;
          var cb = cs.connectedBody;
          if (cb) {
            Vec3.multiply(CC_V3_0, cb.node.worldScale, cs.pivotB);
            cocos2BulletVec3(pivotB, CC_V3_0);
          } else {
            Vec3.multiply(CC_V3_0, node.worldScale, cs.pivotA);
            Vec3.transformQuat(CC_V3_0, CC_V3_0, node.worldRotation);
            Vec3.add(CC_V3_0, CC_V3_0, node.worldPosition);
            cocos2BulletVec3(pivotB, CC_V3_0);
          }
          bt.P2PConstraint_setPivotB(this._impl, pivotB);
        };
        _proto.onComponentSet = function onComponentSet() {
          var cb = this.constraint.connectedBody;
          var bodyA = this._rigidBody.body.impl;
          var bodyB = cb ? cb.body.impl : bt.TypedConstraint_getFixedBody();
          var pivotA = BulletCache.instance.BT_V3_0;
          var pivotB = BulletCache.instance.BT_V3_1;
          this._impl = bt.P2PConstraint_new(bodyA, bodyB, pivotA, pivotB);
          this.setPivotA(this.constraint.pivotA);
          this.setPivotB(this.constraint.pivotB);
          this.updateDebugDrawSize();
        };
        _proto.updateScale0 = function updateScale0() {
          this.setPivotA(this.constraint.pivotA);
        };
        _proto.updateScale1 = function updateScale1() {
          this.setPivotB(this.constraint.pivotB);
        };
        _createClass(BulletP2PConstraint, [{
          key: "constraint",
          get: function get() {
            return this._com;
          }
        }]);
        return BulletP2PConstraint;
      }(BulletConstraint);

      var BulletFixedConstraint = function (_BulletConstraint) {
        _inheritsLoose(BulletFixedConstraint, _BulletConstraint);
        function BulletFixedConstraint() {
          return _BulletConstraint.apply(this, arguments) || this;
        }
        var _proto = BulletFixedConstraint.prototype;
        _proto.setBreakForce = function setBreakForce(v) {
          bt.TypedConstraint_setMaxImpulseThreshold(this._impl, v);
        };
        _proto.setBreakTorque = function setBreakTorque(v) {};
        _proto.onComponentSet = function onComponentSet() {
          var cb = this.constraint.connectedBody;
          var bodyA = this._rigidBody.body.impl;
          var bodyB = cb ? cb.body.impl : bt.TypedConstraint_getFixedBody();
          var trans0 = BulletCache.instance.BT_TRANSFORM_0;
          var trans1 = BulletCache.instance.BT_TRANSFORM_1;
          this._impl = bt.FixedConstraint_new(bodyA, bodyB, trans0, trans1);
          this.setBreakForce(this.constraint.breakForce);
          this.setBreakTorque(this.constraint.breakTorque);
          this.updateFrames();
          this.updateDebugDrawSize();
        };
        _proto.updateFrames = function updateFrames() {
          var cb = this.constraint.connectedBody;
          var bodyA = this._rigidBody.body.sharedBody;
          var pos = CC_V3_0;
          var rot = CC_QUAT_0;
          var trans0 = BulletCache.instance.BT_TRANSFORM_0;
          var trans1 = BulletCache.instance.BT_TRANSFORM_1;
          var quat = BulletCache.instance.BT_QUAT_0;
          var trans = CC_MAT4_0;
          Mat4.fromRT(trans, bodyA.node.worldRotation, bodyA.node.worldPosition);
          Mat4.invert(trans, trans);
          Mat4.getRotation(rot, trans);
          Mat4.getTranslation(pos, trans);
          cocos2BulletVec3(bt.Transform_getOrigin(trans0), pos);
          cocos2BulletQuat(quat, rot);
          bt.Transform_setRotation(trans0, quat);
          if (cb) {
            var bodyB = cb.body.sharedBody;
            Mat4.fromRT(trans, bodyB.node.worldRotation, bodyB.node.worldPosition);
            Mat4.invert(trans, trans);
            Mat4.getRotation(rot, trans);
            Mat4.getTranslation(pos, trans);
            cocos2BulletVec3(bt.Transform_getOrigin(trans1), pos);
            cocos2BulletQuat(quat, rot);
            bt.Transform_setRotation(trans1, quat);
          } else {
            bt.Transform_setIdentity(trans1);
          }
          bt.FixedConstraint_setFrames(this._impl, trans0, trans1);
        };
        _proto.updateScale0 = function updateScale0() {
          this.updateFrames();
        };
        _proto.updateScale1 = function updateScale1() {
          this.updateFrames();
        };
        _createClass(BulletFixedConstraint, [{
          key: "constraint",
          get: function get() {
            return this._com;
          }
        }]);
        return BulletFixedConstraint;
      }(BulletConstraint);

      var BulletHingeConstraint = function (_BulletConstraint) {
        _inheritsLoose(BulletHingeConstraint, _BulletConstraint);
        function BulletHingeConstraint() {
          return _BulletConstraint.apply(this, arguments) || this;
        }
        var _proto = BulletHingeConstraint.prototype;
        _proto.setPivotA = function setPivotA(v) {
          this.updateFrames();
        };
        _proto.setPivotB = function setPivotB(v) {
          this.updateFrames();
        };
        _proto.setAxis = function setAxis(v) {
          this.updateFrames();
        };
        _proto.setLimitEnabled = function setLimitEnabled(v) {
          if (this.constraint.limitEnabled) {
            bt.HingeConstraint_setLimit(this._impl, toRadian(this.constraint.lowerLimit), toRadian(this.constraint.upperLimit), 0.9, 0.3, 1.0);
          } else {
            bt.HingeConstraint_setLimit(this._impl, 1, 0, 0.9, 0.3, 1.0);
          }
        };
        _proto.setLowerLimit = function setLowerLimit(min) {
          if (this.constraint.limitEnabled) {
            bt.HingeConstraint_setLimit(this._impl, toRadian(this.constraint.lowerLimit), toRadian(this.constraint.upperLimit), 0.9, 0.3, 1.0);
          }
        };
        _proto.setUpperLimit = function setUpperLimit(max) {
          if (this.constraint.limitEnabled) {
            bt.HingeConstraint_setLimit(this._impl, toRadian(this.constraint.lowerLimit), toRadian(this.constraint.upperLimit), 0.9, 0.3, 1.0);
          }
        };
        _proto.setMotorEnabled = function setMotorEnabled(v) {
          bt.HingeConstraint_enableMotor(this._impl, v);
          var velocity = -this.constraint.motorVelocity / 60.0;
          var impulse = force2Impulse(this.constraint.motorForceLimit, PhysicsSystem.instance.fixedTimeStep);
          bt.HingeConstraint_setMotorVelocity(this._impl, velocity);
          bt.HingeConstraint_setMaxMotorImpulse(this._impl, impulse);
        };
        _proto.setMotorVelocity = function setMotorVelocity(v) {
          if (this.constraint.motorEnabled) {
            var velocity = -v / 60.0;
            bt.HingeConstraint_setMotorVelocity(this._impl, velocity);
          }
        };
        _proto.setMotorForceLimit = function setMotorForceLimit(v) {
          if (this.constraint.motorEnabled) {
            var impulse = force2Impulse(v, PhysicsSystem.instance.fixedTimeStep);
            bt.HingeConstraint_setMaxMotorImpulse(this._impl, impulse);
          }
        };
        _proto.onComponentSet = function onComponentSet() {
          var cb = this.constraint.connectedBody;
          var bodyA = this._rigidBody.body.impl;
          var bodyB = cb ? cb.body.impl : bt.TypedConstraint_getFixedBody();
          var trans0 = BulletCache.instance.BT_TRANSFORM_0;
          var trans1 = BulletCache.instance.BT_TRANSFORM_1;
          this._impl = bt.HingeConstraint_new(bodyA, bodyB, trans0, trans1);
          this.setLimitEnabled(this.constraint.limitEnabled);
          this.setLowerLimit(this.constraint.lowerLimit);
          this.setUpperLimit(this.constraint.upperLimit);
          this.setMotorEnabled(this.constraint.motorEnabled);
          this.setMotorVelocity(this.constraint.motorVelocity);
          this.setMotorForceLimit(this.constraint.motorForceLimit);
          this.updateFrames();
          this.updateDebugDrawSize();
        };
        _proto.updateFrames = function updateFrames() {
          var cs = this.constraint;
          var node = cs.node;
          var v3_0 = CC_V3_0;
          var rot_0 = CC_QUAT_0;
          var rot_1 = CC_QUAT_1;
          var trans0 = BulletCache.instance.BT_TRANSFORM_0;
          Vec3.multiply(v3_0, node.worldScale, cs.pivotA);
          cocos2BulletVec3(bt.Transform_getOrigin(trans0), v3_0);
          var quat = BulletCache.instance.BT_QUAT_0;
          Vec3.normalize(v3_0, cs.axis);
          Quat.rotationTo(rot_1, Vec3.UNIT_Z, v3_0);
          cocos2BulletQuat(quat, rot_1);
          bt.Transform_setRotation(trans0, quat);
          var trans1 = BulletCache.instance.BT_TRANSFORM_1;
          var cb = this.constraint.connectedBody;
          if (cb) {
            Vec3.multiply(v3_0, cb.node.worldScale, cs.pivotB);
            Quat.multiply(rot_1, node.worldRotation, rot_1);
            Quat.invert(rot_0, cb.node.worldRotation);
            Quat.multiply(rot_1, rot_0, rot_1);
          } else {
            Vec3.multiply(v3_0, node.worldScale, cs.pivotA);
            Vec3.transformQuat(v3_0, v3_0, node.worldRotation);
            Vec3.add(v3_0, v3_0, node.worldPosition);
            Quat.multiply(rot_1, node.worldRotation, rot_1);
          }
          cocos2BulletVec3(bt.Transform_getOrigin(trans1), v3_0);
          cocos2BulletQuat(quat, rot_1);
          bt.Transform_setRotation(trans1, quat);
          bt.HingeConstraint_setFrames(this._impl, trans0, trans1);
        };
        _proto.updateScale0 = function updateScale0() {
          this.updateFrames();
        };
        _proto.updateScale1 = function updateScale1() {
          this.updateFrames();
        };
        _createClass(BulletHingeConstraint, [{
          key: "constraint",
          get: function get() {
            return this._com;
          }
        }]);
        return BulletHingeConstraint;
      }(BulletConstraint);

      var RotateOrder;
      (function (RotateOrder) {
        RotateOrder[RotateOrder["RO_XYZ"] = 0] = "RO_XYZ";
        RotateOrder[RotateOrder["RO_XZY"] = 1] = "RO_XZY";
        RotateOrder[RotateOrder["RO_YXZ"] = 2] = "RO_YXZ";
        RotateOrder[RotateOrder["RO_YZX"] = 3] = "RO_YZX";
        RotateOrder[RotateOrder["RO_ZXY"] = 4] = "RO_ZXY";
        RotateOrder[RotateOrder["RO_ZYX"] = 5] = "RO_ZYX";
      })(RotateOrder || (RotateOrder = {}));
      var BulletDofAxis;
      (function (BulletDofAxis) {
        BulletDofAxis[BulletDofAxis["X"] = 0] = "X";
        BulletDofAxis[BulletDofAxis["Y"] = 1] = "Y";
        BulletDofAxis[BulletDofAxis["Z"] = 2] = "Z";
        BulletDofAxis[BulletDofAxis["TWIST"] = 3] = "TWIST";
        BulletDofAxis[BulletDofAxis["SWING1"] = 4] = "SWING1";
        BulletDofAxis[BulletDofAxis["SWING2"] = 5] = "SWING2";
      })(BulletDofAxis || (BulletDofAxis = {}));
      var BulletConfigurableConstraint = function (_BulletConstraint) {
        _inheritsLoose(BulletConfigurableConstraint, _BulletConstraint);
        function BulletConfigurableConstraint() {
          return _BulletConstraint.apply(this, arguments) || this;
        }
        var _proto = BulletConfigurableConstraint.prototype;
        _proto._setLimit = function _setLimit(v, axis, lower, upper) {
          switch (v) {
            case EConstraintMode.LOCKED:
              bt.Generic6DofSpring2Constraint_setLimit(this._impl, axis, 0, 0);
              break;
            case EConstraintMode.LIMITED:
              bt.Generic6DofSpring2Constraint_setLimit(this._impl, axis, lower, upper);
              break;
            case EConstraintMode.FREE:
              bt.Generic6DofSpring2Constraint_setLimit(this._impl, axis, 1, 0);
              break;
          }
        };
        _proto.setConstraintMode = function setConstraintMode(idx, v) {
          var ll = this.constraint.linearLimitSettings;
          var al = this.constraint.angularLimitSettings;
          var lowers = [0, 0, 0];
          var uppers = [0, 0, 0];
          var upper = 0;
          var lower = 0;
          switch (idx) {
            case 0:
            case 1:
            case 2:
              Vec3.toArray(lowers, ll.lower);
              Vec3.toArray(uppers, ll.upper);
              lower = lowers[idx];
              upper = uppers[idx];
              break;
            case 3:
              upper = toRadian(al.twistExtent) * 0.5;
              lower = -upper;
              break;
            case 4:
              upper = toRadian(al.swingExtent1) * 0.5;
              lower = -upper;
              break;
            case 5:
              upper = toRadian(al.swingExtent2) * 0.5;
              lower = -upper;
              break;
            default:
              error("idx should be in [0, 5], but give " + idx);
              break;
          }
          this._setLimit(v, idx, lower, upper);
        };
        _proto.setLinearLimit = function setLinearLimit(idx, lower, upper) {
          var cm = 0;
          var ll = this.constraint.linearLimitSettings;
          switch (idx) {
            case 0:
              cm = ll.xMotion;
              break;
            case 1:
              cm = ll.yMotion;
              break;
            case 2:
              cm = ll.zMotion;
              break;
          }
          this._setLimit(cm, idx, lower, upper);
        };
        _proto.setAngularExtent = function setAngularExtent(twist, swing1, swing2) {
          var al = this.constraint.angularLimitSettings;
          this._setLimit(al.twistMotion, BulletDofAxis.TWIST, -toRadian(twist) * 0.5, toRadian(twist) * 0.5);
          this._setLimit(al.swingMotion1, BulletDofAxis.SWING1, -toRadian(swing1) * 0.5, toRadian(swing1) * 0.5);
          this._setLimit(al.swingMotion2, BulletDofAxis.SWING2, -toRadian(swing2) * 0.5, toRadian(swing2) * 0.5);
        };
        _proto.setSwingSoftConstraint = function setSwingSoftConstraint(v) {
          bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.SWING1, v);
          bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.SWING2, v);
        };
        _proto.setTwistSoftConstraint = function setTwistSoftConstraint(v) {
          bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.TWIST, v);
        };
        _proto.setLinearSoftConstraint = function setLinearSoftConstraint(v) {
          bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.X, v);
          bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.Y, v);
          bt.Generic6DofSpring2Constraint_enableSpring(this._impl, BulletDofAxis.Z, v);
        };
        _proto.setLinearStiffness = function setLinearStiffness(v) {
          bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.X, v);
          bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.Y, v);
          bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.Z, v);
        };
        _proto.setLinearDamping = function setLinearDamping(v) {
          bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.X, v);
          bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.Y, v);
          bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.Z, v);
        };
        _proto.setLinearRestitution = function setLinearRestitution(v) {
          bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.X, v);
          bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.Y, v);
          bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.Z, v);
        };
        _proto.setSwingStiffness = function setSwingStiffness(v) {
          bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.SWING1, v);
          bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.SWING2, v);
        };
        _proto.setSwingDamping = function setSwingDamping(v) {
          bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.SWING1, v);
          bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.SWING2, v);
        };
        _proto.setSwingRestitution = function setSwingRestitution(v) {
          bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.SWING1, v);
          bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.SWING2, v);
        };
        _proto.setTwistStiffness = function setTwistStiffness(v) {
          bt.Generic6DofSpring2Constraint_setStiffness(this._impl, BulletDofAxis.TWIST, v);
        };
        _proto.setTwistDamping = function setTwistDamping(v) {
          bt.Generic6DofSpring2Constraint_setDamping(this._impl, BulletDofAxis.TWIST, v);
        };
        _proto.setTwistRestitution = function setTwistRestitution(v) {
          bt.Generic6DofSpring2Constraint_setBounce(this._impl, BulletDofAxis.TWIST, v);
        };
        _proto.setDriverMode = function setDriverMode(idx, v) {
          if (v === EDriverMode.DISABLED) {
            bt.Generic6DofSpring2Constraint_enableMotor(this._impl, idx, false);
          } else if (v === EDriverMode.SERVO) {
            bt.Generic6DofSpring2Constraint_enableMotor(this._impl, idx, true);
            bt.Generic6DofSpring2Constraint_setServo(this._impl, idx, true);
          } else if (v === EDriverMode.INDUCTION) {
            bt.Generic6DofSpring2Constraint_enableMotor(this._impl, idx, true);
            bt.Generic6DofSpring2Constraint_setServo(this._impl, idx, false);
          }
        };
        _proto._updateMotorTargetAndVelocity = function _updateMotorTargetAndVelocity(index) {
          var mode = EDriverMode.DISABLED;
          var axis = 0;
          var target = 0;
          var velocity = 0;
          var ld = this.constraint.linearDriverSettings;
          var ad = this.constraint.angularDriverSettings;
          switch (index) {
            case 0:
              axis = BulletDofAxis.X;
              mode = ld.xDrive;
              target = ld.targetPosition.x;
              velocity = -ld.targetVelocity.x;
              break;
            case 1:
              axis = BulletDofAxis.Y;
              mode = ld.yDrive;
              target = ld.targetPosition.y;
              velocity = -ld.targetVelocity.y;
              break;
            case 2:
              axis = BulletDofAxis.Z;
              mode = ld.zDrive;
              target = ld.targetPosition.z;
              velocity = -ld.targetVelocity.z;
              break;
            case 3:
              axis = BulletDofAxis.TWIST;
              mode = ad.twistDrive;
              target = -toRadian(ad.targetOrientation.x);
              velocity = -toRadian(ad.targetVelocity.x);
              break;
            case 4:
              axis = BulletDofAxis.SWING1;
              mode = ad.swingDrive1;
              target = -toRadian(ad.targetOrientation.y);
              velocity = -toRadian(ad.targetVelocity.y);
              break;
            case 5:
              axis = BulletDofAxis.SWING2;
              mode = ad.swingDrive2;
              target = -toRadian(ad.targetOrientation.z);
              velocity = -toRadian(ad.targetVelocity.z);
              break;
          }
          var strength = index > 2 ? ad.strength : ld.strength;
          bt.Generic6DofSpring2Constraint_setServoTarget(this._impl, axis, target);
          if (mode === EDriverMode.SERVO) {
            if (index > 2) {
              bt.Generic6DofSpring2Constraint_setTargetVelocity(this._impl, axis, -target * strength * 0.1);
            } else {
              bt.Generic6DofSpring2Constraint_setTargetVelocity(this._impl, axis, target * strength * 0.1);
            }
          } else if (mode === EDriverMode.INDUCTION) {
            bt.Generic6DofSpring2Constraint_setTargetVelocity(this._impl, axis, velocity);
          }
        };
        _proto.setLinearMotorTarget = function setLinearMotorTarget(v) {
          this._updateMotorTargetAndVelocity(0);
          this._updateMotorTargetAndVelocity(1);
          this._updateMotorTargetAndVelocity(2);
        };
        _proto.setLinearMotorVelocity = function setLinearMotorVelocity(v) {
          this._updateMotorTargetAndVelocity(0);
          this._updateMotorTargetAndVelocity(1);
          this._updateMotorTargetAndVelocity(2);
        };
        _proto.setLinearMotorForceLimit = function setLinearMotorForceLimit(v) {
          bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.X, v);
          bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.Y, v);
          bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.Z, v);
        };
        _proto.setAngularMotorTarget = function setAngularMotorTarget(v) {
          this._updateMotorTargetAndVelocity(3);
          this._updateMotorTargetAndVelocity(4);
          this._updateMotorTargetAndVelocity(5);
        };
        _proto.setAngularMotorVelocity = function setAngularMotorVelocity(v) {
          this._updateMotorTargetAndVelocity(3);
          this._updateMotorTargetAndVelocity(4);
          this._updateMotorTargetAndVelocity(5);
        };
        _proto.setAngularMotorForceLimit = function setAngularMotorForceLimit(v) {
          bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.TWIST, v);
          bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.SWING1, v);
          bt.Generic6DofSpring2Constraint_setMaxMotorForce(this._impl, BulletDofAxis.SWING2, v);
        };
        _proto.setPivotA = function setPivotA(v) {
          this.updateFrames();
        };
        _proto.setPivotB = function setPivotB(v) {
          this.updateFrames();
        };
        _proto.setAutoPivotB = function setAutoPivotB(v) {
          this.updateFrames();
        };
        _proto.setAxis = function setAxis(v) {
          this.updateFrames();
        };
        _proto.setSecondaryAxis = function setSecondaryAxis(v) {
          this.updateFrames();
        };
        _proto.setBreakForce = function setBreakForce(v) {
          var maxForce = Math.max(this.constraint.breakForce, this.constraint.breakTorque);
          var impulse = force2Impulse(maxForce, PhysicsSystem.instance.fixedTimeStep);
          bt.TypedConstraint_setMaxImpulseThreshold(this._impl, impulse);
        };
        _proto.setBreakTorque = function setBreakTorque(v) {
          var maxForce = Math.max(this.constraint.breakForce, this.constraint.breakTorque);
          var impulse = force2Impulse(maxForce, PhysicsSystem.instance.fixedTimeStep);
          bt.TypedConstraint_setMaxImpulseThreshold(this._impl, impulse);
        };
        _proto.onComponentSet = function onComponentSet() {
          var cb = this.constraint.connectedBody;
          var bodyA = this._rigidBody.body.impl;
          var bodyB = cb && cb.body.impl || bt.TypedConstraint_getFixedBody();
          var trans0 = BulletCache.instance.BT_TRANSFORM_0;
          var trans1 = BulletCache.instance.BT_TRANSFORM_1;
          this._impl = bt.Generic6DofSpring2Constraint_new(bodyA, bodyB, trans0, trans1, RotateOrder.RO_YZX);
          var linearLimit = this.constraint.linearLimitSettings;
          var angularLimit = this.constraint.angularLimitSettings;
          this.setConstraintMode(0, linearLimit.xMotion);
          this.setConstraintMode(1, linearLimit.yMotion);
          this.setConstraintMode(2, linearLimit.zMotion);
          this.setConstraintMode(3, angularLimit.twistMotion);
          this.setConstraintMode(4, angularLimit.swingMotion1);
          this.setConstraintMode(5, angularLimit.swingMotion2);
          this.setLinearSoftConstraint(linearLimit.enableSoftConstraint);
          this.setLinearStiffness(linearLimit.stiffness);
          this.setLinearDamping(linearLimit.damping);
          this.setLinearRestitution(linearLimit.restitution);
          this.setSwingSoftConstraint(angularLimit.enableSoftConstraintSwing);
          this.setSwingRestitution(angularLimit.swingRestitution);
          this.setSwingStiffness(angularLimit.swingStiffness);
          this.setSwingDamping(angularLimit.swingDamping);
          this.setTwistSoftConstraint(angularLimit.enableSoftConstraintTwist);
          this.setTwistRestitution(angularLimit.twistRestitution);
          this.setTwistStiffness(angularLimit.twistStiffness);
          this.setTwistDamping(angularLimit.twistDamping);
          var linearMotor = this.constraint.linearDriverSettings;
          var angularMotor = this.constraint.angularDriverSettings;
          this.setDriverMode(0, linearMotor.xDrive);
          this.setDriverMode(1, linearMotor.yDrive);
          this.setDriverMode(2, linearMotor.zDrive);
          this.setDriverMode(3, angularMotor.twistDrive);
          this.setDriverMode(4, angularMotor.swingDrive1);
          this.setDriverMode(5, angularMotor.swingDrive2);
          this.setLinearMotorTarget(linearMotor.targetPosition);
          this.setLinearMotorVelocity(linearMotor.targetVelocity);
          this.setLinearMotorForceLimit(linearMotor.strength);
          this.setAngularMotorTarget(angularMotor.targetOrientation);
          this.setAngularMotorVelocity(angularMotor.targetVelocity);
          this.setAngularMotorForceLimit(angularMotor.strength);
          this.setBreakForce(this.constraint.breakForce);
          this.setBreakTorque(this.constraint.breakTorque);
          this.updateFrames();
          this.updateDebugDrawSize();
        };
        _proto.updateFrames = function updateFrames() {
          var cs = this.constraint;
          var node = cs.node;
          var v3_0 = CC_V3_0;
          var rot_0 = CC_QUAT_0;
          var rot_1 = CC_QUAT_1;
          var trans0 = BulletCache.instance.BT_TRANSFORM_0;
          Vec3.multiply(v3_0, node.worldScale, cs.pivotA);
          cocos2BulletVec3(bt.Transform_getOrigin(trans0), v3_0);
          var quat = BulletCache.instance.BT_QUAT_0;
          var axisX = cs.axis;
          var axisY = cs.secondaryAxis;
          var axisZ = Vec3.cross(CC_V3_1, axisX, axisY);
          var mat = Mat4.set(CC_MAT4_0, axisX.x, axisX.y, axisX.z, 0, axisY.x, axisY.y, axisY.z, 0, axisZ.x, axisZ.y, axisZ.z, 0, 0, 0, 0, 1);
          mat.getRotation(rot_0);
          cocos2BulletQuat(quat, rot_0);
          bt.Transform_setRotation(trans0, quat);
          var trans1 = BulletCache.instance.BT_TRANSFORM_1;
          var cb = this.constraint.connectedBody;
          if (cb) {
            Quat.multiply(rot_0, node.worldRotation, rot_0);
            Quat.invert(rot_1, cb.node.worldRotation);
            Quat.multiply(rot_0, rot_1, rot_0);
            if (cs.autoPivotB) {
              Vec3.multiply(v3_0, cs.node.worldScale, cs.pivotA);
              Vec3.transformQuat(v3_0, v3_0, node.worldRotation);
              Vec3.add(v3_0, v3_0, cs.node.worldPosition);
              Vec3.subtract(v3_0, v3_0, cb.node.worldPosition);
              Vec3.transformQuat(v3_0, v3_0, rot_1);
            } else {
              Vec3.multiply(v3_0, cb.node.worldScale, cs.pivotB);
            }
          } else {
            Vec3.multiply(v3_0, node.worldScale, cs.pivotA);
            Vec3.transformQuat(v3_0, v3_0, node.worldRotation);
            Vec3.add(v3_0, v3_0, node.worldPosition);
            Quat.multiply(rot_0, node.worldRotation, rot_0);
          }
          cocos2BulletVec3(bt.Transform_getOrigin(trans1), v3_0);
          cocos2BulletQuat(quat, rot_0);
          bt.Transform_setRotation(trans1, quat);
          bt.Generic6DofSpring2Constraint_setFrames(this._impl, trans0, trans1);
        };
        _proto.updateScale0 = function updateScale0() {
          this.updateFrames();
        };
        _proto.updateScale1 = function updateScale1() {
          this.updateFrames();
        };
        _createClass(BulletConfigurableConstraint, [{
          key: "constraint",
          get: function get() {
            return this._com;
          }
        }]);
        return BulletConfigurableConstraint;
      }(BulletConstraint);

      var v3_0$2 = new Vec3(0, 0, 0);
      var v3_1 = new Vec3(0, 0, 0);
      new Vec3(0, 0, 0);
      var BulletCharacterController = function () {
        function BulletCharacterController() {
          this.wrappedWorld = void 0;
          this._isEnabled = false;
          this._impl = 0;
          this._comp = null;
          this._btCollisionFlags = 0;
          this._word3 = 0;
          this._dirty = false;
          this._collisionFilterGroup = PhysicsGroup.DEFAULT;
          this._collisionFilterMask = -1;
          this.id = BulletCharacterController.idCounter++;
          this.wrappedWorld = PhysicsSystem.instance.physicsWorld;
        }
        var _proto = BulletCharacterController.prototype;
        _proto.onComponentSet = function onComponentSet() {};
        _proto.updateScale = function updateScale() {};
        _proto.initialize = function initialize(comp) {
          this._comp = comp;
          var group = this._comp.group;
          var mask = PhysicsSystem.instance.collisionMatrix[group];
          this._collisionFilterGroup = group;
          this._collisionFilterMask = mask;
          this.onComponentSet();
          if (this._impl === 0) {
            error('[Physics]: Initialize BulletCharacterController failed');
            return false;
          } else {
            return true;
          }
        };
        _proto.setWrapper = function setWrapper() {
          BulletCache.setWrapper(this._impl, btCache.CCT_CACHE_NAME, this);
          var cctCollisionShapeImpl = bt.CharacterController_getCollisionShape(this.impl);
          BulletCache.setWrapper(cctCollisionShapeImpl, btCache.CCT_CACHE_NAME, this);
        };
        _proto.onEnable = function onEnable() {
          this._isEnabled = true;
          if (!this._impl) {
            this.onComponentSet();
          }
          this.setDetectCollisions(false);
          this.setOverlapRecovery(true);
          PhysicsSystem.instance.physicsWorld.addCCT(this);
          this.setWrapper();
        };
        _proto.onDisable = function onDisable() {
          this._isEnabled = false;
          this.wrappedWorld.removeCCT(this);
          this.onDestroy();
        };
        _proto.onDestroy = function onDestroy() {
          bt._safe_delete(this._impl, EBulletType.EBulletTypeCharacterController);
          BulletCache.delWrapper(this._impl, btCache.CCT_CACHE_NAME);
          this._impl = 0;
        };
        _proto.onLoad = function onLoad() {};
        _proto.getPosition = function getPosition(out) {
          if (!this._impl) return;
          bullet2CocosVec3(out, bt.CharacterController_getPosition(this.impl));
        };
        _proto.setPosition = function setPosition(value) {
          if (!this._impl) return;
          cocos2BulletVec3(bt.CharacterController_getPosition(this.impl), value);
          this.syncPhysicsToScene();
        };
        _proto.setContactOffset = function setContactOffset(value) {
          if (!this._impl) return;
          bt.CharacterController_setContactOffset(this._impl, value);
        };
        _proto.setStepOffset = function setStepOffset(value) {
          if (!this._impl) return;
          bt.CharacterController_setStepOffset(this._impl, value);
        };
        _proto.setSlopeLimit = function setSlopeLimit(value) {
          if (!this._impl) return;
          bt.CharacterController_setSlopeLimit(this._impl, degreesToRadians(value));
        };
        _proto.setDetectCollisions = function setDetectCollisions(value) {
          if (!this._impl) return;
          bt.CharacterController_setCollision(this.impl, value);
        };
        _proto.setOverlapRecovery = function setOverlapRecovery(value) {
          if (!this._impl) return;
          bt.CharacterController_setOverlapRecovery(this.impl, value);
        };
        _proto.onGround = function onGround() {
          return (this._btCollisionFlags & 1 << 2) > 0;
        };
        _proto.syncSceneToPhysics = function syncSceneToPhysics() {
          var node = this.characterController.node;
          if (node.hasChangedFlags) {
            if (node.hasChangedFlags & TransformBit.SCALE) this.syncScale();
            if (node.hasChangedFlags & TransformBit.POSITION) {
              Vec3.add(v3_0$2, node.worldPosition, this.scaledCenter);
              this.setPosition(v3_0$2);
            }
          }
        };
        _proto.syncPhysicsToScene = function syncPhysicsToScene() {
          this.getPosition(v3_0$2);
          v3_0$2.subtract(this.scaledCenter);
          this._comp.node.setWorldPosition(v3_0$2);
        };
        _proto.syncScale = function syncScale() {
          this.updateScale();
        };
        _proto.move = function move(movement, minDist, elapsedTime) {
          if (!this._isEnabled) {
            return;
          }
          var movementBT = BulletCache.instance.BT_V3_0;
          bt.Vec3_set(movementBT, movement.x, movement.y, movement.z);
          this._btCollisionFlags = bt.CharacterController_move(this.impl, movementBT, minDist, elapsedTime);
        };
        _proto.setGroup = function setGroup(v) {
          if (v !== this._collisionFilterGroup) {
            this._collisionFilterGroup = v;
            this._dirty = true;
          }
        };
        _proto.getGroup = function getGroup() {
          return this._collisionFilterGroup;
        };
        _proto.addGroup = function addGroup(v) {
          this._collisionFilterGroup |= v;
          this._dirty = true;
        };
        _proto.removeGroup = function removeGroup(v) {
          this._collisionFilterGroup &= ~v;
          this._dirty = true;
        };
        _proto.setMask = function setMask(v) {
          if (v !== this._collisionFilterMask) {
            this._collisionFilterMask = v;
            this._dirty = true;
          }
        };
        _proto.getMask = function getMask() {
          return this._collisionFilterMask;
        };
        _proto.addMask = function addMask(v) {
          this._collisionFilterMask |= v;
          this._dirty = true;
        };
        _proto.removeMask = function removeMask(v) {
          this._collisionFilterMask &= ~v;
          this._dirty = true;
        };
        _proto.updateEventListener = function updateEventListener() {
          this.wrappedWorld.updateNeedEmitCCTEvents(this.characterController.needCollisionEvent);
        };
        _proto.updateDirty = function updateDirty() {
          if (this._dirty) {
            PhysicsSystem.instance.physicsWorld.removeCCT(this);
            PhysicsSystem.instance.physicsWorld.addCCT(this);
            this._dirty = false;
          }
        };
        _proto.onShapeHitExt = function onShapeHitExt(hit) {
          var shapePtr = bt.ControllerShapeHit_getHitShape(hit);
          var bulletWorld = PhysicsSystem.instance.physicsWorld;
          bulletWorld.cctShapeEventDic.get(this.impl, shapePtr);
          var worldPos = new Vec3();
          bullet2CocosVec3(worldPos, bt.ControllerHit_getHitWorldPos(hit));
          var worldNormal = new Vec3();
          bullet2CocosVec3(worldNormal, bt.ControllerHit_getHitWorldNormal(hit));
          var motionDir = new Vec3();
          bullet2CocosVec3(motionDir, bt.ControllerHit_getHitMotionDir(hit));
          var motionLength = bt.ControllerHit_getHitMotionLength(hit);
          var s = BulletCache.getWrapper(shapePtr, BulletShape.TYPE);
          if (s) {
            bulletWorld.cctShapeEventDic.set(this.impl, shapePtr, {
              BulletCharacterController: this,
              BulletShape: s,
              worldPos: worldPos,
              worldNormal: worldNormal,
              motionDir: motionDir,
              motionLength: motionLength
            });
          }
        };
        _createClass(BulletCharacterController, [{
          key: "isEnabled",
          get: function get() {
            return this._isEnabled;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._impl;
          }
        }, {
          key: "characterController",
          get: function get() {
            return this._comp;
          }
        }, {
          key: "scaledCenter",
          get: function get() {
            Vec3.multiply(v3_1, this._comp.center, this._comp.node.worldScale);
            return v3_1;
          }
        }]);
        return BulletCharacterController;
      }();
      BulletCharacterController.idCounter = 0;

      var v3_0$1 = new Vec3(0, 0, 0);
      var BulletCapsuleCharacterController = function (_BulletCharacterContr) {
        _inheritsLoose(BulletCapsuleCharacterController, _BulletCharacterContr);
        function BulletCapsuleCharacterController() {
          return _BulletCharacterContr.apply(this, arguments) || this;
        }
        var _proto = BulletCapsuleCharacterController.prototype;
        _proto.onComponentSet = function onComponentSet() {
          this.component.node.getWorldPosition(v3_0$1);
          v3_0$1.add(this.scaledCenter);
          var pos = BulletCache.instance.BT_V3_0;
          bt.Vec3_set(pos, v3_0$1.x, v3_0$1.y, v3_0$1.z);
          var upDir = Vec3.UNIT_Y;
          var up = BulletCache.instance.BT_V3_1;
          bt.Vec3_set(up, upDir.x, upDir.y, upDir.z);
          var report = bt.ControllerHitReport.implement(importFunc).$$.ptr;
          var bulletWorld = PhysicsSystem.instance.physicsWorld;
          var controllerDesc = bt.CapsuleCharacterControllerDesc_new(degreesToRadians(this.component.slopeLimit), this.component.stepOffset, this.component.skinWidth, up, pos, report, this.component.radius, this.component.height);
          this._impl = bt.CapsuleCharacterController_new(bulletWorld.impl, controllerDesc, 0);
          this.updateScale();
        };
        _proto.setRadius = function setRadius(value) {
          this.updateScale();
        };
        _proto.setHeight = function setHeight(value) {
          this.updateScale();
        };
        _proto.updateScale = function updateScale() {
          this.updateGeometry();
        };
        _proto.updateGeometry = function updateGeometry() {
          var ws = this.component.node.worldScale;
          var r = this.component.radius * absMax(ws.x, ws.z);
          var h = this.component.height * Math.abs(ws.y);
          bt.CapsuleCharacterController_setRadius(this.impl, r);
          bt.CapsuleCharacterController_setHeight(this.impl, h);
          this._dirty = true;
        };
        _createClass(BulletCapsuleCharacterController, [{
          key: "component",
          get: function get() {
            return this._comp;
          }
        }]);
        return BulletCapsuleCharacterController;
      }(BulletCharacterController);

      var v3_0 = new Vec3(0, 0, 0);
      var BulletBoxCharacterController = function (_BulletCharacterContr) {
        _inheritsLoose(BulletBoxCharacterController, _BulletCharacterContr);
        function BulletBoxCharacterController() {
          return _BulletCharacterContr.apply(this, arguments) || this;
        }
        var _proto = BulletBoxCharacterController.prototype;
        _proto.onComponentSet = function onComponentSet() {
          this.component.node.getWorldPosition(v3_0);
          v3_0.add(this.scaledCenter);
          var pos = BulletCache.instance.BT_V3_0;
          bt.Vec3_set(pos, v3_0.x, v3_0.y, v3_0.z);
          var upDir = Vec3.UNIT_Y;
          var up = BulletCache.instance.BT_V3_1;
          bt.Vec3_set(up, upDir.x, upDir.y, upDir.z);
          var report = bt.ControllerHitReport.implement(importFunc).$$.ptr;
          var bulletWorld = PhysicsSystem.instance.physicsWorld;
          var controllerDesc = bt.BoxCharacterControllerDesc_new(degreesToRadians(this.component.slopeLimit), this.component.stepOffset, this.component.skinWidth, up, pos, report, this.component.halfHeight, this.component.halfSideExtent, this.component.halfForwardExtent);
          this._impl = bt.BoxCharacterController_new(bulletWorld.impl, controllerDesc, 0);
          this.updateScale();
        };
        _proto.setHalfHeight = function setHalfHeight(value) {
          this.updateScale();
        };
        _proto.setHalfSideExtent = function setHalfSideExtent(value) {
          this.updateScale();
        };
        _proto.setHalfForwardExtent = function setHalfForwardExtent(value) {
          this.updateScale();
        };
        _proto.updateScale = function updateScale() {
          this.updateGeometry();
        };
        _proto.updateGeometry = function updateGeometry() {
          var ws = this.component.node.worldScale;
          bt.BoxCharacterController_setHalfSideExtent(this.impl, this.component.halfSideExtent * ws.x);
          bt.BoxCharacterController_setHalfHeight(this.impl, this.component.halfHeight * ws.y);
          bt.BoxCharacterController_setHalfForwardExtent(this.impl, this.component.halfForwardExtent * ws.z);
          this._dirty = true;
        };
        _createClass(BulletBoxCharacterController, [{
          key: "component",
          get: function get() {
            return this._comp;
          }
        }]);
        return BulletBoxCharacterController;
      }(BulletCharacterController);

      game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, function () {
        selector.register('bullet', {
          PhysicsWorld: BulletWorld,
          RigidBody: BulletRigidBody,
          BoxShape: BulletBoxShape,
          SphereShape: BulletSphereShape,
          CapsuleShape: BulletCapsuleShape,
          TrimeshShape: BulletTrimeshShape,
          CylinderShape: BulletCylinderShape,
          ConeShape: BulletConeShape,
          TerrainShape: BulletTerrainShape,
          SimplexShape: BulletSimplexShape,
          PlaneShape: BulletPlaneShape,
          PointToPointConstraint: BulletP2PConstraint,
          HingeConstraint: BulletHingeConstraint,
          FixedConstraint: BulletFixedConstraint,
          ConfigurableConstraint: BulletConfigurableConstraint,
          BoxCharacterController: BulletBoxCharacterController,
          CapsuleCharacterController: BulletCapsuleCharacterController
        });
      });

      var _dec$v, _dec2$r, _class$v, _class2$q, _initializer$o, _initializer2$n, _class3$f;
      var PrimitiveType;
      (function (PrimitiveType) {
        PrimitiveType[PrimitiveType["BOX"] = 0] = "BOX";
        PrimitiveType[PrimitiveType["SPHERE"] = 1] = "SPHERE";
        PrimitiveType[PrimitiveType["CYLINDER"] = 2] = "CYLINDER";
        PrimitiveType[PrimitiveType["CONE"] = 3] = "CONE";
        PrimitiveType[PrimitiveType["CAPSULE"] = 4] = "CAPSULE";
        PrimitiveType[PrimitiveType["TORUS"] = 5] = "TORUS";
        PrimitiveType[PrimitiveType["PLANE"] = 6] = "PLANE";
        PrimitiveType[PrimitiveType["QUAD"] = 7] = "QUAD";
      })(PrimitiveType || (PrimitiveType = {}));
      ccenum(PrimitiveType);
      var Primitive = exports('g8', (_dec$v = ccclass$M('cc.Primitive'), _dec2$r = type$d(PrimitiveType), _dec$v(_class$v = (_class2$q = (_class3$f = function (_Mesh) {
        _inheritsLoose(Primitive, _Mesh);
        function Primitive(type) {
          var _this;
          if (type === void 0) {
            type = PrimitiveType.BOX;
          }
          _this = _Mesh.call(this) || this;
          _this.type = _initializer$o && _initializer$o();
          _this.info = _initializer2$n && _initializer2$n();
          _this.type = type;
          return _this;
        }
        var _proto = Primitive.prototype;
        _proto.onLoaded = function onLoaded() {
          _createMesh(primitives[PrimitiveType[this.type].toLowerCase()](this.info), this);
        };
        return Primitive;
      }(Mesh), _class3$f.PrimitiveType = PrimitiveType, _class3$f), (_initializer$o = applyDecoratedInitializer(_class2$q.prototype, "type", [_dec2$r], function () {
        return PrimitiveType.BOX;
      }), _initializer2$n = applyDecoratedInitializer(_class2$q.prototype, "info", [serializable$p], function () {
        return {};
      })), _class2$q)) || _class$v));
      legacyCC.Primitive = Primitive;

      legacyCC.primitives = primitives;

      var Counter = function () {
        function Counter(id, opts, now) {
          this._opts = void 0;
          this._total = 0;
          this._value = 0;
          this._averageValue = 0;
          this._accumValue = 0;
          this._accumSamples = 0;
          this._id = id;
          this._opts = opts;
          this._accumStart = now;
        }
        var _proto = Counter.prototype;
        _proto.sample = function sample(now) {
          this._average(this._value, now);
        };
        _proto.human = function human() {
          var _this$_opts = this._opts,
            average = _this$_opts.average,
            isInteger = _this$_opts.isInteger;
          var v = average ? this._averageValue : this._value;
          return isInteger ? Math.round(v) : Math.round(v * 100) / 100;
        };
        _proto.alarm = function alarm() {
          if (this._opts.below !== undefined && this._value < this._opts.below) {
            return true;
          }
          if (this._opts.over !== undefined && this._value > this._opts.over) {
            return true;
          }
          return false;
        };
        _proto._average = function _average(v, now) {
          if (now === void 0) {
            now = 0;
          }
          if (this._opts.average) {
            this._accumValue += v;
            ++this._accumSamples;
            var t = now;
            if (t - this._accumStart >= this._opts.average) {
              this._averageValue = this._accumValue / this._accumSamples;
              this._accumValue = 0;
              this._accumStart = t;
              this._accumSamples = 0;
            }
          }
        };
        _createClass(Counter, [{
          key: "value",
          get: function get() {
            return this._value;
          },
          set: function set(val) {
            this._value = val;
          }
        }]);
        return Counter;
      }();

      var _dec$u, _class$u;
      var PerfCounter = (_dec$u = ccclass$M('cc.PerfCounter'), _dec$u(_class$u = function (_Counter) {
        _inheritsLoose(PerfCounter, _Counter);
        function PerfCounter(id, opts, now) {
          var _this;
          _this = _Counter.call(this, id, opts, now) || this;
          _this._time = now;
          return _this;
        }
        var _proto = PerfCounter.prototype;
        _proto.start = function start(now) {
          if (now === void 0) {
            now = 0;
          }
          this._time = now;
        };
        _proto.end = function end(now) {
          if (now === void 0) {
            now = 0;
          }
          this._value = now - this._time;
          this._average(this._value);
        };
        _proto.tick = function tick() {
          this.end();
          this.start();
        };
        _proto.frame = function frame(now) {
          var t = now;
          var e = t - this._time;
          this._total++;
          var avg = this._opts.average || 1000;
          if (e > avg) {
            this._value = this._total * 1000 / e;
            this._total = 0;
            this._time = t;
            this._average(this._value);
          }
        };
        return PerfCounter;
      }(Counter)) || _class$u);

      var _characters = '0123456789. ';
      var _average = 500;
      var _string2offset = {
        0: 0,
        1: 1,
        2: 2,
        3: 3,
        4: 4,
        5: 5,
        6: 6,
        7: 7,
        8: 8,
        9: 9,
        '.': 10
      };
      var _profileInfo = {
        fps: {
          desc: "Framerate (FPS)",
          below: 30,
          average: _average,
          isInteger: true
        },
        draws: {
          desc: 'Draw call',
          isInteger: true
        },
        frame: {
          desc: 'Frame time (ms)',
          min: 0,
          max: 50,
          average: _average
        },
        instances: {
          desc: 'Instance Count',
          isInteger: true
        },
        tricount: {
          desc: 'Triangle',
          isInteger: true
        },
        logic: {
          desc: 'Game Logic (ms)',
          min: 0,
          max: 50,
          average: _average,
          color: '#080'
        },
        physics: {
          desc: 'Physics (ms)',
          min: 0,
          max: 50,
          average: _average
        },
        render: {
          desc: 'Renderer (ms)',
          min: 0,
          max: 50,
          average: _average,
          color: '#f90'
        },
        present: {
          desc: 'Present (ms)',
          min: 0,
          max: 50,
          average: _average,
          color: '#f90'
        },
        textureMemory: {
          desc: 'GFX Texture Mem(M)'
        },
        bufferMemory: {
          desc: 'GFX Buffer Mem(M)'
        }
      };
      var _constants = {
        fontSize: 23,
        quadHeight: 0.4,
        segmentsPerLine: 8,
        textureWidth: 280,
        textureHeight: 280
      };
      var Profiler = exports('g9', function (_System) {
        _inheritsLoose(Profiler, _System);
        function Profiler() {
          var _this;
          _this = _System.call(this) || this;
          _this._profilerStats = null;
          _this._showFPS = false;
          _this._rootNode = null;
          _this._device = null;
          _this._swapchain = null;
          _this._meshRenderer = null;
          _this._canvas = null;
          _this._ctx = null;
          _this._texture = null;
          _this._region = new BufferTextureCopy();
          _this._canvasArr = [];
          _this._regionArr = [_this._region];
          _this.digitsData = null;
          _this.offsetData = null;
          _this.pass = null;
          _this._canvasDone = false;
          _this._statsDone = false;
          _this._inited = false;
          _this._lineHeight = _constants.textureHeight / (Object.keys(_profileInfo).length + 1);
          _this._wordHeight = 0;
          _this._eachNumWidth = 0;
          _this._totalLines = 0;
          _this.lastTime = 0;
          {
            _this._canvas = ccwindow.document.createElement('canvas');
            _this._ctx = _this._canvas.getContext('2d');
            _this._canvasArr.push(_this._canvas);
          }
          return _this;
        }
        var _proto = Profiler.prototype;
        _proto.init = function init() {
          var showFPS = !!settings.querySettings(Settings.Category.PROFILING, 'showFPS');
          if (showFPS) {
            this.showStats();
          } else {
            this.hideStats();
          }
        };
        _proto.isShowingStats = function isShowingStats() {
          return this._showFPS;
        };
        _proto.hideStats = function hideStats() {
          if (this._showFPS) {
            if (this._rootNode) {
              this._rootNode.active = false;
            }
            legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this);
            legacyCC.director.off(legacyCC.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this);
            legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this);
            legacyCC.director.off(legacyCC.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this);
            legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this);
            legacyCC.director.off(legacyCC.Director.EVENT_AFTER_RENDER, this.afterRender, this);
            legacyCC.director.off(legacyCC.Director.EVENT_AFTER_DRAW, this.afterPresent, this);
            this._showFPS = false;
            director.root.pipeline.profiler = null;
            legacyCC.game.config.showFPS = false;
          }
        };
        _proto.showStats = function showStats() {
          if (!this._showFPS) {
            if (!this._device) {
              var root = legacyCC.director.root;
              this._device = deviceManager.gfxDevice;
              this._swapchain = root.mainWindow.swapchain;
            }
            this.generateCanvas();
            this.generateStats();
            legacyCC.game.once(legacyCC.Game.EVENT_ENGINE_INITED, this.generateNode, this);
            legacyCC.game.on(legacyCC.Game.EVENT_RESTART, this.generateNode, this);
            if (this._rootNode) {
              this._rootNode.active = true;
            }
            legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this);
            legacyCC.director.on(legacyCC.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this);
            legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this);
            legacyCC.director.on(legacyCC.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this);
            legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this);
            legacyCC.director.on(legacyCC.Director.EVENT_AFTER_RENDER, this.afterRender, this);
            legacyCC.director.on(legacyCC.Director.EVENT_AFTER_DRAW, this.afterPresent, this);
            this._showFPS = true;
            this._canvasDone = true;
            this._statsDone = true;
            legacyCC.game.config.showFPS = true;
          }
        };
        _proto.generateCanvas = function generateCanvas() {
          if (this._canvasDone) {
            return;
          }
          var textureWidth = _constants.textureWidth,
            textureHeight = _constants.textureHeight;
          if (!this._ctx || !this._canvas) {
            return;
          }
          this._canvas.width = textureWidth;
          this._canvas.height = textureHeight;
          this._canvas.style.width = "" + this._canvas.width;
          this._canvas.style.height = "" + this._canvas.height;
          this._ctx.font = _constants.fontSize + "px Arial";
          this._ctx.textBaseline = 'top';
          this._ctx.fillStyle = '#fff';
          this._texture = this._device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, textureWidth, textureHeight));
          this._region.texExtent.width = textureWidth;
          this._region.texExtent.height = textureHeight;
        };
        _proto.generateStats = function generateStats() {
          if (this._statsDone || !this._ctx || !this._canvas) {
            return;
          }
          this._profilerStats = null;
          var now = performance.now();
          this._ctx.textAlign = 'left';
          var i = 0;
          for (var id in _profileInfo) {
            var element = _profileInfo[id];
            this._ctx.fillText(element.desc, 0, i * this._lineHeight);
            element.counter = new PerfCounter(id, element, now);
            i++;
          }
          this._totalLines = i;
          this._wordHeight = this._totalLines * this._lineHeight / this._canvas.height;
          for (var j = 0; j < _characters.length; ++j) {
            var offset = this._ctx.measureText(_characters[j]).width;
            this._eachNumWidth = Math.max(this._eachNumWidth, offset);
          }
          for (var _j = 0; _j < _characters.length; ++_j) {
            this._ctx.fillText(_characters[_j], _j * this._eachNumWidth, this._totalLines * this._lineHeight);
          }
          this._eachNumWidth /= this._canvas.width;
          this._profilerStats = _profileInfo;
          this._canvasArr[0] = this._canvas;
          this._device.copyTexImagesToTexture(this._canvasArr, this._texture, this._regionArr);
        };
        _proto.generateNode = function generateNode() {
          if (this._rootNode && this._rootNode.isValid) {
            return;
          }
          this._rootNode = new Node$1('PROFILER_NODE');
          this._rootNode._objFlags = legacyCC.Object.Flags.DontSave | legacyCC.Object.Flags.HideInHierarchy;
          legacyCC.game.addPersistRootNode(this._rootNode);
          var managerNode = new Node$1('Profiler_Root');
          managerNode.parent = this._rootNode;
          var height = _constants.quadHeight;
          var rowHeight = height / this._totalLines;
          var lWidth = height / this._wordHeight;
          var scale = rowHeight / _constants.fontSize;
          var columnWidth = this._eachNumWidth * this._canvas.width * scale;
          var vertexPos = [0, height, 0, lWidth, height, 0, lWidth, 0, 0, 0, 0, 0];
          var vertexindices = [0, 2, 1, 0, 3, 2];
          var vertexUV = [0, 0, -1, 0, 1, 0, -1, 0, 1, this._wordHeight, -1, 0, 0, this._wordHeight, -1, 0];
          var offset = 0;
          for (var i = 0; i < this._totalLines; i++) {
            for (var j = 0; j < _constants.segmentsPerLine; j++) {
              vertexPos.push(lWidth + j * columnWidth, height - i * rowHeight, 0);
              vertexPos.push(lWidth + (j + 1) * columnWidth, height - i * rowHeight, 0);
              vertexPos.push(lWidth + (j + 1) * columnWidth, height - (i + 1) * rowHeight, 0);
              vertexPos.push(lWidth + j * columnWidth, height - (i + 1) * rowHeight, 0);
              offset = (i * _constants.segmentsPerLine + j + 1) * 4;
              vertexindices.push(0 + offset, 2 + offset, 1 + offset, 0 + offset, 3 + offset, 2 + offset);
              var idx = i * _constants.segmentsPerLine + j;
              var z = Math.floor(idx / 4);
              var w = idx - z * 4;
              vertexUV.push(0, this._wordHeight, z, w);
              vertexUV.push(this._eachNumWidth, this._wordHeight, z, w);
              vertexUV.push(this._eachNumWidth, 1, z, w);
              vertexUV.push(0, 1, z, w);
            }
          }
          this._meshRenderer = managerNode.addComponent(MeshRenderer);
          this._meshRenderer.mesh = _createMesh({
            positions: vertexPos,
            indices: vertexindices,
            colors: vertexUV
          });
          var _material = new Material();
          _material.initialize({
            effectName: 'util/profiler'
          });
          var pass = this.pass = _material.passes[0];
          var hTexture = pass.getBinding('mainTexture');
          var bDigits = pass.getBinding('digits');
          var bOffset = pass.getBinding('offset');
          pass.bindTexture(hTexture, this._texture);
          this.digitsData = pass.blocks[bDigits];
          this.offsetData = pass.blocks[bOffset];
          this.offsetData[3] = -1;
          this._meshRenderer.material = _material;
          this._meshRenderer.node.layer = Layers.Enum.PROFILER;
          this._inited = true;
        };
        _proto.beforeUpdate = function beforeUpdate() {
          if (!this._profilerStats) {
            return;
          }
          var now = performance.now();
          this._profilerStats.frame.counter.start(now);
          this._profilerStats.logic.counter.start(now);
        };
        _proto.afterUpdate = function afterUpdate() {
          if (!this._profilerStats) {
            return;
          }
          var now = performance.now();
          if (legacyCC.director.isPaused()) {
            this._profilerStats.frame.counter.start(now);
          } else {
            this._profilerStats.logic.counter.end(now);
          }
        };
        _proto.beforePhysics = function beforePhysics() {
          if (!this._profilerStats) {
            return;
          }
          var now = performance.now();
          this._profilerStats.physics.counter.start(now);
        };
        _proto.afterPhysics = function afterPhysics() {
          if (!this._profilerStats) {
            return;
          }
          var now = performance.now();
          this._profilerStats.physics.counter.end(now);
        };
        _proto.beforeDraw = function beforeDraw() {
          if (!this._profilerStats || !this._inited) {
            return;
          }
          var surfaceTransform = this._swapchain.surfaceTransform;
          var clipSpaceSignY = this._device.capabilities.clipSpaceSignY;
          if (surfaceTransform !== this.offsetData[3]) {
            var preTransform = preTransforms[surfaceTransform];
            var x = -0.9;
            var y = -0.9 * clipSpaceSignY;
            if (sys.isXR) {
              x = -0.5;
              y = -0.5 * clipSpaceSignY;
            }
            this.offsetData[0] = x * preTransform[0] + y * preTransform[2];
            this.offsetData[1] = x * preTransform[1] + y * preTransform[3];
            this.offsetData[2] = this._eachNumWidth;
            this.offsetData[3] = surfaceTransform;
          }
          this.pass.setRootBufferDirty(true);
          if (this._meshRenderer.model) {
            director.root.pipeline.profiler = this._meshRenderer.model;
          } else {
            director.root.pipeline.profiler = null;
          }
          var now = performance.now();
          this._profilerStats.render.counter.start(now);
        };
        _proto.afterRender = function afterRender() {
          if (!this._profilerStats || !this._inited) {
            return;
          }
          var now = performance.now();
          this._profilerStats.render.counter.end(now);
          this._profilerStats.present.counter.start(now);
        };
        _proto.afterPresent = function afterPresent() {
          if (!this._profilerStats || !this._inited) {
            return;
          }
          var now = performance.now();
          this._profilerStats.frame.counter.end(now);
          this._profilerStats.fps.counter.frame(now);
          this._profilerStats.present.counter.end(now);
          if (now - this.lastTime < _average) {
            return;
          }
          this.lastTime = now;
          var device = this._device;
          this._profilerStats.draws.counter.value = device.numDrawCalls;
          this._profilerStats.instances.counter.value = device.numInstances;
          this._profilerStats.bufferMemory.counter.value = device.memoryStatus.bufferSize / (1024 * 1024);
          this._profilerStats.textureMemory.counter.value = device.memoryStatus.textureSize / (1024 * 1024);
          this._profilerStats.tricount.counter.value = device.numTris;
          var i = 0;
          var view = this.digitsData;
          for (var id in this._profilerStats) {
            var stat = this._profilerStats[id];
            stat.counter.sample(now);
            var result = stat.counter.human().toString();
            for (var j = _constants.segmentsPerLine - 1; j >= 0; j--) {
              var index = i * _constants.segmentsPerLine + j;
              var character = result[result.length - (_constants.segmentsPerLine - j)];
              var offset = _string2offset[character];
              if (offset === undefined) {
                offset = 11;
              }
              view[index] = offset;
            }
            i++;
          }
        };
        _createClass(Profiler, [{
          key: "_stats",
          get: function get() {
            warn('Profiler._stats is deprecated, please use Profiler.stats instead.');
            return this._profilerStats;
          }
        }, {
          key: "stats",
          get: function get() {
            return this._profilerStats;
          }
        }]);
        return Profiler;
      }(System));
      var profiler = exports('ga', new Profiler());
      director.registerSystem('profiler', profiler, 0);
      legacyCC.profiler = profiler;

      var DataPoolManager = function () {
        function DataPoolManager(device) {
          this.jointTexturePool = void 0;
          this.jointAnimationInfo = void 0;
          this.jointTexturePool = new JointTexturePool(device);
          this.jointAnimationInfo = new JointAnimationInfo(device);
        }
        var _proto = DataPoolManager.prototype;
        _proto.releaseSkeleton = function releaseSkeleton(skeleton) {
          this.jointTexturePool.releaseSkeleton(skeleton);
        };
        _proto.releaseAnimationClip = function releaseAnimationClip(clip) {
          this.jointTexturePool.releaseAnimationClip(clip);
        };
        _proto.clear = function clear() {
          this.jointTexturePool.clear();
          this.jointAnimationInfo.clear();
        };
        return DataPoolManager;
      }();
      legacyCC.internal.DataPoolManager = DataPoolManager;

      var m4_1$1 = new Mat4();
      var m4_2$1 = new Mat4();
      var SkeletalAnimationState = exports('gc', function (_AnimationState) {
        _inheritsLoose(SkeletalAnimationState, _AnimationState);
        function SkeletalAnimationState(clip, name) {
          var _this;
          if (name === void 0) {
            name = '';
          }
          _this = _AnimationState.call(this, clip, name) || this;
          _this._frames = 1;
          _this._bakedDuration = 0;
          _this._animInfo = null;
          _this._sockets = [];
          _this._animInfoMgr = void 0;
          _this._parent = null;
          _this._curvesInited = false;
          _this._animInfoMgr = legacyCC.director.root.dataPoolManager.jointAnimationInfo;
          return _this;
        }
        var _proto = SkeletalAnimationState.prototype;
        _proto.initialize = function initialize(root) {
          if (this._curveLoaded) {
            return;
          }
          this._parent = root.getComponent('cc.SkeletalAnimation');
          var baked = this._parent.useBakedAnimation;
          this._doNotCreateEval = baked;
          _AnimationState.prototype.initialize.call(this, root);
          this._curvesInited = !baked;
          var _SkelAnimDataHub$getO = SkelAnimDataHub.getOrExtract(this.clip),
            frames = _SkelAnimDataHub$getO.frames,
            samples = _SkelAnimDataHub$getO.samples;
          this._frames = frames - 1;
          this._animInfo = this._animInfoMgr.getData(root.uuid);
          this._bakedDuration = this._frames / samples;
          this.setUseBaked(baked);
        };
        _proto.onPlay = function onPlay() {
          var _this2 = this;
          _AnimationState.prototype.onPlay.call(this);
          var baked = this._parent.useBakedAnimation;
          if (baked) {
            this._animInfoMgr.switchClip(this._animInfo, this.clip);
            var users = this._parent.getUsers();
            users.forEach(function (user) {
              user.uploadAnimation(_this2.clip);
            });
          }
        };
        _proto.setUseBaked = function setUseBaked(useBaked) {
          if (useBaked) {
            this._sampleCurves = this._sampleCurvesBaked;
            this.duration = this._bakedDuration;
          } else {
            this._sampleCurves = _AnimationState.prototype._sampleCurves;
            this.duration = this.clip.duration;
            if (!this._curvesInited) {
              this._curveLoaded = false;
              _AnimationState.prototype.initialize.call(this, this._targetNode);
              this._curvesInited = true;
            }
          }
        };
        _proto.rebuildSocketCurves = function rebuildSocketCurves(sockets) {
          this._sockets.length = 0;
          if (!this._targetNode) {
            return;
          }
          var root = this._targetNode;
          for (var i = 0; i < sockets.length; ++i) {
            var socket = sockets[i];
            var targetNode = root.getChildByPath(socket.path);
            if (!socket.target) {
              continue;
            }
            var clipData = SkelAnimDataHub.getOrExtract(this.clip);
            var animPath = socket.path;
            var source = clipData.joints[animPath];
            var animNode = targetNode;
            var downstream = void 0;
            while (!source) {
              var idx = animPath.lastIndexOf('/');
              animPath = animPath.substring(0, idx);
              source = clipData.joints[animPath];
              if (animNode) {
                if (!downstream) {
                  downstream = Mat4.identity(m4_2$1);
                }
                Mat4.fromRTS(m4_1$1, animNode.rotation, animNode.position, animNode.scale);
                Mat4.multiply(downstream, m4_1$1, downstream);
                animNode = animNode.parent;
              }
              if (idx < 0) {
                break;
              }
            }
            var curveData = source && source.transforms;
            var frames = clipData.frames;
            var transforms = [];
            for (var f = 0; f < frames; f++) {
              var mat = void 0;
              if (curveData && downstream) {
                mat = Mat4.multiply(m4_1$1, curveData[f], downstream);
              } else if (curveData) {
                mat = curveData[f];
              } else if (downstream) {
                mat = downstream;
              } else {
                mat = new Mat4();
              }
              var tfm = {
                pos: new Vec3(),
                rot: new Quat(),
                scale: new Vec3()
              };
              Mat4.toRTS(mat, tfm.rot, tfm.pos, tfm.scale);
              transforms.push(tfm);
            }
            this._sockets.push({
              target: socket.target,
              frames: transforms
            });
          }
        };
        _proto._sampleCurvesBaked = function _sampleCurvesBaked(time) {
          var ratio = time / this.duration;
          var info = this._animInfo;
          var clip = this.clip;
          if (info.currentClip !== clip) {
            this._animInfoMgr.switchClip(this._animInfo, clip);
            var users = this._parent.getUsers();
            users.forEach(function (user) {
              user.uploadAnimation(clip);
            });
            info.data[0] = -1;
          }
          var curFrame = ratio * this._frames + 0.5 | 0;
          if (curFrame === info.data[0]) {
            return;
          }
          info.data[0] = curFrame;
          info.dirty = true;
          for (var i = 0; i < this._sockets.length; ++i) {
            var _this$_sockets$i = this._sockets[i],
              target = _this$_sockets$i.target,
              frames = _this$_sockets$i.frames;
            var _frames$curFrame = frames[curFrame],
              pos = _frames$curFrame.pos,
              rot = _frames$curFrame.rot,
              scale = _frames$curFrame.scale;
            target.setRTS(rot, pos, scale);
          }
        };
        return SkeletalAnimationState;
      }(AnimationState$1));

      var _dec$t, _dec2$q, _class$t, _class2$p, _initializer$n, _initializer2$m, _dec3$o, _dec4$h, _dec5$h, _dec6$b, _class4$2, _class5$4, _initializer3$i, _initializer4$g, _class6$1;
      var Socket = exports('gd', (_dec$t = ccclass$M('cc.SkeletalAnimation.Socket'), _dec2$q = type$d(Node$1), _dec$t(_class$t = (_class2$p = function Socket(path, target) {
        if (path === void 0) {
          path = '';
        }
        if (target === void 0) {
          target = null;
        }
        this.path = _initializer$n && _initializer$n();
        this.target = _initializer2$m && _initializer2$m();
        this.path = path;
        this.target = target;
      }, (_initializer$n = applyDecoratedInitializer(_class2$p.prototype, "path", [serializable$p], function () {
        return '';
      }), _initializer2$m = applyDecoratedInitializer(_class2$p.prototype, "target", [_dec2$q], function () {
        return null;
      })), _class2$p)) || _class$t));
      setClassAlias(Socket, 'cc.SkeletalAnimationComponent.Socket');
      var m4_1 = new Mat4();
      var m4_2 = new Mat4();
      function collectRecursively(node, prefix, out) {
        if (prefix === void 0) {
          prefix = '';
        }
        if (out === void 0) {
          out = [];
        }
        for (var i = 0; i < node.children.length; i++) {
          var child = node.children[i];
          if (!child) {
            continue;
          }
          var path = prefix ? prefix + "/" + child.name : child.name;
          out.push(path);
          collectRecursively(child, path, out);
        }
        return out;
      }
      var SkeletalAnimation = exports('ge', (_dec3$o = ccclass$M('cc.SkeletalAnimation'), _dec4$h = executionOrder$1(99), _dec5$h = type$d([Socket]), _dec6$b = type$d([Socket]), _dec3$o(_class4$2 = _dec4$h(_class4$2 = (_class5$4 = (_class6$1 = function (_Animation) {
        _inheritsLoose(SkeletalAnimation, _Animation);
        function SkeletalAnimation() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Animation.call.apply(_Animation, [this].concat(args)) || this;
          _this._useBakedAnimation = _initializer3$i && _initializer3$i();
          _this._sockets = _initializer4$g && _initializer4$g();
          _this._users = new Set();
          _this._currentBakedState = null;
          return _this;
        }
        var _proto = SkeletalAnimation.prototype;
        _proto.onLoad = function onLoad() {
          _Animation.prototype.onLoad.call(this);
          var comps = this.node.getComponentsInChildren(SkinnedMeshRenderer);
          for (var i = 0; i < comps.length; ++i) {
            var comp = comps[i];
            if (comp.skinningRoot === this.node) {
              this.notifySkinnedMeshAdded(comp);
            }
          }
        };
        _proto.onDestroy = function onDestroy() {
          _Animation.prototype.onDestroy.call(this);
          legacyCC.director.root.dataPoolManager.jointAnimationInfo.destroy(this.node.uuid);
          getGlobalAnimationManager().removeSockets(this.node, this._sockets);
          this._removeAllUsers();
        };
        _proto.onEnable = function onEnable() {
          var _this$_currentBakedSt;
          _Animation.prototype.onEnable.call(this);
          (_this$_currentBakedSt = this._currentBakedState) === null || _this$_currentBakedSt === void 0 ? void 0 : _this$_currentBakedSt.resume();
        };
        _proto.onDisable = function onDisable() {
          var _this$_currentBakedSt2;
          _Animation.prototype.onDisable.call(this);
          (_this$_currentBakedSt2 = this._currentBakedState) === null || _this$_currentBakedSt2 === void 0 ? void 0 : _this$_currentBakedSt2.pause();
        };
        _proto.start = function start() {
          this.sockets = this._sockets;
          this._applyBakeFlagChange();
          _Animation.prototype.start.call(this);
        };
        _proto.pause = function pause() {
          if (!this._useBakedEffectively) {
            _Animation.prototype.pause.call(this);
          } else {
            var _this$_currentBakedSt3;
            (_this$_currentBakedSt3 = this._currentBakedState) === null || _this$_currentBakedSt3 === void 0 ? void 0 : _this$_currentBakedSt3.pause();
          }
        };
        _proto.resume = function resume() {
          if (!this._useBakedEffectively) {
            _Animation.prototype.resume.call(this);
          } else {
            var _this$_currentBakedSt4;
            (_this$_currentBakedSt4 = this._currentBakedState) === null || _this$_currentBakedSt4 === void 0 ? void 0 : _this$_currentBakedSt4.resume();
          }
        };
        _proto.stop = function stop() {
          if (!this._useBakedEffectively) {
            _Animation.prototype.stop.call(this);
          } else if (this._currentBakedState) {
            this._currentBakedState.stop();
            this._currentBakedState = null;
          }
        };
        _proto.querySockets = function querySockets() {
          var animPaths = this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip).joints).sort().reduce(function (acc, cur) {
            return cur.startsWith(acc[acc.length - 1] + "/") ? acc : (acc.push(cur), acc);
          }, []) || [];
          if (!animPaths.length) {
            return ['please specify a valid default animation clip first'];
          }
          var out = [];
          for (var i = 0; i < animPaths.length; i++) {
            var path = animPaths[i];
            var node = this.node.getChildByPath(path);
            if (!node) {
              continue;
            }
            out.push(path);
            collectRecursively(node, path, out);
          }
          return out;
        };
        _proto.rebuildSocketAnimations = function rebuildSocketAnimations() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._sockets), _step; !(_step = _iterator()).done;) {
            var socket = _step.value;
            var joint = this.node.getChildByPath(socket.path);
            var target = socket.target;
            if (joint && target) {
              target.name = socket.path.substring(socket.path.lastIndexOf('/') + 1) + " Socket";
              target.parent = this.node;
              getWorldTransformUntilRoot(joint, this.node, m4_1);
              Mat4.fromRTS(m4_2, target.rotation, target.position, target.scale);
              if (!Mat4.equals(m4_2, m4_1)) {
                target.matrix = m4_1;
              }
            }
          }
          for (var _i = 0, _Object$keys = Object.keys(this._nameToState); _i < _Object$keys.length; _i++) {
            var stateName = _Object$keys[_i];
            var state = this._nameToState[stateName];
            state.rebuildSocketCurves(this._sockets);
          }
        };
        _proto.createSocket = function createSocket(path) {
          var socket = this._sockets.find(function (s) {
            return s.path === path;
          });
          if (socket) {
            return socket.target;
          }
          var joint = this.node.getChildByPath(path);
          if (!joint) {
            warn('illegal socket path');
            return null;
          }
          var target = new Node$1();
          target.parent = this.node;
          this._sockets.push(new Socket(path, target));
          this.rebuildSocketAnimations();
          return target;
        };
        _proto.notifySkinnedMeshAdded = function notifySkinnedMeshAdded(skinnedMeshRenderer) {
          var _useBakedEffectively = this._useBakedEffectively;
          var formerBound = skinnedMeshRenderer.associatedAnimation;
          if (formerBound) {
            formerBound._users["delete"](skinnedMeshRenderer);
          }
          skinnedMeshRenderer.associatedAnimation = this;
          skinnedMeshRenderer.setUseBakedAnimation(_useBakedEffectively, true);
          if (_useBakedEffectively) {
            var playingState = this._currentBakedState;
            if (playingState) {
              skinnedMeshRenderer.uploadAnimation(playingState.clip);
            }
          }
          this._users.add(skinnedMeshRenderer);
        };
        _proto.notifySkinnedMeshRemoved = function notifySkinnedMeshRemoved(skinnedMeshRenderer) {
          assertIsTrue(skinnedMeshRenderer.associatedAnimation === this || skinnedMeshRenderer.associatedAnimation === null);
          skinnedMeshRenderer.setUseBakedAnimation(false);
          skinnedMeshRenderer.associatedAnimation = null;
          this._users["delete"](skinnedMeshRenderer);
        };
        _proto.getUsers = function getUsers() {
          return this._users;
        };
        _proto._createState = function _createState(clip, name) {
          return new SkeletalAnimationState(clip, name);
        };
        _proto._doCreateState = function _doCreateState(clip, name) {
          var state = _Animation.prototype._doCreateState.call(this, clip, name);
          state.rebuildSocketCurves(this._sockets);
          return state;
        };
        _proto.doPlayOrCrossFade = function doPlayOrCrossFade(state, duration) {
          if (this._useBakedEffectively) {
            if (this._currentBakedState) {
              this._currentBakedState.stop();
            }
            var skeletalAnimationState = state;
            this._currentBakedState = skeletalAnimationState;
            skeletalAnimationState.play();
          } else {
            _Animation.prototype.doPlayOrCrossFade.call(this, state, duration);
          }
        };
        _proto._removeAllUsers = function _removeAllUsers() {
          var _this2 = this;
          Array.from(this._users).forEach(function (user) {
            _this2.notifySkinnedMeshRemoved(user);
          });
        };
        _proto._applyBakeFlagChange = function _applyBakeFlagChange() {
          var useBakedEffectively = this._useBakedEffectively;
          for (var stateName in this._nameToState) {
            var state = this._nameToState[stateName];
            state.setUseBaked(useBakedEffectively);
          }
          this._users.forEach(function (user) {
            user.setUseBakedAnimation(useBakedEffectively);
          });
          if (useBakedEffectively) {
            getGlobalAnimationManager().removeSockets(this.node, this._sockets);
          } else {
            getGlobalAnimationManager().addSockets(this.node, this._sockets);
            this._currentBakedState = null;
          }
        };
        _createClass(SkeletalAnimation, [{
          key: "sockets",
          get: function get() {
            return this._sockets;
          },
          set: function set(val) {
            if (!this._useBakedEffectively) {
              var animMgr = getGlobalAnimationManager();
              animMgr.removeSockets(this.node, this._sockets);
              animMgr.addSockets(this.node, val);
            }
            this._sockets = val;
            this.rebuildSocketAnimations();
          }
        }, {
          key: "useBakedAnimation",
          get: function get() {
            return this._useBakedAnimation;
          },
          set: function set(value) {
            this._useBakedAnimation = value;
            this._applyBakeFlagChange();
          }
        }, {
          key: "_useBakedEffectively",
          get: function get() {
            {
              return this._useBakedAnimation;
            }
          }
        }]);
        return SkeletalAnimation;
      }(Animation$2), _class6$1.Socket = Socket, _class6$1), (_applyDecoratedDescriptor(_class5$4.prototype, "sockets", [_dec5$h], Object.getOwnPropertyDescriptor(_class5$4.prototype, "sockets"), _class5$4.prototype), _initializer3$i = applyDecoratedInitializer(_class5$4.prototype, "_useBakedAnimation", [serializable$p], function () {
        return true;
      }), _initializer4$g = applyDecoratedInitializer(_class5$4.prototype, "_sockets", [_dec6$b], function () {
        return [];
      })), _class5$4)) || _class4$2) || _class4$2));

      legacyCC.SkeletalAnimationComponent = SkeletalAnimation;
      setClassAlias(SkeletalAnimation, 'cc.SkeletalAnimationComponent');

      var spine;
      (function (spine) {
        (function (MixBlend) {
          MixBlend[MixBlend["setup"] = 0] = "setup";
          MixBlend[MixBlend["first"] = 1] = "first";
          MixBlend[MixBlend["replace"] = 2] = "replace";
          MixBlend[MixBlend["add"] = 3] = "add";
        })(spine.MixBlend || (spine.MixBlend = {}));
        (function (MixDirection) {
          MixDirection[MixDirection["mixIn"] = 0] = "mixIn";
          MixDirection[MixDirection["mixOut"] = 1] = "mixOut";
        })(spine.MixDirection || (spine.MixDirection = {}));
        (function (TimelineType) {
          TimelineType[TimelineType["rotate"] = 0] = "rotate";
          TimelineType[TimelineType["translate"] = 1] = "translate";
          TimelineType[TimelineType["scale"] = 2] = "scale";
          TimelineType[TimelineType["shear"] = 3] = "shear";
          TimelineType[TimelineType["attachment"] = 4] = "attachment";
          TimelineType[TimelineType["color"] = 5] = "color";
          TimelineType[TimelineType["deform"] = 6] = "deform";
          TimelineType[TimelineType["event"] = 7] = "event";
          TimelineType[TimelineType["drawOrder"] = 8] = "drawOrder";
          TimelineType[TimelineType["ikConstraint"] = 9] = "ikConstraint";
          TimelineType[TimelineType["transformConstraint"] = 10] = "transformConstraint";
          TimelineType[TimelineType["pathConstraintPosition"] = 11] = "pathConstraintPosition";
          TimelineType[TimelineType["pathConstraintSpacing"] = 12] = "pathConstraintSpacing";
          TimelineType[TimelineType["pathConstraintMix"] = 13] = "pathConstraintMix";
          TimelineType[TimelineType["twoColor"] = 14] = "twoColor";
        })(spine.TimelineType || (spine.TimelineType = {}));
        (function (EventType) {
          EventType[EventType["start"] = 0] = "start";
          EventType[EventType["interrupt"] = 1] = "interrupt";
          EventType[EventType["end"] = 2] = "end";
          EventType[EventType["dispose"] = 3] = "dispose";
          EventType[EventType["complete"] = 4] = "complete";
          EventType[EventType["event"] = 5] = "event";
        })(spine.EventType || (spine.EventType = {}));
        (function (BlendMode) {
          BlendMode[BlendMode["Normal"] = 0] = "Normal";
          BlendMode[BlendMode["Additive"] = 1] = "Additive";
          BlendMode[BlendMode["Multiply"] = 2] = "Multiply";
          BlendMode[BlendMode["Screen"] = 3] = "Screen";
        })(spine.BlendMode || (spine.BlendMode = {}));
        (function (TransformMode) {
          TransformMode[TransformMode["Normal"] = 0] = "Normal";
          TransformMode[TransformMode["OnlyTranslation"] = 1] = "OnlyTranslation";
          TransformMode[TransformMode["NoRotationOrReflection"] = 2] = "NoRotationOrReflection";
          TransformMode[TransformMode["NoScale"] = 3] = "NoScale";
          TransformMode[TransformMode["NoScaleOrReflection"] = 4] = "NoScaleOrReflection";
        })(spine.TransformMode || (spine.TransformMode = {}));
        (function (PositionMode) {
          PositionMode[PositionMode["Fixed"] = 0] = "Fixed";
          PositionMode[PositionMode["Percent"] = 1] = "Percent";
        })(spine.PositionMode || (spine.PositionMode = {}));
        (function (SpacingMode) {
          SpacingMode[SpacingMode["Length"] = 0] = "Length";
          SpacingMode[SpacingMode["Fixed"] = 1] = "Fixed";
          SpacingMode[SpacingMode["Percent"] = 2] = "Percent";
        })(spine.SpacingMode || (spine.SpacingMode = {}));
        (function (RotateMode) {
          RotateMode[RotateMode["Tangent"] = 0] = "Tangent";
          RotateMode[RotateMode["Chain"] = 1] = "Chain";
          RotateMode[RotateMode["ChainScale"] = 2] = "ChainScale";
        })(spine.RotateMode || (spine.RotateMode = {}));
        (function (TextureFilter) {
          TextureFilter[TextureFilter["Nearest"] = 9728] = "Nearest";
          TextureFilter[TextureFilter["Linear"] = 9729] = "Linear";
          TextureFilter[TextureFilter["MipMap"] = 9987] = "MipMap";
          TextureFilter[TextureFilter["MipMapNearestNearest"] = 9984] = "MipMapNearestNearest";
          TextureFilter[TextureFilter["MipMapLinearNearest"] = 9985] = "MipMapLinearNearest";
          TextureFilter[TextureFilter["MipMapNearestLinear"] = 9986] = "MipMapNearestLinear";
          TextureFilter[TextureFilter["MipMapLinearLinear"] = 9987] = "MipMapLinearLinear";
        })(spine.TextureFilter || (spine.TextureFilter = {}));
        (function (TextureWrap) {
          TextureWrap[TextureWrap["MirroredRepeat"] = 33648] = "MirroredRepeat";
          TextureWrap[TextureWrap["ClampToEdge"] = 33071] = "ClampToEdge";
          TextureWrap[TextureWrap["Repeat"] = 10497] = "Repeat";
        })(spine.TextureWrap || (spine.TextureWrap = {}));
        (function (AttachmentType) {
          AttachmentType[AttachmentType["Region"] = 0] = "Region";
          AttachmentType[AttachmentType["BoundingBox"] = 1] = "BoundingBox";
          AttachmentType[AttachmentType["Mesh"] = 2] = "Mesh";
          AttachmentType[AttachmentType["LinkedMesh"] = 3] = "LinkedMesh";
          AttachmentType[AttachmentType["Path"] = 4] = "Path";
          AttachmentType[AttachmentType["Point"] = 5] = "Point";
          AttachmentType[AttachmentType["Clipping"] = 6] = "Clipping";
        })(spine.AttachmentType || (spine.AttachmentType = {}));
      })(spine || (spine = {}));
      var spine$1 = spine;

      var _listener_ID = 0;
      var _track_ID = 0;
      var TrackEntryListeners = function () {
        function TrackEntryListeners() {
          this.start = void 0;
          this.interrupt = void 0;
          this.end = void 0;
          this.dispose = void 0;
          this.complete = void 0;
          this.event = void 0;
        }
        TrackEntryListeners.getListeners = function getListeners(entry, instance) {
          if (!entry.listener) {
            entry.listener = new TrackEntryListeners();
            var id = ++_track_ID;
            instance.setTrackEntryListener(id, entry);
            TrackEntryListeners._trackSet.set(id, entry);
          }
          return entry.listener;
        };
        TrackEntryListeners.emitListener = function emitListener(id, entry, event) {
          var listener = TrackEntryListeners._listenerSet.get(id);
          if (!listener) return;
          var listener2 = listener;
          if (listener2) {
            listener2(entry, event);
          }
        };
        TrackEntryListeners.emitTrackEntryListener = function emitTrackEntryListener(id, entry, event, eventType) {
          var curTrack = this._trackSet.get(id);
          if (!curTrack) return;
          switch (eventType) {
            case spine$1.EventType.start:
              if (curTrack.listener.start) {
                curTrack.listener.start(entry);
              }
              break;
            case spine$1.EventType.interrupt:
              if (curTrack.listener.interrupt) {
                curTrack.listener.interrupt(entry);
              }
              break;
            case spine$1.EventType.end:
              if (curTrack.listener.end) {
                curTrack.listener.end(entry);
              }
              break;
            case spine$1.EventType.dispose:
              if (curTrack.listener.dispose) {
                curTrack.listener.dispose(entry);
              }
              this._trackSet["delete"](id);
              curTrack.listener = null;
              break;
            case spine$1.EventType.complete:
              if (curTrack.listener.complete) {
                curTrack.listener.complete(entry);
              }
              break;
            case spine$1.EventType.event:
              if (curTrack.listener.event) {
                curTrack.listener.event(entry, event);
              }
              break;
            default:
              warn('TrackEntry doesn\'t handled', eventType);
              break;
          }
        };
        TrackEntryListeners.addListener = function addListener(listener) {
          var id = ++_listener_ID;
          TrackEntryListeners._listenerSet.set(id, listener);
          return id;
        };
        return TrackEntryListeners;
      }();
      TrackEntryListeners._listenerSet = new Map();
      TrackEntryListeners._trackSet = new Map();
      globalThis.TrackEntryListeners = TrackEntryListeners;

      function resizeArray(array, newSize) {
        if (!array) return new Array(newSize);
        if (newSize === array.length) return array;
        if (newSize < array.length) return array.slice(0, newSize);else return new Array(newSize);
      }
      function overrideDefineArrayProp(prototype, getPropVector, name) {
        var _name = "_" + name;
        Object.defineProperty(prototype, name, {
          get: function get() {
            var vectors = getPropVector.call(this);
            var count = vectors.size();
            var array = this[_name];
            array = resizeArray(array, count);
            for (var i = 0; i < count; i++) array[i] = vectors.get(i);
            this[_name] = array;
            return array;
          }
        });
      }
      function overrideDefineArrayArrayProp(prototype, getPropVector, name) {
        var _name = "_" + name;
        Object.defineProperty(prototype, name, {
          get: function get() {
            var vectors = getPropVector.call(this);
            var count = vectors.size();
            var array = this[_name];
            array = resizeArray(array, count);
            for (var i = 0; i < count; i++) {
              var vectorI = vectors.get(i);
              var countJ = vectorI.size();
              var arrayJ = array[i];
              arrayJ = resizeArray(arrayJ, countJ);
              for (var j = 0; j < countJ; j++) arrayJ[j] = vectorI.get(j);
              array[i] = arrayJ;
            }
            this[_name] = array;
            return array;
          }
        });
      }
      function overrideDefineArrayFunction(prototype, getPropVector, name) {
        var _name = "_" + name;
        Object.defineProperty(prototype, name, {
          value: function value() {
            var vectors = getPropVector.call(this);
            var count = vectors.size();
            var array = this[_name];
            array = resizeArray(array, count);
            for (var i = 0; i < count; i++) array[i] = vectors.get(i);
            this[_name] = array;
            return array;
          }
        });
      }
      function overrideDefinePtrStringFunction(prototype, getPtr, name) {
        Object.defineProperty(prototype, name, {
          value: function value() {
            var str = '';
            var ptr = getPtr.call(this);
            var HEAPU8 = spine$1.wasmUtil.wasm.HEAPU8;
            var length = this.length;
            var buffer = HEAPU8.subarray(ptr, ptr + length);
            str = String.fromCharCode.apply(String, buffer);
            return str;
          }
        });
      }
      function overrideClass(wasm) {
        spine$1.wasmUtil = wasm.SpineWasmUtil;
        spine$1.wasmUtil.wasm = wasm;
        spine$1.wasmUtil.spineWasmInit();
        spine$1.SPVectorFloat = wasm.SPVectorFloat;
        spine$1.MathUtils = wasm.MathUtils;
        spine$1.Color = wasm.Color;
        spine$1.String = wasm.String;
        spine$1.Vector2 = wasm.Vector2;
        spine$1.Interpolation = wasm.Interpolation;
        spine$1.Triangulator = wasm.Triangulator;
        spine$1.ConstraintData = wasm.ConstraintData;
        spine$1.IkConstraintData = wasm.IkConstraintData;
        spine$1.PathConstraintData = wasm.PathConstraintData;
        spine$1.SkeletonBounds = wasm.SkeletonBounds;
        spine$1.Event = wasm.Event;
        spine$1.EventData = wasm.EventData;
        spine$1.Attachment = wasm.Attachment;
        spine$1.VertexAttachment = wasm.VertexAttachment;
        spine$1.BoundingBoxAttachment = wasm.BoundingBoxAttachment;
        spine$1.ClippingAttachment = wasm.ClippingAttachment;
        spine$1.MeshAttachment = wasm.MeshAttachment;
        spine$1.PathAttachment = wasm.PathAttachment;
        spine$1.PointAttachment = wasm.PointAttachment;
        spine$1.RegionAttachment = wasm.RegionAttachment;
        spine$1.AtlasAttachmentLoader = wasm.AtlasAttachmentLoader;
        spine$1.TextureAtlasPage = wasm.TextureAtlasPage;
        spine$1.TextureAtlasRegion = wasm.TextureAtlasRegion;
        spine$1.TextureAtlas = wasm.TextureAtlas;
        spine$1.PowOut = wasm.PowOut;
        spine$1.BoneData = wasm.BoneData;
        spine$1.SlotData = wasm.SlotData;
        spine$1.Updatable = wasm.Updatable;
        spine$1.IkConstraint = wasm.IkConstraint;
        spine$1.PathConstraint = wasm.PathConstraint;
        spine$1.TransformConstraintData = wasm.TransformConstraintData;
        spine$1.TransformConstraint = wasm.TransformConstraint;
        spine$1.Bone = wasm.Bone;
        spine$1.Slot = wasm.Slot;
        spine$1.Skin = wasm.Skin;
        spine$1.SkinEntry = wasm.SkinEntry;
        spine$1.SkeletonClipping = wasm.SkeletonClipping;
        spine$1.SkeletonData = wasm.SkeletonData;
        spine$1.TranslateTimeline = wasm.TranslateTimeline;
        spine$1.ScaleTimeline = wasm.ScaleTimeline;
        spine$1.ShearTimeline = wasm.ShearTimeline;
        spine$1.RotateTimeline = wasm.RotateTimeline;
        spine$1.ColorTimeline = wasm.ColorTimeline;
        spine$1.TwoColorTimeline = wasm.TwoColorTimeline;
        spine$1.AttachmentTimeline = wasm.AttachmentTimeline;
        spine$1.DeformTimeline = wasm.DeformTimeline;
        spine$1.EventTimeline = wasm.EventTimeline;
        spine$1.DrawOrderTimeline = wasm.DrawOrderTimeline;
        spine$1.IkConstraintTimeline = wasm.IkConstraintTimeline;
        spine$1.TransformConstraintTimeline = wasm.TransformConstraintTimeline;
        spine$1.PathConstraintPositionTimeline = wasm.PathConstraintPositionTimeline;
        spine$1.PathConstraintMixTimeline = wasm.PathConstraintMixTimeline;
        spine$1.TrackEntry = wasm.TrackEntry;
        spine$1.AnimationStateData = wasm.AnimationStateData;
        spine$1.AnimationState = wasm.AnimationState;
        spine$1.Animation = wasm.Animation;
        spine$1.EventQueue = wasm.EventQueue;
        spine$1.AnimationStateAdapter = wasm.AnimationStateAdapter;
        spine$1.Skeleton = wasm.Skeleton;
        spine$1.SkeletonBinary = wasm.SkeletonBinary;
        spine$1.SkeletonJson = wasm.SkeletonJson;
        spine$1.VertexEffect = wasm.VertexEffect;
        spine$1.JitterEffect = wasm.JitterEffect;
        spine$1.SwirlEffect = wasm.SwirlEffect;
        spine$1.SkeletonInstance = wasm.SkeletonInstance;
        spine$1.SkeletonSystem = wasm.SkeletonSystem;
      }
      function overrideProperty_String() {
        var prototype = spine$1.String.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'length',
          getter: prototype.length
        }, {
          proto: prototype,
          property: 'isEmpty',
          getter: prototype.isEmpty
        }, {
          proto: prototype,
          property: 'str',
          getter: prototype.str
        }];
        propertyPolyfills.forEach(function (prop) {
          get(prop.proto, prop.property, prop.getter);
        });
        overrideDefinePtrStringFunction(prototype, prototype.strPtr, 'strPtr');
      }
      function overrideProperty_Vector2() {
        var prototype = spine$1.Vector2.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'x',
          getter: prototype.getX,
          setter: prototype.setX
        }, {
          proto: prototype,
          property: 'y',
          getter: prototype.getY,
          setter: prototype.setY
        }];
        propertyPolyfills.forEach(function (prop) {
          get(prop.proto, prop.property, prop.getter, prop.setter);
        });
      }
      function overrideProperty_BoneData() {
        var prototype = spine$1.BoneData.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'index',
          getter: prototype.getIndex
        }, {
          proto: prototype,
          property: 'name',
          getter: prototype.getName
        }, {
          proto: prototype,
          property: 'parent',
          getter: prototype.getParent
        }, {
          proto: prototype,
          property: 'length',
          getter: prototype.getLength,
          setter: prototype.setLength
        }, {
          proto: prototype,
          property: 'x',
          getter: prototype.getX,
          setter: prototype.setX
        }, {
          proto: prototype,
          property: 'y',
          getter: prototype.getY,
          setter: prototype.setY
        }, {
          proto: prototype,
          property: 'rotation',
          getter: prototype.getRotation,
          setter: prototype.setRotation
        }, {
          proto: prototype,
          property: 'scaleX',
          getter: prototype.getScaleX,
          setter: prototype.setScaleX
        }, {
          proto: prototype,
          property: 'scaleY',
          getter: prototype.getScaleY,
          setter: prototype.setScaleY
        }, {
          proto: prototype,
          property: 'shearX',
          getter: prototype.getShearX,
          setter: prototype.setShearX
        }, {
          proto: prototype,
          property: 'shearY',
          getter: prototype.getShearY,
          setter: prototype.setShearY
        }, {
          proto: prototype,
          property: 'transformMode',
          getter: prototype.getTransformMode,
          setter: prototype.setTransformMode
        }, {
          proto: prototype,
          property: 'skinRequired',
          getter: prototype.getSkinRequired,
          setter: prototype.setSkinRequired
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
      }
      function overrideProperty_Attachment() {
        var prototype = spine$1.Attachment.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'name',
          getter: prototype.getName
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
      }
      function overrideProperty_ConstraintData() {
        var prototype = spine$1.ConstraintData.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'name',
          getter: prototype.getName
        }, {
          proto: prototype,
          property: 'order',
          getter: prototype.getOrder,
          setter: prototype.setOder
        }, {
          proto: prototype,
          property: 'skinRequired',
          getter: prototype.getSkinRequired,
          setter: prototype.setSkinRequired
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
      }
      function overrideProperty_IkConstraintData() {
        var prototype = spine$1.IkConstraintData.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'target',
          getter: prototype.getTarget,
          setter: prototype.setTarget
        }, {
          proto: prototype,
          property: 'bendDirection',
          getter: prototype.getBendDirection,
          setter: prototype.setBendDirection
        }, {
          proto: prototype,
          property: 'compress',
          getter: prototype.getCompress,
          setter: prototype.setCompress
        }, {
          proto: prototype,
          property: 'stretch',
          getter: prototype.getStretch,
          setter: prototype.setStretch
        }, {
          proto: prototype,
          property: 'uniform',
          getter: prototype.getUniform,
          setter: prototype.setUniform
        }, {
          proto: prototype,
          property: 'mix',
          getter: prototype.getMix,
          setter: prototype.setMix
        }, {
          proto: prototype,
          property: 'softness',
          getter: prototype.getSoftness,
          setter: prototype.setSoftness
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getBones, 'bones');
      }
      function overrideProperty_PathConstraintData() {
        var prototype = spine$1.PathConstraintData.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'target',
          getter: prototype.getTarget,
          setter: prototype.setTarget
        }, {
          proto: prototype,
          property: 'positionMode',
          getter: prototype.getPositionMode,
          setter: prototype.setPositionMode
        }, {
          proto: prototype,
          property: 'spacingMode',
          getter: prototype.getSpacingMode,
          setter: prototype.setSpacingMode
        }, {
          proto: prototype,
          property: 'rotateMode',
          getter: prototype.getRotateMode,
          setter: prototype.setRotateMode
        }, {
          proto: prototype,
          property: 'offsetRotation',
          getter: prototype.getOffsetRotation,
          setter: prototype.setOffsetRotation
        }, {
          proto: prototype,
          property: 'position',
          getter: prototype.getPosition,
          setter: prototype.setPosition
        }, {
          proto: prototype,
          property: 'spacing',
          getter: prototype.getSpacing,
          setter: prototype.setSpacing
        }, {
          proto: prototype,
          property: 'rotateMix',
          getter: prototype.getRotateMix,
          setter: prototype.setRotateMix
        }, {
          proto: prototype,
          property: 'translateMix',
          getter: prototype.getTranslateMix,
          setter: prototype.setTranslateMix
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getBones, 'bones');
      }
      function overrideProperty_Event() {
        var prototype = spine$1.Event.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'data',
          getter: prototype.getData
        }, {
          proto: prototype,
          property: 'intValue',
          getter: prototype.getIntValue,
          setter: prototype.setIntValue
        }, {
          proto: prototype,
          property: 'floatValue',
          getter: prototype.getFloatValue,
          setter: prototype.setFloatValue
        }, {
          proto: prototype,
          property: 'stringValue',
          getter: prototype.getStringValue,
          setter: prototype.setStringValue
        }, {
          proto: prototype,
          property: 'time',
          getter: prototype.getTime
        }, {
          proto: prototype,
          property: 'volume',
          getter: prototype.getVolume,
          setter: prototype.setVolume
        }, {
          proto: prototype,
          property: 'balance',
          getter: prototype.getBalance,
          setter: prototype.setBalance
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
      }
      function overrideProperty_EventData() {
        var prototype = spine$1.EventData.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'name',
          getter: prototype.getName
        }, {
          proto: prototype,
          property: 'intValue',
          getter: prototype.getIntValue,
          setter: prototype.setIntValue
        }, {
          proto: prototype,
          property: 'floatValue',
          getter: prototype.getFloatValue,
          setter: prototype.setFloatValue
        }, {
          proto: prototype,
          property: 'stringValue',
          getter: prototype.getStringValue,
          setter: prototype.setStringValue
        }, {
          proto: prototype,
          property: 'audioPath',
          getter: prototype.getAudioPath,
          setter: prototype.setAudioPath
        }, {
          proto: prototype,
          property: 'volume',
          getter: prototype.getVolume,
          setter: prototype.setVolume
        }, {
          proto: prototype,
          property: 'balance',
          getter: prototype.getBalance,
          setter: prototype.setBalance
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
      }
      function overrideProperty_VertexAttachment() {
        var prototype = spine$1.VertexAttachment.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'id',
          getter: prototype.getId
        }, {
          proto: prototype,
          property: 'worldVerticesLength',
          getter: prototype.getWorldVerticesLength,
          setter: prototype.setWorldVerticesLength
        }, {
          proto: prototype,
          property: 'deformAttachment',
          getter: prototype.getDeformAttachment,
          setter: prototype.setDeformAttachment
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getBones, 'bones');
        overrideDefineArrayProp(prototype, prototype.getVertices, 'vertices');
        var originComputeWorldVertices = prototype.computeWorldVertices;
        var vectors = new spine$1.SPVectorFloat();
        Object.defineProperty(prototype, 'computeWorldVertices', {
          value: function value(slot, start, count, worldVertices, offset, stride) {
            var length = worldVertices.length;
            vectors.resize(length, 0);
            for (var i = 0; i < length; i++) vectors.set(i, worldVertices[i]);
            originComputeWorldVertices.call(this, slot, start, count, vectors, offset, stride);
            for (var _i = 0; _i < length; _i++) worldVertices[_i] = vectors.get(_i);
          }
        });
      }
      function overrideProperty_BoundingBoxAttachment() {
        var prototype = spine$1.BoundingBoxAttachment.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'name',
          getter: prototype.getName
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
      }
      function overrideProperty_ClippingAttachment() {
        var prototype = spine$1.ClippingAttachment.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'endSlot',
          getter: prototype.getEndSlot,
          setter: prototype.setEndSlot
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
      }
      function overrideProperty_MeshAttachment() {
        var prototype = spine$1.MeshAttachment.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'path',
          getter: prototype.getPath,
          setter: prototype.setPath
        }, {
          proto: prototype,
          property: 'color',
          getter: prototype.getColor
        }, {
          proto: prototype,
          property: 'width',
          getter: prototype.getWidth,
          setter: prototype.setWidth
        }, {
          proto: prototype,
          property: 'height',
          getter: prototype.getHeight,
          setter: prototype.setHeight
        }, {
          proto: prototype,
          property: 'hullLength',
          getter: prototype.getHullLength,
          setter: prototype.setHullLength
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getRegionUVs, 'regionUVs');
        overrideDefineArrayProp(prototype, prototype.getUVs, 'uvs');
        overrideDefineArrayProp(prototype, prototype.getTriangles, 'triangles');
        overrideDefineArrayProp(prototype, prototype.getEdges, 'edges');
      }
      function overrideProperty_PathAttachment() {
        var prototype = spine$1.PathAttachment.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'closed',
          getter: prototype.getClosed,
          setter: prototype.setClosed
        }, {
          proto: prototype,
          property: 'constantSpeed',
          getter: prototype.getConstantSpeed,
          setter: prototype.setConstantSpeed
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
        overrideDefineArrayProp(prototype, prototype.getLengths, 'lengths');
      }
      function overrideProperty_PointAttachment() {
        var prototype = spine$1.PointAttachment.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'x',
          getter: prototype.getX,
          setter: prototype.setX
        }, {
          proto: prototype,
          property: 'y',
          getter: prototype.getY,
          setter: prototype.setY
        }, {
          proto: prototype,
          property: 'rotation',
          getter: prototype.getRotation,
          setter: prototype.setRotation
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
      }
      function overrideProperty_RegionAttachment() {
        var prototype = spine$1.RegionAttachment.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'x',
          getter: prototype.getX,
          setter: prototype.setX
        }, {
          proto: prototype,
          property: 'y',
          getter: prototype.getY,
          setter: prototype.setY
        }, {
          proto: prototype,
          property: 'scaleX',
          getter: prototype.getScaleX,
          setter: prototype.setScaleX
        }, {
          proto: prototype,
          property: 'scaleY',
          getter: prototype.getScaleY,
          setter: prototype.setScaleY
        }, {
          proto: prototype,
          property: 'rotation',
          getter: prototype.getRotation,
          setter: prototype.setRotation
        }, {
          proto: prototype,
          property: 'width',
          getter: prototype.getWidth,
          setter: prototype.setWidth
        }, {
          proto: prototype,
          property: 'height',
          getter: prototype.getHeight,
          setter: prototype.setHeight
        }, {
          proto: prototype,
          property: 'color',
          getter: prototype.getColor
        }, {
          proto: prototype,
          property: 'path',
          getter: prototype.getPath,
          setter: prototype.setPath
        }, {
          proto: prototype,
          property: 'rendererObject',
          getter: prototype.getRendererObject
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getOffset, 'offset');
        var getUVs = prototype.getUVs;
        var setUVs = prototype.setUVs;
        var _uvs = '_uvs';
        Object.defineProperty(prototype, 'uvs', {
          get: function get() {
            var vectors = getUVs.call(this);
            var count = vectors.size();
            var array = prototype[_uvs];
            array = resizeArray(array, count);
            for (var i = 0; i < count; i++) array[i] = vectors.get(i);
            prototype[_uvs] = array;
            return array;
          },
          set: function set(value) {
            setUVs.call(this, value[0], value[1], value[2], value[3], value[4] === 1);
          }
        });
        var originComputeWorldVertices = prototype.computeWorldVertices;
        var vectors = new spine$1.SPVectorFloat();
        Object.defineProperty(prototype, 'computeWorldVertices', {
          value: function value(bone, worldVertices, offset, stride) {
            var length = worldVertices.length;
            vectors.resize(length, 0);
            for (var i = 0; i < length; i++) vectors.set(i, worldVertices[i]);
            originComputeWorldVertices.call(this, bone, vectors, offset, stride);
            for (var _i2 = 0; _i2 < length; _i2++) worldVertices[_i2] = vectors.get(_i2);
          }
        });
      }
      function overrideProperty_SlotData() {
        var prototype = spine$1.SlotData.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'index',
          getter: prototype.getIndex
        }, {
          proto: prototype,
          property: 'boneData',
          getter: prototype.getBoneData
        }, {
          proto: prototype,
          property: 'name',
          getter: prototype.getName
        }, {
          proto: prototype,
          property: 'color',
          getter: prototype.getColor
        }, {
          proto: prototype,
          property: 'darkColor',
          getter: prototype.getDarkColor
        }, {
          proto: prototype,
          property: 'blendMode',
          getter: prototype.getBlendMode,
          setter: prototype.setBlendMode
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
      }
      function overrideProperty_IkConstraint() {
        var prototype = spine$1.IkConstraint.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'data',
          getter: prototype.getData
        }, {
          proto: prototype,
          property: 'target',
          getter: prototype.getTarget,
          setter: prototype.setTarget
        }, {
          proto: prototype,
          property: 'bendDirection',
          getter: prototype.getBendDirection,
          setter: prototype.setBendDirection
        }, {
          proto: prototype,
          property: 'compress',
          getter: prototype.getCompress,
          setter: prototype.setCompress
        }, {
          proto: prototype,
          property: 'stretch',
          getter: prototype.getStretch,
          setter: prototype.setStretch
        }, {
          proto: prototype,
          property: 'mix',
          getter: prototype.getMix,
          setter: prototype.setMix
        }, {
          proto: prototype,
          property: 'softness',
          getter: prototype.getSoftness,
          setter: prototype.setSoftness
        }, {
          proto: prototype,
          property: 'active',
          getter: prototype.getActive,
          setter: prototype.setActive
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getBones, 'bones');
      }
      function overrideProperty_PathConstraint() {
        var prototype = spine$1.PathConstraint.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'data',
          getter: prototype.getData
        }, {
          proto: prototype,
          property: 'target',
          getter: prototype.getTarget,
          setter: prototype.setTarget
        }, {
          proto: prototype,
          property: 'position',
          getter: prototype.getPosition,
          setter: prototype.setPosition
        }, {
          proto: prototype,
          property: 'spacing',
          getter: prototype.getSpacing,
          setter: prototype.setSpacing
        }, {
          proto: prototype,
          property: 'rotateMix',
          getter: prototype.getRotateMix,
          setter: prototype.setRotateMix
        }, {
          proto: prototype,
          property: 'translateMix',
          getter: prototype.getTranslateMix,
          setter: prototype.setTranslateMix
        }, {
          proto: prototype,
          property: 'active',
          getter: prototype.getActive,
          setter: prototype.setActive
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getBones, 'bones');
      }
      function overrideProperty_TransformConstraintData() {
        var prototype = spine$1.TransformConstraintData.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'target',
          getter: prototype.getTarget
        }, {
          proto: prototype,
          property: 'rotateMix',
          getter: prototype.getRotateMix
        }, {
          proto: prototype,
          property: 'translateMix',
          getter: prototype.getTranslateMix
        }, {
          proto: prototype,
          property: 'scaleMix',
          getter: prototype.getScaleMix
        }, {
          proto: prototype,
          property: 'shearMix',
          getter: prototype.getShearMix
        }, {
          proto: prototype,
          property: 'offsetRotation',
          getter: prototype.getOffsetRotation
        }, {
          proto: prototype,
          property: 'offsetX',
          getter: prototype.getOffsetX
        }, {
          proto: prototype,
          property: 'offsetY',
          getter: prototype.getOffsetY
        }, {
          proto: prototype,
          property: 'offsetScaleX',
          getter: prototype.getOffsetScaleX
        }, {
          proto: prototype,
          property: 'offsetScaleY',
          getter: prototype.getOffsetScaleY
        }, {
          proto: prototype,
          property: 'offsetShearY',
          getter: prototype.getOffsetShearY
        }, {
          proto: prototype,
          property: 'relative',
          getter: prototype.getRelative
        }, {
          proto: prototype,
          property: 'local',
          getter: prototype.getLocal
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
        overrideDefineArrayProp(prototype, prototype.getBones, 'bones');
      }
      function overrideProperty_TransformConstraint() {
        var prototype = spine$1.TransformConstraint.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'data',
          getter: prototype.getData
        }, {
          proto: prototype,
          property: 'target',
          getter: prototype.getTarget
        }, {
          proto: prototype,
          property: 'rotateMix',
          getter: prototype.getRotateMix,
          setter: prototype.setRotateMix
        }, {
          proto: prototype,
          property: 'translateMix',
          getter: prototype.getTranslateMix,
          setter: prototype.setTranslateMix
        }, {
          proto: prototype,
          property: 'scaleMix',
          getter: prototype.getScaleMix,
          setter: prototype.setScaleMix
        }, {
          proto: prototype,
          property: 'shearMix',
          getter: prototype.getShearMix,
          setter: prototype.setShearMix
        }, {
          proto: prototype,
          property: 'active',
          getter: prototype.getActive,
          setter: prototype.setActive
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getBones, 'bones');
      }
      function overrideProperty_Bone() {
        var prototype = spine$1.Bone.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'skeleton',
          getter: prototype.getSkeleton
        }, {
          proto: prototype,
          property: 'data',
          getter: prototype.getData
        }, {
          proto: prototype,
          property: 'parent',
          getter: prototype.getParent
        }, {
          proto: prototype,
          property: 'x',
          getter: prototype.getX,
          setter: prototype.setX
        }, {
          proto: prototype,
          property: 'y',
          getter: prototype.getY,
          setter: prototype.setY
        }, {
          proto: prototype,
          property: 'rotation',
          getter: prototype.getRotation,
          setter: prototype.setRotation
        }, {
          proto: prototype,
          property: 'scaleX',
          getter: prototype.getScaleX,
          setter: prototype.setScaleX
        }, {
          proto: prototype,
          property: 'scaleY',
          getter: prototype.getScaleY,
          setter: prototype.setScaleY
        }, {
          proto: prototype,
          property: 'shearX',
          getter: prototype.getShearX,
          setter: prototype.setShearX
        }, {
          proto: prototype,
          property: 'shearY',
          getter: prototype.getShearY,
          setter: prototype.setShearY
        }, {
          proto: prototype,
          property: 'ax',
          getter: prototype.getAX,
          setter: prototype.setAX
        }, {
          proto: prototype,
          property: 'ay',
          getter: prototype.getAY,
          setter: prototype.setAY
        }, {
          proto: prototype,
          property: 'arotation',
          getter: prototype.getARotation,
          setter: prototype.setARotation
        }, {
          proto: prototype,
          property: 'ascaleX',
          getter: prototype.getAScaleX,
          setter: prototype.setAScaleX
        }, {
          proto: prototype,
          property: 'ascaleY',
          getter: prototype.getAScaleY,
          setter: prototype.setAScaleY
        }, {
          proto: prototype,
          property: 'ashearX',
          getter: prototype.getAShearX,
          setter: prototype.setAShearX
        }, {
          proto: prototype,
          property: 'ashearY',
          getter: prototype.getAShearY,
          setter: prototype.setAShearY
        }, {
          proto: prototype,
          property: 'appliedValid',
          getter: prototype.getAppliedValid,
          setter: prototype.setAppliedValid
        }, {
          proto: prototype,
          property: 'a',
          getter: prototype.getA,
          setter: prototype.setA
        }, {
          proto: prototype,
          property: 'b',
          getter: prototype.getB,
          setter: prototype.setB
        }, {
          proto: prototype,
          property: 'c',
          getter: prototype.getC,
          setter: prototype.setC
        }, {
          proto: prototype,
          property: 'd',
          getter: prototype.getD,
          setter: prototype.setD
        }, {
          proto: prototype,
          property: 'worldX',
          getter: prototype.getWorldX,
          setter: prototype.setWorldX
        }, {
          proto: prototype,
          property: 'worldY',
          getter: prototype.getWorldY,
          setter: prototype.setWorldY
        }, {
          proto: prototype,
          property: 'active',
          getter: prototype.getActive,
          setter: prototype.setActive
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getChildren, 'children');
      }
      function overrideProperty_Slot() {
        var prototype = spine$1.Slot.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'data',
          getter: prototype.getData
        }, {
          proto: prototype,
          property: 'bone',
          getter: prototype.getBone
        }, {
          proto: prototype,
          property: 'color',
          getter: prototype.getColor
        }, {
          proto: prototype,
          property: 'darkColor',
          getter: prototype.getDarkColor
        }, {
          proto: prototype,
          property: 'skeleton',
          getter: prototype.getSkeleton
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
        overrideDefineArrayProp(prototype, prototype.getDeform, 'deform');
      }
      function overrideProperty_Skin() {
        var prototype = spine$1.Skin.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'name',
          getter: prototype.getName
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
        overrideDefineArrayProp(prototype, prototype.getBones, 'bones');
        overrideDefineArrayProp(prototype, prototype.getAttachments, 'attachments');
        overrideDefineArrayProp(prototype, prototype.getConstraints, 'constraints');
        overrideDefineArrayFunction(prototype, prototype.getAttachments, 'getAttachments');
        var originGetAttachmentsForSlot = prototype.getAttachmentsForSlot;
        Object.defineProperty(prototype, 'getAttachmentsForSlot', {
          value: function value(slotIndex, attachments) {
            var vectors = originGetAttachmentsForSlot.call(this, slotIndex);
            var count = vectors.size();
            attachments = resizeArray(attachments, count);
            for (var i = 0; i < count; i++) attachments[i] = vectors.get(i);
            vectors["delete"]();
          }
        });
        var originFindNamesForSlot = prototype.findNamesForSlot;
        Object.defineProperty(prototype, 'findNamesForSlot', {
          value: function value(slotIndex, names) {
            var vectors = originFindNamesForSlot.call(this, slotIndex);
            var count = vectors.size();
            names = resizeArray(names, count);
            for (var i = 0; i < count; i++) names[i] = vectors.get(i);
            vectors["delete"]();
          }
        });
      }
      function overrideProperty_SkinEntry() {
        var prototype = spine$1.SkinEntry.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'name',
          getter: prototype.getName
        }, {
          proto: prototype,
          property: 'attachment',
          getter: prototype.getAttachment
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
      }
      function overrideProperty_SkeletonClipping() {
        var prototype = spine$1.SkeletonClipping.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'clippedVertices',
          getter: prototype.getClippedVertices
        }, {
          proto: prototype,
          property: 'clippedTriangles',
          getter: prototype.getClippedTriangles
        }, {
          proto: prototype,
          property: 'clippedUVs',
          getter: prototype.getClippedUVs
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
      }
      function overrideProperty_SkeletonData() {
        var prototype = spine$1.SkeletonData.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'name',
          getter: prototype.getName
        }, {
          proto: prototype,
          property: 'defaultSkin',
          getter: prototype.getDefaultSkin,
          setter: prototype.setDefaultSkin
        }, {
          proto: prototype,
          property: 'x',
          getter: prototype.getX,
          setter: prototype.setX
        }, {
          proto: prototype,
          property: 'y',
          getter: prototype.getY,
          setter: prototype.setY
        }, {
          proto: prototype,
          property: 'width',
          getter: prototype.getWidth,
          setter: prototype.setWidth
        }, {
          proto: prototype,
          property: 'height',
          getter: prototype.getHeight,
          setter: prototype.setHeight
        }, {
          proto: prototype,
          property: 'version',
          getter: prototype.getVersion,
          setter: prototype.setVersion
        }, {
          proto: prototype,
          property: 'hash',
          getter: prototype.getHash,
          setter: prototype.setHash
        }, {
          proto: prototype,
          property: 'fps',
          getter: prototype.getFps,
          setter: prototype.setFps
        }, {
          proto: prototype,
          property: 'imagesPath',
          getter: prototype.getImagesPath,
          setter: prototype.setImagesPath
        }, {
          proto: prototype,
          property: 'audioPath',
          getter: prototype.getAudioPath,
          setter: prototype.setAudioPath
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getBones, 'bones');
        overrideDefineArrayProp(prototype, prototype.getSlots, 'slots');
        overrideDefineArrayProp(prototype, prototype.getSkins, 'skins');
        overrideDefineArrayProp(prototype, prototype.getAnimations, 'animations');
        overrideDefineArrayProp(prototype, prototype.getEvents, 'events');
        overrideDefineArrayProp(prototype, prototype.getIkConstraints, 'ikConstraints');
        overrideDefineArrayProp(prototype, prototype.getTransformConstraints, 'transformConstraints');
        overrideDefineArrayProp(prototype, prototype.getPathConstraints, 'pathConstraints');
      }
      function overrideProperty_RotateTimeline() {
        var prototype = spine$1.RotateTimeline.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'boneIndex',
          getter: prototype.getBoneIndex
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
        overrideDefineArrayProp(prototype, prototype.getFrames, 'frames');
      }
      function overrideProperty_ColorTimeline() {
        var prototype = spine$1.ColorTimeline.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'slotIndex',
          getter: prototype.getSlotIndex
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
        overrideDefineArrayProp(prototype, prototype.getFrames, 'frames');
      }
      function overrideProperty_TwoColorTimeline() {
        var prototype = spine$1.TwoColorTimeline.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'slotIndex',
          getter: prototype.getSlotIndex
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
      }
      function overrideProperty_AttachmentTimeline() {
        var prototype = spine$1.AttachmentTimeline.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'slotIndex',
          getter: prototype.getSlotIndex
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
        overrideDefineArrayProp(prototype, prototype.getFrames, 'frames');
        overrideDefineArrayProp(prototype, prototype.getAttachmentNames, 'attachmentNames');
      }
      function overrideProperty_DeformTimeline() {
        var prototype = spine$1.DeformTimeline.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'slotIndex',
          getter: prototype.getSlotIndex
        }, {
          proto: prototype,
          property: 'attachment',
          getter: prototype.getAttachment
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
        overrideDefineArrayProp(prototype, prototype.getFrames, 'frames');
        overrideDefineArrayArrayProp(prototype, prototype.getFrameVertices, 'frameVertices');
      }
      function overrideProperty_EventTimeline() {
        var prototype = spine$1.EventTimeline.prototype;
        overrideDefineArrayProp(prototype, prototype.getFrames, 'frames');
        overrideDefineArrayProp(prototype, prototype.getEvents, 'events');
      }
      function overrideProperty_DrawOrderTimeline() {
        var prototype = spine$1.DrawOrderTimeline.prototype;
        overrideDefineArrayProp(prototype, prototype.getFrames, 'frames');
      }
      function overrideProperty_TrackEntry() {
        var prototype = spine$1.TrackEntry.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'animation',
          getter: prototype.getAnimation
        }, {
          proto: prototype,
          property: 'next',
          getter: prototype.getNext
        }, {
          proto: prototype,
          property: 'mixingFrom',
          getter: prototype.getMixingFrom
        }, {
          proto: prototype,
          property: 'mixingTo',
          getter: prototype.getMixingTo
        }, {
          proto: prototype,
          property: 'trackIndex',
          getter: prototype.getTrackIndex
        }, {
          proto: prototype,
          property: 'loop',
          getter: prototype.getLoop,
          setter: prototype.setLoop
        }, {
          proto: prototype,
          property: 'holdPrevious',
          getter: prototype.getHoldPrevious,
          setter: prototype.setHoldPrevious
        }, {
          proto: prototype,
          property: 'eventThreshold',
          getter: prototype.getEventThreshold,
          setter: prototype.setEventThreshold
        }, {
          proto: prototype,
          property: 'attachmentThreshold',
          getter: prototype.getAttachmentThreshold,
          setter: prototype.setAttachmentThreshold
        }, {
          proto: prototype,
          property: 'drawOrderThreshold',
          getter: prototype.getDrawOrderThreshold,
          setter: prototype.setDrawOrderThreshold
        }, {
          proto: prototype,
          property: 'animationStart',
          getter: prototype.getAnimationStart,
          setter: prototype.setAnimationStart
        }, {
          proto: prototype,
          property: 'animationEnd',
          getter: prototype.getAnimationEnd,
          setter: prototype.setAnimationEnd
        }, {
          proto: prototype,
          property: 'animationLast',
          getter: prototype.getAnimationLast,
          setter: prototype.setAnimationLast
        }, {
          proto: prototype,
          property: 'delay',
          getter: prototype.getDelay,
          setter: prototype.setDelay
        }, {
          proto: prototype,
          property: 'trackTime',
          getter: prototype.getTrackTime,
          setter: prototype.setTrackTime
        }, {
          proto: prototype,
          property: 'trackEnd',
          getter: prototype.getTrackEnd,
          setter: prototype.setTrackEnd
        }, {
          proto: prototype,
          property: 'timeScale',
          getter: prototype.getTimeScale,
          setter: prototype.setTimeScale
        }, {
          proto: prototype,
          property: 'alpha',
          getter: prototype.getAlpha,
          setter: prototype.setAlpha
        }, {
          proto: prototype,
          property: 'mixTime',
          getter: prototype.getMixTime,
          setter: prototype.setMixTime
        }, {
          proto: prototype,
          property: 'mixDuration',
          getter: prototype.getMixDuration,
          setter: prototype.setMixDuration
        }, {
          proto: prototype,
          property: 'mixBlend',
          getter: prototype.getMixBlend,
          setter: prototype.setMixBlend
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
      }
      function overrideProperty_AnimationStateData() {
        var prototype = spine$1.AnimationStateData.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'defaultMix',
          getter: prototype.getDefaultMix
        }, {
          proto: prototype,
          property: 'skeletonData',
          getter: prototype.getSkeletonData
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter);
        });
      }
      function overrideProperty_AnimationState() {
        var prototype = spine$1.AnimationState.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'data',
          getter: prototype.getData
        }, {
          proto: prototype,
          property: 'timeScale',
          getter: prototype.getTimeScale,
          setter: prototype.setTimeScale
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getTracks, 'tracks');
      }
      function overrideProperty_Animation() {
        var prototype = spine$1.Animation.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'name',
          getter: prototype.getName
        }, {
          proto: prototype,
          property: 'duration',
          getter: prototype.getDuration,
          setter: prototype.setDuration
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getTimelines, 'timelines');
      }
      function overrideProperty_Skeleton() {
        var prototype = spine$1.Skeleton.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'data',
          getter: prototype.getData
        }, {
          proto: prototype,
          property: 'skin',
          getter: prototype.getSkin
        }, {
          proto: prototype,
          property: 'color',
          getter: prototype.getColor
        }, {
          proto: prototype,
          property: 'time',
          getter: prototype.getTime
        }, {
          proto: prototype,
          property: 'scaleX',
          getter: prototype.getScaleX,
          setter: prototype.setScaleX
        }, {
          proto: prototype,
          property: 'scaleY',
          getter: prototype.getScaleY,
          setter: prototype.setScaleY
        }, {
          proto: prototype,
          property: 'x',
          getter: prototype.getX,
          setter: prototype.setX
        }, {
          proto: prototype,
          property: 'y',
          getter: prototype.getY,
          setter: prototype.setY
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
        overrideDefineArrayProp(prototype, prototype.getBones, 'bones');
        overrideDefineArrayProp(prototype, prototype.getSlots, 'slots');
        overrideDefineArrayProp(prototype, prototype.getDrawOrder, 'drawOrder');
        overrideDefineArrayProp(prototype, prototype.getIkConstraints, 'ikConstraints');
        overrideDefineArrayProp(prototype, prototype.getTransformConstraints, 'transformConstraints');
        overrideDefineArrayProp(prototype, prototype.getPathConstraints, 'pathConstraints');
        overrideDefineArrayProp(prototype, prototype.getUpdateCacheList, '_updateCache');
      }
      function overrideProperty_JitterEffect() {
        var prototype = spine$1.JitterEffect.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'jitterX',
          getter: prototype.getJitterX,
          setter: prototype.setJitterX
        }, {
          proto: prototype,
          property: 'jitterY',
          getter: prototype.getJitterY,
          setter: prototype.setJitterY
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
      }
      function overrideProperty_SwirlEffect() {
        var prototype = spine$1.SwirlEffect.prototype;
        var propertyPolyfills = [{
          proto: prototype,
          property: 'centerX',
          getter: prototype.getCenterX,
          setter: prototype.setCenterX
        }, {
          proto: prototype,
          property: 'centerY',
          getter: prototype.getCenterY,
          setter: prototype.setCenterY
        }, {
          proto: prototype,
          property: 'radius',
          getter: prototype.getRadius,
          setter: prototype.setRadius
        }, {
          proto: prototype,
          property: 'angle',
          getter: prototype.getAngle,
          setter: prototype.setAngle
        }];
        propertyPolyfills.forEach(function (prop) {
          getset(prop.proto, prop.property, prop.getter, prop.setter);
        });
      }
      function overrideSpineDefine(wasm) {
        overrideClass(wasm);
        overrideProperty_String();
        overrideProperty_Vector2();
        overrideProperty_BoneData();
        overrideProperty_ConstraintData();
        overrideProperty_IkConstraintData();
        overrideProperty_PathConstraintData();
        overrideProperty_Event();
        overrideProperty_EventData();
        overrideProperty_BoundingBoxAttachment();
        overrideProperty_ClippingAttachment();
        overrideProperty_MeshAttachment();
        overrideProperty_PathAttachment();
        overrideProperty_PointAttachment();
        overrideProperty_RegionAttachment();
        overrideProperty_VertexAttachment();
        overrideProperty_SlotData();
        overrideProperty_IkConstraint();
        overrideProperty_PathConstraint();
        overrideProperty_TransformConstraintData();
        overrideProperty_TransformConstraint();
        overrideProperty_Bone();
        overrideProperty_Slot();
        overrideProperty_Skin();
        overrideProperty_Attachment();
        overrideProperty_SkinEntry();
        overrideProperty_SkeletonClipping();
        overrideProperty_SkeletonData();
        overrideProperty_RotateTimeline();
        overrideProperty_ColorTimeline();
        overrideProperty_TwoColorTimeline();
        overrideProperty_AttachmentTimeline();
        overrideProperty_DeformTimeline();
        overrideProperty_EventTimeline();
        overrideProperty_DrawOrderTimeline();
        overrideProperty_TrackEntry();
        overrideProperty_AnimationStateData();
        overrideProperty_AnimationState();
        overrideProperty_Animation();
        overrideProperty_Skeleton();
        overrideProperty_JitterEffect();
        overrideProperty_SwirlEffect();
      }

      var PAGESIZE = 65536;
      var PAGECOUNT = 32 * 16;
      var MEMORYSIZE = PAGESIZE * PAGECOUNT;
      var wasmInstance = null;
      var registerList = [];
      function initWasm(wasmFactory, wasmUrl) {
        return new Promise(function (resolve, reject) {
          var errorMessage = function errorMessage(err) {
            return "[Spine]: Spine wasm load failed: " + err;
          };
          wasmFactory({
            instantiateWasm: function instantiateWasm$1(importObject, receiveInstance) {
              instantiateWasm(wasmUrl, importObject).then(function (result) {
                receiveInstance(result.instance, result.module);
              })["catch"](function (err) {
                return reject(errorMessage(err));
              });
            }
          }).then(function (Instance) {
            wasmInstance = Instance;
            registerList.forEach(function (cb) {
              cb(wasmInstance);
            });
          }).then(resolve)["catch"](function (err) {
            return reject(errorMessage(err));
          });
        });
      }
      function initAsmJS(asmFactory, asmJsMemUrl) {
        return new Promise(function (resolve, reject) {
          fetchBuffer(asmJsMemUrl).then(function (arrayBuffer) {
            var wasmMemory = {};
            wasmMemory.buffer = new ArrayBuffer(MEMORYSIZE);
            var module = {
              wasmMemory: wasmMemory,
              memoryInitializerRequest: {
                response: arrayBuffer,
                status: 200
              }
            };
            return asmFactory(module).then(function (instance) {
              wasmInstance = instance;
              registerList.forEach(function (cb) {
                cb(wasmInstance);
              });
            });
          }).then(resolve)["catch"](reject);
        });
      }
      function shouldUseWasmModule() {
        {
          return sys.hasFeature(sys.Feature.WASM);
        }
      }
      function waitForSpineWasmInstantiation() {
        var errorReport = function errorReport(msg) {
          error(msg);
        };
        return ensureWasmModuleReady().then(function () {
          if (shouldUseWasmModule()) {
            return Promise.all([module.import('./spine.wasm-655fd4f5.js'), module.import('./spine-9a8528df.js')]).then(function (_ref) {
              var wasmFactory = _ref[0]["default"],
                spineWasmUrl = _ref[1]["default"];
              return initWasm(wasmFactory, spineWasmUrl);
            });
          } else {
            return Promise.all([module.import('./spine.asm-97b906da.js'), module.import('./spine.js-6d0b02e3.js')]).then(function (_ref2) {
              var asmFactory = _ref2[0]["default"],
                asmJsMemUrl = _ref2[1]["default"];
              return initAsmJS(asmFactory, asmJsMemUrl);
            });
          }
        })["catch"](errorReport);
      }
      {
        game.onPostInfrastructureInitDelegate.add(waitForSpineWasmInstantiation);
        registerList.push(overrideSpineDefine);
      }

      var _class5$3;
      var MaxCacheTime = 30;
      var FrameTime = 1 / 60;
      var _useTint$1 = true;
      getAttributeStride(vfmtPosUvColor4B);
      var _byteStrideTwoColor$1 = getAttributeStride(vfmtPosUvTwoColor4B);
      var FrameBoneInfo = function FrameBoneInfo() {
        this.a = 0;
        this.b = 0;
        this.c = 0;
        this.d = 0;
        this.worldX = 0;
        this.worldY = 0;
      };
      var SpineModel = function SpineModel() {
        this.vCount = 0;
        this.iCount = 0;
        this.vData = null;
        this.iData = null;
        this.meshes = [];
      };
      var SpineDrawItem = function SpineDrawItem() {
        this.iCount = 0;
        this.blendMode = 0;
        this.textureID = 0;
      };
      var AnimationCache = function () {
        function AnimationCache(data) {
          this._instance = null;
          this._state = null;
          this._skeletonData = null;
          this._skeleton = null;
          this._privateMode = false;
          this._curIndex = -1;
          this._isCompleted = false;
          this._maxFrameIdex = 0;
          this._frameIdx = -1;
          this._inited = false;
          this._invalid = true;
          this._enableCacheAttachedInfo = false;
          this._skeletonInfo = null;
          this._animationName = null;
          this.isCompleted = false;
          this.totalTime = 0;
          this.frames = [];
          this._privateMode = false;
          this._inited = false;
          this._invalid = true;
          this._instance = new spine$1.SkeletonInstance();
          this._instance.isCache = true;
          this._skeletonData = data;
          this._skeleton = this._instance.initSkeleton(data);
          this._instance.setUseTint(_useTint$1);
        }
        var _proto = AnimationCache.prototype;
        _proto.init = function init(skeletonInfo, animationName) {
          this._inited = true;
          this._animationName = animationName;
          this._skeletonInfo = skeletonInfo;
        };
        _proto.setSkin = function setSkin(skinName) {
          if (this._skeleton) this._skeleton.setSkinByName(skinName);
          this._instance.setSkin(skinName);
        };
        _proto.setAnimation = function setAnimation(animationName) {
          var animations = this._skeletonData.animations;
          var animation = null;
          animations.forEach(function (element) {
            if (element.name === animationName) {
              animation = element;
            }
          });
          if (!animation) {
            warn("find no animation named " + animationName + " !!!");
            return;
          }
          this._maxFrameIdex = Math.floor(animation.duration / FrameTime);
          if (this._maxFrameIdex <= 0) this._maxFrameIdex = 1;
          this._instance.setAnimation(0, animationName, false);
        };
        _proto.updateToFrame = function updateToFrame(frameIdx) {
          if (!this._inited) return;
          this.begin();
          if (!this.needToUpdate(frameIdx)) return;
          do {
            this._frameIdx++;
            this.totalTime += FrameTime;
            this._instance.updateAnimation(FrameTime);
            var model = this._instance.updateRenderData();
            this.updateRenderData(this._frameIdx, model);
            if (this._frameIdx >= this._maxFrameIdex) {
              this.isCompleted = true;
            }
          } while (this.needToUpdate(frameIdx));
        };
        _proto.getFrame = function getFrame(frameIdx) {
          var index = frameIdx % this._maxFrameIdex;
          return this.frames[index];
        };
        _proto.invalidAnimationFrames = function invalidAnimationFrames() {
          this._curIndex = -1;
          this._isCompleted = false;
          this.frames.length = 0;
        };
        _proto.updateRenderData = function updateRenderData(index, model) {
          var vc = model.vCount;
          var ic = model.iCount;
          var floatStride = (_byteStrideTwoColor$1 ) / Float32Array.BYTES_PER_ELEMENT;
          var vUint8Buf = new Uint8Array(Float32Array.BYTES_PER_ELEMENT * floatStride * vc);
          var iUint16Buf = new Uint16Array(ic);
          var HEAPU8 = spine$1.wasmUtil.wasm.HEAPU8;
          var vPtr = model.vPtr;
          var vLength = vc * Float32Array.BYTES_PER_ELEMENT * floatStride;
          vUint8Buf.set(HEAPU8.subarray(vPtr, vPtr + vLength));
          var iPtr = model.iPtr;
          var iLength = Uint16Array.BYTES_PER_ELEMENT * ic;
          var iUint8Buf = new Uint8Array(iUint16Buf.buffer);
          iUint8Buf.set(HEAPU8.subarray(iPtr, iPtr + iLength));
          var modelData = new SpineModel();
          modelData.vCount = vc;
          modelData.iCount = ic;
          modelData.vData = vUint8Buf;
          modelData.iData = iUint16Buf;
          var data = model.getData();
          var count = data.size();
          for (var i = 0; i < count; i += 6) {
            var meshData = new SpineDrawItem();
            meshData.iCount = data.get(i + 3);
            meshData.blendMode = data.get(i + 4);
            meshData.textureID = data.get(i + 5);
            modelData.meshes.push(meshData);
          }
          var bones = this._skeleton.bones;
          var boneInfosArray = [];
          bones.forEach(function (bone) {
            var boneInfo = new FrameBoneInfo();
            boneInfo.a = bone.a;
            boneInfo.b = bone.b;
            boneInfo.c = bone.c;
            boneInfo.d = bone.d;
            boneInfo.worldX = bone.worldX;
            boneInfo.worldY = bone.worldY;
            boneInfosArray.push(boneInfo);
          });
          this.frames[index] = {
            model: modelData,
            boneInfos: boneInfosArray
          };
        };
        _proto.begin = function begin() {
          if (!this._invalid) return;
          var skeletonInfo = this._skeletonInfo;
          var preAnimationCache = skeletonInfo === null || skeletonInfo === void 0 ? void 0 : skeletonInfo.curAnimationCache;
          if (preAnimationCache && preAnimationCache !== this) {
            if (this._privateMode) {
              preAnimationCache.invalidAllFrame();
            } else {
              preAnimationCache.updateToFrame(0);
            }
          }
          var listener = skeletonInfo === null || skeletonInfo === void 0 ? void 0 : skeletonInfo.listener;
          this._instance.setAnimation(0, this._animationName, false);
          this.bind(listener);
          skeletonInfo.curAnimationCache = this;
          this._frameIdx = -1;
          this.isCompleted = false;
          this.totalTime = 0;
          this._invalid = false;
        };
        _proto.end = function end() {
          if (!this.needToUpdate()) {
            this._skeletonInfo.curAnimationCache = null;
            this.frames.length = this._frameIdx + 1;
            this.isCompleted = true;
            this.unbind(this._skeletonInfo.listener);
          }
        };
        _proto.bind = function bind(listener) {
          var _this = this;
          var completeHandle = function completeHandle(entry) {
            if (entry && entry.animation.name === _this._animationName) {
              _this.isCompleted = true;
            }
          };
          listener.complete = completeHandle;
        };
        _proto.unbind = function unbind(listener) {
          listener.complete = null;
        };
        _proto.needToUpdate = function needToUpdate(toFrameIdx) {
          return !this.isCompleted && this.totalTime < MaxCacheTime && (toFrameIdx === undefined || this._frameIdx < toFrameIdx);
        };
        _proto.isInited = function isInited() {
          return this._inited;
        };
        _proto.isInvalid = function isInvalid() {
          return this._invalid;
        };
        _proto.invalidAllFrame = function invalidAllFrame() {
          this.isCompleted = false;
          this._invalid = true;
        };
        _proto.enableCacheAttachedInfo = function enableCacheAttachedInfo() {
          if (!this._enableCacheAttachedInfo) {
            this._enableCacheAttachedInfo = true;
            this.invalidAllFrame();
          }
        };
        _proto.clear = function clear() {
          this._inited = false;
          this.invalidAllFrame();
        };
        _proto.destroy = function destroy() {
          if (this._instance) {
            this._instance.destroy();
            this._instance = null;
          }
        };
        _createClass(AnimationCache, [{
          key: "skeleton",
          get: function get() {
            return this._skeleton;
          }
        }]);
        return AnimationCache;
      }();
      var SkeletonCache = function () {
        function SkeletonCache() {
          this._privateMode = void 0;
          this._skeletonCache = void 0;
          this._animationPool = void 0;
          this._sharedCacheMap = new Map();
          this._privateMode = false;
          this._animationPool = {};
          this._skeletonCache = {};
        }
        var _proto2 = SkeletonCache.prototype;
        _proto2.enablePrivateMode = function enablePrivateMode() {
          this._privateMode = true;
        };
        _proto2.clear = function clear() {
          this._animationPool = {};
          this._skeletonCache = {};
        };
        _proto2.invalidAnimationCache = function invalidAnimationCache(uuid) {
          var skeletonInfo = this._skeletonCache[uuid];
          var skeleton = skeletonInfo && skeletonInfo.skeleton;
          if (!skeleton) return;
          var animationsCache = skeletonInfo.animationsCache;
          for (var aniKey in animationsCache) {
            var animationCache = animationsCache[aniKey];
            animationCache.invalidAllFrame();
          }
        };
        _proto2.destroySkeleton = function destroySkeleton(assetUuid) {
          var _this2 = this;
          if (!this._privateMode) {
            var refCount = this._sharedCacheMap.get(assetUuid);
            if (refCount) {
              refCount -= 1;
              if (refCount > 0) {
                this._sharedCacheMap.set(assetUuid, refCount);
                return;
              }
              this._sharedCacheMap["delete"](assetUuid);
            }
          }
          var sharedOperate = function sharedOperate(aniKey, animationCache) {
            _this2._animationPool[assetUuid + "#" + aniKey] = animationCache;
            animationCache.clear();
          };
          var privateOperate = function privateOperate(aniKey, animationCache) {
            animationCache.destroy();
          };
          var operate = this._privateMode ? privateOperate : sharedOperate;
          var skeletonInfo = this._skeletonCache[assetUuid];
          if (!skeletonInfo) return;
          var animationsCache = skeletonInfo.animationsCache;
          for (var aniKey in animationsCache) {
            var animationCache = animationsCache[aniKey];
            if (!animationCache) continue;
            operate(aniKey, animationCache);
          }
          if (skeletonInfo.skeleton) {
            spine$1.wasmUtil.destroySpineSkeleton(skeletonInfo.skeleton);
          }
          delete this._skeletonCache[assetUuid];
        };
        _proto2.createSkeletonInfo = function createSkeletonInfo(skeletonAsset) {
          var uuid = skeletonAsset.uuid;
          var runtimeData = skeletonAsset.getRuntimeData();
          if (!this._privateMode) {
            var refCount = this._sharedCacheMap.get(uuid);
            if (!refCount) {
              refCount = 1;
            } else {
              refCount += 1;
            }
            this._sharedCacheMap.set(uuid, refCount);
          }
          if (this._skeletonCache[uuid]) {
            return this._skeletonCache[uuid];
          }
          var skeleton = new spine$1.Skeleton(runtimeData);
          var clipper = null;
          var state = null;
          var listener = new TrackEntryListeners();
          var skeletonInfo = this._skeletonCache[uuid] = {
            skeleton: skeleton,
            clipper: clipper,
            state: state,
            listener: listener,
            animationsCache: {},
            curAnimationCache: null,
            assetUUID: uuid
          };
          return skeletonInfo;
        };
        _proto2.getSkeletonInfo = function getSkeletonInfo(skeletonAsset) {
          var uuid = skeletonAsset.uuid;
          return this._skeletonCache[uuid];
        };
        _proto2.getAnimationCache = function getAnimationCache(uuid, animationName) {
          var skeletonInfo = this._skeletonCache[uuid];
          if (!skeletonInfo) return null;
          var animationsCache = skeletonInfo.animationsCache;
          return animationsCache[animationName];
        };
        _proto2.initAnimationCache = function initAnimationCache(uuid, data, animationName) {
          var spData = data.getRuntimeData();
          if (!spData) return null;
          var skeletonInfo = this._skeletonCache[uuid];
          var skeleton = skeletonInfo && skeletonInfo.skeleton;
          if (!skeleton) return null;
          var animationsCache = skeletonInfo.animationsCache;
          var animationCache = animationsCache[animationName];
          if (!animationCache) {
            var poolKey = uuid + "#" + animationName;
            animationCache = this._animationPool[poolKey];
            if (animationCache) {
              delete this._animationPool[poolKey];
            } else {
              animationCache = new AnimationCache(spData);
              animationCache._privateMode = this._privateMode;
            }
            animationCache.init(skeletonInfo, animationName);
            animationsCache[animationName] = animationCache;
          }
          animationCache.init(skeletonInfo, animationName);
          animationCache.setAnimation(animationName);
          return animationCache;
        };
        _proto2.destroyCachedAnimations = function destroyCachedAnimations(uuid) {
          if (uuid) {
            var animationPool = this._animationPool;
            for (var _key in animationPool) {
              if (_key.includes(uuid)) {
                animationPool[_key].destroy();
                delete animationPool[_key];
              }
            }
          } else {
            var _animationPool = this._animationPool;
            for (var _key2 in _animationPool) {
              _animationPool[_key2].destroy();
              delete _animationPool[_key2];
            }
          }
        };
        return SkeletonCache;
      }();
      _class5$3 = SkeletonCache;
      SkeletonCache.FrameTime = FrameTime;
      SkeletonCache.sharedCache = new _class5$3();

      var _dec$s, _dec2$p, _dec3$n, _class$s, _class2$o, _initializer$m, _initializer2$l, _initializer3$h, _initializer4$f, _initializer5$d;
      var SkeletonData = (_dec$s = ccclass$M('sp.SkeletonData'), _dec2$p = type$d([Texture2D]), _dec3$n = type$d([CCString]), _dec$s(_class$s = (_class2$o = function (_Asset) {
        _inheritsLoose(SkeletonData, _Asset);
        function SkeletonData() {
          var _this;
          _this = _Asset.call(this) || this;
          _this._skeletonJson = _initializer$m && _initializer$m();
          _this.textures = _initializer2$l && _initializer2$l();
          _this.textureNames = _initializer3$h && _initializer3$h();
          _this.scale = _initializer4$f && _initializer4$f();
          _this._atlasText = _initializer5$d && _initializer5$d();
          _this._buffer = void 0;
          _this._skeletonCache = null;
          _this._skinsEnum = null;
          _this._animsEnum = null;
          _this.reset();
          return _this;
        }
        var _proto = SkeletonData.prototype;
        _proto.createNode = function createNode(callback) {
          var node = new Node$1(this.name);
          var skeleton = node.addComponent('cc.Skeleton');
          skeleton.skeletonData = this;
          return callback(null, node);
        };
        _proto.reset = function reset() {
          this._skeletonCache = null;
        };
        _proto.resetEnums = function resetEnums() {
        };
        _proto.getRuntimeData = function getRuntimeData(quiet) {
          if (this._skeletonCache) {
            return this._skeletonCache;
          }
          if (!(this.textures && this.textures.length > 0) && this.textureNames && this.textureNames.length > 0) {
            if (!quiet) {
              error(this.name + " no textures found!");
            }
            return null;
          }
          var spData = spine$1.wasmUtil.querySpineSkeletonDataByUUID(this._uuid);
          if (spData) {
            this._skeletonCache = spData;
          } else if (this.skeletonJsonStr) {
            this._skeletonCache = spine$1.wasmUtil.createSpineSkeletonDataWithJson(this.skeletonJsonStr, this._atlasText);
            spine$1.wasmUtil.registerSpineSkeletonDataWithUUID(this._skeletonCache, this._uuid);
          } else {
            var rawData = new Uint8Array(this._nativeAsset);
            var byteSize = rawData.length;
            var ptr = spine$1.wasmUtil.queryStoreMemory(byteSize);
            var wasmMem = spine$1.wasmUtil.wasm.HEAPU8.subarray(ptr, ptr + byteSize);
            wasmMem.set(rawData);
            this._skeletonCache = spine$1.wasmUtil.createSpineSkeletonDataWithBinary(byteSize, this._atlasText);
            spine$1.wasmUtil.registerSpineSkeletonDataWithUUID(this._skeletonCache, this._uuid);
          }
          return this._skeletonCache;
        };
        _proto.getSkinsEnum = function getSkinsEnum() {
          if (this._skinsEnum) {
            return this._skinsEnum;
          }
          var sd = this.getRuntimeData(true);
          if (sd) {
            var skins = sd.skins;
            var enumDef = {};
            for (var i = 0; i < skins.length; i++) {
              var name = skins[i].name;
              enumDef[name] = i;
            }
            return this._skinsEnum = Enum(enumDef);
          }
          return null;
        };
        _proto.getAnimsEnum = function getAnimsEnum() {
          if (this._animsEnum && Object.keys(this._animsEnum).length > 1) {
            return this._animsEnum;
          }
          var sd = this.getRuntimeData(true);
          if (sd) {
            var enumDef = {
              '<None>': 0
            };
            var anims = sd.animations;
            for (var i = 0; i < anims.length; i++) {
              var name = anims[i].name;
              enumDef[name] = i + 1;
            }
            return this._animsEnum = Enum(enumDef);
          }
          return null;
        };
        _proto.destroy = function destroy() {
          SkeletonCache.sharedCache.destroyCachedAnimations(this._uuid);
          if (this._skeletonCache) {
            spine$1.wasmUtil.registerSpineSkeletonDataWithUUID(this._skeletonCache, this._uuid);
          }
          return _Asset.prototype.destroy.call(this);
        };
        _createClass(SkeletonData, [{
          key: "skeletonJsonStr",
          get: function get() {
            if (this._skeletonJson) {
              return JSON.stringify(this._skeletonJson);
            }
            return '';
          }
        }, {
          key: "skeletonJson",
          get: function get() {
            return this._skeletonJson;
          },
          set: function set(value) {
            this.reset();
            if (typeof value === 'string') {
              this._skeletonJson = JSON.parse(value);
            } else {
              this._skeletonJson = value;
            }
            if (!this._uuid && value.skeleton) {
              this._uuid = value.skeleton.hash;
            }
          }
        }, {
          key: "atlasText",
          get: function get() {
            return this._atlasText;
          },
          set: function set(value) {
            this._atlasText = value;
            this.reset();
          }
        }, {
          key: "_nativeAsset",
          get: function get() {
            return this._buffer;
          },
          set: function set(bin) {
            this._buffer = bin;
            this.reset();
          }
        }]);
        return SkeletonData;
      }(Asset), (_initializer$m = applyDecoratedInitializer(_class2$o.prototype, "_skeletonJson", [serializable$p], function () {
        return null;
      }), _initializer2$l = applyDecoratedInitializer(_class2$o.prototype, "textures", [serializable$p, _dec2$p], function () {
        return [];
      }), _initializer3$h = applyDecoratedInitializer(_class2$o.prototype, "textureNames", [serializable$p, _dec3$n], function () {
        return [];
      }), _initializer4$f = applyDecoratedInitializer(_class2$o.prototype, "scale", [serializable$p], function () {
        return 1;
      }), _initializer5$d = applyDecoratedInitializer(_class2$o.prototype, "_atlasText", [serializable$p], function () {
        return '';
      })), _class2$o)) || _class$s);
      legacyCC.internal.SpineSkeletonData = SkeletonData;

      var SkeletonSystem = function (_System) {
        _inheritsLoose(SkeletonSystem, _System);
        function SkeletonSystem() {
          var _this;
          _this = _System.call(this) || this;
          _this._skeletons = new Set();
          return _this;
        }
        SkeletonSystem.getInstance = function getInstance() {
          if (!SkeletonSystem._instance) {
            SkeletonSystem._instance = new SkeletonSystem();
            director.registerSystem(SkeletonSystem.ID, SkeletonSystem._instance, System.Priority.HIGH);
          }
          return SkeletonSystem._instance;
        };
        var _proto = SkeletonSystem.prototype;
        _proto.add = function add(skeleton) {
          if (!skeleton) return;
          if (!this._skeletons.has(skeleton)) {
            this._skeletons.add(skeleton);
          }
        };
        _proto.remove = function remove(skeleton) {
          if (!skeleton) return;
          if (this._skeletons.has(skeleton)) {
            this._skeletons["delete"](skeleton);
          }
        };
        _proto.postUpdate = function postUpdate(dt) {
          if (!this._skeletons) {
            return;
          }
          this._skeletons.forEach(function (skeleton) {
            skeleton.updateAnimation(dt);
          });
        };
        _proto.prepareRenderData = function prepareRenderData() {
          if (!this._skeletons) {
            return;
          }
          this._skeletons.forEach(function (skeleton) {
            skeleton.markForUpdateRenderData();
          });
        };
        return SkeletonSystem;
      }(System);
      SkeletonSystem.ID = 'SKELETON';
      SkeletonSystem._instance = void 0;
      legacyCC.internal.SpineSkeletonSystem = SkeletonSystem;

      var tempMat4 = new Mat4();
      var AttachUtil = function () {
        function AttachUtil() {
          this._isInitialized = false;
          this._skeletonBones = null;
          this._socketNodes = null;
          this._keysToDelete = [];
          this._isInitialized = false;
        }
        var _proto = AttachUtil.prototype;
        _proto.init = function init(skeletonComp) {
          var _skeletonComp$socketN;
          this._isInitialized = false;
          if (!skeletonComp || ((_skeletonComp$socketN = skeletonComp.socketNodes) === null || _skeletonComp$socketN === void 0 ? void 0 : _skeletonComp$socketN.size) === 0) return;
          this._skeletonBones = skeletonComp._skeleton.bones;
          if (!this._skeletonBones || this._skeletonBones.length < 1) return;
          this._socketNodes = skeletonComp.socketNodes;
          if (!this._socketNodes || this._socketNodes.size <= 0) return;
          this._isInitialized = true;
          this._syncAttachedNode();
        };
        _proto.updateSkeletonBones = function updateSkeletonBones(bones) {
          this._skeletonBones = bones;
        };
        _proto.reset = function reset() {
          this._isInitialized = false;
          this._skeletonBones = null;
          this._socketNodes = null;
          this._keysToDelete.length = 0;
        };
        _proto._syncAttachedNode = function _syncAttachedNode() {
          if (!this._isInitialized) return;
          var socketNodes = this._socketNodes;
          for (var _iterator = _createForOfIteratorHelperLoose(socketNodes), _step; !(_step = _iterator()).done;) {
            var _step$value = _step.value,
              boneIdx = _step$value[0],
              boneNode = _step$value[1];
            if (!boneNode || !boneNode.isValid) {
              this._keysToDelete.push(boneIdx);
              continue;
            }
            var bone = this._skeletonBones[boneIdx];
            if (bone) this.matrixHandle(boneNode, bone);
          }
          if (this._keysToDelete.length <= 0) return;
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._keysToDelete), _step2; !(_step2 = _iterator2()).done;) {
            var _boneIdx = _step2.value;
            socketNodes["delete"](_boneIdx);
          }
          this._keysToDelete.length = 0;
        };
        _proto.matrixHandle = function matrixHandle(node, bone) {
          var tm = tempMat4;
          tm.m00 = bone.a;
          tm.m01 = bone.c;
          tm.m04 = bone.b;
          tm.m05 = bone.d;
          tm.m12 = bone.worldX;
          tm.m13 = bone.worldY;
          node.matrix = tempMat4;
        };
        return AttachUtil;
      }();

      var _dec$r, _dec2$o, _class$r, _class2$n, _initializer$l, _initializer2$k, _dec3$m, _dec4$g, _dec5$g, _dec6$a, _dec7$8, _dec8$6, _dec9$5, _class4$1, _class5$2, _initializer3$g, _initializer4$e, _initializer5$c, _initializer6$9, _initializer7$9, _initializer8$9, _initializer9$8, _initializer10$8, _initializer11$8, _initializer12$7, _initializer13$5, _initializer14$4, _initializer15$3, _initializer16$3, _class6;
      var CUSTOM_SLOT_TEXTURE_BEGIN = 10000;
      var _slotTextureID = CUSTOM_SLOT_TEXTURE_BEGIN;
      var timeScale = 1.0;
      var AnimationCacheMode;
      (function (AnimationCacheMode) {
        AnimationCacheMode[AnimationCacheMode["UNSET"] = -1] = "UNSET";
        AnimationCacheMode[AnimationCacheMode["REALTIME"] = 0] = "REALTIME";
        AnimationCacheMode[AnimationCacheMode["SHARED_CACHE"] = 1] = "SHARED_CACHE";
        AnimationCacheMode[AnimationCacheMode["PRIVATE_CACHE"] = 2] = "PRIVATE_CACHE";
      })(AnimationCacheMode || (AnimationCacheMode = {}));
      ccenum(AnimationCacheMode);
      var DefaultSkinsEnum;
      (function (DefaultSkinsEnum) {
        DefaultSkinsEnum[DefaultSkinsEnum["default"] = 0] = "default";
      })(DefaultSkinsEnum || (DefaultSkinsEnum = {}));
      ccenum(DefaultSkinsEnum);
      var DefaultAnimsEnum;
      (function (DefaultAnimsEnum) {
        DefaultAnimsEnum[DefaultAnimsEnum["<None>"] = 0] = "<None>";
      })(DefaultAnimsEnum || (DefaultAnimsEnum = {}));
      ccenum(DefaultAnimsEnum);
      var SpineMaterialType;
      (function (SpineMaterialType) {
        SpineMaterialType[SpineMaterialType["COLORED_TEXTURED"] = 0] = "COLORED_TEXTURED";
        SpineMaterialType[SpineMaterialType["TWO_COLORED"] = 1] = "TWO_COLORED";
      })(SpineMaterialType || (SpineMaterialType = {}));
      var SpineSocket = (_dec$r = ccclass$M('sp.Skeleton.SpineSocket'), _dec2$o = type$d(Node$1), _dec$r(_class$r = (_class2$n = function SpineSocket(path, target) {
        if (path === void 0) {
          path = '';
        }
        if (target === void 0) {
          target = null;
        }
        this.path = _initializer$l && _initializer$l();
        this.target = _initializer2$k && _initializer2$k();
        this.path = path;
        this.target = target;
      }, (_initializer$l = applyDecoratedInitializer(_class2$n.prototype, "path", [serializable$p], function () {
        return '';
      }), _initializer2$k = applyDecoratedInitializer(_class2$n.prototype, "target", [_dec2$o, serializable$p], function () {
        return null;
      })), _class2$n)) || _class$r);
      setClassAlias(SpineSocket, 'sp.Skeleton.SpineSocket');
      var Skeleton = (_dec3$m = ccclass$M('sp.Skeleton'), _dec4$g = type$d(SkeletonData), _dec5$g = type$d(DefaultSkinsEnum), _dec6$a = type$d(DefaultAnimsEnum), _dec7$8 = type$d(AnimationCacheMode), _dec8$6 = type$d([SpineSocket]), _dec9$5 = type$d(Material), _dec3$m(_class4$1 = (_class5$2 = (_class6 = function (_UIRenderer) {
        _inheritsLoose(Skeleton, _UIRenderer);
        function Skeleton() {
          var _this;
          _this = _UIRenderer.call(this) || this;
          _this._skeletonData = _initializer3$g && _initializer3$g();
          _this.defaultSkin = _initializer4$e && _initializer4$e();
          _this.defaultAnimation = _initializer5$c && _initializer5$c();
          _this._premultipliedAlpha = _initializer6$9 && _initializer6$9();
          _this._timeScale = _initializer7$9 && _initializer7$9();
          _this._preCacheMode = _initializer8$9 && _initializer8$9();
          _this._cacheMode = _initializer9$8 && _initializer9$8();
          _this._sockets = _initializer10$8 && _initializer10$8();
          _this._useTint = _initializer11$8 && _initializer11$8();
          _this._debugMesh = _initializer12$7 && _initializer12$7();
          _this._debugBones = _initializer13$5 && _initializer13$5();
          _this._debugSlots = _initializer14$4 && _initializer14$4();
          _this._enableBatch = _initializer15$3 && _initializer15$3();
          _this._runtimeData = null;
          _this._skeleton = null;
          _this._instance = null;
          _this._state = null;
          _this._textures = [];
          _this._skeletonInfo = null;
          _this._animationName = '';
          _this._skinName = '';
          _this._drawList = new RecyclePool(function () {
            return {
              material: null,
              texture: null,
              indexOffset: 0,
              indexCount: 0
            };
          }, 1);
          _this._materialCache = {};
          _this.paused = false;
          _this._enumSkins = Enum({});
          _this._enumAnimations = Enum({});
          _this.attachUtil = void 0;
          _this._socketNodes = new Map();
          _this._cachedSockets = new Map();
          _this._startEntry = void 0;
          _this._endEntry = void 0;
          _this._paused = false;
          _this._accTime = 0;
          _this._playCount = 0;
          _this._skeletonCache = null;
          _this._animCache = null;
          _this._animationQueue = [];
          _this._headAniInfo = null;
          _this._isAniComplete = true;
          _this._playTimes = 0;
          _this._curFrame = null;
          _this._needUpdateSkeltonData = true;
          _this._listener = null;
          _this._debugRenderer = null;
          _this._startSlotIndex = void 0;
          _this._endSlotIndex = void 0;
          _this._slotTextures = null;
          _this._vLength = 0;
          _this._vBuffer = null;
          _this._iLength = 0;
          _this._iBuffer = null;
          _this._model = void 0;
          _this._tempColor = {
            r: 0,
            g: 0,
            b: 0,
            a: 0
          };
          _this.loop = _initializer16$3 && _initializer16$3();
          _this._useVertexOpacity = true;
          _this._startEntry = {
            animation: {
              name: ''
            },
            trackIndex: 0
          };
          _this._endEntry = {
            animation: {
              name: ''
            },
            trackIndex: 0
          };
          _this._startSlotIndex = -1;
          _this._endSlotIndex = -1;
          {
            _this._instance = new spine$1.SkeletonInstance();
            _this._instance.dtRate = _this._timeScale * timeScale;
            _this._instance.isCache = _this.isAnimationCached();
          }
          _this.attachUtil = new AttachUtil();
          return _this;
        }
        var _proto = Skeleton.prototype;
        _proto.__preload = function __preload() {
          _UIRenderer.prototype.__preload.call(this);
          this._updateSkeletonData();
          this._updateDebugDraw();
        };
        _proto.onRestore = function onRestore() {
          this.updateMaterial();
          this.markForUpdateRenderData();
        };
        _proto.getState = function getState() {
          return this._state;
        };
        _proto.onEnable = function onEnable() {
          _UIRenderer.prototype.onEnable.call(this);
          if (this._instance) {
            this._instance.enable = true;
          }
          this._flushAssembler();
          SkeletonSystem.getInstance().add(this);
        };
        _proto.onDisable = function onDisable() {
          _UIRenderer.prototype.onDisable.call(this);
          if (this._instance) {
            this._instance.enable = false;
          }
          SkeletonSystem.getInstance().remove(this);
        };
        _proto.onDestroy = function onDestroy() {
          var _this$_slotTextures;
          this._drawList.destroy();
          this.destroyRenderData();
          this._cleanMaterialCache();
          this._vBuffer = null;
          this._iBuffer = null;
          this.attachUtil.reset();
          (_this$_slotTextures = this._slotTextures) === null || _this$_slotTextures === void 0 ? void 0 : _this$_slotTextures.clear();
          this._slotTextures = null;
          this._cachedSockets.clear();
          this._socketNodes.clear();
          this._animCache = null;
          SkeletonSystem.getInstance().remove(this);
          if (this._instance) {
            this._instance.destroy();
            this._instance = null;
          }
          this._destroySkeletonInfo(this._skeletonCache);
          this._skeletonCache = null;
          _UIRenderer.prototype.onDestroy.call(this);
        };
        _proto.clearAnimation = function clearAnimation(trackIndex) {
          if (!this.isAnimationCached()) {
            this.clearTrack(trackIndex || 0);
            this.setToSetupPose();
          }
        };
        _proto.clearAnimations = function clearAnimations() {
          if (!this.isAnimationCached()) {
            this.clearTracks();
            this.setToSetupPose();
          }
        };
        _proto._updateSkeletonData = function _updateSkeletonData() {
          var skeletonData = this._skeletonData;
          if (!skeletonData) {
            this._runtimeData = null;
            this._state = null;
            this._skeleton = null;
            this._textures = [];
            this._refreshInspector();
            return;
          }
          if (this._instance) {
            this._instance.dtRate = this._timeScale * timeScale;
          }
          this._needUpdateSkeltonData = false;
          this._runtimeData = skeletonData.getRuntimeData();
          if (!this._runtimeData) return;
          this.setSkeletonData(this._runtimeData);
          this._textures = skeletonData.textures;
          this._refreshInspector();
          if (this.defaultAnimation) this.animation = this.defaultAnimation.toString();
          if (this.defaultSkin && this.defaultSkin !== '') this.setSkin(this.defaultSkin);
          this._updateUseTint();
          this._indexBoneSockets();
          this._updateSocketBindings();
          this.attachUtil.init(this);
          this._preCacheMode = this._cacheMode;
        };
        _proto.setSkeletonData = function setSkeletonData(skeletonData) {
          {
            var preSkeletonCache = this._skeletonCache;
            if (this._cacheMode === AnimationCacheMode.SHARED_CACHE) {
              this._skeletonCache = SkeletonCache.sharedCache;
            } else if (this._cacheMode === AnimationCacheMode.PRIVATE_CACHE) {
              this._skeletonCache = new SkeletonCache();
              this._skeletonCache.enablePrivateMode();
            } else {
              this._skeletonCache = null;
            }
            if (preSkeletonCache !== this._skeletonCache) {
              this._destroySkeletonInfo(preSkeletonCache);
            }
          }
          if (this.isAnimationCached()) {
            if (this.debugBones || this.debugSlots) {
              warn('Debug bones or slots is invalid in cached mode');
            }
            var skeletonInfo = this._skeletonCache.getSkeletonInfo(this._skeletonData);
            if (this._skeletonInfo !== skeletonInfo) {
              this._destroySkeletonInfo(this._skeletonCache);
              this._skeletonInfo = this._skeletonCache.createSkeletonInfo(this._skeletonData);
              this._skeleton = this._skeletonInfo.skeleton;
            }
          } else {
            this._skeleton = this._instance.initSkeleton(skeletonData);
            this._state = this._instance.getAnimationState();
            this._instance.setPremultipliedAlpha(this._premultipliedAlpha);
          }
          this._flushAssembler();
        };
        _proto.setSlotsRange = function setSlotsRange(startSlotIndex, endSlotIndex) {
          if (this.isAnimationCached()) {
            warn('Slots visible range can not be modified in cached mode.');
          } else {
            this._startSlotIndex = startSlotIndex;
            this._endSlotIndex = endSlotIndex;
          }
        };
        _proto.getAttachment = function getAttachment(slotName, attachmentName) {
          if (this._skeleton) {
            return this._skeleton.getAttachmentByName(slotName, attachmentName);
          }
          return null;
        };
        _proto.setAttachment = function setAttachment(slotName, attachmentName) {
          if (this._skeleton) {
            this._skeleton.setAttachment(slotName, attachmentName);
          }
          this.invalidAnimationCache();
        };
        _proto.getTextureAtlas = function getTextureAtlas(regionAttachment) {
          return regionAttachment.region;
        };
        _proto.setAnimation = function setAnimation(trackIndex, name, loop) {
          if (!(typeof name === 'string')) {
            logID(7511);
            return null;
          }
          var animation = this._skeleton.data.findAnimation(name);
          if (!animation) {
            logID(7509, name);
            return null;
          }
          var trackEntry = null;
          if (loop === undefined) loop = true;
          this._playTimes = loop ? 0 : 1;
          if (this.isAnimationCached()) {
            if (trackIndex !== 0) {
              warn('Track index can not greater than 0 in cached mode.');
            }
            if (!this._skeletonCache) return null;
            var cache = this._skeletonCache.getAnimationCache(this._skeletonData.uuid, name);
            if (!cache) {
              var _cache;
              cache = this._skeletonCache.initAnimationCache(this.skeletonData.uuid, this._skeletonData, name);
              (_cache = cache) === null || _cache === void 0 ? void 0 : _cache.setSkin(this._skinName);
            }
            if (cache) {
              this._animationName = name;
              this._isAniComplete = false;
              this._accTime = 0;
              this._playCount = 0;
              this._animCache = cache;
              if (this._socketNodes.size > 0) {
                this._animCache.enableCacheAttachedInfo();
              }
              this._animCache.updateToFrame(0);
              this._curFrame = this._animCache.frames[0];
            }
          } else {
            this._animationName = name;
            trackEntry = this._instance.setAnimation(trackIndex, name, loop);
          }
          this.markForUpdateRenderData();
          return trackEntry;
        };
        _proto.addAnimation = function addAnimation(trackIndex, name, loop, delay) {
          delay = delay || 0;
          if (this.isAnimationCached()) {
            if (trackIndex !== 0) {
              warn('Track index can not greater than 0 in cached mode.');
            }
            this._animationQueue.push({
              animationName: name,
              loop: loop,
              delay: delay
            });
            return null;
          } else if (this._skeleton) {
            var _this$_state;
            var animation = this._skeleton.data.findAnimation(name);
            if (!animation) {
              logID(7510, name);
              return null;
            }
            return (_this$_state = this._state) === null || _this$_state === void 0 ? void 0 : _this$_state.addAnimationWith(trackIndex, animation, loop, delay);
          }
          return null;
        };
        _proto.findAnimation = function findAnimation(name) {
          if (this._skeleton) {
            return this._skeleton.data.findAnimation(name);
          }
          return null;
        };
        _proto.getCurrent = function getCurrent(trackIndex) {
          if (this.isAnimationCached()) {
            warn('\'getCurrent\' interface can not be invoked in cached mode.');
          } else if (this._state) {
            return this._state.getCurrent(trackIndex);
          }
          return null;
        };
        _proto.setSkin = function setSkin(name) {
          if (this._skeleton) this._skeleton.setSkinByName(name);
          this._instance.setSkin(name);
          if (this.isAnimationCached()) {
            if (this._animCache) {
              this._animCache.setSkin(name);
            }
          }
          this._skinName = name;
          this.invalidAnimationCache();
        };
        _proto.updateAnimation = function updateAnimation(dt) {
          this.markForUpdateRenderData();
          if (this.paused) return;
          if (this.isAnimationCached()) {
            dt *= this._timeScale * timeScale;
            if (this._isAniComplete) {
              var _this$_headAniInfo;
              if (this._animationQueue.length === 0 && !this._headAniInfo) {
                var frameCache = this._animCache;
                if (frameCache && frameCache.isInvalid()) {
                  frameCache.updateToFrame(0);
                  var frames = frameCache.frames;
                  this._curFrame = frames[frames.length - 1];
                }
                return;
              }
              if (!this._headAniInfo) {
                this._headAniInfo = this._animationQueue.shift();
              }
              this._accTime += dt;
              if (this._accTime > ((_this$_headAniInfo = this._headAniInfo) === null || _this$_headAniInfo === void 0 ? void 0 : _this$_headAniInfo.delay)) {
                var aniInfo = this._headAniInfo;
                this._headAniInfo = null;
                this.setAnimation(0, aniInfo === null || aniInfo === void 0 ? void 0 : aniInfo.animationName, aniInfo === null || aniInfo === void 0 ? void 0 : aniInfo.loop);
              }
              return;
            }
            this._updateCache(dt);
          } else {
            this._instance.updateAnimation(dt);
          }
        };
        _proto._updateCache = function _updateCache(dt) {
          var frameCache = this._animCache;
          if (!frameCache.isInited()) {
            return;
          }
          var frames = frameCache.frames;
          var frameTime = SkeletonCache.FrameTime;
          if (this._accTime === 0 && this._playCount === 0) {
            this._startEntry.animation.name = this._animationName;
            if (this._listener && this._listener.start) {
              this._listener.start(this._startEntry);
            }
          }
          this._accTime += dt;
          var frameIdx = Math.floor(this._accTime / frameTime);
          if (!frameCache.isCompleted) {
            frameCache.updateToFrame(frameIdx);
          }
          this._curFrame = frames[frameIdx];
          if (this._curFrame !== undefined) {
            this.attachUtil.updateSkeletonBones(this._curFrame.boneInfos);
          }
          if (frameCache.isCompleted && frameIdx >= frames.length) {
            this._playCount++;
            if (this._playTimes > 0 && this._playCount >= this._playTimes) {
              this._curFrame = frames[frames.length - 1];
              this._accTime = 0;
              this._playCount = 0;
              this._isAniComplete = true;
              this._emitCacheCompleteEvent();
              return;
            }
            this._accTime = 0;
            frameIdx = 0;
            this._curFrame = frames[frameIdx];
            this._emitCacheCompleteEvent();
          }
        };
        _proto._emitCacheCompleteEvent = function _emitCacheCompleteEvent() {
          if (!this._listener) return;
          this._endEntry.animation.name = this._animationName;
          if (this._listener.complete) this._listener.complete(this._endEntry);
          if (this._listener.end) this._listener.end(this._endEntry);
        };
        _proto.updateRenderData = function updateRenderData() {
          if (this.isAnimationCached()) {
            if (!this._curFrame) return null;
            var model = this._curFrame.model;
            return model;
          } else {
            var _model = this._instance.updateRenderData();
            return _model;
          }
        };
        _proto._flushAssembler = function _flushAssembler() {
          var assembler = Skeleton.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
          }
          if (this._skeleton && this._assembler) {
            this._renderData = this._assembler.createData(this);
            this.markForUpdateRenderData();
            this._updateColor();
          }
        };
        _proto._render = function _render(batcher) {
          var indicesCount = 0;
          if (this.renderData && this._drawList.length > 0) {
            var rd = this.renderData;
            var chunk = rd.chunk;
            var accessor = chunk.vertexAccessor;
            var meshBuffer = rd.getMeshBuffer();
            var origin = meshBuffer.indexOffset;
            for (var i = 0; i < this._drawList.length; i++) {
              var dc = this._drawList.data[i];
              if (dc.texture) {
                batcher.commitMiddleware(this, meshBuffer, origin + dc.indexOffset, dc.indexCount, dc.texture, dc.material, this._enableBatch);
              }
              indicesCount += dc.indexCount;
            }
            var subIndices = rd.indices.subarray(0, indicesCount);
            accessor.appendIndices(chunk.bufferId, subIndices);
            accessor.getMeshBuffer(chunk.bufferId).setDirty();
          }
        };
        _proto.requestDrawData = function requestDrawData(material, textureID, indexOffset, indexCount) {
          var draw = this._drawList.add();
          draw.material = material;
          if (textureID < CUSTOM_SLOT_TEXTURE_BEGIN) {
            draw.texture = this._textures[textureID];
          } else {
            var _this$_slotTextures2;
            var texture = (_this$_slotTextures2 = this._slotTextures) === null || _this$_slotTextures2 === void 0 ? void 0 : _this$_slotTextures2.get(textureID);
            if (texture) draw.texture = texture;
          }
          draw.indexOffset = indexOffset;
          draw.indexCount = indexCount;
          return draw;
        };
        _proto._updateBuiltinMaterial = function _updateBuiltinMaterial() {
          var material = builtinResMgr.get('default-spine-material');
          return material;
        };
        _proto.updateMaterial = function updateMaterial() {
          var mat;
          if (this._customMaterial) mat = this._customMaterial;else mat = this._updateBuiltinMaterial();
          this.setSharedMaterial(mat, 0);
          this._cleanMaterialCache();
        };
        _proto.getMaterialTemplate = function getMaterialTemplate() {
          if (this.customMaterial !== null) return this.customMaterial;
          if (this.material) return this.material;
          this.updateMaterial();
          return this.material;
        };
        _proto._cleanMaterialCache = function _cleanMaterialCache() {
          for (var val in this._materialCache) {
            this._materialCache[val].destroy();
          }
          this._materialCache = {};
        };
        _proto.getMaterialForBlendAndTint = function getMaterialForBlendAndTint(src, dst, type) {
          var key = type + "/" + src + "/" + dst;
          var inst = this._materialCache[key];
          if (inst) {
            return inst;
          }
          var material = this.getMaterialTemplate();
          var matInfo = {
            parent: material,
            subModelIdx: 0,
            owner: this
          };
          inst = new MaterialInstance(matInfo);
          this._materialCache[key] = inst;
          inst.overridePipelineStates({
            blendState: {
              blendColor: Color$1.WHITE,
              targets: [{
                blendEq: BlendOp.ADD,
                blendAlphaEq: BlendOp.ADD,
                blendSrc: src,
                blendDst: dst,
                blendSrcAlpha: src,
                blendDstAlpha: dst
              }]
            }
          });
          var useTwoColor = false;
          if (type === SpineMaterialType.TWO_COLORED) {
            useTwoColor = true;
          }
          var useLocal = !this._enableBatch;
          inst.recompileShaders({
            TWO_COLORED: useTwoColor,
            USE_LOCAL: useLocal
          });
          return inst;
        };
        _proto._updateAnimEnum = function _updateAnimEnum() {
          var animEnum;
          if (this.skeletonData) {
            animEnum = this.skeletonData.getAnimsEnum();
          } else {
            animEnum = DefaultAnimsEnum;
          }
          this._enumAnimations = Enum({});
          Object.assign(this._enumAnimations, animEnum);
          Enum.update(this._enumAnimations);
          setPropertyEnumType(this, '_animationIndex', this._enumAnimations);
        };
        _proto._updateSkinEnum = function _updateSkinEnum() {
          var skinEnum;
          if (this.skeletonData) {
            skinEnum = this.skeletonData.getSkinsEnum();
          } else {
            skinEnum = DefaultSkinsEnum;
          }
          this._enumSkins = Enum({});
          Object.assign(this._enumSkins, skinEnum);
          Enum.update(this._enumSkins);
          setPropertyEnumType(this, '_defaultSkinIndex', this._enumSkins);
        };
        _proto._refreshInspector = function _refreshInspector() {
        };
        _proto.destroyRenderData = function destroyRenderData() {
          this._drawList.reset();
          _UIRenderer.prototype.destroyRenderData.call(this);
        };
        _proto.createRenderEntity = function createRenderEntity() {
          var renderEntity = new RenderEntity(RenderEntityType.DYNAMIC);
          renderEntity.setUseLocal(true);
          return renderEntity;
        };
        _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
          if (enable === void 0) {
            enable = true;
          }
          _UIRenderer.prototype.markForUpdateRenderData.call(this, enable);
          if (this._debugRenderer) {
            this._debugRenderer.markForUpdateRenderData(enable);
          }
        };
        _proto.syncAttachedNode = function syncAttachedNode() {
          this.attachUtil._syncAttachedNode();
        };
        _proto.isAnimationCached = function isAnimationCached() {
          return this._cacheMode !== AnimationCacheMode.REALTIME;
        };
        _proto.setAnimationCacheMode = function setAnimationCacheMode(cacheMode) {
          if (this._preCacheMode !== cacheMode) {
            this._cacheMode = cacheMode;
            this._preCacheMode = cacheMode;
            if (this._instance) {
              this._instance.isCache = this.isAnimationCached();
            }
            this._updateSkeletonData();
            this.markForUpdateRenderData();
          }
        };
        _proto.setToSetupPose = function setToSetupPose() {
          if (this._skeleton) {
            this._skeleton.setToSetupPose();
          }
        };
        _proto.setBonesToSetupPose = function setBonesToSetupPose() {
          if (this._skeleton) {
            this._skeleton.setBonesToSetupPose();
          }
        };
        _proto.setSlotsToSetupPose = function setSlotsToSetupPose() {
          if (this._skeleton) {
            this._skeleton.setSlotsToSetupPose();
          }
        };
        _proto.invalidAnimationCache = function invalidAnimationCache() {
          if (!this.isAnimationCached()) return;
          if (this._skeletonCache) {
            this._skeletonCache.invalidAnimationCache(this._skeletonData.uuid);
          }
        };
        _proto.findBone = function findBone(boneName) {
          if (this._skeleton) {
            return this._skeleton.findBone(boneName);
          }
          return null;
        };
        _proto.findSlot = function findSlot(slotName) {
          if (this._skeleton) {
            return this._skeleton.findSlot(slotName);
          }
          return null;
        };
        _proto.setMix = function setMix(fromAnimation, toAnimation, duration) {
          if (this.isAnimationCached()) {
            warn('cached mode not support setMix!!!');
            return;
          }
          if (this._state) {
            this._instance.setMix(fromAnimation, toAnimation, duration);
          }
        };
        _proto.clearTracks = function clearTracks() {
          if (this.isAnimationCached()) {
            warn('\'clearTracks\' interface can not be invoked in cached mode.');
          } else if (this._state) {
            this._state.clearTracks();
            this.setToSetupPose();
          }
        };
        _proto.clearTrack = function clearTrack(trackIndex) {
          if (this.isAnimationCached()) {
            warn('\'clearTrack\' interface can not be invoked in cached mode.');
          } else if (this._state) {
            this._state.clearTrack(trackIndex);
          }
        };
        _proto.updateWorldTransform = function updateWorldTransform() {
          if (!this.isAnimationCached()) return;
          if (this._skeleton) {
            this._skeleton.updateWorldTransform();
          }
        };
        _proto._verifySockets = function _verifySockets(sockets) {
          for (var i = 0, l = sockets.length; i < l; i++) {
            var target = sockets[i].target;
            if (target) {
              if (!target.parent || target.parent !== this.node) {
                error("Target node " + target.name + " is expected to be a direct child of " + this.node.name);
                continue;
              }
            }
          }
          var uniqueSocketNode = new Map();
          sockets.forEach(function (x) {
            if (x.target) {
              if (uniqueSocketNode.get(x.target)) {
                error("Target node " + x.target.name + " has existed.");
              } else {
                uniqueSocketNode.set(x.target, true);
              }
            }
          });
        };
        _proto._updateSocketBindings = function _updateSocketBindings() {
          if (!this._skeleton) return;
          this._socketNodes.clear();
          for (var i = 0, l = this._sockets.length; i < l; i++) {
            var socket = this._sockets[i];
            if (socket.path && socket.target) {
              var boneIdx = this._cachedSockets.get(socket.path);
              if (!boneIdx) {
                error("Skeleton data does not contain path " + socket.path);
                continue;
              }
              this._socketNodes.set(boneIdx, socket.target);
            }
          }
        };
        _proto._indexBoneSockets = function _indexBoneSockets() {
          if (!this._skeleton) {
            return;
          }
          this._cachedSockets.clear();
          var bones = this._skeleton.bones;
          var getBoneName = function getBoneName(bone) {
            if (bone.parent == null) return bone.data.name || '<Unamed>';
            return getBoneName(bones[bone.parent.data.index]) + "/" + bone.data.name;
          };
          for (var i = 0, l = bones.length; i < l; i++) {
            var bd = bones[i].data;
            var boneName = getBoneName(bones[i]);
            this._cachedSockets.set(boneName, bd.index);
          }
        };
        _proto.querySockets = function querySockets() {
          if (!this._skeleton) {
            return [];
          }
          if (this._cachedSockets.size === 0) {
            this._indexBoneSockets();
          }
          if (this._cachedSockets.size > 0) {
            return Array.from(this._cachedSockets.keys()).sort();
          }
          return [];
        };
        _proto._updateUseTint = function _updateUseTint() {
          this._cleanMaterialCache();
          this.destroyRenderData();
          {
            if (!this.isAnimationCached()) {
              this._instance.setUseTint(this._useTint);
            }
          }
          if (this._assembler && this._skeleton) {
            this._renderData = this._assembler.createData(this);
            this.markForUpdateRenderData();
          }
        };
        _proto._updateBatch = function _updateBatch() {
          this._cleanMaterialCache();
          this.markForUpdateRenderData();
        };
        _proto._updateDebugDraw = function _updateDebugDraw() {
          if (this.debugBones || this.debugSlots || this.debugMesh) {
            if (!this._debugRenderer) {
              var debugDrawNode = new Node$1('DEBUG_DRAW_NODE');
              debugDrawNode.layer = this.node.layer;
              debugDrawNode.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
              var debugDraw = debugDrawNode.addComponent(Graphics);
              debugDraw.lineWidth = 5;
              debugDraw.strokeColor = new Color$1(255, 0, 0, 255);
              this._debugRenderer = debugDraw;
              debugDrawNode.parent = this.node;
              this.node.on(NodeEventType.LAYER_CHANGED, this._applyLayer, this);
            }
            if (this.isAnimationCached()) {
              warn('Debug bones or slots is invalid in cached mode');
            } else {
              this._instance.setDebugMode(true);
            }
          } else if (this._debugRenderer) {
            this.node.off(NodeEventType.LAYER_CHANGED, this._applyLayer, this);
            this._debugRenderer.node.destroy();
            this._debugRenderer = null;
            if (!this.isAnimationCached()) {
              if (this._instance) {
                this._instance.setDebugMode(false);
              }
            }
          }
        };
        _proto._updateUITransform = function _updateUITransform() {
          var uiTrans = this.node._uiProps.uiTransformComp;
          var skeletonData = this._runtimeData;
          if (!skeletonData) {
            uiTrans.setContentSize(100, 100);
            uiTrans.anchorX = 0.5;
            uiTrans.anchorX = 0.5;
            return;
          }
          var width = skeletonData.width;
          var height = skeletonData.height;
          if (width && height) {
            uiTrans.setContentSize(width, height);
            if (width !== 0) uiTrans.anchorX = Math.abs(skeletonData.x) / width;
            if (height !== 0) uiTrans.anchorY = Math.abs(skeletonData.y) / height;
          }
        };
        _proto._updateColor = function _updateColor() {
          var a = this.node._uiProps.opacity;
          if (this._tempColor.r === this._color.r && this._tempColor.g === this.color.g && this._tempColor.b === this.color.b && this._tempColor.a === a) {
            return;
          }
          this.node._uiProps.colorDirty = true;
          this._tempColor.r = this._color.r;
          this._tempColor.g = this._color.g;
          this._tempColor.b = this._color.b;
          this._tempColor.a = a;
          var r = this._color.r / 255.0;
          var g = this._color.g / 255.0;
          var b = this._color.b / 255.0;
          this._instance.setColor(r, g, b, a);
        };
        _proto.setVertexEffectDelegate = function setVertexEffectDelegate(effectDelegate) {
          if (!this._instance) {
            return;
          }
          if (!effectDelegate) {
            this._instance.clearEffect();
            return;
          }
          var effectType = effectDelegate === null || effectDelegate === void 0 ? void 0 : effectDelegate.getEffectType();
          if (effectType === 'jitter') {
            var jitterEffect = effectDelegate === null || effectDelegate === void 0 ? void 0 : effectDelegate.getJitterVertexEffect();
            this._instance.setJitterEffect(jitterEffect);
          } else if (effectType === 'swirl') {
            var swirlEffect = effectDelegate === null || effectDelegate === void 0 ? void 0 : effectDelegate.getJitterVertexEffect();
            this._instance.setSwirlEffect(swirlEffect);
          }
        };
        _proto._ensureListener = function _ensureListener() {
          if (!this._listener) {
            this._listener = new TrackEntryListeners();
          }
        };
        _proto.setStartListener = function setStartListener(listener) {
          this._ensureListener();
          var listenerID = TrackEntryListeners.addListener(listener);
          this._instance.setListener(listenerID, spine$1.EventType.start);
          this._listener.start = listener;
        };
        _proto.setInterruptListener = function setInterruptListener(listener) {
          this._ensureListener();
          var listenerID = TrackEntryListeners.addListener(listener);
          this._instance.setListener(listenerID, spine$1.EventType.interrupt);
          this._listener.interrupt = listener;
        };
        _proto.setEndListener = function setEndListener(listener) {
          this._ensureListener();
          var listenerID = TrackEntryListeners.addListener(listener);
          this._instance.setListener(listenerID, spine$1.EventType.end);
          this._listener.end = listener;
        };
        _proto.setDisposeListener = function setDisposeListener(listener) {
          this._ensureListener();
          var listenerID = TrackEntryListeners.addListener(listener);
          this._instance.setListener(listenerID, spine$1.EventType.dispose);
          this._listener.dispose = listener;
        };
        _proto.setCompleteListener = function setCompleteListener(listener) {
          this._ensureListener();
          var listenerID = TrackEntryListeners.addListener(listener);
          this._instance.setListener(listenerID, spine$1.EventType.complete);
          this._listener.complete = listener;
        };
        _proto.setEventListener = function setEventListener(listener) {
          this._ensureListener();
          var listenerID = TrackEntryListeners.addListener(listener);
          this._instance.setListener(listenerID, spine$1.EventType.event);
          this._listener.event = listener;
        };
        _proto.setTrackStartListener = function setTrackStartListener(entry, listener) {
          TrackEntryListeners.getListeners(entry, this._instance).start = listener;
        };
        _proto.setTrackInterruptListener = function setTrackInterruptListener(entry, listener) {
          TrackEntryListeners.getListeners(entry, this._instance).interrupt = listener;
        };
        _proto.setTrackEndListener = function setTrackEndListener(entry, listener) {
          TrackEntryListeners.getListeners(entry, this._instance).end = listener;
        };
        _proto.setTrackDisposeListener = function setTrackDisposeListener(entry, listener) {
          TrackEntryListeners.getListeners(entry, this._instance).dispose = listener;
        };
        _proto.setTrackCompleteListener = function setTrackCompleteListener(entry, listener) {
          var onComplete = function onComplete(trackEntry) {
            var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
            TrackEntryListeners.addListener(listener);
            listener(trackEntry, loopCount);
          };
          TrackEntryListeners.getListeners(entry, this._instance).complete = onComplete;
        };
        _proto.setTrackEventListener = function setTrackEventListener(entry, listener) {
          TrackEntryListeners.getListeners(entry, this._instance).event = listener;
        };
        _proto.getDebugShapes = function getDebugShapes() {
          return this._instance.getDebugShapes();
        };
        _proto.setSlotTexture = function setSlotTexture(slotName, tex2d, createNew) {
          if (this.isAnimationCached()) {
            error("Cached mode can't change texture of slot");
            return;
          }
          var slot = this.findSlot(slotName);
          if (!slot) {
            error("No slot named:" + slotName);
            return;
          }
          var width = tex2d.width;
          var height = tex2d.height;
          var createNewAttachment = createNew || false;
          this._instance.resizeSlotRegion(slotName, width, height, createNewAttachment);
          if (!this._slotTextures) this._slotTextures = new Map();
          var textureID = 0;
          this._slotTextures.forEach(function (value, key) {
            if (value === tex2d) textureID = key;
          });
          if (textureID === 0) {
            textureID = ++_slotTextureID;
            this._slotTextures.set(textureID, tex2d);
          }
          this._instance.setSlotTexture(slotName, textureID);
        };
        _proto._destroySkeletonInfo = function _destroySkeletonInfo(skeletonCache) {
          if (skeletonCache && this._skeletonInfo) {
            skeletonCache.destroySkeleton(this._skeletonInfo.assetUUID);
            this._skeletonInfo = null;
          }
        };
        _proto._applyLayer = function _applyLayer() {
          if (this._debugRenderer) {
            this._debugRenderer.node.layer = this.node.layer;
          }
        };
        _createClass(Skeleton, [{
          key: "drawList",
          get: function get() {
            return this._drawList;
          }
        }, {
          key: "skeletonData",
          get: function get() {
            return this._skeletonData;
          },
          set: function set(value) {
            if (value) value.resetEnums();
            if (this._skeletonData !== value) {
              this.destroyRenderData();
              this._skeletonData = value;
              this.defaultSkin = '';
              this.defaultAnimation = '';
              this._animationName = '';
              this._skinName = '';
              this._updateSkeletonData();
              this._updateUITransform();
            }
          }
        }, {
          key: "_defaultSkinIndex",
          get: function get() {
            if (this.skeletonData) {
              var skinsEnum = this.skeletonData.getSkinsEnum();
              if (skinsEnum) {
                if (this.defaultSkin === '') {
                  if (skinsEnum.hasOwnProperty(0)) {
                    this._defaultSkinIndex = 0;
                    return 0;
                  }
                } else {
                  var skinIndex = skinsEnum[this.defaultSkin];
                  if (skinIndex !== undefined) {
                    return skinIndex;
                  }
                }
              }
            }
            return 0;
          },
          set: function set(value) {
            var skinsEnum;
            if (this.skeletonData) {
              skinsEnum = this.skeletonData.getSkinsEnum();
            }
            if (!skinsEnum) {
              error(this.name + " skin enums are invalid");
              return;
            }
            var skinName = skinsEnum[value];
            if (skinName !== undefined) {
              this.defaultSkin = String(skinName);
              this.setSkin(this.defaultSkin);
              this._refreshInspector();
              this.markForUpdateRenderData();
            } else {
              error(this.name + " skin enums are invalid");
            }
          }
        }, {
          key: "_animationIndex",
          get: function get() {
            var animationName = this.animation;
            if (this.skeletonData) {
              if (animationName) {
                var animsEnum = this.skeletonData.getAnimsEnum();
                if (animsEnum) {
                  var animIndex = animsEnum[animationName];
                  if (animIndex !== undefined) {
                    return animIndex;
                  }
                }
              } else {
                this._refreshInspector();
              }
            }
            return 0;
          },
          set: function set(value) {
            var animsEnum;
            if (this.skeletonData) {
              animsEnum = this.skeletonData.getAnimsEnum();
            }
            if (!animsEnum) {
              error(this.name + " animation enums are invalid");
              return;
            }
            var animName = String(animsEnum[value]);
            if (animName !== undefined) {
              this.animation = animName;
              {
                this.animation = animName;
              }
            } else {
              error(this.name + " animation enums are invalid");
            }
          }
        }, {
          key: "defaultCacheMode",
          get: function get() {
            return this._cacheMode;
          },
          set: function set(mode) {
            this._cacheMode = mode;
            this.setAnimationCacheMode(this._cacheMode);
          }
        }, {
          key: "premultipliedAlpha",
          get: function get() {
            return this._premultipliedAlpha;
          },
          set: function set(v) {
            if (v !== this._premultipliedAlpha) {
              this._premultipliedAlpha = v;
              this._instance.setPremultipliedAlpha(v);
              this.markForUpdateRenderData();
            }
          }
        }, {
          key: "timeScale",
          get: function get() {
            return this._timeScale;
          },
          set: function set(value) {
            if (value !== this._timeScale) {
              this._timeScale = value;
              if (this._instance) {
                this._instance.dtRate = this._timeScale * timeScale;
              }
            }
          }
        }, {
          key: "useTint",
          get: function get() {
            return this._useTint;
          },
          set: function set(value) {
            if (value !== this._useTint) {
              this._useTint = value;
              this._updateUseTint();
            }
          }
        }, {
          key: "enableBatch",
          get: function get() {
            return this._enableBatch;
          },
          set: function set(value) {
            if (value !== this._enableBatch) {
              this._enableBatch = value;
              this._updateBatch();
            }
          }
        }, {
          key: "sockets",
          get: function get() {
            return this._sockets;
          },
          set: function set(val) {
            this._sockets = val;
            this._updateSocketBindings();
            this.attachUtil.init(this);
          }
        }, {
          key: "debugSlots",
          get: function get() {
            return this._debugSlots;
          },
          set: function set(v) {
            if (v !== this._debugSlots) {
              this._debugSlots = v;
              this._updateDebugDraw();
              this.markForUpdateRenderData();
            }
          }
        }, {
          key: "debugBones",
          get: function get() {
            return this._debugBones;
          },
          set: function set(v) {
            if (v !== this._debugBones) {
              this._debugBones = v;
              this._updateDebugDraw();
              this.markForUpdateRenderData();
            }
          }
        }, {
          key: "debugMesh",
          get: function get() {
            return this._debugMesh;
          },
          set: function set(value) {
            if (value !== this._debugMesh) {
              this._debugMesh = value;
              this._updateDebugDraw();
              this.markForUpdateRenderData();
            }
          }
        }, {
          key: "socketNodes",
          get: function get() {
            return this._socketNodes;
          }
        }, {
          key: "animation",
          get: function get() {
            return this._animationName;
          },
          set: function set(value) {
            if (value) {
              this.setAnimation(0, value, this.loop);
            } else {
              this.clearAnimation(0);
            }
          }
        }, {
          key: "customMaterial",
          get: function get() {
            return this._customMaterial;
          },
          set: function set(val) {
            this._customMaterial = val;
            this.updateMaterial();
            this.markForUpdateRenderData();
          }
        }]);
        return Skeleton;
      }(UIRenderer), _class6.SpineSocket = SpineSocket, _class6.AnimationCacheMode = AnimationCacheMode, _class6), (_initializer3$g = applyDecoratedInitializer(_class5$2.prototype, "_skeletonData", [serializable$p], function () {
        return null;
      }), _initializer4$e = applyDecoratedInitializer(_class5$2.prototype, "defaultSkin", [serializable$p], function () {
        return '';
      }), _initializer5$c = applyDecoratedInitializer(_class5$2.prototype, "defaultAnimation", [serializable$p], function () {
        return '';
      }), _initializer6$9 = applyDecoratedInitializer(_class5$2.prototype, "_premultipliedAlpha", [serializable$p], function () {
        return true;
      }), _initializer7$9 = applyDecoratedInitializer(_class5$2.prototype, "_timeScale", [serializable$p], function () {
        return 1;
      }), _initializer8$9 = applyDecoratedInitializer(_class5$2.prototype, "_preCacheMode", [serializable$p], function () {
        return AnimationCacheMode.UNSET;
      }), _initializer9$8 = applyDecoratedInitializer(_class5$2.prototype, "_cacheMode", [serializable$p], function () {
        return AnimationCacheMode.REALTIME;
      }), _initializer10$8 = applyDecoratedInitializer(_class5$2.prototype, "_sockets", [serializable$p], function () {
        return [];
      }), _initializer11$8 = applyDecoratedInitializer(_class5$2.prototype, "_useTint", [serializable$p], function () {
        return false;
      }), _initializer12$7 = applyDecoratedInitializer(_class5$2.prototype, "_debugMesh", [serializable$p], function () {
        return false;
      }), _initializer13$5 = applyDecoratedInitializer(_class5$2.prototype, "_debugBones", [serializable$p], function () {
        return false;
      }), _initializer14$4 = applyDecoratedInitializer(_class5$2.prototype, "_debugSlots", [serializable$p], function () {
        return false;
      }), _initializer15$3 = applyDecoratedInitializer(_class5$2.prototype, "_enableBatch", [serializable$p], function () {
        return false;
      }), _applyDecoratedDescriptor(_class5$2.prototype, "skeletonData", [_dec4$g], Object.getOwnPropertyDescriptor(_class5$2.prototype, "skeletonData"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "_defaultSkinIndex", [_dec5$g], Object.getOwnPropertyDescriptor(_class5$2.prototype, "_defaultSkinIndex"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "_animationIndex", [_dec6$a], Object.getOwnPropertyDescriptor(_class5$2.prototype, "_animationIndex"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "defaultCacheMode", [_dec7$8], Object.getOwnPropertyDescriptor(_class5$2.prototype, "defaultCacheMode"), _class5$2.prototype), _initializer16$3 = applyDecoratedInitializer(_class5$2.prototype, "loop", [serializable$p], function () {
        return true;
      }), _applyDecoratedDescriptor(_class5$2.prototype, "sockets", [_dec8$6], Object.getOwnPropertyDescriptor(_class5$2.prototype, "sockets"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "customMaterial", [override$1, _dec9$5], Object.getOwnPropertyDescriptor(_class5$2.prototype, "customMaterial"), _class5$2.prototype)), _class5$2)) || _class4$1);
      legacyCC.internal.SpineSkeleton = Skeleton;

      var VertexEffectDelegate = function () {
        function VertexEffectDelegate() {
          this.name = 'sp.VertexEffectDelegate';
          this._vertexEffect = void 0;
          this._interpolation = void 0;
          this._effectType = void 0;
          this._vertexEffect = null;
          this._interpolation = null;
          this._effectType = 'none';
        }
        var _proto = VertexEffectDelegate.prototype;
        _proto.clear = function clear() {
          this._vertexEffect = null;
          this._interpolation = null;
          this._effectType = 'none';
        };
        _proto.initJitter = function initJitter(jitterX, jitterY) {
          this._effectType = 'jitter';
          this._vertexEffect = new spine$1.JitterEffect(jitterX, jitterY);
          return this._vertexEffect;
        };
        _proto.initSwirlWithPow = function initSwirlWithPow(radius, power) {
          this._effectType = 'swirl';
          this._interpolation = new spine$1.Pow(power);
          this._vertexEffect = new spine$1.SwirlEffect(radius, this._interpolation);
          return this._vertexEffect;
        };
        _proto.initSwirlWithPowOut = function initSwirlWithPowOut(radius, power) {
          this._effectType = 'swirl';
          this._interpolation = new spine$1.PowOut(power);
          this._vertexEffect = new spine$1.SwirlEffect(radius, this._interpolation);
          return this._vertexEffect;
        };
        _proto.getJitterVertexEffect = function getJitterVertexEffect() {
          return this._vertexEffect;
        };
        _proto.getSwirlVertexEffect = function getSwirlVertexEffect() {
          return this._vertexEffect;
        };
        _proto.getVertexEffect = function getVertexEffect() {
          return this._vertexEffect;
        };
        _proto.getEffectType = function getEffectType() {
          return this._effectType;
        };
        return VertexEffectDelegate;
      }();

      var _slotColor = new Color$1(0, 0, 255, 255);
      var _boneColor = new Color$1(255, 0, 0, 255);
      var _originColor = new Color$1(0, 255, 0, 255);
      var _meshColor = new Color$1(255, 255, 0, 255);
      var _nodeR;
      var _nodeG;
      var _nodeB;
      var _nodeA;
      var _accessor$1 = null;
      var _tintAccessor = null;
      var _premultipliedAlpha = false;
      var _useTint = false;
      var _byteStrideOneColor = getAttributeStride(vfmtPosUvColor4B);
      var _byteStrideTwoColor = getAttributeStride(vfmtPosUvTwoColor4B);
      var DEBUG_TYPE_REGION = 0;
      var DEBUG_TYPE_MESH = 1;
      var tempVecPos = new Vec3(0, 0, 0);
      function _getSlotMaterial(blendMode, comp) {
        var src;
        var dst;
        switch (blendMode) {
          case 1:
            src = _premultipliedAlpha ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
            dst = BlendFactor.ONE;
            break;
          case 2:
            src = BlendFactor.DST_COLOR;
            dst = BlendFactor.ONE_MINUS_SRC_ALPHA;
            break;
          case 3:
            src = BlendFactor.ONE;
            dst = BlendFactor.ONE_MINUS_SRC_COLOR;
            break;
          case 0:
          default:
            src = _premultipliedAlpha ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
            dst = BlendFactor.ONE_MINUS_SRC_ALPHA;
            break;
        }
        return comp.getMaterialForBlendAndTint(src, dst, _useTint ? SpineMaterialType.TWO_COLORED : SpineMaterialType.COLORED_TEXTURED);
      }
      var simple$1 = {
        vCount: 32767,
        ensureAccessor: function ensureAccessor(useTint) {
          var accessor = useTint ? _tintAccessor : _accessor$1;
          if (!accessor) {
            var device = director.root.device;
            var batcher = director.root.batcher2D;
            var attributes = useTint ? vfmtPosUvTwoColor4B : vfmtPosUvColor4B;
            if (useTint) {
              accessor = _tintAccessor = new StaticVBAccessor(device, attributes, this.vCount);
              batcher.registerBufferAccessor(Number.parseInt('SPINETINT', 36), _tintAccessor);
            } else {
              accessor = _accessor$1 = new StaticVBAccessor(device, attributes, this.vCount);
              batcher.registerBufferAccessor(Number.parseInt('SPINE', 36), _accessor$1);
            }
          }
          return accessor;
        },
        createData: function createData(comp) {
          var rd = comp.renderData;
          if (!rd) {
            var useTint = comp.useTint || comp.isAnimationCached();
            var accessor = this.ensureAccessor(useTint);
            rd = RenderData.add(useTint ? vfmtPosUvTwoColor4B : vfmtPosUvColor4B, accessor);
          }
          return rd;
        },
        updateRenderData: function updateRenderData(comp, batcher) {
          var skeleton = comp._skeleton;
          if (skeleton) {
            updateComponentRenderData(comp);
          }
        }
      };
      function updateComponentRenderData(comp, batcher) {
        comp.drawList.reset();
        if (comp.color.a === 0) return;
        comp._updateColor();
        _premultipliedAlpha = comp.premultipliedAlpha;
        _useTint = comp.useTint || comp.isAnimationCached();
        if (comp.isAnimationCached()) {
          cacheTraverse(comp);
        } else {
          realTimeTraverse(comp);
        }
        var rd = comp.renderData;
        var accessor = _useTint ? _tintAccessor : _accessor$1;
        comp.syncAttachedNode();
        if (rd.vertexCount > 0 || rd.indexCount > 0) accessor.getMeshBuffer(rd.chunk.bufferId).setDirty();
      }
      function realTimeTraverse(comp) {
        var _comp$_vBuffer, _comp$_iBuffer;
        var floatStride = (comp.useTint ? _byteStrideTwoColor : _byteStrideOneColor) / Float32Array.BYTES_PER_ELEMENT;
        var model = comp.updateRenderData();
        var vc = model.vCount;
        var ic = model.iCount;
        if (vc < 1 || ic < 1) return;
        var rd = comp.renderData;
        if (rd.vertexCount !== vc || rd.indexCount !== ic) {
          rd.resize(vc, ic);
          rd.indices = new Uint16Array(ic);
          comp._vLength = vc * Float32Array.BYTES_PER_ELEMENT * floatStride;
          comp._vBuffer = new Uint8Array(rd.chunk.vb.buffer, rd.chunk.vb.byteOffset, Float32Array.BYTES_PER_ELEMENT * rd.chunk.vb.length);
          comp._iLength = Uint16Array.BYTES_PER_ELEMENT * ic;
          comp._iBuffer = new Uint8Array(rd.indices.buffer);
        }
        var vbuf = rd.chunk.vb;
        var vPtr = model.vPtr;
        var iPtr = model.iPtr;
        var ibuf = rd.indices;
        var HEAPU8 = spine$1.wasmUtil.wasm.HEAPU8;
        (_comp$_vBuffer = comp._vBuffer) === null || _comp$_vBuffer === void 0 ? void 0 : _comp$_vBuffer.set(HEAPU8.subarray(vPtr, vPtr + comp._vLength), 0);
        (_comp$_iBuffer = comp._iBuffer) === null || _comp$_iBuffer === void 0 ? void 0 : _comp$_iBuffer.set(HEAPU8.subarray(iPtr, iPtr + comp._iLength), 0);
        var chunkOffset = rd.chunk.vertexOffset;
        for (var i = 0; i < ic; i++) ibuf[i] += chunkOffset;
        var data = model.getData();
        var count = data.size();
        var indexOffset = 0;
        var indexCount = 0;
        for (var _i = 0; _i < count; _i += 6) {
          indexCount = data.get(_i + 3);
          var material = _getSlotMaterial(data.get(_i + 4), comp);
          var textureID = data.get(_i + 5);
          comp.requestDrawData(material, textureID, indexOffset, indexCount);
          indexOffset += indexCount;
        }
        if (comp.enableBatch) {
          var worldMat = comp.node.worldMatrix;
          var index = 0;
          for (var _i2 = 0; _i2 < vc; _i2++) {
            index = _i2 * floatStride;
            tempVecPos.x = vbuf[index];
            tempVecPos.y = vbuf[index + 1];
            tempVecPos.transformMat4(worldMat);
            vbuf[index] = tempVecPos.x;
            vbuf[index + 1] = tempVecPos.y;
            vbuf[index + 2] = 0;
          }
        }
        var graphics = comp._debugRenderer;
        var locSkeleton = comp._skeleton;
        if (graphics && (comp.debugBones || comp.debugSlots || comp.debugMesh)) {
          graphics.clear();
          var debugShapes = comp.getDebugShapes();
          var shapeCount = debugShapes.size();
          for (var _i3 = 0; _i3 < shapeCount; _i3++) {
            var shape = debugShapes.get(_i3);
            if (shape.type === DEBUG_TYPE_REGION && comp.debugSlots) {
              graphics.strokeColor = _slotColor;
              var vertexFloatOffset = shape.vOffset * floatStride;
              var vertexFloatCount = shape.vCount * floatStride;
              graphics.moveTo(vbuf[vertexFloatOffset], vbuf[vertexFloatOffset + 1]);
              for (var ii = vertexFloatOffset + floatStride, nn = vertexFloatOffset + vertexFloatCount; ii < nn; ii += floatStride) {
                graphics.lineTo(vbuf[ii], vbuf[ii + 1]);
              }
              graphics.close();
              graphics.stroke();
            } else if (shape.type === DEBUG_TYPE_MESH && comp.debugMesh) {
              graphics.strokeColor = _meshColor;
              var iCount = shape.iCount;
              var iOffset = shape.iOffset;
              for (var _ii = iOffset, _nn = iOffset + iCount; _ii < _nn; _ii += 3) {
                var v1 = ibuf[_ii] * floatStride;
                var v2 = ibuf[_ii + 1] * floatStride;
                var v3 = ibuf[_ii + 2] * floatStride;
                graphics.moveTo(vbuf[v1], vbuf[v1 + 1]);
                graphics.lineTo(vbuf[v2], vbuf[v2 + 1]);
                graphics.lineTo(vbuf[v3], vbuf[v3 + 1]);
                graphics.close();
                graphics.stroke();
              }
            }
          }
          if (comp.debugBones) {
            graphics.strokeColor = _boneColor;
            graphics.fillColor = _slotColor;
            for (var _i4 = 0, n = locSkeleton.bones.length; _i4 < n; _i4++) {
              var bone = locSkeleton.bones[_i4];
              var x = bone.data.length * bone.a + bone.worldX;
              var y = bone.data.length * bone.c + bone.worldY;
              graphics.moveTo(bone.worldX, bone.worldY);
              graphics.lineTo(x, y);
              graphics.stroke();
              graphics.circle(bone.worldX, bone.worldY, Math.PI * 1.5);
              graphics.fill();
              if (_i4 === 0) {
                graphics.fillColor = _originColor;
              }
            }
          }
        }
      }
      function cacheTraverse(comp) {
        var model = comp.updateRenderData();
        if (!model) return;
        var vc = model.vCount;
        var ic = model.iCount;
        if (vc < 1 || ic < 1) return;
        var rd = comp.renderData;
        if (rd.vertexCount !== vc || rd.indexCount !== ic) {
          rd.resize(vc, ic);
          rd.indices = new Uint16Array(ic);
        }
        var vbuf = rd.chunk.vb;
        var vUint8Buf = new Uint8Array(vbuf.buffer, vbuf.byteOffset, Float32Array.BYTES_PER_ELEMENT * vbuf.length);
        vUint8Buf.set(model.vData);
        var nodeColor = comp.color;
        if (nodeColor._val !== 0xffffffff || _premultipliedAlpha) {
          _nodeR = nodeColor.r / 255;
          _nodeG = nodeColor.g / 255;
          _nodeB = nodeColor.b / 255;
          _nodeA = nodeColor.a / 255;
          for (var i = 0; i < vc; i++) {
            var index = i * _byteStrideTwoColor + 5 * Float32Array.BYTES_PER_ELEMENT;
            var R = vUint8Buf[index];
            var G = vUint8Buf[index + 1];
            var B = vUint8Buf[index + 2];
            var A = vUint8Buf[index + 3];
            var fA = A * _nodeA;
            var multiplier = _premultipliedAlpha ? fA / 255 : 1;
            vUint8Buf[index] = Math.floor(multiplier * R * _nodeR);
            vUint8Buf[index + 1] = Math.floor(multiplier * G * _nodeG);
            vUint8Buf[index + 2] = Math.floor(multiplier * B * _nodeB);
            vUint8Buf[index + 3] = Math.floor(fA);
            vUint8Buf[index + 4] = Math.floor(vUint8Buf[index + 4] * _nodeR);
            vUint8Buf[index + 5] = Math.floor(vUint8Buf[index + 5] * _nodeG);
            vUint8Buf[index + 6] = Math.floor(vUint8Buf[index + 6] * _nodeB);
            vUint8Buf[index + 7] = _premultipliedAlpha ? 255 : 0;
          }
        }
        var iUint16Buf = rd.indices;
        iUint16Buf.set(model.iData);
        var chunkOffset = rd.chunk.vertexOffset;
        for (var _i5 = 0; _i5 < ic; _i5++) {
          iUint16Buf[_i5] += chunkOffset;
        }
        var meshes = model.meshes;
        var count = meshes.length;
        var indexOffset = 0;
        var indexCount = 0;
        for (var _i6 = 0; _i6 < count; _i6++) {
          var mesh = meshes[_i6];
          var material = _getSlotMaterial(mesh.blendMode, comp);
          var textureID = mesh.textureID;
          indexCount = mesh.iCount;
          comp.requestDrawData(material, textureID, indexOffset, indexCount);
          indexOffset += indexCount;
        }
        var floatStride = _byteStrideTwoColor / Float32Array.BYTES_PER_ELEMENT;
        if (comp.enableBatch) {
          var worldMat = comp.node.worldMatrix;
          var _index = 0;
          for (var _i7 = 0; _i7 < vc; _i7++) {
            _index = _i7 * floatStride;
            tempVecPos.x = vbuf[_index];
            tempVecPos.y = vbuf[_index + 1];
            tempVecPos.z = 0;
            tempVecPos.transformMat4(worldMat);
            vbuf[_index] = tempVecPos.x;
            vbuf[_index + 1] = tempVecPos.y;
            vbuf[_index + 2] = tempVecPos.z;
          }
        }
      }
      legacyCC.internal.SpineAssembler = simple$1;

      var simpleSpineAssembler = {
        getAssembler: function getAssembler() {
          return simple$1;
        }
      };
      Skeleton.Assembler = simpleSpineAssembler;

      var ATTACHMENT_TYPE;
      (function (ATTACHMENT_TYPE) {
        ATTACHMENT_TYPE[ATTACHMENT_TYPE["REGION"] = 0] = "REGION";
        ATTACHMENT_TYPE[ATTACHMENT_TYPE["BOUNDING_BOX"] = 1] = "BOUNDING_BOX";
        ATTACHMENT_TYPE[ATTACHMENT_TYPE["MESH"] = 2] = "MESH";
        ATTACHMENT_TYPE[ATTACHMENT_TYPE["SKINNED_MESH"] = 3] = "SKINNED_MESH";
      })(ATTACHMENT_TYPE || (ATTACHMENT_TYPE = {}));
      ccenum(ATTACHMENT_TYPE);
      var AnimationEventType;
      (function (AnimationEventType) {
        AnimationEventType[AnimationEventType["START"] = 0] = "START";
        AnimationEventType[AnimationEventType["INTERRUPT"] = 1] = "INTERRUPT";
        AnimationEventType[AnimationEventType["END"] = 2] = "END";
        AnimationEventType[AnimationEventType["DISPOSE"] = 3] = "DISPOSE";
        AnimationEventType[AnimationEventType["COMPLETE"] = 4] = "COMPLETE";
        AnimationEventType[AnimationEventType["EVENT"] = 5] = "EVENT";
      })(AnimationEventType || (AnimationEventType = {}));
      ccenum(AnimationEventType);

      var index = /*#__PURE__*/Object.freeze({
        __proto__: null,
        spine: spine$1,
        get ATTACHMENT_TYPE () { return ATTACHMENT_TYPE; },
        get AnimationEventType () { return AnimationEventType; },
        timeScale: timeScale,
        get AnimationCacheMode () { return AnimationCacheMode; },
        get DefaultSkinsEnum () { return DefaultSkinsEnum; },
        get DefaultAnimsEnum () { return DefaultAnimsEnum; },
        get SpineMaterialType () { return SpineMaterialType; },
        SpineSocket: SpineSocket,
        Skeleton: Skeleton,
        SkeletonData: SkeletonData,
        VertexEffectDelegate: VertexEffectDelegate,
        simpleSpineAssembler: simpleSpineAssembler
      });
      exports('gf', index);

      var HeightField = exports('gg', function () {
        function HeightField(w, h) {
          this.data = new Uint16Array();
          this.w = 0;
          this.h = 0;
          this.w = w;
          this.h = h;
          this.data = new Uint16Array(w * h);
          for (var i = 0; i < w * h; ++i) {
            this.data[i] = 0;
          }
        }
        var _proto = HeightField.prototype;
        _proto.set = function set(i, j, value) {
          this.data[j * this.w + i] = value;
        };
        _proto.get = function get(i, j) {
          return this.data[j * this.w + i];
        };
        _proto.getClamp = function getClamp(i, j) {
          i = clamp$1(i, 0, this.w - 1);
          j = clamp$1(j, 0, this.h - 1);
          return this.get(i, j);
        };
        _proto.getAt = function getAt(x, y) {
          var fx = x;
          var fy = y;
          var ix0 = Math.floor(fx);
          var iz0 = Math.floor(fy);
          var ix1 = ix0 + 1;
          var iz1 = iz0 + 1;
          var dx = fx - ix0;
          var dz = fy - iz0;
          ix0 = clamp$1(ix0, 0, this.w - 1);
          iz0 = clamp$1(iz0, 0, this.h - 1);
          ix1 = clamp$1(ix1, 0, this.w - 1);
          iz1 = clamp$1(iz1, 0, this.h - 1);
          var a = this.get(ix0, iz0);
          var b = this.get(ix1, iz0);
          var c = this.get(ix0, iz1);
          var d = this.get(ix1, iz1);
          var m = (b + c) * 0.5;
          if (dx + dz <= 1.0) {
            d = m + (m - a);
          } else {
            a = m + (m - d);
          }
          var h1 = a * (1.0 - dx) + b * dx;
          var h2 = c * (1.0 - dx) + d * dx;
          var h = h1 * (1.0 - dz) + h2 * dz;
          return h;
        };
        return HeightField;
      }());

      var TERRAIN_LOD_VERTS = 33;
      var TERRAIN_LOD_TILES = 32;
      var TERRAIN_LOD_LEVELS = 4;
      var TERRAIN_LOD_NORTH_INDEX = 0;
      var TERRAIN_LOD_SOUTH_INDEX = 1;
      var TERRAIN_LOD_WEST_INDEX = 2;
      var TERRAIN_LOD_EAST_INDEX = 3;
      var TERRAIN_LOD_MAX_DISTANCE = 100000000000000.0;
      var TerrainLodKey = function () {
        function TerrainLodKey() {
          this.level = 0;
          this.north = 0;
          this.south = 0;
          this.west = 0;
          this.east = 0;
        }
        var _proto = TerrainLodKey.prototype;
        _proto.equals = function equals(rk) {
          return this.level === rk.level && this.north === rk.north && this.south === rk.south && this.west === rk.west && this.east === rk.east;
        };
        return TerrainLodKey;
      }();
      var TerrainIndexPool = function TerrainIndexPool() {
        this.size = 0;
        this.indices = null;
      };
      var TerrainIndexData = function TerrainIndexData() {
        this.key = new TerrainLodKey();
        this.start = 0;
        this.size = 0;
        this.buffer = null;
        this.primCount = 0;
      };
      var TerrainLod = function () {
        TerrainLod.mapIndex = function mapIndex(i, j, k) {
          return i * (TERRAIN_LOD_LEVELS * TERRAIN_LOD_LEVELS) + j * TERRAIN_LOD_LEVELS + k;
        };
        function TerrainLod() {
          this._bodyIndexPool = void 0;
          this._connecterIndexPool = void 0;
          this._indexMap = [];
          this._indexBuffer = new Uint16Array();
          this._bodyIndexPool = new Array(TERRAIN_LOD_LEVELS);
          for (var i = 0; i < TERRAIN_LOD_LEVELS; ++i) {
            this._bodyIndexPool[i] = new TerrainIndexPool();
          }
          this._connecterIndexPool = new Array(TERRAIN_LOD_LEVELS * TERRAIN_LOD_LEVELS * 4);
          for (var _i = 0; _i < TERRAIN_LOD_LEVELS; ++_i) {
            for (var j = 0; j < TERRAIN_LOD_LEVELS; ++j) {
              for (var k = 0; k < 4; ++k) {
                this._connecterIndexPool[TerrainLod.mapIndex(_i, j, k)] = new TerrainIndexPool();
              }
            }
          }
          for (var _i2 = 0; _i2 < TERRAIN_LOD_LEVELS; ++_i2) {
            this._genBodyIndex(_i2);
          }
          for (var _i3 = 0; _i3 < TERRAIN_LOD_LEVELS; ++_i3) {
            for (var _j = 0; _j < TERRAIN_LOD_LEVELS; ++_j) {
              this._genConnecterIndexNorth(_i3, _j);
              this._genConnecterIndexSouth(_i3, _j);
              this._genConnecterIndexWest(_i3, _j);
              this._genConnecterIndexEast(_i3, _j);
            }
          }
          var levels = TERRAIN_LOD_LEVELS;
          for (var l = 0; l < levels; ++l) {
            for (var n = 0; n < levels; ++n) {
              if (n < l) {
                continue;
              }
              for (var s = 0; s < levels; ++s) {
                if (s < l) {
                  continue;
                }
                for (var w = 0; w < levels; ++w) {
                  if (w < l) {
                    continue;
                  }
                  for (var e = 0; e < levels; ++e) {
                    if (e < l) {
                      continue;
                    }
                    var _k = new TerrainLodKey();
                    _k.level = l;
                    _k.north = n;
                    _k.south = s;
                    _k.west = w;
                    _k.east = e;
                    this._genIndexData(_k);
                  }
                }
              }
            }
          }
        }
        var _proto2 = TerrainLod.prototype;
        _proto2.getIndexData = function getIndexData(k) {
          for (var i = 0; i < this._indexMap.length; ++i) {
            if (this._indexMap[i].key.equals(k)) {
              return this._indexMap[i];
            }
          }
          return null;
        };
        _proto2._genBodyIndex = function _genBodyIndex(level) {
          var step = 1 << level;
          var tiles = TERRAIN_LOD_TILES >> level;
          var start = 0;
          if (level < TERRAIN_LOD_LEVELS - 1) {
            tiles -= 2;
            start = step * TERRAIN_LOD_VERTS + step;
          }
          if (tiles === 0 || tiles === 0) {
            return;
          }
          var count = tiles * tiles * 6;
          this._bodyIndexPool[level].indices = new Uint16Array(count);
          var index = 0;
          var indices = new Uint16Array(count);
          var row_c = start;
          var row_n = row_c + TERRAIN_LOD_VERTS * step;
          for (var y = 0; y < tiles; ++y) {
            for (var x = 0; x < tiles; ++x) {
              indices[index++] = row_n + x * step;
              indices[index++] = row_n + (x + 1) * step;
              indices[index++] = row_c + x * step;
              indices[index++] = row_n + (x + 1) * step;
              indices[index++] = row_c + (x + 1) * step;
              indices[index++] = row_c + x * step;
            }
            row_c += TERRAIN_LOD_VERTS * step;
            row_n += TERRAIN_LOD_VERTS * step;
          }
          this._bodyIndexPool[level].size = index;
          this._bodyIndexPool[level].indices = indices;
        };
        _proto2._genConnecterIndexNorth = function _genConnecterIndexNorth(level, connecter) {
          var connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_NORTH_INDEX);
          if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) {
            this._connecterIndexPool[connecterIndex].size = 0;
            this._connecterIndexPool[connecterIndex].indices = null;
            return;
          }
          var self_step = 1 << level;
          var neighbor_step = 1 << connecter;
          var self_tile = TERRAIN_LOD_TILES >> level;
          var count = self_tile * 2 + 2;
          var index = 0;
          var indices = new Uint16Array(count);
          indices[index++] = 0;
          indices[index++] = 0;
          for (var i = 1; i < self_tile; ++i) {
            var x1 = i * self_step;
            var y1 = self_step;
            var x0 = x1 / neighbor_step * neighbor_step;
            var y0 = y1 - self_step;
            var index0 = y1 * TERRAIN_LOD_VERTS + x1;
            var index1 = y0 * TERRAIN_LOD_VERTS + x0;
            indices[index++] = index0;
            indices[index++] = index1;
          }
          indices[index++] = TERRAIN_LOD_VERTS - 1;
          indices[index++] = TERRAIN_LOD_VERTS - 1;
          this._connecterIndexPool[connecterIndex].size = index;
          this._connecterIndexPool[connecterIndex].indices = indices;
        };
        _proto2._genConnecterIndexSouth = function _genConnecterIndexSouth(level, connecter) {
          var connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_SOUTH_INDEX);
          if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) {
            this._connecterIndexPool[connecterIndex].size = 0;
            this._connecterIndexPool[connecterIndex].indices = null;
            return;
          }
          var self_step = 1 << level;
          var neighbor_step = 1 << connecter;
          var self_tile = TERRAIN_LOD_TILES >> level;
          var count = self_tile * 2 + 2;
          var index = 0;
          var indices = new Uint16Array(count);
          indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS;
          indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS;
          for (var i = 1; i < self_tile; ++i) {
            var x0 = i * self_step;
            var y0 = TERRAIN_LOD_VERTS - 1 - self_step;
            var x1 = x0 / neighbor_step * neighbor_step;
            var y1 = y0 + self_step;
            var index0 = y1 * TERRAIN_LOD_VERTS + x1;
            var index1 = y0 * TERRAIN_LOD_VERTS + x0;
            indices[index++] = index0;
            indices[index++] = index1;
          }
          indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1;
          indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1;
          this._connecterIndexPool[connecterIndex].size = index;
          this._connecterIndexPool[connecterIndex].indices = indices;
        };
        _proto2._genConnecterIndexWest = function _genConnecterIndexWest(level, connecter) {
          var connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_WEST_INDEX);
          if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) {
            this._connecterIndexPool[connecterIndex].size = 0;
            this._connecterIndexPool[connecterIndex].indices = null;
            return;
          }
          var self_step = 1 << level;
          var neighbor_step = 1 << connecter;
          var self_tile = TERRAIN_LOD_TILES >> level;
          var count = self_tile * 2 + 2;
          var index = 0;
          var indices = new Uint16Array(count);
          indices[index++] = 0;
          indices[index++] = 0;
          for (var i = 1; i < self_tile; ++i) {
            var x0 = 0;
            var y0 = i * self_step / neighbor_step * neighbor_step;
            var x1 = self_step;
            var y1 = i * self_step;
            var index0 = y0 * TERRAIN_LOD_VERTS + x0;
            var index1 = y1 * TERRAIN_LOD_VERTS + x1;
            indices[index++] = index0;
            indices[index++] = index1;
          }
          indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS;
          indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS;
          this._connecterIndexPool[connecterIndex].size = index;
          this._connecterIndexPool[connecterIndex].indices = indices;
        };
        _proto2._genConnecterIndexEast = function _genConnecterIndexEast(level, connecter) {
          var connecterIndex = TerrainLod.mapIndex(level, connecter, TERRAIN_LOD_EAST_INDEX);
          if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) {
            this._connecterIndexPool[connecterIndex].size = 0;
            this._connecterIndexPool[connecterIndex].indices = null;
            return;
          }
          var self_step = 1 << level;
          var neighbor_step = 1 << connecter;
          var self_tile = TERRAIN_LOD_TILES >> level;
          var count = self_tile * 2 + 2;
          var index = 0;
          var indices = new Uint16Array(count);
          indices[index++] = TERRAIN_LOD_VERTS - 1;
          indices[index++] = TERRAIN_LOD_VERTS - 1;
          for (var i = 1; i < self_tile; ++i) {
            var x0 = TERRAIN_LOD_VERTS - 1 - self_step;
            var y0 = i * self_step;
            var x1 = TERRAIN_LOD_VERTS - 1;
            var y1 = i * self_step / neighbor_step * neighbor_step;
            var index0 = y0 * TERRAIN_LOD_VERTS + x0;
            var index1 = y1 * TERRAIN_LOD_VERTS + x1;
            indices[index++] = index0;
            indices[index++] = index1;
          }
          indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1;
          indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1;
          this._connecterIndexPool[connecterIndex].size = index;
          this._connecterIndexPool[connecterIndex].indices = indices;
        };
        _proto2._getConnenterIndex = function _getConnenterIndex(i, j, k) {
          return this._connecterIndexPool[TerrainLod.mapIndex(i, j, k)];
        };
        _proto2._genIndexData = function _genIndexData(k) {
          var data = this.getIndexData(k);
          if (data != null) {
            return data;
          }
          var body = this._bodyIndexPool[k.level];
          var north = this._getConnenterIndex(k.level, k.north, TERRAIN_LOD_NORTH_INDEX);
          var south = this._getConnenterIndex(k.level, k.south, TERRAIN_LOD_SOUTH_INDEX);
          var west = this._getConnenterIndex(k.level, k.west, TERRAIN_LOD_WEST_INDEX);
          var east = this._getConnenterIndex(k.level, k.east, TERRAIN_LOD_EAST_INDEX);
          data = new TerrainIndexData();
          data.size = 0;
          data.primCount = 0;
          if (body.indices != null) {
            data.size += body.size;
          }
          if (north.indices) {
            data.size += (north.size - 2) * 3;
          }
          if (south.indices) {
            data.size += (south.size - 2) * 3;
          }
          if (west.indices) {
            data.size += (west.size - 2) * 3;
          }
          if (east.indices) {
            data.size += (east.size - 2) * 3;
          }
          if (data.size === 0) {
            return null;
          }
          var index = 0;
          data.buffer = new Uint16Array(data.size);
          data.key.level = k.level;
          data.key.east = k.east;
          data.key.west = k.west;
          data.key.north = k.north;
          data.key.south = k.south;
          if (body.indices) {
            for (var i = 0; i < body.size; ++i) {
              data.buffer[index++] = body.indices[i];
            }
          }
          if (north.indices) {
            for (var _i4 = 0; _i4 < north.size - 2; _i4 += 2) {
              var a = north.indices[_i4 + 0];
              var b = north.indices[_i4 + 1];
              var c = north.indices[_i4 + 2];
              var d = north.indices[_i4 + 3];
              data.buffer[index++] = a;
              data.buffer[index++] = c;
              data.buffer[index++] = b;
              data.buffer[index++] = c;
              data.buffer[index++] = d;
              data.buffer[index++] = b;
            }
          }
          if (south.indices) {
            for (var _i5 = 0; _i5 < south.size - 2; _i5 += 2) {
              var _a = south.indices[_i5 + 0];
              var _b = south.indices[_i5 + 1];
              var _c = south.indices[_i5 + 2];
              var _d = south.indices[_i5 + 3];
              data.buffer[index++] = _a;
              data.buffer[index++] = _c;
              data.buffer[index++] = _b;
              data.buffer[index++] = _c;
              data.buffer[index++] = _d;
              data.buffer[index++] = _b;
            }
          }
          if (west.indices) {
            for (var _i6 = 0; _i6 < west.size - 2; _i6 += 2) {
              var _a2 = west.indices[_i6 + 0];
              var _b2 = west.indices[_i6 + 1];
              var _c2 = west.indices[_i6 + 2];
              var _d2 = west.indices[_i6 + 3];
              data.buffer[index++] = _a2;
              data.buffer[index++] = _c2;
              data.buffer[index++] = _b2;
              data.buffer[index++] = _c2;
              data.buffer[index++] = _d2;
              data.buffer[index++] = _b2;
            }
          }
          if (east.indices) {
            for (var _i7 = 0; _i7 < east.size - 2; _i7 += 2) {
              var _a3 = east.indices[_i7 + 0];
              var _b3 = east.indices[_i7 + 1];
              var _c3 = east.indices[_i7 + 2];
              var _d3 = east.indices[_i7 + 3];
              data.buffer[index++] = _a3;
              data.buffer[index++] = _c3;
              data.buffer[index++] = _b3;
              data.buffer[index++] = _c3;
              data.buffer[index++] = _d3;
              data.buffer[index++] = _b3;
            }
          }
          data.primCount = index / 3;
          data.start = this._indexBuffer.length;
          this._indexMap.push(data);
          var temp = new Uint16Array(data.start + data.size);
          temp.set(this._indexBuffer, 0);
          temp.set(data.buffer, data.start);
          this._indexBuffer = temp;
          return data;
        };
        return TerrainLod;
      }();

      var _dec$q, _class$q, _class2$m, _initializer$k, _initializer2$j, _initializer3$f, _initializer4$d, _dec2$n, _class4, _class5$1, _initializer5$b, _initializer6$8, _initializer7$8, _initializer8$8, _initializer9$7, _dec3$l, _class8, _class9, _initializer10$7, _initializer11$7, _initializer12$6, _initializer13$4, _initializer14$3, _dec4$f, _dec5$f, _dec6$9, _dec7$7, _dec8$5, _dec9$4, _dec10$2, _dec11$1, _class12, _class13, _initializer15$2, _initializer16$2, _initializer17$1, _initializer18$1, _initializer19, _initializer20, _initializer21, _initializer22;
      var TERRAIN_EFFECT_UUID = '1d08ef62-a503-4ce2-8b9a-46c90873f7d3';
      var TerrainInfo = exports('gh', (_dec$q = ccclass$M('cc.TerrainInfo'), _dec$q(_class$q = (_class2$m = function () {
        function TerrainInfo() {
          this.tileSize = _initializer$k && _initializer$k();
          this.blockCount = _initializer2$j && _initializer2$j();
          this.weightMapSize = _initializer3$f && _initializer3$f();
          this.lightMapSize = _initializer4$d && _initializer4$d();
        }
        _createClass(TerrainInfo, [{
          key: "size",
          get: function get() {
            var sz = new Size$1(0, 0);
            sz.width = this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY * this.tileSize;
            sz.height = this.blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY * this.tileSize;
            return sz;
          }
        }, {
          key: "tileCount",
          get: function get() {
            var _tileCount = [0, 0];
            _tileCount[0] = this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY;
            _tileCount[1] = this.blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY;
            return _tileCount;
          }
        }, {
          key: "vertexCount",
          get: function get() {
            var _vertexCount = this.tileCount;
            _vertexCount[0] += 1;
            _vertexCount[1] += 1;
            return _vertexCount;
          }
        }]);
        return TerrainInfo;
      }(), (_initializer$k = applyDecoratedInitializer(_class2$m.prototype, "tileSize", [serializable$p], function () {
        return 1;
      }), _initializer2$j = applyDecoratedInitializer(_class2$m.prototype, "blockCount", [serializable$p], function () {
        return [1, 1];
      }), _initializer3$f = applyDecoratedInitializer(_class2$m.prototype, "weightMapSize", [serializable$p], function () {
        return 128;
      }), _initializer4$d = applyDecoratedInitializer(_class2$m.prototype, "lightMapSize", [serializable$p], function () {
        return 128;
      })), _class2$m)) || _class$q));
      var TerrainLayer = exports('gi', (_dec2$n = ccclass$M('cc.TerrainLayer'), _dec2$n(_class4 = (_class5$1 = function TerrainLayer() {
        this.detailMap = _initializer5$b && _initializer5$b();
        this.normalMap = _initializer6$8 && _initializer6$8();
        this.tileSize = _initializer7$8 && _initializer7$8();
        this.metallic = _initializer8$8 && _initializer8$8();
        this.roughness = _initializer9$7 && _initializer9$7();
      }, (_initializer5$b = applyDecoratedInitializer(_class5$1.prototype, "detailMap", [serializable$p], function () {
        return null;
      }), _initializer6$8 = applyDecoratedInitializer(_class5$1.prototype, "normalMap", [serializable$p], function () {
        return null;
      }), _initializer7$8 = applyDecoratedInitializer(_class5$1.prototype, "tileSize", [serializable$p], function () {
        return 1;
      }), _initializer8$8 = applyDecoratedInitializer(_class5$1.prototype, "metallic", [serializable$p], function () {
        return 0;
      }), _initializer9$7 = applyDecoratedInitializer(_class5$1.prototype, "roughness", [serializable$p], function () {
        return 1;
      })), _class5$1)) || _class4));
      var TerrainRenderable = function (_ModelRenderer) {
        _inheritsLoose(TerrainRenderable, _ModelRenderer);
        function TerrainRenderable() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ModelRenderer.call.apply(_ModelRenderer, [this].concat(args)) || this;
          _this._model = null;
          _this._meshData = null;
          _this._brushPass = null;
          _this._brushMaterial = null;
          _this._currentMaterial = null;
          _this._currentMaterialLayers = 0;
          _this._lightmap = null;
          return _this;
        }
        var _proto = TerrainRenderable.prototype;
        _proto.destroy = function destroy() {
          if (this._model != null) {
            legacyCC.director.root.destroyModel(this._model);
            this._model = null;
          }
          return _ModelRenderer.prototype.destroy.call(this);
        };
        _proto._destroyModel = function _destroyModel() {
          if (this._model != null) {
            legacyCC.director.root.destroyModel(this._model);
            this._model = null;
          }
          if (this._meshData != null) {
            this._meshData.destroy();
            this._meshData = null;
          }
        };
        _proto._invalidMaterial = function _invalidMaterial() {
          if (this._currentMaterial == null) {
            return;
          }
          this._clearMaterials();
          this._brushPass = null;
          this._currentMaterial = null;
          if (this._model != null) {
            this._model.enabled = false;
          }
        };
        _proto._updateMaterial = function _updateMaterial(block, init) {
          if (this._meshData == null || this._model == null) {
            return false;
          }
          var nLayers = block.getMaxLayer();
          if (this._currentMaterial == null || nLayers !== this._currentMaterialLayers) {
            this._currentMaterial = new Material();
            this._currentMaterial.initialize({
              effectAsset: block.getTerrain().getEffectAsset(),
              defines: block._getMaterialDefines(nLayers)
            });
            if (this._brushMaterial !== null) {
              var brushMaterialInstance = new Material();
              brushMaterialInstance.copy(this._brushMaterial);
              this._brushPass = null;
              if (brushMaterialInstance.passes !== null && brushMaterialInstance.passes.length > 0) {
                this._brushPass = brushMaterialInstance.passes[0];
                var passes = this._currentMaterial.passes;
                passes.push(this._brushPass);
                brushMaterialInstance.passes.pop();
              }
            }
            if (init) {
              this._model.initSubModel(0, this._meshData, this._currentMaterial);
            }
            this.setSharedMaterial(this._currentMaterial, 0);
            this._currentMaterialLayers = nLayers;
            this._model.enabled = true;
            this._model.receiveShadow = block.getTerrain().receiveShadow;
            return true;
          }
          return false;
        };
        _proto._updateLightingmap = function _updateLightingmap(texture, uvParam) {
          if (this._model == null) {
            return;
          }
          this._lightmap = texture;
          this._updateReceiveDirLight();
          this._model.updateLightingmap(texture, uvParam);
        };
        _proto._onMaterialModified = function _onMaterialModified(idx, mtl) {
          if (this._model == null) {
            return;
          }
          this._onRebuildPSO(idx, mtl || this._getBuiltinMaterial());
        };
        _proto._onRebuildPSO = function _onRebuildPSO(idx, material) {
          if (this._model) {
            this._model.setSubModelMaterial(idx, material);
          }
        };
        _proto._clearMaterials = function _clearMaterials() {
          if (this._model == null) {
            return;
          }
          this._onMaterialModified(0, null);
        };
        _proto._onUpdateReceiveDirLight = function _onUpdateReceiveDirLight(visibility, forceClose) {
          if (forceClose === void 0) {
            forceClose = false;
          }
          if (!this._model) {
            return;
          }
          if (forceClose) {
            this._model.receiveDirLight = false;
            return;
          }
          if (this.node && (visibility & this.node.layer) === this.node.layer || visibility & this._model.visFlags) {
            this._model.receiveDirLight = true;
          } else {
            this._model.receiveDirLight = false;
          }
        };
        _proto._updateReceiveDirLight = function _updateReceiveDirLight() {
          var scene = this.node.scene;
          if (!scene || !scene.renderScene) {
            return;
          }
          var mainLight = scene.renderScene.mainLight;
          if (!mainLight) {
            return;
          }
          var visibility = mainLight.visibility;
          if (!mainLight.node) {
            return;
          }
          if (mainLight.node.mobility === MobilityMode.Static && this._lightmap) {
            this._onUpdateReceiveDirLight(visibility, true);
          } else {
            this._onUpdateReceiveDirLight(visibility);
          }
        };
        _proto._getBuiltinMaterial = function _getBuiltinMaterial() {
          return builtinResMgr.get('missing-material');
        };
        return TerrainRenderable;
      }(ModelRenderer);
      var TerrainBlockLightmapInfo = exports('gj', (_dec3$l = ccclass$M('cc.TerrainBlockLightmapInfo'), _dec3$l(_class8 = (_class9 = function TerrainBlockLightmapInfo() {
        this.texture = _initializer10$7 && _initializer10$7();
        this.UOff = _initializer11$7 && _initializer11$7();
        this.VOff = _initializer12$6 && _initializer12$6();
        this.UScale = _initializer13$4 && _initializer13$4();
        this.VScale = _initializer14$3 && _initializer14$3();
      }, (_initializer10$7 = applyDecoratedInitializer(_class9.prototype, "texture", [serializable$p], function () {
        return null;
      }), _initializer11$7 = applyDecoratedInitializer(_class9.prototype, "UOff", [serializable$p], function () {
        return 0;
      }), _initializer12$6 = applyDecoratedInitializer(_class9.prototype, "VOff", [serializable$p], function () {
        return 0;
      }), _initializer13$4 = applyDecoratedInitializer(_class9.prototype, "UScale", [serializable$p], function () {
        return 0;
      }), _initializer14$3 = applyDecoratedInitializer(_class9.prototype, "VScale", [serializable$p], function () {
        return 0;
      })), _class9)) || _class8));
      var TerrainBlock = exports('gk', function () {
        function TerrainBlock(t, i, j) {
          this._terrain = void 0;
          this._node = void 0;
          this._renderable = void 0;
          this._index = [1, 1];
          this._weightMap = null;
          this._lightmapInfo = null;
          this._lodLevel = 0;
          this._lodKey = new TerrainLodKey();
          this._errorMetrics = [0, 0, 0, 0];
          this._LevelDistances = [TERRAIN_LOD_MAX_DISTANCE, TERRAIN_LOD_MAX_DISTANCE, TERRAIN_LOD_MAX_DISTANCE, TERRAIN_LOD_MAX_DISTANCE];
          this._bbMin = new Vec3();
          this._bbMax = new Vec3();
          this._terrain = t;
          this._index[0] = i;
          this._index[1] = j;
          this._lightmapInfo = t._getLightmapInfo(i, j);
          this._node = new Node$1('TerrainBlock');
          this._node.setParent(this._terrain.node);
          this._node.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
          this._node.layer = this._terrain.node.layer;
          this._renderable = this._node.addComponent(TerrainRenderable);
        }
        var _proto2 = TerrainBlock.prototype;
        _proto2.build = function build() {
          var gfxDevice = director.root.device;
          var vertexData = new Float32Array(TERRAIN_BLOCK_VERTEX_SIZE * TERRAIN_BLOCK_VERTEX_COMPLEXITY * TERRAIN_BLOCK_VERTEX_COMPLEXITY);
          this._buildVertexData(vertexData);
          var vertexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, TERRAIN_BLOCK_VERTEX_SIZE * Float32Array.BYTES_PER_ELEMENT * TERRAIN_BLOCK_VERTEX_COMPLEXITY * TERRAIN_BLOCK_VERTEX_COMPLEXITY, TERRAIN_BLOCK_VERTEX_SIZE * Float32Array.BYTES_PER_ELEMENT));
          vertexBuffer.update(vertexData);
          this._buildBoundingBox();
          var gfxAttributes = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F)];
          this._renderable._meshData = new RenderingSubMesh([vertexBuffer], gfxAttributes, PrimitiveMode.TRIANGLE_LIST, this._terrain._getSharedIndexBuffer(), null, false);
          this._renderable._model = legacyCC.director.root.createModel(Model);
          this._renderable._model.createBoundingShape(this._bbMin, this._bbMax);
          this._renderable._model.node = this._renderable._model.transform = this._node;
          if (this._renderable.node.scene != null) {
            this.visible = true;
          }
          this._updateWeightMap();
          this._updateMaterial(true);
          if (this._terrain.lodEnable) {
            this._updateLodBuffer(vertexData);
            this._updateIndexBuffer();
          }
        };
        _proto2.rebuild = function rebuild() {
          this._updateHeight();
          this._updateWeightMap();
          this._renderable._invalidMaterial();
          this._updateMaterial(false);
        };
        _proto2.destroy = function destroy() {
          this.visible = false;
          this._renderable._destroyModel();
          if (this._node != null && this._node.isValid) {
            this._node.destroy();
          }
          if (this._weightMap != null) {
            this._weightMap.destroy();
          }
        };
        _proto2.update = function update() {
          this._updateMaterial(false);
          if (this.lightmap !== this._renderable._lightmap) {
            this._renderable._updateLightingmap(this.lightmap, this.lightmapUVParam);
          }
          var useNormalMap = this._terrain.useNormalMap;
          var usePBR = this._terrain.usePBR;
          var getDetailTex = function getDetailTex(layer) {
            return layer !== null ? layer.detailMap : null;
          };
          var getNormalTex = function getNormalTex(layer) {
            var normalTex = layer !== null ? layer.normalMap : null;
            if (normalTex === null) {
              normalTex = builtinResMgr.get('normal-texture');
            }
            return normalTex;
          };
          var mtl = this._renderable._currentMaterial;
          if (mtl !== null) {
            var nLayers = this.getMaxLayer();
            var uvScale = new Vec4(1, 1, 1, 1);
            var roughness = new Vec4(1, 1, 1, 1);
            var metallic = new Vec4(0, 0, 0, 0);
            if (nLayers === 0) {
              if (this.layers[0] !== -1) {
                var l0 = this._terrain.getLayer(this.layers[0]);
                if (l0 !== null) {
                  uvScale.x = 1.0 / l0.tileSize;
                  roughness.x = l0.roughness;
                  metallic.x = l0.metallic;
                }
                mtl.setProperty('detailMap0', getDetailTex(l0));
                if (useNormalMap) {
                  mtl.setProperty('normalMap0', getNormalTex(l0));
                }
              } else {
                mtl.setProperty('detailMap0', builtinResMgr.get('default-texture'));
                if (useNormalMap) {
                  mtl.setProperty('normalMap0', builtinResMgr.get('normal-texture'));
                }
              }
            } else if (nLayers === 1) {
              var _l = this._terrain.getLayer(this.layers[0]);
              var l1 = this._terrain.getLayer(this.layers[1]);
              if (_l !== null) {
                uvScale.x = 1.0 / _l.tileSize;
                roughness.x = _l.roughness;
                metallic.x = _l.metallic;
              }
              if (l1 !== null) {
                uvScale.y = 1.0 / l1.tileSize;
                roughness.y = l1.roughness;
                metallic.y = l1.metallic;
              }
              mtl.setProperty('weightMap', this._weightMap);
              mtl.setProperty('detailMap0', getDetailTex(_l));
              mtl.setProperty('detailMap1', getDetailTex(l1));
              if (useNormalMap) {
                mtl.setProperty('normalMap0', getNormalTex(_l));
                mtl.setProperty('normalMap1', getNormalTex(l1));
              }
            } else if (nLayers === 2) {
              var _l2 = this._terrain.getLayer(this.layers[0]);
              var _l3 = this._terrain.getLayer(this.layers[1]);
              var l2 = this._terrain.getLayer(this.layers[2]);
              if (_l2 !== null) {
                uvScale.x = 1.0 / _l2.tileSize;
                roughness.x = _l2.roughness;
                metallic.x = _l2.metallic;
              }
              if (_l3 !== null) {
                uvScale.y = 1.0 / _l3.tileSize;
                roughness.y = _l3.roughness;
                metallic.y = _l3.metallic;
              }
              if (l2 !== null) {
                uvScale.z = 1.0 / l2.tileSize;
                roughness.z = l2.roughness;
                metallic.z = l2.metallic;
              }
              mtl.setProperty('weightMap', this._weightMap);
              mtl.setProperty('detailMap0', getDetailTex(_l2));
              mtl.setProperty('detailMap1', getDetailTex(_l3));
              mtl.setProperty('detailMap2', getDetailTex(l2));
              if (useNormalMap) {
                mtl.setProperty('normalMap0', getNormalTex(_l2));
                mtl.setProperty('normalMap1', getNormalTex(_l3));
                mtl.setProperty('normalMap2', getNormalTex(l2));
              }
            } else if (nLayers === 3) {
              var _l4 = this._terrain.getLayer(this.layers[0]);
              var _l5 = this._terrain.getLayer(this.layers[1]);
              var _l6 = this._terrain.getLayer(this.layers[2]);
              var l3 = this._terrain.getLayer(this.layers[3]);
              if (_l4 !== null) {
                uvScale.x = 1.0 / _l4.tileSize;
                roughness.x = _l4.roughness;
                metallic.x = _l4.metallic;
              }
              if (_l5 !== null) {
                uvScale.y = 1.0 / _l5.tileSize;
                roughness.y = _l5.roughness;
                metallic.y = _l5.metallic;
              }
              if (_l6 !== null) {
                uvScale.z = 1.0 / _l6.tileSize;
                roughness.z = _l6.roughness;
                metallic.z = _l6.metallic;
              }
              if (l3 !== null) {
                uvScale.w = 1.0 / l3.tileSize;
                roughness.w = l3.roughness;
                metallic.w = l3.metallic;
              }
              mtl.setProperty('weightMap', this._weightMap);
              mtl.setProperty('detailMap0', getDetailTex(_l4));
              mtl.setProperty('detailMap1', getDetailTex(_l5));
              mtl.setProperty('detailMap2', getDetailTex(_l6));
              mtl.setProperty('detailMap3', getDetailTex(l3));
              if (useNormalMap) {
                mtl.setProperty('normalMap0', getNormalTex(_l4));
                mtl.setProperty('normalMap1', getNormalTex(_l5));
                mtl.setProperty('normalMap2', getNormalTex(_l6));
                mtl.setProperty('normalMap3', getNormalTex(l3));
              }
            }
            mtl.setProperty('UVScale', uvScale);
            if (usePBR) {
              mtl.setProperty('roughness', roughness);
              mtl.setProperty('metallic', metallic);
            }
          }
        };
        _proto2._buildLodInfo = function _buildLodInfo() {
          var vertexData = new Float32Array(TERRAIN_BLOCK_VERTEX_SIZE * TERRAIN_BLOCK_VERTEX_COMPLEXITY * TERRAIN_BLOCK_VERTEX_COMPLEXITY);
          this._buildVertexData(vertexData);
          this._updateLodBuffer(vertexData);
          this._updateIndexBuffer();
        };
        _proto2._updateLevel = function _updateLevel(camPos) {
          var maxLevel = TERRAIN_LOD_LEVELS - 1;
          var bbMin = new Vec3();
          var bbMax = new Vec3();
          Vec3.add(bbMin, this._bbMin, this._terrain.node.getWorldPosition());
          Vec3.add(bbMax, this._bbMax, this._terrain.node.getWorldPosition());
          var d1 = Vec3.distance(bbMin, camPos);
          var d2 = Vec3.distance(bbMax, camPos);
          var d = Math.min(d1, d2);
          d -= this._terrain.LodBias;
          this._lodLevel = 0;
          while (this._lodLevel < maxLevel) {
            var ld1 = this._LevelDistances[this._lodLevel + 1];
            if (d <= ld1) {
              break;
            }
            ++this._lodLevel;
          }
        };
        _proto2.setBrushMaterial = function setBrushMaterial(mtl) {
          if (this._renderable._brushMaterial !== mtl) {
            this._renderable._invalidMaterial();
            this._renderable._brushMaterial = mtl;
          }
        };
        _proto2._getBrushMaterial = function _getBrushMaterial() {
          return this._renderable ? this._renderable._brushMaterial : null;
        };
        _proto2._getBrushPass = function _getBrushPass() {
          return this._renderable ? this._renderable._brushPass : null;
        };
        _proto2.getTerrain = function getTerrain() {
          return this._terrain;
        };
        _proto2.getIndex = function getIndex() {
          return this._index;
        };
        _proto2.getRect = function getRect() {
          var rect = new Rect$1();
          rect.x = this._index[0] * TERRAIN_BLOCK_TILE_COMPLEXITY;
          rect.y = this._index[1] * TERRAIN_BLOCK_TILE_COMPLEXITY;
          rect.width = TERRAIN_BLOCK_TILE_COMPLEXITY;
          rect.height = TERRAIN_BLOCK_TILE_COMPLEXITY;
          return rect;
        };
        _proto2.setLayer = function setLayer(index, layerId) {
          if (this.layers[index] !== layerId) {
            this._terrain.setBlockLayer(this._index[0], this._index[1], index, layerId);
            this._renderable._invalidMaterial();
            this._updateMaterial(false);
          }
        };
        _proto2.getLayer = function getLayer(index) {
          return this.layers[index];
        };
        _proto2.getMaxLayer = function getMaxLayer() {
          if (this.layers[3] >= 0) {
            return 3;
          }
          if (this.layers[2] >= 0) {
            return 2;
          }
          if (this.layers[1] >= 0) {
            return 1;
          }
          return 0;
        };
        _proto2._getMaterialDefines = function _getMaterialDefines(nLayers) {
          var lightmapMacroValue = 1;
          if (this._terrain.node && this._terrain.node.scene) {
            if (this._terrain.node.scene.globals.bakedWithStationaryMainLight) {
              lightmapMacroValue = 2;
            }
          }
          return {
            LAYERS: nLayers + 1,
            CC_USE_LIGHTMAP: this.lightmap !== null ? lightmapMacroValue : 0,
            USE_NORMALMAP: this._terrain.useNormalMap ? 1 : 0,
            USE_PBR: this._terrain.usePBR ? 1 : 0
          };
        };
        _proto2._invalidMaterial = function _invalidMaterial() {
          this._renderable._invalidMaterial();
        };
        _proto2._updateMaterial = function _updateMaterial(init) {
          if (this._renderable._updateMaterial(this, init)) {
            if (this.lightmap !== null) {
              this.lightmap.setWrapMode(WrapMode$1.CLAMP_TO_BORDER, WrapMode$1.CLAMP_TO_BORDER);
            }
            this._renderable._updateLightingmap(this.lightmap, this.lightmapUVParam);
          }
        };
        _proto2._updateHeight = function _updateHeight() {
          if (this._renderable._meshData == null) {
            return;
          }
          var vertexData = new Float32Array(TERRAIN_BLOCK_VERTEX_SIZE * TERRAIN_BLOCK_VERTEX_COMPLEXITY * TERRAIN_BLOCK_VERTEX_COMPLEXITY);
          this._buildVertexData(vertexData);
          this._renderable._meshData.vertexBuffers[0].update(vertexData);
          this._buildBoundingBox();
          this._renderable._model.createBoundingShape(this._bbMin, this._bbMax);
          this._renderable._model.updateWorldBound();
          this._updateLodBuffer(vertexData);
          this._updateIndexBuffer();
        };
        _proto2._updateWeightMap = function _updateWeightMap() {
          var nLayers = this.getMaxLayer();
          if (nLayers === 0) {
            if (this._weightMap != null) {
              this._weightMap.destroy();
              this._weightMap = null;
            }
            return;
          }
          if (this._weightMap == null) {
            this._weightMap = new Texture2D();
            this._weightMap.create(this._terrain.weightMapSize, this._terrain.weightMapSize, PixelFormat.RGBA8888);
            this._weightMap.setFilters(Filter.LINEAR, Filter.LINEAR);
            this._weightMap.setWrapMode(WrapMode$1.CLAMP_TO_EDGE, WrapMode$1.CLAMP_TO_EDGE);
          }
          var weightData = new Uint8Array(this._terrain.weightMapSize * this._terrain.weightMapSize * 4);
          var weightIndex = 0;
          for (var j = 0; j < this._terrain.weightMapSize; ++j) {
            for (var i = 0; i < this._terrain.weightMapSize; ++i) {
              var x = this._index[0] * this._terrain.weightMapSize + i;
              var y = this._index[1] * this._terrain.weightMapSize + j;
              var w = this._terrain.getWeight(x, y);
              weightData[weightIndex * 4 + 0] = Math.floor(w.x * 255);
              weightData[weightIndex * 4 + 1] = Math.floor(w.y * 255);
              weightData[weightIndex * 4 + 2] = Math.floor(w.z * 255);
              weightData[weightIndex * 4 + 3] = Math.floor(w.w * 255);
              weightIndex += 1;
            }
          }
          this._weightMap.uploadData(weightData);
        };
        _proto2._updateLightmap = function _updateLightmap(info) {
          this._lightmapInfo = info;
          this._invalidMaterial();
        };
        _proto2._updateLod = function _updateLod() {
          var key = new TerrainLodKey();
          key.level = this._lodLevel;
          key.north = this._lodLevel;
          key.south = this._lodLevel;
          key.west = this._lodLevel;
          key.east = this._lodLevel;
          if (this._index[0] > 0) {
            var n = this.getTerrain().getBlock(this._index[0] - 1, this._index[1]);
            key.west = n._lodLevel;
            if (key.west < this._lodLevel) {
              key.west = this._lodLevel;
            }
          }
          if (this._index[0] < this._terrain.info.blockCount[0] - 1) {
            var _n = this.getTerrain().getBlock(this._index[0] + 1, this._index[1]);
            key.east = _n._lodLevel;
            if (key.east < this._lodLevel) {
              key.east = this._lodLevel;
            }
          }
          if (this._index[1] > 0) {
            var _n2 = this.getTerrain().getBlock(this._index[0], this._index[1] - 1);
            key.north = _n2._lodLevel;
            if (key.north < this._lodLevel) {
              key.north = this._lodLevel;
            }
          }
          if (this._index[1] < this._terrain.info.blockCount[1] - 1) {
            var _n3 = this.getTerrain().getBlock(this._index[0], this._index[1] + 1);
            key.south = _n3._lodLevel;
            if (key.south < this._lodLevel) {
              key.south = this._lodLevel;
            }
          }
          if (this._lodKey.equals(key)) {
            return;
          }
          this._lodKey = key;
          this._updateIndexBuffer();
        };
        _proto2._resetLod = function _resetLod() {
          var key = new TerrainLodKey();
          key.level = 0;
          key.north = 0;
          key.south = 0;
          key.west = 0;
          key.east = 0;
          if (this._lodKey.equals(key)) {
            return;
          }
          this._lodKey = key;
          this._updateIndexBuffer();
        };
        _proto2._updateIndexBuffer = function _updateIndexBuffer() {
          if (this._renderable._meshData === null) {
            return;
          }
          if (this._renderable._model === null) {
            return;
          }
          if (this._renderable._model.subModels.length === 0) {
            return;
          }
          var indexData = this._terrain._getIndexData(this._lodKey);
          if (indexData === null) {
            return;
          }
          var model = this._renderable._model.subModels[0];
          model.inputAssembler.firstIndex = indexData.start;
          model.inputAssembler.indexCount = indexData.size;
        };
        _proto2._getHeight = function _getHeight(x, y, verts) {
          var idx = TERRAIN_BLOCK_VERTEX_COMPLEXITY * y + x;
          return verts[idx * TERRAIN_BLOCK_VERTEX_SIZE + 1];
        };
        _proto2._updateLodBuffer = function _updateLodBuffer(vertices) {
          this._lodLevel = 0;
          this._lodKey = new TerrainLodKey();
          this._calcErrorMetrics(vertices);
          this._calcLevelDistances(vertices);
        };
        _proto2._calcErrorMetrics = function _calcErrorMetrics(vertices) {
          this._errorMetrics[0] = 0;
          for (var i = 1; i < TERRAIN_LOD_LEVELS; ++i) {
            this._errorMetrics[i] = this._calcErrorMetric(i, vertices);
          }
          for (var _i2 = 2; _i2 < TERRAIN_LOD_LEVELS; ++_i2) {
            this._errorMetrics[_i2] = Math.max(this._errorMetrics[_i2], this._errorMetrics[_i2 - 1]);
          }
        };
        _proto2._calcErrorMetric = function _calcErrorMetric(level, vertices) {
          var err = 0.0;
          var step = 1 << level;
          var xSectionVertices = TERRAIN_BLOCK_VERTEX_COMPLEXITY;
          var ySectionVertices = TERRAIN_BLOCK_VERTEX_COMPLEXITY;
          var xSides = xSectionVertices - 1 >> level;
          var ySides = ySectionVertices - 1 >> level;
          for (var y = 0; y < ySectionVertices; y += step) {
            for (var x = 0; x < xSides; ++x) {
              var x0 = x * step;
              var x1 = x0 + step;
              var xm = (x1 + x0) / 2;
              var h0 = this._getHeight(x0, y, vertices);
              var h1 = this._getHeight(x1, y, vertices);
              var hm = this._getHeight(xm, y, vertices);
              var hmi = (h0 + h1) / 2;
              var delta = Math.abs(hm - hmi);
              err = Math.max(err, delta);
            }
          }
          for (var _x2 = 0; _x2 < xSectionVertices; _x2 += step) {
            for (var _y2 = 0; _y2 < ySides; ++_y2) {
              var y0 = _y2 * step;
              var y1 = y0 + step;
              var ym = (y0 + y1) / 2;
              var _h = this._getHeight(_x2, y0, vertices);
              var _h2 = this._getHeight(_x2, y1, vertices);
              var _hm = this._getHeight(_x2, ym, vertices);
              var _hmi = (_h + _h2) / 2;
              var _delta = Math.abs(_hm - _hmi);
              err = Math.max(err, _delta);
            }
          }
          for (var _y3 = 0; _y3 < ySides; ++_y3) {
            var _y4 = _y3 * step;
            var _y5 = _y4 + step;
            var _ym = (_y4 + _y5) / 2;
            for (var _x3 = 0; _x3 < xSides; ++_x3) {
              var _x4 = _x3 * step;
              var _x5 = _x4 + step;
              var _xm = (_x4 + _x5) / 2;
              var _h3 = this._getHeight(_x4, _y4, vertices);
              var _h4 = this._getHeight(_x5, _y5, vertices);
              var _hm2 = this._getHeight(_xm, _ym, vertices);
              var _hmi2 = (_h3 + _h4) / 2;
              var _delta2 = Math.abs(_hm2 - _hmi2);
              err = Math.max(err, _delta2);
            }
          }
          return err;
        };
        _proto2._calcLevelDistances = function _calcLevelDistances(vertices) {
          var pixelErr = 4;
          var resolution = 768;
          var c = 1.0 / (2 * pixelErr / resolution);
          for (var i = 1; i < TERRAIN_LOD_LEVELS; ++i) {
            var e = this._errorMetrics[i];
            var d = e * c;
            this._LevelDistances[i] = d;
          }
        };
        _proto2._buildVertexData = function _buildVertexData(vertexData) {
          var index = 0;
          for (var j = 0; j < TERRAIN_BLOCK_VERTEX_COMPLEXITY; ++j) {
            for (var i = 0; i < TERRAIN_BLOCK_VERTEX_COMPLEXITY; ++i) {
              var x = this._index[0] * TERRAIN_BLOCK_TILE_COMPLEXITY + i;
              var y = this._index[1] * TERRAIN_BLOCK_TILE_COMPLEXITY + j;
              var position = this._terrain.getPosition(x, y);
              var normal = this._terrain.getNormal(x, y);
              var uv = new Vec2(i / TERRAIN_BLOCK_TILE_COMPLEXITY, j / TERRAIN_BLOCK_TILE_COMPLEXITY);
              vertexData[index++] = position.x;
              vertexData[index++] = position.y;
              vertexData[index++] = position.z;
              vertexData[index++] = normal.x;
              vertexData[index++] = normal.y;
              vertexData[index++] = normal.z;
              vertexData[index++] = uv.x;
              vertexData[index++] = uv.y;
            }
          }
        };
        _proto2._buildBoundingBox = function _buildBoundingBox() {
          this._bbMin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
          this._bbMax.set(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);
          for (var j = 0; j < TERRAIN_BLOCK_VERTEX_COMPLEXITY; ++j) {
            for (var i = 0; i < TERRAIN_BLOCK_VERTEX_COMPLEXITY; ++i) {
              var x = this._index[0] * TERRAIN_BLOCK_TILE_COMPLEXITY + i;
              var y = this._index[1] * TERRAIN_BLOCK_TILE_COMPLEXITY + j;
              var position = this._terrain.getPosition(x, y);
              Vec3.min(this._bbMin, this._bbMin, position);
              Vec3.max(this._bbMax, this._bbMax, position);
            }
          }
        };
        _createClass(TerrainBlock, [{
          key: "valid",
          get: function get() {
            if (this._terrain === null) {
              return false;
            }
            var blocks = this._terrain.getBlocks();
            for (var i = 0; i < blocks.length; ++i) {
              if (blocks[i] === this) {
                return true;
              }
            }
            return false;
          }
        }, {
          key: "material",
          get: function get() {
            return this._renderable ? this._renderable._currentMaterial : null;
          }
        }, {
          key: "layers",
          get: function get() {
            return this._terrain.getBlockLayers(this._index[0], this._index[1]);
          }
        }, {
          key: "weightmap",
          get: function get() {
            return this._weightMap;
          }
        }, {
          key: "lightmap",
          get: function get() {
            return this._lightmapInfo ? this._lightmapInfo.texture : null;
          }
        }, {
          key: "lightmapUVParam",
          get: function get() {
            if (this._lightmapInfo != null) {
              return new Vec4(this._lightmapInfo.UOff, this._lightmapInfo.VOff, this._lightmapInfo.UScale, this._lightmapInfo.VScale);
            }
            return new Vec4(0, 0, 0, 0);
          }
        }, {
          key: "visible",
          get: function get() {
            if (this._renderable._model !== null) {
              return this._renderable._model.scene !== null;
            }
            return false;
          },
          set: function set(val) {
            if (this._renderable._model !== null) {
              if (val) {
                if (this._terrain.node != null && this._terrain.node.scene != null && this._terrain.node.scene.renderScene != null && this._renderable._model.scene == null) {
                  this._terrain.node.scene.renderScene.addModel(this._renderable._model);
                }
              } else if (this._renderable._model.scene !== null) {
                this._renderable._model.scene.removeModel(this._renderable._model);
              }
            }
          }
        }]);
        return TerrainBlock;
      }());
      var Terrain = exports('gl', (_dec4$f = ccclass$M('cc.Terrain'), _dec5$f = type$d(TerrainAsset), _dec6$9 = type$d(EffectAsset), _dec7$7 = type$d(TerrainBlockLightmapInfo), _dec8$5 = type$d(CCFloat), _dec9$4 = type$d(TerrainAsset), _dec10$2 = type$d(EffectAsset), _dec11$1 = type$d(TerrainInfo), _dec4$f(_class12 = disallowMultiple$1(_class12 = (_class13 = function (_Component) {
        _inheritsLoose(Terrain, _Component);
        function Terrain() {
          var _this2;
          _this2 = _Component.call(this) || this;
          _this2.__asset = _initializer15$2 && _initializer15$2();
          _this2._effectAsset = _initializer16$2 && _initializer16$2();
          _this2._lightmapInfos = _initializer17$1 && _initializer17$1();
          _this2._receiveShadow = _initializer18$1 && _initializer18$1();
          _this2._useNormalmap = _initializer19 && _initializer19();
          _this2._usePBR = _initializer20 && _initializer20();
          _this2._lodEnable = _initializer21 && _initializer21();
          _this2._lodBias = _initializer22 && _initializer22();
          _this2._buitinAsset = null;
          _this2._tileSize = 1;
          _this2._blockCount = [1, 1];
          _this2._weightMapSize = 128;
          _this2._lightMapSize = 128;
          _this2._heights = new Uint16Array();
          _this2._weights = new Uint8Array();
          _this2._normals = new Float32Array();
          _this2._layerList = [];
          _this2._layerBuffer = [];
          _this2._blocks = [];
          _this2._lod = null;
          _this2._sharedIndexBuffer = null;
          _this2._sharedLodIndexBuffer = null;
          for (var i = 0; i < TERRAIN_MAX_LAYER_COUNT; ++i) {
            _this2._layerList.push(null);
          }
          return _this2;
        }
        var _proto3 = Terrain.prototype;
        _proto3.build = function build(info) {
          this._tileSize = info.tileSize;
          this._blockCount[0] = info.blockCount[0];
          this._blockCount[1] = info.blockCount[1];
          this._weightMapSize = info.weightMapSize;
          this._lightMapSize = info.lightMapSize;
          return this._buildImp();
        };
        _proto3.rebuild = function rebuild(info) {
          for (var i = 0; i < this._blocks.length; ++i) {
            this._blocks[i].destroy();
          }
          this._blocks = [];
          this._resetLightmap(false);
          this._rebuildLayerBuffer(info);
          var heightsChanged = this._rebuildHeights(info);
          this._rebuildWeights(info);
          this._tileSize = info.tileSize;
          this._blockCount[0] = info.blockCount[0];
          this._blockCount[1] = info.blockCount[1];
          this._weightMapSize = info.weightMapSize;
          this._lightMapSize = info.lightMapSize;
          if (heightsChanged) {
            this._normals = new Float32Array(this.heights.length * 3);
            this._buildNormals();
          }
          for (var j = 0; j < this._blockCount[1]; ++j) {
            for (var _i3 = 0; _i3 < this._blockCount[0]; ++_i3) {
              this._blocks.push(new TerrainBlock(this, _i3, j));
            }
          }
          for (var _i4 = 0; _i4 < this._blocks.length; ++_i4) {
            this._blocks[_i4].build();
          }
        };
        _proto3.importHeightField = function importHeightField(hf, heightScale) {
          var index = 0;
          for (var j = 0; j < this.vertexCount[1]; ++j) {
            for (var i = 0; i < this.vertexCount[0]; ++i) {
              var u = i / this.tileCount[0];
              var v = j / this.tileCount[1];
              var h = hf.getAt(u * hf.w, v * hf.h) * heightScale;
              this._heights[index++] = h;
            }
          }
          this._buildNormals();
          for (var _i5 = 0; _i5 < this._blocks.length; ++_i5) {
            this._blocks[_i5]._updateHeight();
          }
        };
        _proto3.exportHeightField = function exportHeightField(hf, heightScale) {
          var index = 0;
          for (var j = 0; j < hf.h; ++j) {
            for (var i = 0; i < hf.w; ++i) {
              var u = i / (hf.w - 1);
              var v = j / (hf.h - 1);
              var x = u * this.size.width;
              var y = v * this.size.height;
              var h = this.getHeightAt(x, y);
              if (h != null) {
                hf.data[index++] = h * heightScale;
              }
            }
          }
        };
        _proto3.exportAsset = function exportAsset() {
          var asset = new TerrainAsset();
          asset.tileSize = this.tileSize;
          asset.blockCount = this.blockCount;
          asset.lightMapSize = this.lightMapSize;
          asset.weightMapSize = this.weightMapSize;
          asset.heights = this.heights;
          asset.weights = this.weights;
          asset.layerBuffer = new Array(this._blocks.length * 4);
          for (var i = 0; i < this._blocks.length; ++i) {
            asset.layerBuffer[i * 4 + 0] = this._blocks[i].layers[0];
            asset.layerBuffer[i * 4 + 1] = this._blocks[i].layers[1];
            asset.layerBuffer[i * 4 + 2] = this._blocks[i].layers[2];
            asset.layerBuffer[i * 4 + 3] = this._blocks[i].layers[3];
          }
          this.exportLayerListToAsset(asset);
          return asset;
        };
        _proto3.exportLayerListToAsset = function exportLayerListToAsset(asset) {
          asset.layerInfos.length = 0;
          for (var i = 0; i < this._layerList.length; ++i) {
            var temp = this._layerList[i];
            if (temp && temp.detailMap && isValid(temp.detailMap)) {
              var layer = new TerrainLayerInfo();
              layer.slot = i;
              layer.tileSize = temp.tileSize;
              layer.detailMap = temp.detailMap;
              layer.normalMap = temp.normalMap;
              layer.metallic = temp.metallic;
              layer.roughness = temp.roughness;
              asset.layerInfos.push(layer);
            }
          }
        };
        _proto3.getEffectAsset = function getEffectAsset() {
          if (this._effectAsset === null) {
            return legacyCC.EffectAsset.get(TERRAIN_EFFECT_UUID);
          }
          return this._effectAsset;
        };
        _proto3.onEnable = function onEnable() {
          if (this._blocks.length === 0) {
            this._buildImp();
          }
          for (var i = 0; i < this._blocks.length; ++i) {
            this._blocks[i].visible = true;
          }
          legacyCC.director.root.pipelineEvent.on(PipelineEventType.RENDER_CAMERA_BEGIN, this.onUpdateFromCamera, this);
        };
        _proto3.onDisable = function onDisable() {
          legacyCC.director.root.pipelineEvent.off(PipelineEventType.RENDER_CAMERA_BEGIN, this.onUpdateFromCamera, this);
          for (var i = 0; i < this._blocks.length; ++i) {
            this._blocks[i].visible = false;
          }
        };
        _proto3.onDestroy = function onDestroy() {
          for (var i = 0; i < this._blocks.length; ++i) {
            this._blocks[i].destroy();
          }
          this._blocks = [];
          for (var _i6 = 0; _i6 < this._layerList.length; ++_i6) {
            this._layerList[_i6] = null;
          }
          if (this._sharedIndexBuffer != null) {
            this._sharedIndexBuffer.destroy();
          }
          if (this._sharedLodIndexBuffer != null) {
            this._sharedLodIndexBuffer.destroy();
          }
        };
        _proto3.onRestore = function onRestore() {
          this.onEnable();
          this._buildImp(true);
        };
        _proto3.update = function update(deltaTime) {
          for (var i = 0; i < this._blocks.length; ++i) {
            this._blocks[i].update();
          }
        };
        _proto3.onUpdateFromCamera = function onUpdateFromCamera(cam) {
          if (!this.lodEnable || this._sharedLodIndexBuffer == null) {
            return;
          }
          if (cam.scene !== this._getRenderScene()) {
            return;
          }
          for (var i = 0; i < this._blocks.length; ++i) {
            this._blocks[i]._updateLevel(cam.position);
          }
          for (var _i7 = 0; _i7 < this._blocks.length; ++_i7) {
            this._blocks[_i7]._updateLod();
          }
        };
        _proto3.addLayer = function addLayer(layer) {
          for (var i = 0; i < this._layerList.length; ++i) {
            var _this$_layerList$i;
            if (this._layerList[i] === null || this._layerList[i] && ((_this$_layerList$i = this._layerList[i]) === null || _this$_layerList$i === void 0 ? void 0 : _this$_layerList$i.detailMap) === null) {
              this._layerList[i] = layer;
              if (this._asset) {
                this.exportLayerListToAsset(this._asset);
              }
              return i;
            }
          }
          return -1;
        };
        _proto3.setLayer = function setLayer(i, layer) {
          this._layerList[i] = layer;
          if (this._asset) {
            this.exportLayerListToAsset(this._asset);
          }
        };
        _proto3.removeLayer = function removeLayer(id) {
          this._layerList[id] = null;
          if (this._asset) {
            this.exportLayerListToAsset(this._asset);
          }
        };
        _proto3.getLayer = function getLayer(id) {
          if (id === -1) {
            return null;
          }
          return this._layerList[id];
        };
        _proto3.getPosition = function getPosition(i, j) {
          var x = i * this._tileSize;
          var z = j * this._tileSize;
          var y = this.getHeight(i, j);
          return new Vec3(x, y, z);
        };
        _proto3.getHeightField = function getHeightField() {
          return this._heights;
        };
        _proto3.setHeight = function setHeight(i, j, h) {
          h = clamp$1(h, TERRAIN_HEIGHT_FMIN, TERRAIN_HEIGHT_FMAX);
          this._heights[j * this.vertexCount[0] + i] = TERRAIN_HEIGHT_BASE + h / TERRAIN_HEIGHT_FACTORY;
        };
        _proto3.getHeight = function getHeight(i, j) {
          return (this._heights[j * this.vertexCount[0] + i] - TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY;
        };
        _proto3.getHeightClamp = function getHeightClamp(i, j) {
          i = clamp$1(i, 0, this.vertexCount[0] - 1);
          j = clamp$1(j, 0, this.vertexCount[1] - 1);
          return this.getHeight(i, j);
        };
        _proto3.getHeightAt = function getHeightAt(x, y) {
          var fx = x / this.tileSize;
          var fy = y / this.tileSize;
          var ix0 = Math.floor(fx);
          var iz0 = Math.floor(fy);
          var ix1 = ix0 + 1;
          var iz1 = iz0 + 1;
          var dx = fx - ix0;
          var dz = fy - iz0;
          if (ix0 < 0 || ix0 > this.vertexCount[0] - 1 || iz0 < 0 || iz0 > this.vertexCount[1] - 1) {
            return null;
          }
          ix0 = clamp$1(ix0, 0, this.vertexCount[0] - 1);
          iz0 = clamp$1(iz0, 0, this.vertexCount[1] - 1);
          ix1 = clamp$1(ix1, 0, this.vertexCount[0] - 1);
          iz1 = clamp$1(iz1, 0, this.vertexCount[1] - 1);
          var a = this.getHeight(ix0, iz0);
          var b = this.getHeight(ix1, iz0);
          var c = this.getHeight(ix0, iz1);
          var d = this.getHeight(ix1, iz1);
          var m = (b + c) * 0.5;
          if (dx + dz <= 1.0) {
            d = m + (m - a);
          } else {
            a = m + (m - d);
          }
          var h1 = a * (1.0 - dx) + b * dx;
          var h2 = c * (1.0 - dx) + d * dx;
          var h = h1 * (1.0 - dz) + h2 * dz;
          return h;
        };
        _proto3._setNormal = function _setNormal(i, j, n) {
          var index = j * this.vertexCount[0] + i;
          this._normals[index * 3 + 0] = n.x;
          this._normals[index * 3 + 1] = n.y;
          this._normals[index * 3 + 2] = n.z;
        };
        _proto3.getNormal = function getNormal(i, j) {
          var index = j * this.vertexCount[0] + i;
          var n = new Vec3();
          n.x = this._normals[index * 3 + 0];
          n.y = this._normals[index * 3 + 1];
          n.z = this._normals[index * 3 + 2];
          return n;
        };
        _proto3.getNormalAt = function getNormalAt(x, y) {
          var fx = x / this.tileSize;
          var fy = y / this.tileSize;
          var ix0 = Math.floor(fx);
          var iz0 = Math.floor(fy);
          var ix1 = ix0 + 1;
          var iz1 = iz0 + 1;
          var dx = fx - ix0;
          var dz = fy - iz0;
          if (ix0 < 0 || ix0 > this.vertexCount[0] - 1 || iz0 < 0 || iz0 > this.vertexCount[1] - 1) {
            return null;
          }
          ix0 = clamp$1(ix0, 0, this.vertexCount[0] - 1);
          iz0 = clamp$1(iz0, 0, this.vertexCount[1] - 1);
          ix1 = clamp$1(ix1, 0, this.vertexCount[0] - 1);
          iz1 = clamp$1(iz1, 0, this.vertexCount[1] - 1);
          var a = this.getNormal(ix0, iz0);
          var b = this.getNormal(ix1, iz0);
          var c = this.getNormal(ix0, iz1);
          var d = this.getNormal(ix1, iz1);
          var m = new Vec3();
          Vec3.add(m, b, c).multiplyScalar(0.5);
          if (dx + dz <= 1.0) {
            d.set(m);
            d.subtract(a);
            d.add(m);
          } else {
            a.set(m);
            a.subtract(d);
            a.add(m);
          }
          var n1 = new Vec3();
          var n2 = new Vec3();
          var n = new Vec3();
          Vec3.lerp(n1, a, b, dx);
          Vec3.lerp(n2, c, d, dx);
          Vec3.lerp(n, n1, n2, dz);
          return n;
        };
        _proto3.setWeight = function setWeight(i, j, w) {
          var index = j * this._weightMapSize * this._blockCount[0] + i;
          this._weights[index * 4 + 0] = w.x * 255;
          this._weights[index * 4 + 1] = w.y * 255;
          this._weights[index * 4 + 2] = w.z * 255;
          this._weights[index * 4 + 3] = w.w * 255;
        };
        _proto3.getWeight = function getWeight(i, j) {
          var index = j * this._weightMapSize * this._blockCount[0] + i;
          var w = new Vec4();
          w.x = this._weights[index * 4 + 0] / 255.0;
          w.y = this._weights[index * 4 + 1] / 255.0;
          w.z = this._weights[index * 4 + 2] / 255.0;
          w.w = this._weights[index * 4 + 3] / 255.0;
          return w;
        };
        _proto3.getWeightAt = function getWeightAt(x, y) {
          var uWeightComplexity = this.weightMapSize * this.blockCount[0];
          var vWeightComplexity = this.weightMapSize * this.blockCount[1];
          if (uWeightComplexity === 0 || vWeightComplexity === 0) {
            return null;
          }
          var fx = x / uWeightComplexity;
          var fy = y / vWeightComplexity;
          var ix0 = Math.floor(fx);
          var iz0 = Math.floor(fy);
          var ix1 = ix0 + 1;
          var iz1 = iz0 + 1;
          var dx = fx - ix0;
          var dz = fy - iz0;
          if (ix0 < 0 || ix0 > uWeightComplexity - 1 || iz0 < 0 || iz0 > vWeightComplexity - 1) {
            return null;
          }
          ix0 = clamp$1(ix0, 0, uWeightComplexity - 1);
          iz0 = clamp$1(iz0, 0, vWeightComplexity - 1);
          ix1 = clamp$1(ix1, 0, uWeightComplexity - 1);
          iz1 = clamp$1(iz1, 0, vWeightComplexity - 1);
          var a = this.getWeight(ix0, iz0);
          var b = this.getWeight(ix1, iz0);
          var c = this.getWeight(ix0, iz1);
          var d = this.getWeight(ix1, iz1);
          var m = new Vec4();
          Vec4.add(m, b, c).multiplyScalar(0.5);
          if (dx + dz <= 1.0) {
            d = new Vec4();
            Vec4.subtract(d, m, a).add(m);
          } else {
            a = new Vec4();
            Vec4.subtract(a, m, d).add(m);
          }
          var n1 = new Vec4();
          var n2 = new Vec4();
          var n = new Vec4();
          Vec4.lerp(n1, a, b, dx);
          Vec4.lerp(n2, c, d, dx);
          Vec4.lerp(n, n1, n2, dz);
          return n;
        };
        _proto3.getMaxWeightLayerAt = function getMaxWeightLayerAt(x, y) {
          var uWeightComplexity = this.weightMapSize * this.blockCount[0];
          var vWeightComplexity = this.weightMapSize * this.blockCount[1];
          if (uWeightComplexity === 0 || vWeightComplexity === 0) {
            return null;
          }
          var fx = x / uWeightComplexity;
          var fy = y / vWeightComplexity;
          var ix0 = Math.floor(fx);
          var iz0 = Math.floor(fy);
          if (ix0 < 0 || ix0 > uWeightComplexity - 1 || iz0 < 0 || iz0 > vWeightComplexity - 1) {
            return null;
          }
          var w = this.getWeight(ix0, iz0);
          var bx = Math.floor(x / this.weightMapSize);
          var by = Math.floor(y / this.weightMapSize);
          var block = this.getBlock(bx, by);
          var i = 0;
          if (w.y > w[i] && block.getLayer(1) !== -1) {
            i = 1;
          }
          if (w.y > w[i] && block.getLayer(2) !== -1) {
            i = 2;
          }
          if (w.z > w[i] && block.getLayer(3) !== -1) {
            i = 3;
          }
          i = block.getLayer(i);
          return this.getLayer(i);
        };
        _proto3.getBlockLayers = function getBlockLayers(i, j) {
          var layerIndex = (j * this._blockCount[0] + i) * TERRAIN_MAX_BLEND_LAYERS;
          return [this._layerBuffer[layerIndex], this._layerBuffer[layerIndex + 1], this._layerBuffer[layerIndex + 2], this._layerBuffer[layerIndex + 3]];
        };
        _proto3.getBlockLayer = function getBlockLayer(i, j, index) {
          var layerIndex = (j * this._blockCount[0] + i) * TERRAIN_MAX_BLEND_LAYERS;
          return this._layerBuffer[layerIndex + index];
        };
        _proto3.setBlockLayer = function setBlockLayer(i, j, index, layerId) {
          var layerIndex = (j * this._blockCount[0] + i) * TERRAIN_MAX_BLEND_LAYERS;
          this._layerBuffer[layerIndex + index] = layerId;
        };
        _proto3.getBlock = function getBlock(i, j) {
          return this._blocks[j * this._blockCount[0] + i];
        };
        _proto3.getBlocks = function getBlocks() {
          return this._blocks;
        };
        _proto3.rayCheck = function rayCheck(start, dir, step, worldSpace) {
          if (worldSpace === void 0) {
            worldSpace = true;
          }
          var MAX_COUNT = 2000;
          var trace = start;
          if (worldSpace) {
            Vec3.subtract(trace, start, this.node.getWorldPosition());
          }
          var delta = new Vec3();
          delta.set(dir);
          delta.multiplyScalar(step);
          var position = null;
          if (dir.equals(new Vec3(0, 1, 0))) {
            var y = this.getHeightAt(trace.x, trace.z);
            if (y != null && trace.y <= y) {
              position = new Vec3(trace.x, y, trace.z);
            }
          } else if (dir.equals(new Vec3(0, -1, 0))) {
            var _y6 = this.getHeightAt(trace.x, trace.z);
            if (_y6 != null && trace.y >= _y6) {
              position = new Vec3(trace.x, _y6, trace.z);
            }
          } else {
            var i = 0;
            while (i++ < MAX_COUNT) {
              var _y7 = this.getHeightAt(trace.x, trace.z);
              if (_y7 != null && trace.y <= _y7) {
                break;
              }
              trace.add(dir);
            }
            while (i++ < MAX_COUNT) {
              var _y8 = this.getHeightAt(trace.x, trace.z);
              if (_y8 != null && trace.y <= _y8) {
                position = new Vec3(trace.x, _y8, trace.z);
                break;
              }
              trace.add(delta);
            }
          }
          return position;
        };
        _proto3._createSharedIndexBuffer = function _createSharedIndexBuffer() {
          var gfxDevice = deviceManager.gfxDevice;
          if (this._lod !== null) {
            var gfxBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, Uint16Array.BYTES_PER_ELEMENT * this._lod._indexBuffer.length, Uint16Array.BYTES_PER_ELEMENT));
            gfxBuffer.update(this._lod._indexBuffer);
            return gfxBuffer;
          } else {
            var indexData = new Uint16Array(TERRAIN_BLOCK_TILE_COMPLEXITY * TERRAIN_BLOCK_TILE_COMPLEXITY * 6);
            var index = 0;
            for (var j = 0; j < TERRAIN_BLOCK_TILE_COMPLEXITY; ++j) {
              for (var i = 0; i < TERRAIN_BLOCK_TILE_COMPLEXITY; ++i) {
                var a = j * TERRAIN_BLOCK_VERTEX_COMPLEXITY + i;
                var b = j * TERRAIN_BLOCK_VERTEX_COMPLEXITY + i + 1;
                var c = (j + 1) * TERRAIN_BLOCK_VERTEX_COMPLEXITY + i;
                var d = (j + 1) * TERRAIN_BLOCK_VERTEX_COMPLEXITY + i + 1;
                indexData[index++] = a;
                indexData[index++] = c;
                indexData[index++] = b;
                indexData[index++] = b;
                indexData[index++] = c;
                indexData[index++] = d;
              }
            }
            var _gfxBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, Uint16Array.BYTES_PER_ELEMENT * indexData.length, Uint16Array.BYTES_PER_ELEMENT));
            _gfxBuffer.update(indexData);
            return _gfxBuffer;
          }
        };
        _proto3._getSharedIndexBuffer = function _getSharedIndexBuffer() {
          if (this._sharedLodIndexBuffer !== null) {
            return this._sharedLodIndexBuffer;
          }
          if (this._sharedIndexBuffer !== null) {
            return this._sharedIndexBuffer;
          }
          if (this.lodEnable && this._lod === null) {
            this._lod = new TerrainLod();
          }
          if (this._lod !== null) {
            this._sharedLodIndexBuffer = this._createSharedIndexBuffer();
            return this._sharedLodIndexBuffer;
          } else {
            this._sharedIndexBuffer = this._createSharedIndexBuffer();
            return this._sharedIndexBuffer;
          }
        };
        _proto3._getIndexData = function _getIndexData(key) {
          if (this._sharedLodIndexBuffer !== null && this._lod !== null) {
            return this._lod.getIndexData(key);
          }
          return null;
        };
        _proto3._resetLightmap = function _resetLightmap(enable) {
          this._lightmapInfos.length = 0;
          if (enable) {
            for (var i = 0; i < this._blockCount[0] * this._blockCount[1]; ++i) {
              this._lightmapInfos.push(new TerrainBlockLightmapInfo());
            }
          }
        };
        _proto3._updateLightmap = function _updateLightmap(blockId, tex, uOff, vOff, uScale, vScale) {
          if (tex) {
            if (this._lightmapInfos.length === 0) {
              for (var i = 0; i < this._blockCount[0] * this._blockCount[1]; ++i) {
                this._lightmapInfos.push(new TerrainBlockLightmapInfo());
              }
            }
          } else if (this._lightmapInfos.length === 0) {
            return;
          }
          this._lightmapInfos[blockId].texture = tex;
          this._lightmapInfos[blockId].UOff = uOff;
          this._lightmapInfos[blockId].VOff = vOff;
          this._lightmapInfos[blockId].UScale = uScale;
          this._lightmapInfos[blockId].VScale = vScale;
          this._blocks[blockId]._updateLightmap(this._lightmapInfos[blockId]);
        };
        _proto3._getLightmapInfo = function _getLightmapInfo(i, j) {
          var index = j * this._blockCount[0] + i;
          return index < this._lightmapInfos.length ? this._lightmapInfos[index] : null;
        };
        _proto3._calcNormal = function _calcNormal(x, z) {
          var flip = 1;
          var here = this.getPosition(x, z);
          var right;
          var up;
          if (x < this.vertexCount[0] - 1) {
            right = this.getPosition(x + 1, z);
          } else {
            flip *= -1;
            right = this.getPosition(x - 1, z);
          }
          if (z < this.vertexCount[1] - 1) {
            up = this.getPosition(x, z + 1);
          } else {
            flip *= -1;
            up = this.getPosition(x, z - 1);
          }
          right.subtract(here);
          up.subtract(here);
          var normal = new Vec3();
          normal.set(up);
          normal.cross(right);
          normal.multiplyScalar(flip);
          normal.normalize();
          return normal;
        };
        _proto3._buildNormals = function _buildNormals() {
          var index = 0;
          for (var y = 0; y < this.vertexCount[1]; ++y) {
            for (var x = 0; x < this.vertexCount[0]; ++x) {
              var n = this._calcNormal(x, y);
              this._normals[index * 3 + 0] = n.x;
              this._normals[index * 3 + 1] = n.y;
              this._normals[index * 3 + 2] = n.z;
              index += 1;
            }
          }
        };
        _proto3._buildImp = function _buildImp(restore) {
          var _this3 = this;
          if (restore === void 0) {
            restore = false;
          }
          if (this.valid) {
            return;
          }
          var terrainAsset = this.__asset;
          if (this._buitinAsset !== terrainAsset) {
            this._buitinAsset = terrainAsset;
          }
          if (!restore && terrainAsset !== null) {
            this._tileSize = terrainAsset.tileSize;
            this._blockCount = terrainAsset.blockCount;
            this._weightMapSize = terrainAsset.weightMapSize;
            this._lightMapSize = terrainAsset.lightMapSize;
            this._heights = terrainAsset.heights;
            this._normals = terrainAsset.normals;
            this._weights = terrainAsset.weights;
            this._layerBuffer = terrainAsset.layerBuffer;
            for (var i = 0; i < this._layerList.length; ++i) {
              this._layerList[i] = null;
            }
            if (terrainAsset.version < TERRAIN_DATA_VERSION5) {
              var _loop = function _loop() {
                var layer = new TerrainLayer();
                var layerInfo = terrainAsset.layerBinaryInfos[_i8];
                layer.tileSize = layerInfo.tileSize;
                legacyCC.assetManager.loadAny(layerInfo.detailMapId, function (err, asset) {
                  layer.detailMap = asset;
                });
                if (layerInfo.normalMapId !== '') {
                  legacyCC.assetManager.loadAny(layerInfo.normalMapId, function (err, asset) {
                    layer.normalMap = asset;
                  });
                }
                layer.roughness = layerInfo.roughness;
                layer.metallic = layerInfo.metallic;
                _this3._layerList[layerInfo.slot] = layer;
              };
              for (var _i8 = 0; _i8 < terrainAsset.layerBinaryInfos.length; ++_i8) {
                _loop();
              }
            } else {
              for (var _i9 = 0; _i9 < terrainAsset.layerInfos.length; ++_i9) {
                var layer = new TerrainLayer();
                var layerInfo = terrainAsset.layerInfos[_i9];
                layer.tileSize = layerInfo.tileSize;
                layer.detailMap = layerInfo.detailMap;
                layer.normalMap = layerInfo.normalMap;
                layer.roughness = layerInfo.roughness;
                layer.metallic = layerInfo.metallic;
                this._layerList[layerInfo.slot] = layer;
              }
            }
          }
          if (this._blockCount[0] === 0 || this._blockCount[1] === 0) {
            return;
          }
          var vertexCount = this.vertexCount[0] * this.vertexCount[1];
          if (this._heights === null || this._heights.length !== vertexCount) {
            this._heights = new Uint16Array(vertexCount);
            this._normals = new Float32Array(vertexCount * 3);
            for (var _i10 = 0; _i10 < vertexCount; ++_i10) {
              this._heights[_i10] = TERRAIN_HEIGHT_BASE;
              this._normals[_i10 * 3 + 0] = 0;
              this._normals[_i10 * 3 + 1] = 1;
              this._normals[_i10 * 3 + 2] = 0;
            }
          }
          if (this._normals === null || this._normals.length !== vertexCount * 3) {
            this._normals = new Float32Array(vertexCount * 3);
            this._buildNormals();
          }
          var layerBufferSize = this.blockCount[0] * this.blockCount[1] * TERRAIN_MAX_BLEND_LAYERS;
          if (this._layerBuffer === null || this._layerBuffer.length !== layerBufferSize) {
            this._layerBuffer = new Array(layerBufferSize);
            for (var _i11 = 0; _i11 < layerBufferSize; ++_i11) {
              this._layerBuffer[_i11] = -1;
            }
          }
          var weightMapComplexityU = this._weightMapSize * this._blockCount[0];
          var weightMapComplexityV = this._weightMapSize * this._blockCount[1];
          if (this._weights.length !== weightMapComplexityU * weightMapComplexityV * 4) {
            this._weights = new Uint8Array(weightMapComplexityU * weightMapComplexityV * 4);
            for (var _i12 = 0; _i12 < weightMapComplexityU * weightMapComplexityV; ++_i12) {
              this._weights[_i12 * 4 + 0] = 255;
              this._weights[_i12 * 4 + 1] = 0;
              this._weights[_i12 * 4 + 2] = 0;
              this._weights[_i12 * 4 + 3] = 0;
            }
          }
          for (var j = 0; j < this._blockCount[1]; ++j) {
            for (var _i13 = 0; _i13 < this._blockCount[0]; ++_i13) {
              this._blocks.push(new TerrainBlock(this, _i13, j));
            }
          }
          for (var _i14 = 0; _i14 < this._blocks.length; ++_i14) {
            this._blocks[_i14].build();
          }
        };
        _proto3._rebuildHeights = function _rebuildHeights(info) {
          if (this.vertexCount[0] === info.vertexCount[0] && this.vertexCount[1] === info.vertexCount[1]) {
            return false;
          }
          var heights = new Uint16Array(info.vertexCount[0] * info.vertexCount[1]);
          for (var i = 0; i < heights.length; ++i) {
            heights[i] = TERRAIN_HEIGHT_BASE;
          }
          var w = Math.min(this.vertexCount[0], info.vertexCount[0]);
          var h = Math.min(this.vertexCount[1], info.vertexCount[1]);
          for (var j = 0; j < h; ++j) {
            for (var _i15 = 0; _i15 < w; ++_i15) {
              var index0 = j * info.vertexCount[0] + _i15;
              var index1 = j * this.vertexCount[0] + _i15;
              heights[index0] = this._heights[index1];
            }
          }
          this._heights = heights;
          return true;
        };
        _proto3._rebuildLayerBuffer = function _rebuildLayerBuffer(info) {
          if (this.blockCount[0] === info.blockCount[0] && this.blockCount[1] === info.blockCount[1]) {
            return false;
          }
          var layerBuffer = [];
          layerBuffer.length = info.blockCount[0] * info.blockCount[1] * TERRAIN_MAX_BLEND_LAYERS;
          for (var i = 0; i < layerBuffer.length; ++i) {
            layerBuffer[i] = -1;
          }
          var w = Math.min(this.blockCount[0], info.blockCount[0]);
          var h = Math.min(this.blockCount[1], info.blockCount[1]);
          for (var j = 0; j < h; ++j) {
            for (var _i16 = 0; _i16 < w; ++_i16) {
              var index0 = j * info.blockCount[0] + _i16;
              var index1 = j * this.blockCount[0] + _i16;
              for (var l = 0; l < TERRAIN_MAX_BLEND_LAYERS; ++l) {
                layerBuffer[index0 * TERRAIN_MAX_BLEND_LAYERS + l] = this._layerBuffer[index1 * TERRAIN_MAX_BLEND_LAYERS + l];
              }
            }
          }
          this._layerBuffer = layerBuffer;
          return true;
        };
        _proto3._rebuildWeights = function _rebuildWeights(info) {
          var _this4 = this;
          var oldWeightMapSize = this._weightMapSize;
          var oldWeightMapComplexityU = this._weightMapSize * this._blockCount[0];
          var oldWeightMapComplexityV = this._weightMapSize * this._blockCount[1];
          var weightMapComplexityU = info.weightMapSize * info.blockCount[0];
          var weightMapComplexityV = info.weightMapSize * info.blockCount[1];
          if (weightMapComplexityU === oldWeightMapComplexityU && weightMapComplexityV === oldWeightMapComplexityV) {
            return false;
          }
          var weights = new Uint8Array(weightMapComplexityU * weightMapComplexityV * 4);
          for (var i = 0; i < weightMapComplexityU * weightMapComplexityV; ++i) {
            weights[i * 4 + 0] = 255;
            weights[i * 4 + 1] = 0;
            weights[i * 4 + 2] = 0;
            weights[i * 4 + 3] = 0;
          }
          var w = Math.min(info.blockCount[0], this._blockCount[0]);
          var h = Math.min(info.blockCount[1], this._blockCount[1]);
          var getOldWeight = function getOldWeight(_i, _j, _weights) {
            var index = _j * oldWeightMapComplexityU + _i;
            var weight = new Vec4();
            weight.x = _weights[index * 4 + 0] / 255.0;
            weight.y = _weights[index * 4 + 1] / 255.0;
            weight.z = _weights[index * 4 + 2] / 255.0;
            weight.w = _weights[index * 4 + 3] / 255.0;
            return weight;
          };
          var sampleOldWeight = function sampleOldWeight(_x, _y, _xOff, _yOff, _weights) {
            var ix0 = Math.floor(_x);
            var iz0 = Math.floor(_y);
            var ix1 = Math.min(ix0 + 1, oldWeightMapSize - 1);
            var iz1 = Math.min(iz0 + 1, oldWeightMapSize - 1);
            var dx = _x - ix0;
            var dz = _y - iz0;
            var a = getOldWeight(ix0 + _xOff, iz0 + _yOff, _this4._weights);
            var b = getOldWeight(ix1 + _xOff, iz0 + _yOff, _this4._weights);
            var c = getOldWeight(ix0 + _xOff, iz1 + _yOff, _this4._weights);
            var d = getOldWeight(ix1 + _xOff, iz1 + _yOff, _this4._weights);
            var m = new Vec4();
            Vec4.add(m, b, c).multiplyScalar(0.5);
            if (dx + dz <= 1.0) {
              d.set(m);
              d.subtract(a);
              d.add(m);
            } else {
              a.set(m);
              a.subtract(d);
              a.add(m);
            }
            var n1 = new Vec4();
            var n2 = new Vec4();
            var n = new Vec4();
            Vec4.lerp(n1, a, b, dx);
            Vec4.lerp(n2, c, d, dx);
            Vec4.lerp(n, n1, n2, dz);
            return n;
          };
          for (var j = 0; j < h; ++j) {
            for (var _i17 = 0; _i17 < w; ++_i17) {
              var uOff = _i17 * oldWeightMapSize;
              var vOff = j * oldWeightMapSize;
              for (var v = 0; v < info.weightMapSize; ++v) {
                for (var u = 0; u < info.weightMapSize; ++u) {
                  var _w = void 0;
                  if (info.weightMapSize === oldWeightMapSize) {
                    _w = getOldWeight(u + uOff, v + vOff, this._weights);
                  } else {
                    var x = u / (info.weightMapSize - 1) * (oldWeightMapSize - 1);
                    var y = v / (info.weightMapSize - 1) * (oldWeightMapSize - 1);
                    _w = sampleOldWeight(x, y, uOff, vOff, this._weights);
                  }
                  var du = _i17 * info.weightMapSize + u;
                  var dv = j * info.weightMapSize + v;
                  var index = dv * weightMapComplexityU + du;
                  weights[index * 4 + 0] = _w.x * 255;
                  weights[index * 4 + 1] = _w.y * 255;
                  weights[index * 4 + 2] = _w.z * 255;
                  weights[index * 4 + 3] = _w.w * 255;
                }
              }
            }
          }
          this._weights = weights;
          return true;
        };
        _createClass(Terrain, [{
          key: "_asset",
          get: function get() {
            return this.__asset;
          },
          set: function set(value) {
            this.__asset = value;
            if (this._buitinAsset !== this.__asset) {
              this._buitinAsset = this.__asset;
              for (var i = 0; i < this._blocks.length; ++i) {
                this._blocks[i].destroy();
              }
              this._blocks = [];
              if (this.__asset === null) {
                this._effectAsset = null;
                this._lightmapInfos = [];
                this._receiveShadow = false;
                this._useNormalmap = false;
                this._usePBR = false;
                this._tileSize = 1;
                this._blockCount = [1, 1];
                this._weightMapSize = 128;
                this._lightMapSize = 128;
                this._heights = new Uint16Array();
                this._weights = new Uint8Array();
                this._normals = new Float32Array();
                this._layerBuffer = [];
                this._blocks = [];
                this._layerList = [];
                for (var _i18 = 0; _i18 < TERRAIN_MAX_LAYER_COUNT; ++_i18) {
                  this._layerList.push(null);
                }
              }
              if (deviceManager.gfxDevice) {
                this._buildImp();
              }
            }
          }
        }, {
          key: "effectAsset",
          get: function get() {
            return this._effectAsset;
          },
          set: function set(value) {
            if (this._effectAsset === value) {
              return;
            }
            this._effectAsset = value;
            for (var i = 0; i < this._blocks.length; ++i) {
              this._blocks[i]._invalidMaterial();
            }
          }
        }, {
          key: "receiveShadow",
          get: function get() {
            return this._receiveShadow;
          },
          set: function set(val) {
            this._receiveShadow = val;
            for (var i = 0; i < this._blocks.length; i++) {
              this._blocks[i]._invalidMaterial();
            }
          }
        }, {
          key: "useNormalMap",
          get: function get() {
            return this._useNormalmap;
          },
          set: function set(val) {
            this._useNormalmap = val;
            for (var i = 0; i < this._blocks.length; i++) {
              this._blocks[i]._invalidMaterial();
            }
          }
        }, {
          key: "usePBR",
          get: function get() {
            return this._usePBR;
          },
          set: function set(val) {
            this._usePBR = val;
            for (var i = 0; i < this._blocks.length; i++) {
              this._blocks[i]._invalidMaterial();
            }
          }
        }, {
          key: "lodEnable",
          get: function get() {
            return this._lodEnable;
          },
          set: function set(val) {
            this._lodEnable = val;
            if (this._lodEnable && this._lod === null) {
              this._lod = new TerrainLod();
              if (this._sharedLodIndexBuffer === null) {
                this._sharedLodIndexBuffer = this._createSharedIndexBuffer();
              }
              for (var i = 0; i < this._blocks.length; ++i) {
                this._blocks[i].destroy();
              }
              this._blocks = [];
              for (var j = 0; j < this._blockCount[1]; ++j) {
                for (var _i19 = 0; _i19 < this._blockCount[0]; ++_i19) {
                  this._blocks.push(new TerrainBlock(this, _i19, j));
                }
              }
              for (var _i20 = 0; _i20 < this._blocks.length; ++_i20) {
                this._blocks[_i20].build();
              }
            }
            if (!this._lodEnable) {
              for (var _i21 = 0; _i21 < this._blocks.length; _i21++) {
                this._blocks[_i21]._resetLod();
              }
            }
          }
        }, {
          key: "LodBias",
          get: function get() {
            return this._lodBias;
          },
          set: function set(val) {
            this._lodBias = val;
          }
        }, {
          key: "size",
          get: function get() {
            var sz = new Size$1(0, 0);
            sz.width = this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY * this.tileSize;
            sz.height = this.blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY * this.tileSize;
            return sz;
          }
        }, {
          key: "tileSize",
          get: function get() {
            return this._tileSize;
          }
        }, {
          key: "tileCount",
          get: function get() {
            return [this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY, this.blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY];
          }
        }, {
          key: "vertexCount",
          get: function get() {
            var _vertexCount = this.tileCount;
            _vertexCount[0] += 1;
            _vertexCount[1] += 1;
            return _vertexCount;
          }
        }, {
          key: "blockCount",
          get: function get() {
            return this._blockCount;
          }
        }, {
          key: "lightMapSize",
          get: function get() {
            return this._lightMapSize;
          }
        }, {
          key: "weightMapSize",
          get: function get() {
            return this._weightMapSize;
          }
        }, {
          key: "heights",
          get: function get() {
            return this._heights;
          }
        }, {
          key: "weights",
          get: function get() {
            return this._weights;
          }
        }, {
          key: "valid",
          get: function get() {
            return this._blocks.length > 0;
          }
        }, {
          key: "info",
          get: function get() {
            var ti = new TerrainInfo();
            ti.tileSize = this.tileSize;
            ti.blockCount[0] = this.blockCount[0];
            ti.blockCount[1] = this.blockCount[1];
            ti.weightMapSize = this.weightMapSize;
            ti.lightMapSize = this.lightMapSize;
            return ti;
          }
        }]);
        return Terrain;
      }(Component), (_initializer15$2 = applyDecoratedInitializer(_class13.prototype, "__asset", [_dec5$f, serializable$p], function () {
        return null;
      }), _initializer16$2 = applyDecoratedInitializer(_class13.prototype, "_effectAsset", [_dec6$9, serializable$p], function () {
        return null;
      }), _initializer17$1 = applyDecoratedInitializer(_class13.prototype, "_lightmapInfos", [_dec7$7, serializable$p], function () {
        return [];
      }), _initializer18$1 = applyDecoratedInitializer(_class13.prototype, "_receiveShadow", [serializable$p], function () {
        return false;
      }), _initializer19 = applyDecoratedInitializer(_class13.prototype, "_useNormalmap", [serializable$p], function () {
        return false;
      }), _initializer20 = applyDecoratedInitializer(_class13.prototype, "_usePBR", [serializable$p], function () {
        return false;
      }), _initializer21 = applyDecoratedInitializer(_class13.prototype, "_lodEnable", [serializable$p], function () {
        return false;
      }), _initializer22 = applyDecoratedInitializer(_class13.prototype, "_lodBias", [_dec8$5, serializable$p], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class13.prototype, "_asset", [_dec9$4], Object.getOwnPropertyDescriptor(_class13.prototype, "_asset"), _class13.prototype), _applyDecoratedDescriptor(_class13.prototype, "effectAsset", [_dec10$2], Object.getOwnPropertyDescriptor(_class13.prototype, "effectAsset"), _class13.prototype), _applyDecoratedDescriptor(_class13.prototype, "info", [_dec11$1], Object.getOwnPropertyDescriptor(_class13.prototype, "info"), _class13.prototype)), _class13)) || _class12) || _class12));

      var Orientation;
      (function (Orientation) {
        Orientation[Orientation["ORTHO"] = 0] = "ORTHO";
        Orientation[Orientation["HEX"] = 1] = "HEX";
        Orientation[Orientation["ISO"] = 2] = "ISO";
      })(Orientation || (Orientation = {}));
      ccenum(Orientation);
      var Property;
      (function (Property) {
        Property[Property["NONE"] = 0] = "NONE";
        Property[Property["MAP"] = 1] = "MAP";
        Property[Property["LAYER"] = 2] = "LAYER";
        Property[Property["OBJECTGROUP"] = 3] = "OBJECTGROUP";
        Property[Property["OBJECT"] = 4] = "OBJECT";
        Property[Property["TILE"] = 5] = "TILE";
      })(Property || (Property = {}));
      ccenum(Property);
      var TileFlag;
      (function (TileFlag) {
        TileFlag[TileFlag["HORIZONTAL"] = 2147483648] = "HORIZONTAL";
        TileFlag[TileFlag["VERTICAL"] = 1073741824] = "VERTICAL";
        TileFlag[TileFlag["DIAGONAL"] = 536870912] = "DIAGONAL";
        TileFlag[TileFlag["FLIPPED_ALL"] = 4026531840] = "FLIPPED_ALL";
        TileFlag[TileFlag["FLIPPED_MASK"] = 268435455] = "FLIPPED_MASK";
      })(TileFlag || (TileFlag = {}));
      ccenum(TileFlag);
      var StaggerAxis;
      (function (StaggerAxis) {
        StaggerAxis[StaggerAxis["STAGGERAXIS_X"] = 0] = "STAGGERAXIS_X";
        StaggerAxis[StaggerAxis["STAGGERAXIS_Y"] = 1] = "STAGGERAXIS_Y";
      })(StaggerAxis || (StaggerAxis = {}));
      ccenum(StaggerAxis);
      var StaggerIndex;
      (function (StaggerIndex) {
        StaggerIndex[StaggerIndex["STAGGERINDEX_ODD"] = 0] = "STAGGERINDEX_ODD";
        StaggerIndex[StaggerIndex["STAGGERINDEX_EVEN"] = 1] = "STAGGERINDEX_EVEN";
      })(StaggerIndex || (StaggerIndex = {}));
      ccenum(StaggerIndex);
      var RenderOrder;
      (function (RenderOrder) {
        RenderOrder[RenderOrder["RightDown"] = 0] = "RightDown";
        RenderOrder[RenderOrder["RightUp"] = 1] = "RightUp";
        RenderOrder[RenderOrder["LeftDown"] = 2] = "LeftDown";
        RenderOrder[RenderOrder["LeftUp"] = 3] = "LeftUp";
      })(RenderOrder || (RenderOrder = {}));
      ccenum(RenderOrder);
      var TMXObjectType;
      (function (TMXObjectType) {
        TMXObjectType[TMXObjectType["RECT"] = 0] = "RECT";
        TMXObjectType[TMXObjectType["ELLIPSE"] = 1] = "ELLIPSE";
        TMXObjectType[TMXObjectType["POLYGON"] = 2] = "POLYGON";
        TMXObjectType[TMXObjectType["POLYLINE"] = 3] = "POLYLINE";
        TMXObjectType[TMXObjectType["IMAGE"] = 4] = "IMAGE";
        TMXObjectType[TMXObjectType["TEXT"] = 5] = "TEXT";
      })(TMXObjectType || (TMXObjectType = {}));
      ccenum(TMXObjectType);
      var TMXTilesetInfo = function () {
        function TMXTilesetInfo() {
          this.name = '';
          this.firstGid = 0;
          this.spacing = 0;
          this.margin = 0;
          this.sourceImage = void 0;
          this.imageName = null;
          this.imageOffset = null;
          this.imageSize = new Size$1(0, 0);
          this.tileOffset = new Vec2(0, 0);
          this._tileSize = new Size$1(0, 0);
          this.collection = false;
        }
        var _proto = TMXTilesetInfo.prototype;
        _proto.rectForGID = function rectForGID(gid_, result) {
          var rect = result || new Rect$1(0, 0, 0, 0);
          rect.width = this._tileSize.width;
          rect.height = this._tileSize.height;
          var gid = gid_;
          gid &= TileFlag.FLIPPED_MASK;
          gid -= this.firstGid;
          if (this.imageOffset) {
            rect.x = this.imageOffset.x;
            rect.y = this.imageOffset.y;
          } else {
            var max_x = Math.floor((this.imageSize.width - this.margin * 2 + this.spacing) / (this._tileSize.width + this.spacing));
            rect.x = Math.round(gid % max_x * (this._tileSize.width + this.spacing) + this.margin);
            rect.y = Math.round(Math.floor(gid / max_x) * (this._tileSize.height + this.spacing) + this.margin);
          }
          return rect;
        };
        return TMXTilesetInfo;
      }();
      var TMXObjectGroupInfo = function () {
        function TMXObjectGroupInfo() {
          this.properties = {};
          this.name = '';
          this.objects = [];
          this.visible = true;
          this.opacity = 0;
          this.color = new Color$1(255, 255, 255, 255);
          this.offset = new Vec2(0, 0);
          this.draworder = 'topdown';
          this.tintColor = null;
        }
        var _proto2 = TMXObjectGroupInfo.prototype;
        _proto2.getProperties = function getProperties() {
          return this.properties;
        };
        _proto2.setProperties = function setProperties(value) {
          this.properties = value;
        };
        return TMXObjectGroupInfo;
      }();
      var TMXLayerInfo = function () {
        function TMXLayerInfo() {
          this.properties = {};
          this.name = '';
          this.layerSize = null;
          this.tiles = [];
          this.visible = true;
          this.opacity = 0;
          this.ownTiles = true;
          this.minGID = 100000;
          this.maxGID = 0;
          this.offset = new Vec2(0, 0);
          this.tintColor = null;
        }
        var _proto3 = TMXLayerInfo.prototype;
        _proto3.getProperties = function getProperties() {
          return this.properties;
        };
        _proto3.setProperties = function setProperties(value) {
          this.properties = value;
        };
        return TMXLayerInfo;
      }();
      TMXLayerInfo.ATTRIB_NONE = 1 << 0;
      TMXLayerInfo.ATTRIB_BASE64 = 1 << 1;
      TMXLayerInfo.ATTRIB_GZIP = 1 << 2;
      TMXLayerInfo.ATTRIB_ZLIB = 1 << 3;
      var TMXImageLayerInfo = function TMXImageLayerInfo() {
        this.name = '';
        this.visible = true;
        this.width = 0;
        this.height = 0;
        this.offset = new Vec2(0, 0);
        this.opacity = 0;
        this.trans = new Color$1(255, 255, 255, 255);
        this.sourceImage = void 0;
        this.tintColor = null;
      };

      function uint8ArrayToUint32Array(uint8Arr) {
        if (uint8Arr.length % 4 !== 0) return null;
        var arrLen = uint8Arr.length / 4;
        var retArr = window.Uint32Array ? new Uint32Array(arrLen) : [];
        for (var i = 0; i < arrLen; i++) {
          var offset = i * 4;
          retArr[i] = uint8Arr[offset] + uint8Arr[offset + 1] * (1 << 8) + uint8Arr[offset + 2] * (1 << 16) + uint8Arr[offset + 3] * (1 << 24);
        }
        return retArr;
      }
      function strToHAlign(value) {
        var hAlign = Label.HorizontalAlign;
        switch (value) {
          case 'center':
            return hAlign.CENTER;
          case 'right':
            return hAlign.RIGHT;
          default:
            return hAlign.LEFT;
        }
      }
      function strToVAlign(value) {
        var vAlign = Label.VerticalAlign;
        switch (value) {
          case 'center':
            return vAlign.CENTER;
          case 'bottom':
            return vAlign.BOTTOM;
          default:
            return vAlign.TOP;
        }
      }
      function strToColor(value) {
        if (!value) {
          return new Color$1(0, 0, 0, 255);
        }
        value = value.indexOf('#') !== -1 ? value.substring(1) : value;
        if (value.length === 8) {
          var a = parseInt(value.substr(0, 2), 16) || 255;
          var r = parseInt(value.substr(2, 2), 16) || 0;
          var g = parseInt(value.substr(4, 2), 16) || 0;
          var b = parseInt(value.substr(6, 2), 16) || 0;
          return new Color$1(r, g, b, a);
        } else {
          var _r = parseInt(value.substr(0, 2), 16) || 0;
          var _g = parseInt(value.substr(2, 2), 16) || 0;
          var _b = parseInt(value.substr(4, 2), 16) || 0;
          return new Color$1(_r, _g, _b, 255);
        }
      }
      function getPropertyList(node, map) {
        var res = [];
        var properties = node.getElementsByTagName('properties');
        for (var i = 0; i < properties.length; ++i) {
          var property = properties[i].getElementsByTagName('property');
          for (var j = 0; j < property.length; ++j) {
            res.push(property[j]);
          }
        }
        map = map || {};
        for (var _i = 0; _i < res.length; _i++) {
          var element = res[_i];
          var name = element.getAttribute('name');
          var type = element.getAttribute('type') || 'string';
          var value = element.getAttribute('value');
          if (type === 'int') {
            value = parseInt(value);
          } else if (type === 'float') {
            value = parseFloat(value);
          } else if (type === 'bool') {
            value = value === 'true';
          } else if (type === 'color') {
            value = strToColor(value);
          }
          map[name] = value;
        }
        return map;
      }
      var TMXMapInfo = function () {
        function TMXMapInfo(tmxFile, tsxContentMap, spfTexturesMap, textureSizes, imageLayerTextures) {
          this.properties = {};
          this.orientation = null;
          this.parentElement = null;
          this.parentGID = 0;
          this.layerAttrs = 0;
          this.storingCharacters = false;
          this.currentString = null;
          this.renderOrder = RenderOrder.RightDown;
          this._supportVersion = [1, 4, 0];
          this._objectGroups = [];
          this._allChildren = [];
          this._mapSize = new Size$1(0, 0);
          this._tileSize = new Size$1(0, 0);
          this._layers = [];
          this._tilesets = [];
          this._imageLayers = [];
          this._tileProperties = new Map();
          this._tileAnimations = {};
          this._tsxContentMap = null;
          this._spriteFrameMap = null;
          this._spfSizeMap = {};
          this._staggerAxis = null;
          this._staggerIndex = null;
          this._hexSideLength = 0;
          this._imageLayerSPF = null;
          this.initWithXML(tmxFile, tsxContentMap, spfTexturesMap, textureSizes, imageLayerTextures);
        }
        var _proto = TMXMapInfo.prototype;
        _proto.getOrientation = function getOrientation() {
          return this.orientation;
        };
        _proto.setOrientation = function setOrientation(value) {
          this.orientation = value;
        };
        _proto.getStaggerAxis = function getStaggerAxis() {
          return this._staggerAxis;
        };
        _proto.setStaggerAxis = function setStaggerAxis(value) {
          this._staggerAxis = value;
        };
        _proto.getStaggerIndex = function getStaggerIndex() {
          return this._staggerIndex;
        };
        _proto.setStaggerIndex = function setStaggerIndex(value) {
          this._staggerIndex = value;
        };
        _proto.getHexSideLength = function getHexSideLength() {
          return this._hexSideLength;
        };
        _proto.setHexSideLength = function setHexSideLength(value) {
          this._hexSideLength = value;
        };
        _proto.getMapSize = function getMapSize() {
          return new Size$1(this._mapSize.width, this._mapSize.height);
        };
        _proto.setMapSize = function setMapSize(value) {
          this._mapSize.width = value.width;
          this._mapSize.height = value.height;
        };
        _proto.getTileSize = function getTileSize() {
          return new Size$1(this._tileSize.width, this._tileSize.height);
        };
        _proto.setTileSize = function setTileSize(value) {
          this._tileSize.width = value.width;
          this._tileSize.height = value.height;
        };
        _proto.getLayers = function getLayers() {
          return this._layers;
        };
        _proto.setLayers = function setLayers(value) {
          this._allChildren.push(value);
          this._layers.push(value);
        };
        _proto.getImageLayers = function getImageLayers() {
          return this._imageLayers;
        };
        _proto.setImageLayers = function setImageLayers(value) {
          this._allChildren.push(value);
          this._imageLayers.push(value);
        };
        _proto.getTilesets = function getTilesets() {
          return this._tilesets;
        };
        _proto.setTilesets = function setTilesets(value) {
          this._tilesets.push(value);
        };
        _proto.getObjectGroups = function getObjectGroups() {
          return this._objectGroups;
        };
        _proto.setObjectGroups = function setObjectGroups(value) {
          this._allChildren.push(value);
          this._objectGroups.push(value);
        };
        _proto.getAllChildren = function getAllChildren() {
          return this._allChildren;
        };
        _proto.getParentElement = function getParentElement() {
          return this.parentElement;
        };
        _proto.setParentElement = function setParentElement(value) {
          this.parentElement = value;
        };
        _proto.getParentGID = function getParentGID() {
          return this.parentGID;
        };
        _proto.setParentGID = function setParentGID(value) {
          this.parentGID = value;
        };
        _proto.getLayerAttribs = function getLayerAttribs() {
          return this.layerAttrs;
        };
        _proto.setLayerAttribs = function setLayerAttribs(value) {
          this.layerAttrs = value;
        };
        _proto.getStoringCharacters = function getStoringCharacters() {
          return this.storingCharacters;
        };
        _proto.setStoringCharacters = function setStoringCharacters(value) {
          this.storingCharacters = value;
        };
        _proto.getProperties = function getProperties() {
          return this.properties;
        };
        _proto.setProperties = function setProperties(value) {
          this.properties = value;
        };
        _proto.initWithXML = function initWithXML(tmxString, tsxMap, spfTextureMap, textureSizes, imageLayerTextures) {
          this._tilesets.length = 0;
          this._layers.length = 0;
          this._imageLayers.length = 0;
          this._tsxContentMap = tsxMap;
          this._spriteFrameMap = spfTextureMap;
          this._imageLayerSPF = imageLayerTextures;
          this._spfSizeMap = textureSizes;
          this._objectGroups.length = 0;
          this._allChildren.length = 0;
          this.properties = {};
          this._tileProperties = new Map();
          this._tileAnimations = new Map();
          this.currentString = '';
          this.storingCharacters = false;
          this.layerAttrs = TMXLayerInfo.ATTRIB_NONE;
          this.parentElement = null;
          return this.parseXMLString(tmxString);
        };
        _proto.parseXMLString = function parseXMLString(xmlStr, tilesetFirstGid) {
          var parser = new SAXParser();
          var mapXML = parser.parse(xmlStr);
          var i;
          var map = mapXML.documentElement;
          var orientationStr = map.getAttribute('orientation');
          var staggerAxisStr = map.getAttribute('staggeraxis');
          var staggerIndexStr = map.getAttribute('staggerindex');
          var hexSideLengthStr = map.getAttribute('hexsidelength');
          var renderorderStr = map.getAttribute('renderorder');
          var version = map.getAttribute('version') || '1.0.0';
          if (map.nodeName === 'map') {
            var versionArr = version.split('.');
            var supportVersion = this._supportVersion;
            for (i = 0; i < supportVersion.length; i++) {
              var v = parseInt(versionArr[i]) || 0;
              var sv = supportVersion[i];
              if (sv < v) {
                logID(7216, version);
                break;
              }
            }
            if (orientationStr === 'orthogonal') this.orientation = Orientation.ORTHO;else if (orientationStr === 'isometric') this.orientation = Orientation.ISO;else if (orientationStr === 'hexagonal') this.orientation = Orientation.HEX;else if (orientationStr !== null) logID(7217, orientationStr);
            if (renderorderStr === 'right-up') {
              this.renderOrder = RenderOrder.RightUp;
            } else if (renderorderStr === 'left-up') {
              this.renderOrder = RenderOrder.LeftUp;
            } else if (renderorderStr === 'left-down') {
              this.renderOrder = RenderOrder.LeftDown;
            } else {
              this.renderOrder = RenderOrder.RightDown;
            }
            if (staggerAxisStr === 'x') {
              this.setStaggerAxis(StaggerAxis.STAGGERAXIS_X);
            } else if (staggerAxisStr === 'y') {
              this.setStaggerAxis(StaggerAxis.STAGGERAXIS_Y);
            }
            if (staggerIndexStr === 'odd') {
              this.setStaggerIndex(StaggerIndex.STAGGERINDEX_ODD);
            } else if (staggerIndexStr === 'even') {
              this.setStaggerIndex(StaggerIndex.STAGGERINDEX_EVEN);
            }
            if (hexSideLengthStr) {
              this.setHexSideLength(parseFloat(hexSideLengthStr));
            }
            var mapSize = new Size$1(0, 0);
            mapSize.width = parseFloat(map.getAttribute('width'));
            mapSize.height = parseFloat(map.getAttribute('height'));
            this.setMapSize(mapSize);
            mapSize = new Size$1(0, 0);
            mapSize.width = parseFloat(map.getAttribute('tilewidth'));
            mapSize.height = parseFloat(map.getAttribute('tileheight'));
            this.setTileSize(mapSize);
            this.properties = getPropertyList(map);
          }
          var tilesets = map.getElementsByTagName('tileset');
          if (map.nodeName !== 'map') {
            tilesets = [];
            tilesets.push(map);
          }
          for (i = 0; i < tilesets.length; i++) {
            var curTileset = tilesets[i];
            var tsxName = curTileset.getAttribute('source');
            if (tsxName) {
              var currentFirstGID = parseInt(curTileset.getAttribute('firstgid'));
              var tsxXmlString = this._tsxContentMap[tsxName];
              if (tsxXmlString) {
                this.parseXMLString(tsxXmlString, currentFirstGID);
              }
            } else {
              var images = curTileset.getElementsByTagName('image');
              var collection = images.length > 1;
              var firstImage = images[0];
              var firstImageName = firstImage.getAttribute('source');
              firstImageName = firstImageName.replace(/\\/g, '/');
              var tiles = curTileset.getElementsByTagName('tile');
              var tileCount = tiles && tiles.length || 1;
              var tile = null;
              var tilesetName = curTileset.getAttribute('name') || '';
              var tilesetSpacing = parseInt(curTileset.getAttribute('spacing')) || 0;
              var tilesetMargin = parseInt(curTileset.getAttribute('margin')) || 0;
              var fgid = tilesetFirstGid || parseInt(curTileset.getAttribute('firstgid')) || 0;
              var tilesetSize = new Size$1(0, 0);
              tilesetSize.width = parseFloat(curTileset.getAttribute('tilewidth'));
              tilesetSize.height = parseFloat(curTileset.getAttribute('tileheight'));
              var curTileOffset = curTileset.getElementsByTagName('tileoffset')[0];
              var tileOffsetX = 0;
              var tileOffsetY = 0;
              if (curTileOffset) {
                tileOffsetX = parseFloat(curTileOffset.getAttribute('x')) || 0;
                tileOffsetY = parseFloat(curTileOffset.getAttribute('y')) || 0;
              }
              var tileset = null;
              for (var tileIdx = 0; tileIdx < tileCount; tileIdx++) {
                var curImage = images[tileIdx] ? images[tileIdx] : firstImage;
                if (!curImage) continue;
                var curImageName = curImage.getAttribute('source');
                curImageName = curImageName.replace(/\\/g, '/');
                if (!tileset || collection) {
                  tileset = new TMXTilesetInfo();
                  tileset.name = tilesetName;
                  tileset.firstGid = fgid & TileFlag.FLIPPED_MASK;
                  tileset.tileOffset.x = tileOffsetX;
                  tileset.tileOffset.y = tileOffsetY;
                  tileset.collection = collection;
                  if (!collection) {
                    tileset.imageName = curImageName;
                    tileset.imageSize.width = parseFloat(curImage.getAttribute('width')) || 0;
                    tileset.imageSize.height = parseFloat(curImage.getAttribute('height')) || 0;
                    tileset.sourceImage = this._spriteFrameMap[curImageName];
                    if (!tileset.sourceImage) {
                      var nameWithPostfix = TMXMapInfo.getNameWithPostfix(curImageName);
                      tileset.imageName = nameWithPostfix;
                      tileset.sourceImage = this._spriteFrameMap[nameWithPostfix];
                      if (!tileset.sourceImage) {
                        var shortName = TMXMapInfo.getShortName(curImageName);
                        tileset.imageName = shortName;
                        tileset.sourceImage = this._spriteFrameMap[shortName];
                        if (!tileset.sourceImage) {
                          console.error("[error]: " + shortName + " not find in [" + Object.keys(this._spriteFrameMap).join(', ') + "]");
                          errorID(7221, curImageName);
                          console.warn("Please try asset type of " + curImageName + " to 'sprite-frame'");
                        }
                      }
                    }
                  }
                  tileset.spacing = tilesetSpacing;
                  tileset.margin = tilesetMargin;
                  tileset._tileSize.width = tilesetSize.width;
                  tileset._tileSize.height = tilesetSize.height;
                  this.setTilesets(tileset);
                }
                tile = tiles && tiles[tileIdx];
                if (!tile) {
                  continue;
                }
                this.parentGID = fgid + (parseInt(tile.getAttribute('id')) || 0);
                var tileImages = tile.getElementsByTagName('image');
                if (tile.hasAttribute('x') && tile.hasAttribute('y')) {
                  tileset.imageOffset = new Vec2(parseFloat(tile.getAttribute('x')) || 0, parseFloat(tile.getAttribute('y')) || 0);
                }
                var hastilesize = tile.hasAttribute('width') && tile.hasAttribute('height');
                if (hastilesize) {
                  tileset._tileSize.width = parseFloat(tile.getAttribute('width')) || 0;
                  tileset._tileSize.height = parseFloat(tile.getAttribute('height')) || 0;
                }
                if (tileImages && tileImages.length > 0) {
                  var image = tileImages[0];
                  var imageName = image.getAttribute('source');
                  imageName = imageName.replace(/\\/g, '/');
                  tileset.imageName = imageName;
                  tileset.imageSize.width = parseFloat(image.getAttribute('width')) || 0;
                  tileset.imageSize.height = parseFloat(image.getAttribute('height')) || 0;
                  if (!hastilesize) {
                    tileset._tileSize.width = tileset.imageSize.width;
                    tileset._tileSize.height = tileset.imageSize.height;
                  }
                  tileset.sourceImage = this._spriteFrameMap[imageName];
                  if (!tileset.sourceImage) {
                    var _nameWithPostfix = TMXMapInfo.getNameWithPostfix(imageName);
                    tileset.imageName = _nameWithPostfix;
                    tileset.sourceImage = this._spriteFrameMap[_nameWithPostfix];
                    if (!tileset.sourceImage) {
                      var _shortName = TMXMapInfo.getShortName(imageName);
                      tileset.imageName = _shortName;
                      tileset.sourceImage = this._spriteFrameMap[_shortName];
                      if (!tileset.sourceImage) {
                        errorID(7221, imageName);
                        console.warn("Please try asset type of " + imageName + " to 'sprite-frame'");
                      }
                    }
                  }
                  tileset.firstGid = this.parentGID & TileFlag.FLIPPED_MASK;
                }
                var pid = (TileFlag.FLIPPED_MASK & this.parentGID) >>> 0;
                this._tileProperties.set(pid, getPropertyList(tile));
                var animations = tile.getElementsByTagName('animation');
                if (animations && animations.length > 0) {
                  var animation = animations[0];
                  var framesData = animation.getElementsByTagName('frame');
                  var animationProp = {
                    frames: [],
                    dt: 0,
                    frameIdx: 0
                  };
                  this._tileAnimations.set(pid, animationProp);
                  var frames = animationProp.frames;
                  for (var frameIdx = 0; frameIdx < framesData.length; frameIdx++) {
                    var frame = framesData[frameIdx];
                    var tileid = fgid + (parseInt(frame.getAttribute('tileid')) || 0);
                    var duration = parseFloat(frame.getAttribute('duration')) || 0;
                    frames.push({
                      tileid: tileid,
                      duration: duration / 1000,
                      grid: null
                    });
                  }
                }
              }
            }
          }
          var childNodes = map.childNodes;
          for (i = 0; i < childNodes.length; i++) {
            var childNode = childNodes[i];
            if (this._shouldIgnoreNode(childNode)) {
              continue;
            }
            if (childNode.nodeName === 'imagelayer') {
              var imageLayer = this._parseImageLayer(childNode);
              if (imageLayer) {
                this.setImageLayers(imageLayer);
              }
            }
            if (childNode.nodeName === 'layer') {
              var layer = this._parseLayer(childNode);
              this.setLayers(layer);
            }
            if (childNode.nodeName === 'objectgroup') {
              var objectGroup = this._parseObjectGroup(childNode);
              this.setObjectGroups(objectGroup);
            }
          }
          return map;
        };
        _proto._shouldIgnoreNode = function _shouldIgnoreNode(node) {
          return node.nodeType === 3 || node.nodeType === 8 || node.nodeType === 4;
        };
        _proto._parseImageLayer = function _parseImageLayer(selLayer) {
          var datas = selLayer.getElementsByTagName('image');
          if (!datas || datas.length === 0) return null;
          var imageLayer = new TMXImageLayerInfo();
          imageLayer.name = selLayer.getAttribute('name');
          imageLayer.offset.x = parseFloat(selLayer.getAttribute('offsetx')) || 0;
          imageLayer.offset.y = parseFloat(selLayer.getAttribute('offsety')) || 0;
          var visible = selLayer.getAttribute('visible');
          imageLayer.visible = !(visible === '0');
          var opacity = selLayer.getAttribute('opacity');
          imageLayer.opacity = opacity ? Math.round(255 * parseFloat(opacity)) : 255;
          var tintColor = selLayer.getAttribute('tintcolor');
          imageLayer.tintColor = tintColor ? strToColor(tintColor) : null;
          var data = datas[0];
          var source = data.getAttribute('source');
          imageLayer.sourceImage = this._imageLayerSPF[source];
          imageLayer.width = parseInt(data.getAttribute('width')) || 0;
          imageLayer.height = parseInt(data.getAttribute('height')) || 0;
          imageLayer.trans = strToColor(data.getAttribute('trans'));
          if (!imageLayer.sourceImage) {
            errorID(7221, source);
            console.warn("Please try asset type of " + source + " to 'sprite-frame'");
            return null;
          }
          return imageLayer;
        };
        _proto._parseLayer = function _parseLayer(selLayer) {
          var data = selLayer.getElementsByTagName('data')[0];
          var layer = new TMXLayerInfo();
          layer.name = selLayer.getAttribute('name');
          var layerSize = new Size$1(0, 0);
          layerSize.width = parseFloat(selLayer.getAttribute('width'));
          layerSize.height = parseFloat(selLayer.getAttribute('height'));
          layer.layerSize = layerSize;
          var visible = selLayer.getAttribute('visible');
          layer.visible = !(visible === '0');
          var opacity = selLayer.getAttribute('opacity');
          if (opacity) layer.opacity = Math.round(255 * parseFloat(opacity));else layer.opacity = 255;
          layer.offset = new Vec2(parseFloat(selLayer.getAttribute('offsetx')) || 0, parseFloat(selLayer.getAttribute('offsety')) || 0);
          var tintColor = selLayer.getAttribute('tintcolor');
          layer.tintColor = tintColor ? strToColor(tintColor) : null;
          var nodeValue = '';
          for (var j = 0; j < data.childNodes.length; j++) {
            nodeValue += data.childNodes[j].nodeValue;
          }
          nodeValue = nodeValue.trim();
          var compression = data.getAttribute('compression');
          var encoding = data.getAttribute('encoding');
          if (compression && compression !== 'gzip' && compression !== 'zlib') {
            logID(7218);
            return null;
          }
          var tiles;
          switch (compression) {
            case 'gzip':
              tiles = codec.unzipBase64AsArray(nodeValue, 4);
              break;
            case 'zlib':
              {
                var inflator = new _p.Inflate(codec.Base64.decodeAsArray(nodeValue, 1));
                tiles = uint8ArrayToUint32Array(inflator.decompress());
                break;
              }
            case null:
            case '':
              if (encoding === 'base64') tiles = codec.Base64.decodeAsArray(nodeValue, 4);else if (encoding === 'csv') {
                tiles = [];
                var csvTiles = nodeValue.split(',');
                for (var csvIdx = 0; csvIdx < csvTiles.length; csvIdx++) tiles.push(parseInt(csvTiles[csvIdx]));
              } else {
                var selDataTiles = data.getElementsByTagName('tile');
                tiles = [];
                for (var xmlIdx = 0; xmlIdx < selDataTiles.length; xmlIdx++) tiles.push(parseInt(selDataTiles[xmlIdx].getAttribute('gid')));
              }
              break;
            default:
              if (this.layerAttrs === TMXLayerInfo.ATTRIB_NONE) logID(7219);
              break;
          }
          if (tiles) {
            layer.tiles = new Uint32Array(tiles);
          }
          layer.properties = getPropertyList(selLayer);
          return layer;
        };
        _proto._parseObjectGroup = function _parseObjectGroup(selGroup) {
          var objectGroup = new TMXObjectGroupInfo();
          objectGroup.name = selGroup.getAttribute('name') || '';
          objectGroup.offset = new Vec2(parseFloat(selGroup.getAttribute('offsetx')), parseFloat(selGroup.getAttribute('offsety')));
          var opacity = selGroup.getAttribute('opacity');
          if (opacity) objectGroup.opacity = Math.round(255 * parseFloat(opacity));else objectGroup.opacity = 255;
          var tintColor = selGroup.getAttribute('tintcolor');
          objectGroup.tintColor = tintColor ? strToColor(tintColor) : null;
          var visible = selGroup.getAttribute('visible');
          if (visible && parseInt(visible) === 0) objectGroup.visible = false;
          var color = selGroup.getAttribute('color');
          if (color) objectGroup.color.fromHEX(color);
          var draworder = selGroup.getAttribute('draworder');
          if (draworder) objectGroup.draworder = draworder;
          objectGroup.setProperties(getPropertyList(selGroup));
          var objects = selGroup.getElementsByTagName('object');
          if (objects) {
            for (var j = 0; j < objects.length; j++) {
              var selObj = objects[j];
              var objectProp = {};
              objectProp.id = selObj.getAttribute('id') || j;
              objectProp.name = selObj.getAttribute('name') || '';
              objectProp.width = parseFloat(selObj.getAttribute('width')) || 0;
              objectProp.height = parseFloat(selObj.getAttribute('height')) || 0;
              objectProp.x = parseFloat(selObj.getAttribute('x')) || 0;
              objectProp.y = parseFloat(selObj.getAttribute('y')) || 0;
              objectProp.rotation = parseFloat(selObj.getAttribute('rotation')) || 0;
              getPropertyList(selObj, objectProp);
              var visibleAttr = selObj.getAttribute('visible');
              objectProp.visible = !(visibleAttr && parseInt(visibleAttr) === 0);
              var texts = selObj.getElementsByTagName('text');
              if (texts && texts.length > 0) {
                var text = texts[0];
                objectProp.type = TMXObjectType.TEXT;
                objectProp.wrap = text.getAttribute('wrap') === '1';
                objectProp.color = strToColor(text.getAttribute('color'));
                objectProp.halign = strToHAlign(text.getAttribute('halign'));
                objectProp.valign = strToVAlign(text.getAttribute('valign'));
                objectProp.pixelsize = parseInt(text.getAttribute('pixelsize')) || 16;
                objectProp.text = text.childNodes[0].nodeValue;
              }
              var gid = selObj.getAttribute('gid');
              if (gid) {
                objectProp.gid = parseInt(gid);
                objectProp.type = TMXObjectType.IMAGE;
              }
              var ellipse = selObj.getElementsByTagName('ellipse');
              if (ellipse && ellipse.length > 0) {
                objectProp.type = TMXObjectType.ELLIPSE;
              }
              var polygonProps = selObj.getElementsByTagName('polygon');
              if (polygonProps && polygonProps.length > 0) {
                objectProp.type = TMXObjectType.POLYGON;
                var selPgPointStr = polygonProps[0].getAttribute('points');
                if (selPgPointStr) objectProp.points = this._parsePointsString(selPgPointStr);
              }
              var polylineProps = selObj.getElementsByTagName('polyline');
              if (polylineProps && polylineProps.length > 0) {
                objectProp.type = TMXObjectType.POLYLINE;
                var selPlPointStr = polylineProps[0].getAttribute('points');
                if (selPlPointStr) objectProp.polylinePoints = this._parsePointsString(selPlPointStr);
              }
              if (!objectProp.type) {
                objectProp.type = TMXObjectType.RECT;
              }
              objectGroup.objects.push(objectProp);
            }
            if (draworder !== 'index') {
              objectGroup.objects.sort(function (a, b) {
                return a.y - b.y;
              });
            }
          }
          return objectGroup;
        };
        _proto._parsePointsString = function _parsePointsString(pointsString) {
          if (!pointsString) return null;
          var points = [];
          var pointsStr = pointsString.split(' ');
          for (var i = 0; i < pointsStr.length; i++) {
            var selPointStr = pointsStr[i].split(',');
            points.push({
              x: parseFloat(selPointStr[0]),
              y: parseFloat(selPointStr[1])
            });
          }
          return points;
        };
        _proto.setTileAnimations = function setTileAnimations(animations) {
          this._tileAnimations = animations;
        };
        _proto.getTileAnimations = function getTileAnimations() {
          return this._tileAnimations;
        };
        _proto.getTileProperties = function getTileProperties() {
          return this._tileProperties;
        };
        _proto.setTileProperties = function setTileProperties(tileProperties) {
          this._tileProperties = tileProperties;
        };
        _proto.getCurrentString = function getCurrentString() {
          return this.currentString;
        };
        _proto.setCurrentString = function setCurrentString(currentString) {
          this.currentString = currentString;
        };
        TMXMapInfo.getNameWithPostfix = function getNameWithPostfix(name) {
          name = name.replace(/\\/g, '/');
          var slashIndex = name.lastIndexOf('/') + 1;
          var strLen = name.length;
          return name.substring(slashIndex, strLen);
        };
        TMXMapInfo.getShortName = function getShortName(name) {
          name = name.replace(/\\/g, '/');
          var slashIndex = name.lastIndexOf('/') + 1;
          var dotIndex = name.lastIndexOf('.');
          dotIndex = dotIndex < 0 ? name.length : dotIndex;
          return name.substring(slashIndex, dotIndex);
        };
        _createClass(TMXMapInfo, [{
          key: "mapSize",
          get: function get() {
            return this._mapSize;
          }
        }, {
          key: "tileSize",
          get: function get() {
            return this._tileSize;
          }
        }, {
          key: "mapWidth",
          get: function get() {
            return this._mapSize.width;
          },
          set: function set(width) {
            this._mapSize.width = width;
          }
        }, {
          key: "mapHeight",
          get: function get() {
            return this._mapSize.height;
          },
          set: function set(height) {
            this._mapSize.height = height;
          }
        }, {
          key: "tileWidth",
          get: function get() {
            return this._tileSize.width;
          },
          set: function set(width) {
            this._tileSize.width = width;
          }
        }, {
          key: "tileHeight",
          get: function get() {
            return this._tileSize.height;
          },
          set: function set(height) {
            this._tileSize.height = height;
          }
        }]);
        return TMXMapInfo;
      }();

      var _dec$p, _dec2$m, _dec3$k, _dec4$e, _dec5$e, _dec6$8, _dec7$6, _class$p, _class2$l, _initializer$j, _initializer2$i;
      var TiledTile = exports('gS', (_dec$p = ccclass$M('cc.TiledTile'), _dec2$m = requireComponent(UITransform), _dec3$k = type$d(CCInteger), _dec4$e = type$d(CCInteger), _dec5$e = type$d(CCInteger), _dec6$8 = type$d(CCInteger), _dec7$6 = type$d(CCInteger), _dec$p(_class$p = _dec2$m(_class$p = (_class2$l = function (_Component) {
        _inheritsLoose(TiledTile, _Component);
        function TiledTile() {
          var _this;
          _this = _Component.call(this) || this;
          _this._layer = null;
          _this._x = _initializer$j && _initializer$j();
          _this._y = _initializer2$i && _initializer2$i();
          return _this;
        }
        var _proto = TiledTile.prototype;
        _proto.onEnable = function onEnable() {
          var parent = this.node.parent;
          this._layer = parent.getComponent('cc.TiledLayer');
          this.node.on(NodeEventType.TRANSFORM_CHANGED, this._updatePosition, this);
          this.node.on(NodeEventType.SIZE_CHANGED, this._updatePosition, this);
          this._resetTile();
          this.updateInfo();
        };
        _proto.onDisable = function onDisable() {
          this._resetTile();
          this.node.off(NodeEventType.TRANSFORM_CHANGED, this._updatePosition, this);
          this.node.off(NodeEventType.SIZE_CHANGED, this._updatePosition, this);
        };
        _proto._resetTile = function _resetTile() {
          if (this._layer && this._layer.getTiledTileAt(this._x, this._y) === this) {
            this._layer.setTiledTileAt(this._x, this._y, null);
          }
        };
        _proto.updateInfo = function updateInfo() {
          if (!this._layer) return;
          var x = this._x;
          var y = this._y;
          if (this._layer.getTiledTileAt(x, y)) {
            warn('There is already a TiledTile at [%s, %s]', x, y);
            return;
          }
          var p = this._layer.getPositionAt(x, y);
          this.node.setPosition(p.x, p.y);
          this._layer.setTiledTileAt(x, y, this);
          this._layer.markForUpdateRenderData();
        };
        _proto._updatePosition = function _updatePosition() {
          this._layer.markForUpdateRenderData();
        };
        _createClass(TiledTile, [{
          key: "x",
          get: function get() {
            return this._x;
          },
          set: function set(value) {
            if (value === this._x) return;
            if (this._layer && this._layer.isInvalidPosition(value, this._y)) {
              warn("Invalid x, the valid value is between [%s] ~ [%s]", 0, this._layer.layerSize.width);
              return;
            }
            this._resetTile();
            this._x = value;
            this.updateInfo();
          }
        }, {
          key: "y",
          get: function get() {
            return this._y;
          },
          set: function set(value) {
            if (value === this._y) return;
            if (this._layer && this._layer.isInvalidPosition(this._x, value)) {
              warn("Invalid y, the valid value is between [%s] ~ [%s]", 0, this._layer.layerSize.height);
              return;
            }
            this._resetTile();
            this._y = value;
            this.updateInfo();
          }
        }, {
          key: "grid",
          get: function get() {
            if (this._layer) {
              return this._layer.getTileGIDAt(this._x, this._y);
            }
            return 0;
          },
          set: function set(value) {
            if (this._layer) {
              this._layer.setTileGIDAt(value, this._x, this._y);
            }
          }
        }]);
        return TiledTile;
      }(Component), (_initializer$j = applyDecoratedInitializer(_class2$l.prototype, "_x", [_dec3$k], function () {
        return 0;
      }), _initializer2$i = applyDecoratedInitializer(_class2$l.prototype, "_y", [_dec4$e], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$l.prototype, "x", [_dec5$e], Object.getOwnPropertyDescriptor(_class2$l.prototype, "x"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "y", [_dec6$8], Object.getOwnPropertyDescriptor(_class2$l.prototype, "y"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "grid", [_dec7$6], Object.getOwnPropertyDescriptor(_class2$l.prototype, "grid"), _class2$l.prototype)), _class2$l)) || _class$p) || _class$p));

      function fillTextureGrids(tileset, texGrids, spFrame) {
        var spf = spFrame || tileset.sourceImage;
        var tex = spf.texture;
        var collection = tileset.collection;
        if (!tileset.imageSize.width || !tileset.imageSize.height) {
          var sourceImage = tileset.sourceImage;
          tileset.imageSize.width = sourceImage.width;
          tileset.imageSize.height = sourceImage.height;
        }
        var imageWidth = tileset.imageSize.width;
        var imageHeight = tileset.imageSize.height;
        var tw = tileset._tileSize.width;
        var th = tileset._tileSize.height;
        var texWidth = spf.width;
        var texHeight = spf.height;
        var spacing = tileset.spacing;
        var margin = tileset.margin;
        var count = 1;
        if (!collection) {
          var cols = Math.floor((imageWidth - margin * 2 + spacing) / (tw + spacing));
          var rows = Math.floor((imageHeight - margin * 2 + spacing) / (th + spacing));
          count = Math.max(1, rows * cols);
        }
        var firstGid = tileset.firstGid;
        var grid = null;
        var override = !!texGrids.get(firstGid);
        var maxGid = tileset.firstGid + count;
        var gid = firstGid;
        for (; gid < maxGid; ++gid) {
          if (override && !texGrids.get(gid)) {
            override = false;
          }
          if (!override && texGrids.get(gid)) {
            break;
          }
          grid = {
            tileset: tileset,
            x: 0,
            y: 0,
            width: tw,
            height: th,
            t: 0,
            l: 0,
            r: 0,
            b: 0,
            cx: 0,
            cy: 0,
            offsetX: 0,
            offsetY: 0,
            rotated: false,
            gid: gid,
            spriteFrame: spf,
            texture: tex
          };
          tileset.rectForGID(gid, grid);
          if (!spFrame || count > 1 || tileset.imageOffset) {
            if (spFrame) {
              grid._name = spFrame.name;
              var lm = spFrame.unbiasUV[0];
              var bm = spFrame.rotated ? spFrame.unbiasUV[1] : spFrame.unbiasUV[5];
              grid.l = lm + (grid.x + 0.5) / texWidth;
              grid.t = bm + (grid.y + 0.5) / texHeight;
              grid.r = lm + (grid.x + grid.width - 0.5) / texWidth;
              grid.b = bm + (grid.y + grid.height - 0.5) / texHeight;
              grid._rect = new Rect$1(grid.x, grid.y, grid.width, grid.height);
            } else {
              grid.l = grid.x / texWidth;
              grid.t = grid.y / texHeight;
              grid.r = (grid.x + grid.width) / texWidth;
              grid.b = (grid.y + grid.height) / texHeight;
              grid._rect = new Rect$1(grid.x, grid.y, grid.width, grid.height);
            }
          } else if (spFrame.rotated) {
            grid._rotated = true;
            grid._name = spFrame.name;
            grid._rect = spFrame.getRect();
            grid.l = spFrame.unbiasUV[0];
            grid.t = spFrame.unbiasUV[1];
            grid.r = spFrame.unbiasUV[4];
            grid.b = spFrame.unbiasUV[3];
          } else {
            grid._name = spFrame.name;
            grid._rect = spFrame.getRect();
            grid.l = spFrame.unbiasUV[0];
            grid.t = spFrame.unbiasUV[5];
            grid.r = spFrame.unbiasUV[2];
            grid.b = spFrame.unbiasUV[1];
          }
          grid.cx = (grid.l + grid.r) / 2;
          grid.cy = (grid.t + grid.b) / 2;
          texGrids.set(gid, grid);
        }
      }

      var _dec$o, _class$o, _dec2$l, _class3$e;
      var _mat4_temp$3 = new Mat4();
      var _vec2_temp = new Vec2();
      var _vec3_temp = new Vec3();
      var _vec3_temp2 = new Vec3();
      var _tempRowCol = {
        row: 0,
        col: 0
      };
      var TiledUserNodeData = exports('gP', (_dec$o = ccclass$M('cc.TiledUserNodeData'), _dec$o(_class$o = function (_Component) {
        _inheritsLoose(TiledUserNodeData, _Component);
        function TiledUserNodeData() {
          var _this;
          _this = _Component.call(this) || this;
          _this._index = -1;
          _this._row = -1;
          _this._col = -1;
          _this._tiledLayer = null;
          return _this;
        }
        return TiledUserNodeData;
      }(Component)) || _class$o));
      var TiledLayer = exports('gQ', (_dec2$l = ccclass$M('cc.TiledLayer'), _dec2$l(_class3$e = function (_UIRenderer) {
        _inheritsLoose(TiledLayer, _UIRenderer);
        var _proto = TiledLayer.prototype;
        _proto.requestDrawInfo = function requestDrawInfo(idx) {
          if (!this._drawInfoList[idx]) {
            this._drawInfoList[idx] = new RenderDrawInfo();
            this._drawInfoList[idx].setDrawInfoType(RenderDrawInfoType.MIDDLEWARE);
          }
          return this._drawInfoList[idx];
        };
        function TiledLayer() {
          var _this2;
          _this2 = _UIRenderer.call(this) || this;
          _this2._userNodeGrid = {};
          _this2._userNodeMap = {};
          _this2._userNodeDirty = false;
          _this2.tiledTiles = [];
          _this2._viewPort = {
            x: -1,
            y: -1,
            width: -1,
            height: -1
          };
          _this2._cullingRect = {
            leftDown: {
              row: -1,
              col: -1
            },
            rightTop: {
              row: -1,
              col: -1
            }
          };
          _this2._cullingDirty = true;
          _this2._rightTop = {
            row: -1,
            col: -1
          };
          _this2._layerInfo = null;
          _this2._mapInfo = null;
          _this2._topOffset = 0;
          _this2._downOffset = 0;
          _this2._leftOffset = 0;
          _this2._rightOffset = 0;
          _this2.tiles = [];
          _this2.vertices = [];
          _this2._verticesDirty = true;
          _this2._layerName = '';
          _this2._layerSize = void 0;
          _this2._minGID = void 0;
          _this2._maxGID = void 0;
          _this2._layerOrientation = null;
          _this2._opacity = void 0;
          _this2._tintColor = void 0;
          _this2.texGrids = null;
          _this2._textures = [];
          _this2._tilesets = [];
          _this2._leftDownToCenterX = 0;
          _this2._leftDownToCenterY = 0;
          _this2._hasTiledNodeGrid = false;
          _this2._hasAniGrid = false;
          _this2._animations = null;
          _this2._enableCulling = void 0;
          _this2.colorChanged = false;
          _this2._properties = void 0;
          _this2.renderOrder = void 0;
          _this2._staggerAxis = void 0;
          _this2._staggerIndex = void 0;
          _this2._hexSideLength = void 0;
          _this2._mapTileSize = void 0;
          _this2._odd_even = void 0;
          _this2._diffX1 = void 0;
          _this2._diffY1 = void 0;
          _this2._useAutomaticVertexZ = void 0;
          _this2._vertexZvalue = void 0;
          _this2._offset = void 0;
          _this2._tiledDataArray = [];
          _this2._cameraNode = void 0;
          _this2._drawInfoList = [];
          _this2._tiledDataArrayIdx = 0;
          return _this2;
        }
        _proto.hasTiledNode = function hasTiledNode() {
          return this._hasTiledNodeGrid;
        };
        _proto.hasAnimation = function hasAnimation() {
          return this._hasAniGrid;
        };
        _proto.addUserNode = function addUserNode(node) {
          var dataComp = node.getComponent(TiledUserNodeData);
          if (dataComp) {
            warn('CCTiledLayer:addUserNode node has been added');
            return false;
          }
          dataComp = node.addComponent(TiledUserNodeData);
          node.parent = this.node;
          this._userNodeMap[node.uuid] = dataComp;
          dataComp._row = -1;
          dataComp._col = -1;
          dataComp._tiledLayer = this;
          this._nodeLocalPosToLayerPos(node.getPosition(), _vec2_temp);
          this._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol);
          this._addUserNodeToGrid(dataComp, _tempRowCol);
          this._updateCullingOffsetByUserNode(node);
          node.on(NodeEventType.TRANSFORM_CHANGED, this._userNodePosChange, dataComp);
          node.on(NodeEventType.SIZE_CHANGED, this._userNodeSizeChange, dataComp);
          return true;
        };
        _proto.removeUserNode = function removeUserNode(node) {
          var dataComp = node.getComponent(TiledUserNodeData);
          if (!dataComp) {
            warn('CCTiledLayer:removeUserNode node is not exist');
            return false;
          }
          node.off(NodeEventType.TRANSFORM_CHANGED, this._userNodePosChange, dataComp);
          node.off(NodeEventType.SIZE_CHANGED, this._userNodeSizeChange, dataComp);
          this._removeUserNodeFromGrid(dataComp);
          delete this._userNodeMap[node.uuid];
          node._removeComponent(dataComp);
          dataComp.destroy();
          node.removeFromParent();
          return true;
        };
        _proto.destroyUserNode = function destroyUserNode(node) {
          this.removeUserNode(node);
          node.destroy();
        };
        _proto._nodeLocalPosToLayerPos = function _nodeLocalPosToLayerPos(nodePos, out) {
          out.x = nodePos.x + this._leftDownToCenterX;
          out.y = nodePos.y + this._leftDownToCenterY;
        };
        _proto.getNodesByRowCol = function getNodesByRowCol(row, col) {
          var rowData = this._userNodeGrid[row];
          if (!rowData) return null;
          return rowData[col];
        };
        _proto.getNodesCountByRow = function getNodesCountByRow(row) {
          var rowData = this._userNodeGrid[row];
          if (!rowData) return 0;
          return rowData.count;
        };
        _proto._updateAllUserNode = function _updateAllUserNode() {
          this._userNodeGrid = {};
          for (var dataId in this._userNodeMap) {
            var dataComp = this._userNodeMap[dataId];
            this._nodeLocalPosToLayerPos(dataComp.node.getPosition(), _vec2_temp);
            this._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol);
            this._addUserNodeToGrid(dataComp, _tempRowCol);
            this._updateCullingOffsetByUserNode(dataComp.node);
          }
        };
        _proto._updateCullingOffsetByUserNode = function _updateCullingOffsetByUserNode(node_) {
          var node = node_._uiProps.uiTransformComp.contentSize;
          if (this._topOffset < node.height) {
            this._topOffset = node.height;
          }
          if (this._downOffset < node.height) {
            this._downOffset = node.height;
          }
          if (this._leftOffset < node.width) {
            this._leftOffset = node.width;
          }
          if (this._rightOffset < node.width) {
            this._rightOffset = node.width;
          }
        };
        _proto._userNodeSizeChange = function _userNodeSizeChange() {
          var dataComp = this;
          var node = dataComp.node;
          var self = dataComp._tiledLayer;
          self._updateCullingOffsetByUserNode(node);
          self._userNodeDirty = true;
          self.markForUpdateRenderData();
        };
        _proto._userNodePosChange = function _userNodePosChange() {
          var dataComp = this;
          var node = dataComp.node;
          var self = dataComp._tiledLayer;
          self._nodeLocalPosToLayerPos(node.getPosition(), _vec2_temp);
          self._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol);
          self._limitInLayer(_tempRowCol);
          if (_tempRowCol.row === dataComp._row && _tempRowCol.col === dataComp._col) return;
          self._removeUserNodeFromGrid(dataComp);
          self._addUserNodeToGrid(dataComp, _tempRowCol);
        };
        _proto._removeUserNodeFromGrid = function _removeUserNodeFromGrid(dataComp) {
          var row = dataComp._row;
          var col = dataComp._col;
          var index = dataComp._index;
          var rowData = this._userNodeGrid[row];
          var colData = rowData && rowData[col];
          if (colData) {
            rowData.count--;
            colData.count--;
            colData.list[index] = null;
            if (colData.count <= 0) {
              colData.list.length = 0;
              colData.count = 0;
            }
          }
          dataComp._row = -1;
          dataComp._col = -1;
          dataComp._index = -1;
          this._userNodeDirty = true;
          this.markForUpdateRenderData();
        };
        _proto._limitInLayer = function _limitInLayer(rowCol) {
          var row = rowCol.row;
          var col = rowCol.col;
          if (row < 0) rowCol.row = 0;
          if (row > this._rightTop.row) rowCol.row = this._rightTop.row;
          if (col < 0) rowCol.col = 0;
          if (col > this._rightTop.col) rowCol.col = this._rightTop.col;
        };
        _proto._addUserNodeToGrid = function _addUserNodeToGrid(dataComp, tempRowCol) {
          var row = tempRowCol.row;
          var col = tempRowCol.col;
          var rowData = this._userNodeGrid[row] = this._userNodeGrid[row] || {
            count: 0
          };
          var colData = rowData[col] = rowData[col] || {
            count: 0,
            list: []
          };
          dataComp._row = row;
          dataComp._col = col;
          dataComp._index = colData.list.length;
          rowData.count++;
          colData.count++;
          colData.list.push(dataComp);
          this._userNodeDirty = true;
        };
        _proto.isUserNodeDirty = function isUserNodeDirty() {
          return this._userNodeDirty;
        };
        _proto.setUserNodeDirty = function setUserNodeDirty(value) {
          this._userNodeDirty = value;
        };
        _proto._reinstallCamera = function _reinstallCamera() {
          var camera = director.root.batcher2D.getFirstRenderCamera(this.node);
          var cameraNode = camera === null || camera === void 0 ? void 0 : camera.node;
          if (this._cameraNode !== cameraNode) {
            this._uninstallCamera();
            if (cameraNode) {
              cameraNode.on(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this);
              cameraNode.on(NodeEventType.SIZE_CHANGED, this.updateCulling, this);
              this._cameraNode = cameraNode;
            }
          }
          return camera;
        };
        _proto._uninstallCamera = function _uninstallCamera() {
          if (this._cameraNode) {
            this._cameraNode.off(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this);
            this._cameraNode.off(NodeEventType.SIZE_CHANGED, this.updateCulling, this);
            delete this._cameraNode;
          }
        };
        _proto.onEnable = function onEnable() {
          _UIRenderer.prototype.onEnable.call(this);
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
          this.node.on(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this);
          this.node.on(NodeEventType.SIZE_CHANGED, this.updateCulling, this);
          this.node.parent.on(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this);
          this.node.parent.on(NodeEventType.SIZE_CHANGED, this.updateCulling, this);
          this.markForUpdateRenderData();
          this.scheduleOnce(this.updateCulling.bind(this));
        };
        _proto.onDisable = function onDisable() {
          var _this$node$parent, _this$node$parent2;
          _UIRenderer.prototype.onDisable.call(this);
          (_this$node$parent = this.node.parent) === null || _this$node$parent === void 0 ? void 0 : _this$node$parent.off(NodeEventType.SIZE_CHANGED, this.updateCulling, this);
          (_this$node$parent2 = this.node.parent) === null || _this$node$parent2 === void 0 ? void 0 : _this$node$parent2.off(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this);
          this.node.off(NodeEventType.SIZE_CHANGED, this.updateCulling, this);
          this.node.off(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this);
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
          this._uninstallCamera();
        };
        _proto._syncAnchorPoint = function _syncAnchorPoint() {
          var node = this.node;
          var trans = node._uiProps.uiTransformComp;
          var scale = node.getScale();
          this._leftDownToCenterX = trans.width * trans.anchorX * scale.x;
          this._leftDownToCenterY = trans.height * trans.anchorY * scale.y;
          this._cullingDirty = true;
          this.markForUpdateRenderData();
        };
        _proto.getLayerName = function getLayerName() {
          return this._layerName;
        };
        _proto.setLayerName = function setLayerName(layerName) {
          this._layerName = layerName;
        };
        _proto.getProperty = function getProperty(propertyName) {
          return this._properties[propertyName];
        };
        _proto.getPositionAt = function getPositionAt(pos, y) {
          var x;
          if (y !== undefined) {
            x = Math.floor(pos);
            y = Math.floor(y);
          } else {
            x = Math.floor(pos.x);
            y = Math.floor(pos.y);
          }
          switch (this._layerOrientation) {
            case Orientation.ORTHO:
              return this._positionForOrthoAt(x, y);
            case Orientation.ISO:
              return this._positionForIsoAt(x, y);
            case Orientation.HEX:
              return this._positionForHexAt(x, y);
          }
          return null;
        };
        _proto.isInvalidPosition = function isInvalidPosition(x, y) {
          return x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0;
        };
        _proto._positionForIsoAt = function _positionForIsoAt(x, y) {
          var offsetX = 0;
          var offsetY = 0;
          var index = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          var gidAndFlags = this.tiles[index];
          if (gidAndFlags) {
            var gid = (gidAndFlags & TileFlag.FLIPPED_MASK) >>> 0;
            var tileset = this.texGrids.get(gid).tileset;
            var offset = tileset.tileOffset;
            offsetX = offset.x;
            offsetY = offset.y;
          }
          return new Vec2(this._mapTileSize.width * 0.5 * (this._layerSize.height + x - y - 1) + offsetX, this._mapTileSize.height * 0.5 * (this._layerSize.width - x + this._layerSize.height - y - 2) - offsetY);
        };
        _proto._positionForOrthoAt = function _positionForOrthoAt(x, y) {
          var offsetX = 0;
          var offsetY = 0;
          var index = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          var gidAndFlags = this.tiles[index];
          if (gidAndFlags) {
            var gid = (gidAndFlags & TileFlag.FLIPPED_MASK) >>> 0;
            var tileset = this.texGrids.get(gid).tileset;
            var offset = tileset.tileOffset;
            offsetX = offset.x;
            offsetY = offset.y;
          }
          return new Vec2(x * this._mapTileSize.width + offsetX, (this._layerSize.height - y - 1) * this._mapTileSize.height - offsetY);
        };
        _proto._positionForHexAt = function _positionForHexAt(col, row) {
          var tileWidth = this._mapTileSize.width;
          var tileHeight = this._mapTileSize.height;
          var rows = this._layerSize.height;
          var index = Math.floor(col) + Math.floor(row) * this._layerSize.width;
          var gid = (this.tiles[index] & TileFlag.FLIPPED_MASK) >>> 0;
          var offset;
          if (this.texGrids.get(gid)) {
            offset = this.texGrids.get(gid).tileset.tileOffset;
          } else {
            offset = {
              x: 0,
              y: 0
            };
          }
          var odd_even = this._staggerIndex === StaggerIndex.STAGGERINDEX_ODD ? 1 : -1;
          var x = 0;
          var y = 0;
          var diffX = 0;
          var diffY = 0;
          switch (this._staggerAxis) {
            case StaggerAxis.STAGGERAXIS_Y:
              diffX = 0;
              if (row % 2 === 1) {
                diffX = tileWidth / 2 * odd_even;
              }
              x = col * tileWidth + diffX + offset.x;
              y = (rows - row - 1) * (tileHeight - (tileHeight - this._hexSideLength) / 2) - offset.y;
              break;
            case StaggerAxis.STAGGERAXIS_X:
              diffY = 0;
              if (col % 2 === 1) {
                diffY = tileHeight / 2 * -odd_even;
              }
              x = col * (tileWidth - (tileWidth - this._hexSideLength) / 2) + offset.x;
              y = (rows - row - 1) * tileHeight + diffY - offset.y;
              break;
          }
          return new Vec2(x, y);
        };
        _proto.setTilesGIDAt = function setTilesGIDAt(gids, beginCol, beginRow, totalCols) {
          if (!gids || gids.length === 0 || totalCols <= 0) return;
          if (beginRow < 0) beginRow = 0;
          if (beginCol < 0) beginCol = 0;
          var gidsIdx = 0;
          var endCol = beginCol + totalCols;
          for (var row = beginRow;; row++) {
            for (var col = beginCol; col < endCol; col++) {
              if (gidsIdx >= gids.length) return;
              this._updateTileForGID(gids[gidsIdx], col, row);
              gidsIdx++;
            }
          }
        };
        _proto.setTileGIDAt = function setTileGIDAt(gid, x, y, flags) {
          var ugid = (gid & TileFlag.FLIPPED_MASK) >>> 0;
          x = Math.floor(x);
          y = Math.floor(y);
          if (this.isInvalidPosition(x, y)) {
            throw new Error('cc.TiledLayer.setTileGIDAt(): invalid position');
          }
          if (!this.tiles || !this._tilesets || this._tilesets.length === 0) {
            logID(7238);
            return;
          }
          if (ugid !== 0 && ugid < this._tilesets[0].firstGid) {
            logID(7239, gid);
            return;
          }
          flags = flags || 0;
          this._updateTileForGID((ugid | flags) >>> 0, x, y);
        };
        _proto._updateTileForGID = function _updateTileForGID(gidAndFlags, x, y) {
          var idx = 0 | x + y * this._layerSize.width;
          if (idx >= this.tiles.length) return;
          var oldGIDAndFlags = this.tiles[idx];
          if (gidAndFlags === oldGIDAndFlags) return;
          var gid = (gidAndFlags & TileFlag.FLIPPED_MASK) >>> 0;
          var grid = this.texGrids.get(gid);
          if (grid) {
            this.tiles[idx] = gidAndFlags;
            this._updateVertex(x, y);
          } else {
            this.tiles[idx] = 0;
          }
          this._cullingDirty = true;
        };
        _proto.getTileGIDAt = function getTileGIDAt(x, y) {
          if (this.isInvalidPosition(x, y)) {
            throw new Error('cc.TiledLayer.getTileGIDAt(): invalid position');
          }
          if (!this.tiles) {
            logID(7237);
            return null;
          }
          var index = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          var tile = this.tiles[index];
          return (tile & TileFlag.FLIPPED_MASK) >>> 0;
        };
        _proto.getTileFlagsAt = function getTileFlagsAt(x, y) {
          if (this.isInvalidPosition(x, y)) {
            throw new Error('TiledLayer.getTileFlagsAt: invalid position');
          }
          if (!this.tiles) {
            logID(7240);
            return null;
          }
          var idx = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          var tile = this.tiles[idx];
          return (tile & TileFlag.FLIPPED_ALL) >>> 0;
        };
        _proto.setCullingDirty = function setCullingDirty(value) {
          this._cullingDirty = value;
        };
        _proto.isCullingDirty = function isCullingDirty() {
          return this._cullingDirty;
        };
        _proto.updateViewPort = function updateViewPort(x, y, width, height) {
          if (this._viewPort.width === width && this._viewPort.height === height && this._viewPort.x === x && this._viewPort.y === y) {
            return;
          }
          this._viewPort.x = x;
          this._viewPort.y = y;
          this._viewPort.width = width;
          this._viewPort.height = height;
          var reserveLine = 1;
          if (this._layerOrientation === Orientation.ISO) {
            reserveLine = 2;
          }
          var vpx = this._viewPort.x - this._offset.x + this._leftDownToCenterX;
          var vpy = this._viewPort.y - this._offset.y + this._leftDownToCenterY;
          var leftDownX = vpx - this._leftOffset;
          var leftDownY = vpy - this._downOffset;
          var rightTopX = vpx + width + this._rightOffset;
          var rightTopY = vpy + height + this._topOffset;
          var leftDown = this._cullingRect.leftDown;
          var rightTop = this._cullingRect.rightTop;
          if (leftDownX < 0) leftDownX = 0;
          if (leftDownY < 0) leftDownY = 0;
          this._positionToRowCol(leftDownX, leftDownY, _tempRowCol);
          _tempRowCol.row -= reserveLine;
          _tempRowCol.col -= reserveLine;
          _tempRowCol.row = _tempRowCol.row > 0 ? _tempRowCol.row : 0;
          _tempRowCol.col = _tempRowCol.col > 0 ? _tempRowCol.col : 0;
          if (_tempRowCol.row !== leftDown.row || _tempRowCol.col !== leftDown.col) {
            leftDown.row = _tempRowCol.row;
            leftDown.col = _tempRowCol.col;
            this._cullingDirty = true;
          }
          if (rightTopX < 0 || rightTopY < 0) {
            _tempRowCol.row = -1;
            _tempRowCol.col = -1;
          } else {
            this._positionToRowCol(rightTopX, rightTopY, _tempRowCol);
            _tempRowCol.row++;
            _tempRowCol.col++;
          }
          if (_tempRowCol.row !== rightTop.row || _tempRowCol.col !== rightTop.col) {
            rightTop.row = _tempRowCol.row;
            rightTop.col = _tempRowCol.col;
            this._cullingDirty = true;
          }
          if (this._cullingDirty) this.markForUpdateRenderData();
        };
        _proto._positionToRowCol = function _positionToRowCol(x, y, result) {
          var maptw = this._mapTileSize.width;
          var mapth = this._mapTileSize.height;
          var maptw2 = maptw * 0.5;
          var mapth2 = mapth * 0.5;
          var row = 0;
          var col = 0;
          var diffX2 = 0;
          var diffY2 = 0;
          var axis = this._staggerAxis;
          switch (this._layerOrientation) {
            case Orientation.ORTHO:
              col = Math.floor(x / maptw);
              row = Math.floor(y / mapth);
              break;
            case Orientation.ISO:
              col = Math.floor(x / maptw2);
              row = Math.floor(y / mapth2);
              break;
            case Orientation.HEX:
              if (axis === StaggerAxis.STAGGERAXIS_Y) {
                row = Math.floor(y / (mapth - this._diffY1));
                diffX2 = row % 2 === 1 ? maptw2 * this._odd_even : 0;
                col = Math.floor((x - diffX2) / maptw);
              } else {
                col = Math.floor(x / (maptw - this._diffX1));
                diffY2 = col % 2 === 1 ? mapth2 * -this._odd_even : 0;
                row = Math.floor((y - diffY2) / mapth);
              }
              break;
          }
          result.row = row;
          result.col = col;
          return result;
        };
        _proto.updateCulling = function updateCulling() {
          if (this._enableCulling) {
            this.node.updateWorldTransform();
            Mat4.invert(_mat4_temp$3, this.node.getWorldMatrix());
            var camera = this._reinstallCamera();
            if (camera) {
              _vec3_temp.x = 0;
              _vec3_temp.y = 0;
              _vec3_temp.z = 0;
              _vec3_temp2.x = camera.width;
              _vec3_temp2.y = camera.height;
              _vec3_temp2.z = 0;
              camera.screenToWorld(_vec3_temp, _vec3_temp);
              camera.screenToWorld(_vec3_temp2, _vec3_temp2);
              Vec3.transformMat4(_vec3_temp, _vec3_temp, _mat4_temp$3);
              Vec3.transformMat4(_vec3_temp2, _vec3_temp2, _mat4_temp$3);
              this.updateViewPort(_vec3_temp.x, _vec3_temp.y, _vec3_temp2.x - _vec3_temp.x, _vec3_temp2.y - _vec3_temp.y);
            }
          }
        };
        _proto.getLayerOrientation = function getLayerOrientation() {
          return this._layerOrientation;
        };
        _proto.getProperties = function getProperties() {
          return this._properties;
        };
        _proto._updateVertex = function _updateVertex(col, row) {
          var FLIPPED_MASK = TileFlag.FLIPPED_MASK;
          var vertices = this.vertices;
          var layerOrientation = this._layerOrientation;
          var tiles = this.tiles;
          if (!tiles) {
            return;
          }
          var rightTop = this._rightTop;
          var maptw = this._mapTileSize.width;
          var mapth = this._mapTileSize.height;
          var maptw2 = maptw * 0.5;
          var mapth2 = mapth * 0.5;
          var rows = this._layerSize.height;
          var cols = this._layerSize.width;
          var grids = this.texGrids;
          var left = 0;
          var bottom = 0;
          var axis;
          var diffX1;
          var diffY1;
          var odd_even;
          var diffX2;
          var diffY2;
          if (layerOrientation === Orientation.HEX) {
            axis = this._staggerAxis;
            diffX1 = this._diffX1;
            diffY1 = this._diffY1;
            odd_even = this._odd_even;
          }
          var cullingCol = 0;
          var cullingRow = 0;
          var gridGID = 0;
          var topBorder = 0;
          var downBorder = 0;
          var leftBorder = 0;
          var rightBorder = 0;
          var index = row * cols + col;
          var gid = tiles[index];
          gridGID = (gid & FLIPPED_MASK) >>> 0;
          var grid = grids.get(gridGID);
          if (!grid) {
            return;
          }
          if (this._animations.get(gridGID)) {
            this._hasAniGrid = this._hasAniGrid || true;
          }
          switch (layerOrientation) {
            case Orientation.ORTHO:
              cullingCol = col;
              cullingRow = rows - row - 1;
              left = cullingCol * maptw;
              bottom = cullingRow * mapth;
              break;
            case Orientation.ISO:
              cullingCol = rows + col - row - 1;
              cullingRow = rows + cols - col - row - 2;
              left = maptw2 * cullingCol;
              bottom = mapth2 * cullingRow;
              break;
            case Orientation.HEX:
              diffX2 = axis === StaggerAxis.STAGGERAXIS_Y && row % 2 === 1 ? maptw2 * odd_even : 0;
              diffY2 = axis === StaggerAxis.STAGGERAXIS_X && col % 2 === 1 ? mapth2 * -odd_even : 0;
              left = col * (maptw - diffX1) + diffX2;
              bottom = (rows - row - 1) * (mapth - diffY1) + diffY2;
              cullingCol = col;
              cullingRow = rows - row - 1;
              break;
          }
          var rowData = vertices[cullingRow] = vertices[cullingRow] || {
            minCol: 0,
            maxCol: 0
          };
          var colData = rowData[cullingCol] = rowData[cullingCol] || {
            left: 0,
            bottom: 0,
            index: 0
          };
          if (rowData.minCol > cullingCol) {
            rowData.minCol = cullingCol;
          }
          if (rowData.maxCol < cullingCol) {
            rowData.maxCol = cullingCol;
          }
          if (rightTop.row < cullingRow) {
            rightTop.row = cullingRow;
            if (layerOrientation === Orientation.ISO) {
              rightTop.row += 1;
            }
          }
          if (rightTop.col < cullingCol) {
            rightTop.col = cullingCol;
            if (layerOrientation === Orientation.ISO) {
              rightTop.col += 1;
            }
          }
          var tileOffset = grid.tileset.tileOffset;
          left += this._offset.x + tileOffset.x + grid.offsetX;
          bottom += this._offset.y - tileOffset.y - grid.offsetY;
          topBorder = -tileOffset.y + grid.tileset._tileSize.height - mapth;
          topBorder = topBorder < 0 ? 0 : topBorder;
          downBorder = tileOffset.y < 0 ? 0 : tileOffset.y;
          leftBorder = -tileOffset.x < 0 ? 0 : -tileOffset.x;
          rightBorder = tileOffset.x + grid.tileset._tileSize.width - maptw;
          rightBorder = rightBorder < 0 ? 0 : rightBorder;
          if (this._rightOffset < leftBorder) {
            this._rightOffset = leftBorder;
          }
          if (this._leftOffset < rightBorder) {
            this._leftOffset = rightBorder;
          }
          if (this._topOffset < downBorder) {
            this._topOffset = downBorder;
          }
          if (this._downOffset < topBorder) {
            this._downOffset = topBorder;
          }
          colData.left = left;
          colData.bottom = bottom;
          colData.index = index;
          this._cullingDirty = true;
        };
        _proto._updateVertices = function _updateVertices() {
          var vertices = this.vertices;
          vertices.length = 0;
          var tiles = this.tiles;
          if (!tiles) {
            return;
          }
          var rightTop = this._rightTop;
          rightTop.row = -1;
          rightTop.col = -1;
          var rows = this._layerSize.height;
          var cols = this._layerSize.width;
          this._topOffset = 0;
          this._downOffset = 0;
          this._leftOffset = 0;
          this._rightOffset = 0;
          this._hasAniGrid = false;
          for (var row = 0; row < rows; ++row) {
            for (var col = 0; col < cols; ++col) {
              this._updateVertex(col, row);
            }
          }
          this._verticesDirty = false;
        };
        _proto.getTiledTileAt = function getTiledTileAt(x, y, forceCreate) {
          if (this.isInvalidPosition(x, y)) {
            throw new Error('TiledLayer.getTiledTileAt: invalid position');
          }
          if (!this.tiles) {
            logID(7236);
            return null;
          }
          var index = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          var tile = this.tiledTiles[index];
          if (!tile && forceCreate) {
            var node = new Node$1();
            tile = node.addComponent(TiledTile);
            tile._x = x;
            tile._y = y;
            tile._layer = this;
            tile.updateInfo();
            node.parent = this.node;
            return tile;
          }
          return tile;
        };
        _proto.setTiledTileAt = function setTiledTileAt(x, y, tiledTile) {
          if (this.isInvalidPosition(x, y)) {
            throw new Error('TiledLayer.setTiledTileAt: invalid position');
          }
          if (!this.tiles) {
            logID(7236);
            return null;
          }
          var index = Math.floor(x) + Math.floor(y) * this._layerSize.width;
          this.tiledTiles[index] = tiledTile;
          this._cullingDirty = true;
          if (tiledTile) {
            this._hasTiledNodeGrid = true;
          } else {
            this._hasTiledNodeGrid = this.tiledTiles.some(function (tiledNode) {
              return !!tiledNode;
            });
          }
          return tiledTile;
        };
        _proto.getTexture = function getTexture(index) {
          index = index || 0;
          if (this._textures && index >= 0 && this._textures.length > index) {
            return this._textures[index];
          }
          return null;
        };
        _proto.getTextures = function getTextures() {
          return this._textures;
        };
        _proto.setTexture = function setTexture(texture) {
          this.setTextures([texture]);
        };
        _proto.setTextures = function setTextures(textures) {
          this._textures = textures;
          this.markForUpdateRenderData();
        };
        _proto.getLayerSize = function getLayerSize() {
          return this._layerSize;
        };
        _proto.getMapTileSize = function getMapTileSize() {
          return this._mapTileSize;
        };
        _proto.getTileSet = function getTileSet(index) {
          index = index || 0;
          if (this._tilesets && index >= 0 && this._tilesets.length > index) {
            return this._tilesets[index];
          }
          return null;
        };
        _proto.getTileSets = function getTileSets() {
          return this._tilesets;
        };
        _proto.setTileSet = function setTileSet(tileset) {
          this.setTileSets([tileset]);
        };
        _proto.setTileSets = function setTileSets(tilesets) {
          this._tilesets = tilesets;
          var textures = this._textures = [];
          var texGrids = this.texGrids;
          texGrids.clear();
          for (var i = 0; i < tilesets.length; i++) {
            var tileset = tilesets[i];
            if (tileset) {
              textures[i] = tileset.sourceImage;
            }
          }
          for (var _i = 0, l = tilesets.length; _i < l; ++_i) {
            var tilesetInfo = tilesets[_i];
            if (!tilesetInfo) continue;
            fillTextureGrids(tilesetInfo, texGrids, tilesetInfo.sourceImage);
          }
          this._prepareToRender();
        };
        _proto.init = function init(layerInfo, mapInfo, tilesets, textures, texGrids) {
          this._cullingDirty = true;
          this._layerInfo = layerInfo;
          this._mapInfo = mapInfo;
          var size = layerInfo.layerSize;
          this._layerName = layerInfo.name;
          this.tiles = layerInfo.tiles;
          this._properties = layerInfo.properties;
          this._layerSize = size;
          this._minGID = layerInfo.minGID;
          this._maxGID = layerInfo.maxGID;
          this._opacity = layerInfo.opacity;
          if (layerInfo.tintColor) {
            this._tintColor = layerInfo.tintColor;
          }
          this.renderOrder = mapInfo.renderOrder;
          this._staggerAxis = mapInfo.getStaggerAxis();
          this._staggerIndex = mapInfo.getStaggerIndex();
          this._hexSideLength = mapInfo.getHexSideLength();
          this._animations = mapInfo.getTileAnimations();
          this._tilesets = tilesets;
          this._textures = textures;
          this.texGrids = texGrids;
          this._layerOrientation = mapInfo.orientation;
          this._mapTileSize = mapInfo.getTileSize();
          var maptw = this._mapTileSize.width;
          var mapth = this._mapTileSize.height;
          var layerW = this._layerSize.width;
          var layerH = this._layerSize.height;
          if (this._layerOrientation === Orientation.HEX) {
            var width = 0;
            var height = 0;
            var tileWidth = maptw & ~1;
            var tileHeight = mapth & ~1;
            this._odd_even = this._staggerIndex === StaggerIndex.STAGGERINDEX_ODD ? 1 : -1;
            if (this._staggerAxis === StaggerAxis.STAGGERAXIS_X) {
              this._diffX1 = (tileWidth - this._hexSideLength) / 2;
              this._diffY1 = 0;
              width = (this._diffX1 + this._hexSideLength) * layerW + this._diffX1;
              height = tileHeight * layerH + tileHeight / 2;
            } else {
              this._diffX1 = 0;
              this._diffY1 = (tileHeight - this._hexSideLength) / 2;
              width = tileWidth * layerW + tileWidth / 2;
              height = (this._diffY1 + this._hexSideLength) * layerH + this._diffY1;
            }
            this.node._uiProps.uiTransformComp.setContentSize(width, height);
          } else if (this._layerOrientation === Orientation.ISO) {
            var wh = layerW + layerH;
            this.node._uiProps.uiTransformComp.setContentSize(maptw * 0.5 * wh, mapth * 0.5 * wh);
          } else {
            this.node._uiProps.uiTransformComp.setContentSize(layerW * maptw, layerH * mapth);
          }
          this._offset = new Vec2(layerInfo.offset.x, -layerInfo.offset.y);
          this._useAutomaticVertexZ = false;
          this._vertexZvalue = 0;
          this._syncAnchorPoint();
          this._prepareToRender();
        };
        _proto._prepareToRender = function _prepareToRender() {
          this._updateVertices();
          this._updateAllUserNode();
        };
        _proto.requestTiledRenderData = function requestTiledRenderData() {
          var arr = this._tiledDataArray;
          while (arr.length > 0 && arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) {
            arr.pop();
          }
          if (arr.length > 0) {
            var last = arr[arr.length - 1];
            if (last.renderData && last.renderData.vertexCount === 0) {
              return last;
            }
          }
          var comb = {
            renderData: null,
            texture: null
          };
          this._tiledDataArray.push(comb);
          return comb;
        };
        _proto.requestSubNodesData = function requestSubNodesData() {
          var arr = this._tiledDataArray;
          if (arr.length > 0) {
            if (arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) {
              return arr[arr.length - 1];
            }
          }
          var renderData = [];
          var comb = {
            subNodes: renderData
          };
          this._tiledDataArray.push(comb);
          return comb;
        };
        _proto.destroyRenderData = function destroyRenderData() {
          this._tiledDataArray.forEach(function (rd) {
            var renderData = rd.renderData;
            if (renderData) RenderData.remove(renderData);
          });
          this._tiledDataArray.length = 0;
          _UIRenderer.prototype.destroyRenderData.call(this);
        };
        _proto._flushAssembler = function _flushAssembler() {
          var assembler = TiledLayer.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
            this._assembler.createData(this);
          }
          if (this._tiledDataArray.length === 0) {
            this.markForUpdateRenderData();
            this._updateColor();
          }
        };
        _proto._render = function _render(ui) {
          for (var i = 0; i < this._tiledDataArray.length; i++) {
            this._tiledDataArrayIdx = i;
            var m = this._tiledDataArray[i];
            if (m.subNodes) {
              m.subNodes.forEach(function (c) {
                if (c) ui.walk(c.node);
              });
            } else {
              var td = m;
              if (td.texture) {
                ui.commitComp(this, td.renderData, td.texture, this._assembler, null);
              }
            }
          }
          this.node._static = true;
        };
        _proto.createRenderEntity = function createRenderEntity() {
          return new RenderEntity(RenderEntityType.CROSSED);
        };
        _proto.fillIndicesBuffer = function fillIndicesBuffer(renderData, drawInfo) {
          var iBuf = renderData.chunk.meshBuffer.iData;
          var indexOffset = renderData.chunk.meshBuffer.indexOffset;
          drawInfo.setIndexOffset(indexOffset);
          var vertexId = renderData.chunk.vertexOffset;
          var quadCount = renderData.vertexCount / 4;
          for (var i = 0; i < quadCount; i += 1) {
            iBuf[indexOffset] = vertexId;
            iBuf[indexOffset + 1] = vertexId + 1;
            iBuf[indexOffset + 2] = vertexId + 2;
            iBuf[indexOffset + 3] = vertexId + 2;
            iBuf[indexOffset + 4] = vertexId + 1;
            iBuf[indexOffset + 5] = vertexId + 3;
            indexOffset += 6;
            vertexId += 4;
          }
          renderData.chunk.meshBuffer.indexOffset = indexOffset;
          drawInfo.setIBCount(quadCount * 6);
        };
        _proto.prepareDrawData = function prepareDrawData() {
          var _this3 = this;
          this._drawInfoList.length = 0;
          var entity = this.renderEntity;
          entity.clearDynamicRenderDrawInfos();
          var tiledDataArray = this._tiledDataArray;
          var idx = 0;
          tiledDataArray.forEach(function (m) {
            if (m.subNodes) {
              m.subNodes.forEach(function (c) {
                if (c) {
                  if (!_this3._drawInfoList[idx]) {
                    _this3._drawInfoList[idx] = new RenderDrawInfo();
                  }
                  var drawInfo = _this3._drawInfoList[idx];
                  drawInfo.setDrawInfoType(RenderDrawInfoType.SUB_NODE);
                  drawInfo.setSubNode(c.node);
                  entity.setDynamicRenderDrawInfo(drawInfo, idx);
                  idx++;
                }
              });
            } else {
              var td = m;
              if (td.texture) {
                if (!_this3._drawInfoList[idx]) {
                  _this3._drawInfoList[idx] = new RenderDrawInfo();
                }
                var drawInfo = _this3._drawInfoList[idx];
                td.renderData.fillDrawInfoAttributes(drawInfo);
                drawInfo.setTexture(td.texture.getGFXTexture());
                drawInfo.setSampler(td.texture.getGFXSampler());
                drawInfo.setMaterial(_this3.getRenderMaterial(0));
                _this3.fillIndicesBuffer(td.renderData, drawInfo);
                entity.setDynamicRenderDrawInfo(drawInfo, idx);
                idx++;
              }
            }
          });
        };
        _createClass(TiledLayer, [{
          key: "cullingRect",
          get: function get() {
            return this._cullingRect;
          }
        }, {
          key: "rightTop",
          get: function get() {
            return this._rightTop;
          }
        }, {
          key: "layerSize",
          get: function get() {
            return this._layerSize;
          }
        }, {
          key: "tiledDataArray",
          get: function get() {
            return this._tiledDataArray;
          }
        }, {
          key: "leftDownToCenterX",
          get: function get() {
            return this._leftDownToCenterX;
          }
        }, {
          key: "leftDownToCenterY",
          get: function get() {
            return this._leftDownToCenterY;
          }
        }, {
          key: "enableCulling",
          get: function get() {
            return this._enableCulling;
          },
          set: function set(value) {
            if (this._enableCulling !== value) {
              this._enableCulling = value;
              this._cullingDirty = true;
              this.markForUpdateRenderData();
            }
          }
        }]);
        return TiledLayer;
      }(UIRenderer)) || _class3$e));

      var _dec$n, _dec2$k, _dec3$j, _class$n, _class2$k;
      var TiledObjectGroup = exports('gR', (_dec$n = ccclass$M('cc.TiledObjectGroup'), _dec2$k = requireComponent(UITransform), _dec3$j = type$d(CCBoolean), _dec$n(_class$n = _dec2$k(_class$n = (_class2$k = function (_Component) {
        _inheritsLoose(TiledObjectGroup, _Component);
        function TiledObjectGroup() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._premultiplyAlpha = false;
          _this._groupName = void 0;
          _this._positionOffset = void 0;
          _this._mapInfo = void 0;
          _this._properties = void 0;
          _this._offset = void 0;
          _this._opacity = void 0;
          _this._tintColor = null;
          _this._animations = void 0;
          _this._hasAniObj = void 0;
          _this._texGrids = void 0;
          _this.aniObjects = void 0;
          _this._objects = [];
          return _this;
        }
        var _proto = TiledObjectGroup.prototype;
        _proto.getPositionOffset = function getPositionOffset() {
          return this._positionOffset;
        };
        _proto.getProperties = function getProperties() {
          return this._properties;
        };
        _proto.getGroupName = function getGroupName() {
          return this._groupName;
        };
        _proto.getProperty = function getProperty(propertyName) {
          return this._properties[propertyName.toString()];
        };
        _proto.getObject = function getObject(objectName) {
          for (var i = 0, len = this._objects.length; i < len; i++) {
            var obj = this._objects[i];
            if (obj && obj.name === objectName) {
              return obj;
            }
          }
          return null;
        };
        _proto.getObjects = function getObjects() {
          return this._objects;
        };
        _proto._init = function _init(groupInfo, mapInfo, texGrids) {
          var FLIPPED_MASK = TileFlag.FLIPPED_MASK;
          var FLAG_HORIZONTAL = TileFlag.HORIZONTAL;
          var FLAG_VERTICAL = TileFlag.VERTICAL;
          this._groupName = groupInfo.name;
          this._positionOffset = groupInfo.offset;
          this._mapInfo = mapInfo;
          this._properties = groupInfo.getProperties();
          this._offset = new Vec2(groupInfo.offset.x, -groupInfo.offset.y);
          this._opacity = groupInfo.opacity;
          if (groupInfo.tintColor) {
            this._tintColor = groupInfo.tintColor;
          }
          this._texGrids = texGrids;
          this._animations = mapInfo.getTileAnimations();
          this.aniObjects = [];
          this._hasAniObj = false;
          var mapSize = mapInfo.mapSize;
          var tileSize = mapInfo.tileSize;
          var width = 0;
          var height = 0;
          var colorVal = new Color$1();
          var iso = Orientation.ISO === mapInfo.orientation;
          if (mapInfo.orientation === Orientation.HEX) {
            if (mapInfo.getStaggerAxis() === StaggerAxis.STAGGERAXIS_X) {
              height = tileSize.height * (mapSize.height + 0.5);
              width = (tileSize.width + mapInfo.getHexSideLength()) * Math.floor(mapSize.width / 2) + tileSize.width * (mapSize.width % 2);
            } else {
              width = tileSize.width * (mapSize.width + 0.5);
              height = (tileSize.height + mapInfo.getHexSideLength()) * Math.floor(mapSize.height / 2) + tileSize.height * (mapSize.height % 2);
            }
          } else if (iso) {
            var wh = mapSize.width + mapSize.height;
            width = tileSize.width * 0.5 * wh;
            height = tileSize.height * 0.5 * wh;
          } else {
            width = mapSize.width * tileSize.width;
            height = mapSize.height * tileSize.height;
          }
          var transComp = this.node._uiProps.uiTransformComp;
          transComp.setContentSize(width, height);
          var leftTopX = width * transComp.anchorX;
          var leftTopY = height * (1 - transComp.anchorY);
          var objects = groupInfo.objects;
          var aliveNodes = {};
          for (var i = 0, l = objects.length; i < l; i++) {
            var object = objects[i];
            var objType = object.type;
            object.offset = new Vec2(object.x, object.y);
            var points = object.points || object.polylinePoints;
            if (points) {
              for (var pi = 0; pi < points.length; pi++) {
                points[pi].y *= -1;
              }
            }
            if (iso) {
              var posIdxX = object.x / tileSize.height;
              var posIdxY = object.y / tileSize.height;
              object.x = tileSize.width * 0.5 * (mapSize.height + posIdxX - posIdxY);
              object.y = tileSize.height * 0.5 * (mapSize.width + mapSize.height - posIdxX - posIdxY);
            } else {
              object.y = height - object.y;
            }
            if (objType === TMXObjectType.TEXT) {
              var textName = "text" + object.id;
              aliveNodes[textName] = true;
              var textNode = this.node.getChildByName(textName);
              if (!textNode) {
                textNode = new Node$1();
              }
              textNode.setRotationFromEuler(0, 0, -object.rotation);
              textNode.setPosition(object.x - leftTopX, object.y - leftTopY);
              textNode.name = textName;
              textNode.parent = this.node;
              textNode.setSiblingIndex(i);
              textNode.layer = this.node.layer;
              var label = textNode.getComponent(Label);
              if (!label) {
                label = textNode.addComponent(Label);
              }
              var textTransComp = textNode._uiProps.uiTransformComp;
              textNode.active = object.visible;
              textTransComp.anchorX = 0;
              textTransComp.anchorY = 1;
              if (this._tintColor) {
                colorVal.set(this._tintColor);
                colorVal.a *= this._opacity / 255;
                label.color.set(colorVal);
              } else {
                var c = label.color;
                c.a *= this._opacity / 255;
              }
              label.overflow = Label.Overflow.SHRINK;
              label.lineHeight = object.height;
              label.string = object.text;
              label.horizontalAlign = object.halign;
              label.verticalAlign = object.valign;
              label.fontSize = object.pixelsize;
              textTransComp.setContentSize(object.width, object.height);
            } else if (objType === TMXObjectType.IMAGE) {
              var gid = object.gid;
              var gridGID = (gid & FLIPPED_MASK) >>> 0;
              var grid = texGrids.get(gridGID);
              if (!grid) continue;
              var tileset = grid.tileset;
              var imgName = "img" + object.id;
              aliveNodes[imgName] = true;
              var imgNode = this.node.getChildByName(imgName);
              object.width = object.width || grid.width;
              object.height = object.height || grid.height;
              if (imgNode && imgNode._objFlags & CCObject.Flags.HideInHierarchy) {
                imgNode.removeFromParent();
                imgNode.hideFlags |= CCObject.Flags.DontSave;
                imgNode.destroy();
                imgNode = null;
              }
              if (!imgNode) {
                imgNode = new Node$1();
              }
              if (this._animations.get(gridGID)) {
                this.aniObjects.push({
                  object: object,
                  imgNode: imgNode,
                  gridGID: gridGID
                });
                this._hasAniObj = true;
              }
              var tileOffsetX = tileset.tileOffset.x;
              var tileOffsetY = tileset.tileOffset.y;
              imgNode.active = object.visible;
              imgNode.setRotationFromEuler(0, 0, -object.rotation);
              imgNode.setPosition(object.x - leftTopX, object.y - leftTopY);
              imgNode.name = imgName;
              imgNode.parent = this.node;
              imgNode.setSiblingIndex(i);
              imgNode.layer = this.node.layer;
              var sprite = imgNode.getComponent(Sprite);
              if (!sprite) {
                sprite = imgNode.addComponent(Sprite);
              }
              var imgTrans = imgNode._uiProps.uiTransformComp;
              if (iso) {
                imgTrans.anchorX = 0.5 + tileOffsetX / object.width;
                imgTrans.anchorY = tileOffsetY / object.height;
              } else {
                imgTrans.anchorX = tileOffsetX / object.width;
                imgTrans.anchorY = tileOffsetY / object.height;
              }
              if (this._tintColor) {
                colorVal.set(this._tintColor);
                colorVal.a *= this._opacity / 255;
                sprite.color.set(colorVal);
              } else {
                var _c = sprite.color;
                _c.a *= this._opacity / 255;
              }
              sprite.sizeMode = Sprite.SizeMode.CUSTOM;
              var srcBlendFactor = this._premultiplyAlpha ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
              if (sprite.srcBlendFactor !== srcBlendFactor) {
                sprite.srcBlendFactor = srcBlendFactor;
                if (sprite.material) {
                  sprite._updateBlendFunc();
                }
              }
              var spf = grid.spriteFrame;
              if (!spf) {
                spf = new SpriteFrame();
              } else {
                spf = spf.clone();
              }
              if ((gid & FLAG_HORIZONTAL) >>> 0) {
                spf.flipUVX = !spf.flipUVX;
              }
              if ((gid & FLAG_VERTICAL) >>> 0) {
                spf.flipUVY = !spf.flipUVY;
              }
              spf.rotated = grid._rotated;
              spf.rect = grid._rect;
              sprite.spriteFrame = spf;
              imgTrans.setContentSize(object.width, object.height);
              sprite.markForUpdateRenderData();
            }
          }
          this._objects = objects;
          var children = this.node.children;
          var uselessExp = /^(?:img|text)\d+$/;
          for (var _i = 0, n = children.length; _i < n; _i++) {
            var _c2 = children[_i];
            var cName = _c2.name;
            var isUseless = uselessExp.test(cName);
            if (isUseless && !aliveNodes[cName]) _c2.destroy();
          }
        };
        _proto.update = function update(dt) {
          if (!this._hasAniObj) {
            return;
          }
          var aniObjects = this.aniObjects;
          var _texGrids = this._texGrids;
          var iso = Orientation.ISO === this._mapInfo.orientation;
          for (var i = 0, len = aniObjects.length; i < len; i++) {
            var aniObj = aniObjects[i];
            var gridGID = aniObj.gridGID;
            var grid = _texGrids.get(gridGID);
            if (!grid) {
              continue;
            }
            var tileset = grid.tileset;
            var object = aniObj.object;
            var imgNode = aniObj.imgNode;
            var tileOffsetX = tileset.tileOffset.x;
            var tileOffsetY = tileset.tileOffset.y;
            var imgTrans = imgNode._uiProps.uiTransformComp;
            if (iso) {
              imgTrans.anchorX = 0.5 + tileOffsetX / object.width;
              imgTrans.anchorY = tileOffsetY / object.height;
            } else {
              imgTrans.anchorX = tileOffsetX / object.width;
              imgTrans.anchorY = tileOffsetY / object.height;
            }
            var sp = imgNode.getComponent(Sprite);
            var spf = sp.spriteFrame;
            spf.rotated = grid._rotated;
            spf.rect = grid._rect;
            sp.spriteFrame = spf;
            sp.markForUpdateRenderData();
          }
        };
        _createClass(TiledObjectGroup, [{
          key: "premultiplyAlpha",
          get: function get() {
            return this._premultiplyAlpha;
          },
          set: function set(value) {
            this._premultiplyAlpha = value;
          }
        }, {
          key: "offset",
          get: function get() {
            return this._offset;
          }
        }]);
        return TiledObjectGroup;
      }(Component), (_applyDecoratedDescriptor(_class2$k.prototype, "premultiplyAlpha", [_dec3$j], Object.getOwnPropertyDescriptor(_class2$k.prototype, "premultiplyAlpha"), _class2$k.prototype)), _class2$k)) || _class$n) || _class$n));

      var _dec$m, _dec2$j, _dec3$i, _dec4$d, _dec5$d, _dec6$7, _dec7$5, _dec8$4, _class$m, _class2$j, _initializer$i, _initializer2$h, _initializer3$e, _initializer4$c, _initializer5$a, _initializer6$7, _initializer7$7, _initializer8$7;
      var TiledMapAsset = exports('gO', (_dec$m = ccclass$M('cc.TiledMapAsset'), _dec2$j = type$d([TextAsset]), _dec3$i = type$d([CCString]), _dec4$d = type$d([SpriteFrame]), _dec5$d = type$d([SpriteFrame]), _dec6$7 = type$d([CCString]), _dec7$5 = type$d([CCString]), _dec8$4 = type$d([Size$1]), _dec$m(_class$m = (_class2$j = function (_Asset) {
        _inheritsLoose(TiledMapAsset, _Asset);
        function TiledMapAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.tmxXmlStr = _initializer$i && _initializer$i();
          _this.tsxFiles = _initializer2$h && _initializer2$h();
          _this.tsxFileNames = _initializer3$e && _initializer3$e();
          _this.spriteFrames = _initializer4$c && _initializer4$c();
          _this.imageLayerSpriteFrame = _initializer5$a && _initializer5$a();
          _this.imageLayerSpriteFrameNames = _initializer6$7 && _initializer6$7();
          _this.spriteFrameNames = _initializer7$7 && _initializer7$7();
          _this.spriteFrameSizes = _initializer8$7 && _initializer8$7();
          return _this;
        }
        return TiledMapAsset;
      }(Asset), (_initializer$i = applyDecoratedInitializer(_class2$j.prototype, "tmxXmlStr", [serializable$p], function () {
        return '';
      }), _initializer2$h = applyDecoratedInitializer(_class2$j.prototype, "tsxFiles", [serializable$p, _dec2$j], function () {
        return [];
      }), _initializer3$e = applyDecoratedInitializer(_class2$j.prototype, "tsxFileNames", [serializable$p, _dec3$i], function () {
        return [];
      }), _initializer4$c = applyDecoratedInitializer(_class2$j.prototype, "spriteFrames", [serializable$p, _dec4$d], function () {
        return [];
      }), _initializer5$a = applyDecoratedInitializer(_class2$j.prototype, "imageLayerSpriteFrame", [serializable$p, _dec5$d], function () {
        return [];
      }), _initializer6$7 = applyDecoratedInitializer(_class2$j.prototype, "imageLayerSpriteFrameNames", [serializable$p, _dec6$7], function () {
        return [];
      }), _initializer7$7 = applyDecoratedInitializer(_class2$j.prototype, "spriteFrameNames", [serializable$p, _dec7$5], function () {
        return [];
      }), _initializer8$7 = applyDecoratedInitializer(_class2$j.prototype, "spriteFrameSizes", [serializable$p, _dec8$4], function () {
        return [];
      })), _class2$j)) || _class$m));

      var _dec$l, _dec2$i, _dec3$h, _class$l, _class2$i, _initializer$h, _initializer2$g, _initializer3$d, _class3$d;
      var TiledMap = exports('gN', (_dec$l = ccclass$M('cc.TiledMap'), _dec2$i = requireComponent(UITransform), _dec3$h = type$d(TiledMapAsset), _dec$l(_class$l = _dec2$i(_class$l = (_class2$i = (_class3$d = function (_Component) {
        _inheritsLoose(TiledMap, _Component);
        function TiledMap() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._texGrids = new Map();
          _this._textures = [];
          _this._tilesets = [];
          _this._animations = new Map();
          _this._imageLayers = [];
          _this._layers = [];
          _this._groups = [];
          _this._images = [];
          _this._properties = {};
          _this._tileProperties = new Map();
          _this._mapInfo = null;
          _this._mapSize = new Size$1(0, 0);
          _this._tileSize = new Size$1(0, 0);
          _this._mapOrientation = Orientation.ORTHO;
          _this._isApplied = false;
          _this._tmxFile = _initializer$h && _initializer$h();
          _this._enableCulling = _initializer2$g && _initializer2$g();
          _this.cleanupImageCache = _initializer3$d && _initializer3$d();
          return _this;
        }
        var _proto = TiledMap.prototype;
        _proto.getMapSize = function getMapSize() {
          return this._mapSize;
        };
        _proto.getTileSize = function getTileSize() {
          return this._tileSize;
        };
        _proto.getMapOrientation = function getMapOrientation() {
          return this._mapOrientation;
        };
        _proto.getObjectGroups = function getObjectGroups() {
          return this._groups;
        };
        _proto.getObjectGroup = function getObjectGroup(groupName) {
          var groups = this._groups;
          for (var i = 0, l = groups.length; i < l; i++) {
            var group = groups[i];
            if (group && group.getGroupName() === groupName) {
              return group;
            }
          }
          return null;
        };
        _proto.getProperties = function getProperties() {
          return this._properties;
        };
        _proto.getLayers = function getLayers() {
          return this._layers;
        };
        _proto.getLayer = function getLayer(layerName) {
          var layers = this._layers;
          for (var i = 0, l = layers.length; i < l; i++) {
            var layer = layers[i];
            if (layer && layer.getLayerName() === layerName) {
              return layer;
            }
          }
          return null;
        };
        _proto._changeLayer = function _changeLayer(layerName, replaceLayer) {
          var layers = this._layers;
          for (var i = 0, l = layers.length; i < l; i++) {
            var layer = layers[i];
            if (layer && layer.getLayerName() === layerName) {
              layers[i] = replaceLayer;
              return;
            }
          }
        };
        _proto.getProperty = function getProperty(propertyName) {
          return this._properties[propertyName.toString()];
        };
        _proto.getPropertiesForGID = function getPropertiesForGID(gid) {
          return this._tileProperties.get(gid);
        };
        _proto.__preload = function __preload() {
          if (!this._tmxFile) {
            return;
          }
          if (this._isApplied === false) {
            this._applyFile();
            this._isApplied = true;
          }
        };
        _proto.onEnable = function onEnable() {
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
        };
        _proto.onDisable = function onDisable() {
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
        };
        _proto._applyFile = function _applyFile() {
          var spriteFrames = [];
          var spriteFramesCache = {};
          var file = this._tmxFile;
          if (file) {
            var spfNames = file.spriteFrameNames;
            var spfSizes = file.spriteFrameSizes;
            var fSpriteFrames = file.spriteFrames;
            var spfTexturesMap = {};
            var spfTextureSizeMap = {};
            for (var i = 0; i < spfNames.length; ++i) {
              var texName = spfNames[i];
              spfTextureSizeMap[texName] = spfSizes[i];
              spriteFrames[i] = fSpriteFrames[i];
              var frame = spriteFrames[i];
              if (frame) {
                spriteFramesCache[frame.name] = frame;
                spfTexturesMap[texName] = frame;
              }
            }
            var imageLayerTextures = {};
            var texValues = file.imageLayerSpriteFrame;
            spfNames = file.imageLayerSpriteFrameNames;
            for (var _i = 0; _i < texValues.length; ++_i) {
              imageLayerTextures[spfNames[_i]] = texValues[_i];
            }
            var tsxFileNames = file.tsxFileNames;
            var tsxFiles = file.tsxFiles;
            var tsxContentMap = {};
            for (var _i2 = 0; _i2 < tsxFileNames.length; ++_i2) {
              if (tsxFileNames[_i2].length > 0) {
                tsxContentMap[tsxFileNames[_i2]] = tsxFiles[_i2].text;
              }
            }
            var mapInfo = new TMXMapInfo(file.tmxXmlStr, tsxContentMap, spfTexturesMap, spfTextureSizeMap, imageLayerTextures);
            var tilesets = mapInfo.getTilesets();
            if (!tilesets || tilesets.length === 0) {
              logID(7241);
            }
            this._buildWithMapInfo(mapInfo);
          } else {
            this._releaseMapInfo();
          }
        };
        _proto._releaseMapInfo = function _releaseMapInfo() {
          var layers = this._layers;
          for (var i = 0, l = layers.length; i < l; i++) {
            var _layers$i$node$parent, _layers$i$node$parent2;
            (_layers$i$node$parent = layers[i].node.parent) === null || _layers$i$node$parent === void 0 ? void 0 : _layers$i$node$parent.off(NodeEventType.SIZE_CHANGED, layers[i].updateCulling, layers[i]);
            (_layers$i$node$parent2 = layers[i].node.parent) === null || _layers$i$node$parent2 === void 0 ? void 0 : _layers$i$node$parent2.off(NodeEventType.TRANSFORM_CHANGED, layers[i].updateCulling, layers[i]);
            layers[i].node.removeFromParent();
            layers[i].node.destroy();
          }
          layers.length = 0;
          var groups = this._groups;
          for (var _i3 = 0, _l = groups.length; _i3 < _l; _i3++) {
            groups[_i3].node.removeFromParent();
            groups[_i3].node.destroy();
          }
          groups.length = 0;
          var images = this._images;
          for (var _i4 = 0, _l2 = images.length; _i4 < _l2; _i4++) {
            images[_i4].removeFromParent();
            images[_i4].destroy();
          }
          images.length = 0;
        };
        _proto._syncAnchorPoint = function _syncAnchorPoint() {
          var anchor = this.node._uiProps.uiTransformComp.anchorPoint;
          var leftTopX = this.node._uiProps.uiTransformComp.width * anchor.x;
          var leftTopY = this.node._uiProps.uiTransformComp.height * (1 - anchor.y);
          var i;
          var l;
          for (i = 0, l = this._layers.length; i < l; i++) {
            var layerInfo = this._layers[i];
            var layerNode = layerInfo.node;
            layerNode._uiProps.uiTransformComp.setAnchorPoint(anchor);
          }
          for (i = 0, l = this._groups.length; i < l; i++) {
            var groupInfo = this._groups[i];
            var groupNode = groupInfo.node._uiProps.uiTransformComp;
            groupNode.anchorX = 0.5;
            groupNode.anchorY = 0.5;
            var x = groupInfo.offset.x - leftTopX + groupNode.width * groupNode.anchorX;
            var y = groupInfo.offset.y + leftTopY - groupNode.height * groupNode.anchorY;
            groupInfo.node.setPosition(x, y);
          }
          for (i = 0, l = this._images.length; i < l; i++) {
            var image = this._images[i]._uiProps.uiTransformComp;
            image.anchorX = 0.5;
            image.anchorY = 0.5;
            var _x = this._images[i]._offset.x - leftTopX + image.width * image.anchorX;
            var _y = this._images[i]._offset.y + leftTopY - image.height * image.anchorY;
            this._images[i].setPosition(_x, _y);
          }
        };
        _proto._fillAniGrids = function _fillAniGrids(texGrids, animations) {
          for (var _iterator = _createForOfIteratorHelperLoose(animations.keys()), _step; !(_step = _iterator()).done;) {
            var i = _step.value;
            var animation = animations.get(i);
            if (!animation) continue;
            var frames = animation.frames;
            for (var j = 0; j < frames.length; j++) {
              var frame = frames[j];
              frame.grid = texGrids.get(frame.tileid);
            }
          }
        };
        _proto._buildLayerAndGroup = function _buildLayerAndGroup() {
          var tilesets = this._tilesets;
          var texGrids = this._texGrids;
          var animations = this._animations;
          texGrids.clear();
          for (var i = 0, l = tilesets.length; i < l; ++i) {
            var tilesetInfo = tilesets[i];
            if (!tilesetInfo) continue;
            if (!tilesetInfo.sourceImage) {
              console.warn("Can't find the spriteFrame of tilesets " + i);
              continue;
            }
            fillTextureGrids(tilesetInfo, texGrids, tilesetInfo.sourceImage);
          }
          this._fillAniGrids(texGrids, animations);
          var layers = this._layers;
          var groups = this._groups;
          var images = this._images;
          var oldNodeNames = {};
          for (var _i5 = 0, n = layers.length; _i5 < n; _i5++) {
            oldNodeNames[layers[_i5].node.name] = true;
          }
          for (var _i6 = 0, _n = groups.length; _i6 < _n; _i6++) {
            oldNodeNames[groups[_i6].node.name] = true;
          }
          for (var _i7 = 0, _n2 = images.length; _i7 < _n2; _i7++) {
            oldNodeNames[images[_i7].name] = true;
          }
          layers = this._layers = [];
          groups = this._groups = [];
          images = this._images = [];
          var mapInfo = this._mapInfo;
          var node = this.node;
          var layerInfos = mapInfo.getAllChildren();
          var textures = this._textures;
          var maxWidth = 0;
          var maxHeight = 0;
          if (layerInfos && layerInfos.length > 0) {
            for (var _i8 = 0, len = layerInfos.length; _i8 < len; _i8++) {
              var layerInfo = layerInfos[_i8];
              var name = layerInfo.name;
              var child = this.node.getChildByName(name);
              oldNodeNames[name] = false;
              if (!child) {
                child = new Node$1();
                child.name = name;
                child.layer = node.layer;
                node.addChild(child);
              }
              child.setSiblingIndex(_i8);
              child.active = layerInfo.visible;
              if (layerInfo instanceof TMXLayerInfo) {
                var layer = child.getComponent(TiledLayer);
                if (!layer) {
                  layer = child.addComponent(TiledLayer);
                }
                layer.init(layerInfo, mapInfo, tilesets, textures, texGrids);
                layer.enableCulling = this._enableCulling;
                layerInfo.ownTiles = false;
                layers.push(layer);
              } else if (layerInfo instanceof TMXObjectGroupInfo) {
                var group = child.getComponent(TiledObjectGroup);
                if (!group) {
                  group = child.addComponent(TiledObjectGroup);
                }
                group._init(layerInfo, mapInfo, texGrids);
                groups.push(group);
              } else if (layerInfo instanceof TMXImageLayerInfo) {
                var spriteFrame = layerInfo.sourceImage;
                child.layerInfo = layerInfo;
                child._offset = new Vec2(layerInfo.offset.x, -layerInfo.offset.y);
                var image = child.getComponent(Sprite);
                if (!image) {
                  image = child.addComponent(Sprite);
                }
                var color = image.color;
                color.a *= layerInfo.opacity;
                image.spriteFrame = spriteFrame;
                var width = spriteFrame.width;
                var height = spriteFrame.height;
                if (spriteFrame.original) {
                  width = spriteFrame.originalSize.width;
                  height = spriteFrame.originalSize.height;
                }
                child._uiProps.uiTransformComp.setContentSize(width, height);
                images.push(child);
              }
              maxWidth = Math.max(maxWidth, child._uiProps.uiTransformComp.width);
              maxHeight = Math.max(maxHeight, child._uiProps.uiTransformComp.height);
            }
          }
          var children = node.children;
          for (var _i9 = 0, _n3 = children.length; _i9 < _n3; _i9++) {
            var c = children[_i9];
            if (oldNodeNames[c.name]) {
              c.destroy();
            }
          }
          this.node._uiProps.uiTransformComp.setContentSize(maxWidth, maxHeight);
          this._syncAnchorPoint();
        };
        _proto._buildWithMapInfo = function _buildWithMapInfo(mapInfo) {
          var _this2 = this;
          this._mapInfo = mapInfo;
          this._mapSize = mapInfo.getMapSize();
          this._tileSize = mapInfo.getTileSize();
          this._mapOrientation = mapInfo.orientation;
          this._properties = mapInfo.properties;
          this._tileProperties = mapInfo.getTileProperties();
          this._imageLayers = mapInfo.getImageLayers();
          this._animations = mapInfo.getTileAnimations();
          this._tilesets = mapInfo.getTilesets();
          var tilesets = this._tilesets;
          this._textures.length = 0;
          var totalTextures = [];
          for (var i = 0, l = tilesets.length; i < l; ++i) {
            var tilesetInfo = tilesets[i];
            if (!tilesetInfo || !tilesetInfo.sourceImage) continue;
            this._textures[i] = tilesetInfo.sourceImage;
            totalTextures.push(tilesetInfo.sourceImage);
          }
          for (var _i10 = 0; _i10 < this._imageLayers.length; _i10++) {
            var imageLayer = this._imageLayers[_i10];
            if (!imageLayer || !imageLayer.sourceImage) continue;
            totalTextures.push(imageLayer.sourceImage);
          }
          this._buildLayerAndGroup();
          if (this.cleanupImageCache) {
            this._textures.forEach(function (tex) {
              _this2.doCleanupImageCache(tex);
            });
          }
        };
        _proto.doCleanupImageCache = function doCleanupImageCache(texture) {
          if (texture._image instanceof HTMLImageElement) {
            texture._image.src = '';
          } else if (sys.hasFeature(sys.Feature.IMAGE_BITMAP) && texture._image instanceof ImageBitmap) {
            if (texture._image.close) texture._image.close();
          }
          texture._image = null;
        };
        _proto.lateUpdate = function lateUpdate(dt) {
          var animations = this._animations;
          var texGrids = this._texGrids;
          for (var _iterator2 = _createForOfIteratorHelperLoose(animations.keys()), _step2; !(_step2 = _iterator2()).done;) {
            var aniGID = _step2.value;
            var animation = animations.get(aniGID);
            var frames = animation.frames;
            var frame = frames[animation.frameIdx];
            animation.dt += dt;
            if (frame.duration < animation.dt) {
              animation.dt = 0;
              animation.frameIdx++;
              if (animation.frameIdx >= frames.length) {
                animation.frameIdx = 0;
              }
              frame = frames[animation.frameIdx];
            }
            texGrids.set(aniGID, frame.grid);
          }
          var layers = this.getLayers();
          for (var i = 0, l = layers.length; i < l; i++) {
            var layer = layers[i];
            if (layer.hasAnimation() || layer.node.hasChangedFlags) {
              layer.markForUpdateRenderData();
            }
          }
        };
        _createClass(TiledMap, [{
          key: "tmxAsset",
          get: function get() {
            return this._tmxFile;
          },
          set: function set(value) {
            if (this._tmxFile !== value || EDITOR) {
              this._tmxFile = value;
              this._applyFile();
              this._isApplied = true;
            }
          }
        }, {
          key: "enableCulling",
          get: function get() {
            return this._enableCulling;
          },
          set: function set(value) {
            this._enableCulling = value;
            var layers = this._layers;
            for (var i = 0; i < layers.length; ++i) {
              layers[i].enableCulling = value;
            }
          }
        }]);
        return TiledMap;
      }(Component), _class3$d.Orientation = Orientation, _class3$d.Property = Property, _class3$d.TileFlag = TileFlag, _class3$d.StaggerAxis = StaggerAxis, _class3$d.StaggerIndex = StaggerIndex, _class3$d.TMXObjectType = TMXObjectType, _class3$d.RenderOrder = RenderOrder, _class3$d), (_initializer$h = applyDecoratedInitializer(_class2$i.prototype, "_tmxFile", [serializable$p], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$i.prototype, "tmxAsset", [_dec3$h], Object.getOwnPropertyDescriptor(_class2$i.prototype, "tmxAsset"), _class2$i.prototype), _initializer2$g = applyDecoratedInitializer(_class2$i.prototype, "_enableCulling", [serializable$p], function () {
        return true;
      }), _initializer3$d = applyDecoratedInitializer(_class2$i.prototype, "cleanupImageCache", [serializable$p], function () {
        return true;
      })), _class2$i)) || _class$l) || _class$l));

      var MaxGridsLimit = Math.ceil(65535 / 6);
      var vec3_temps = [];
      for (var i = 0; i < 4; i++) {
        vec3_temps.push(new Vec3());
      }
      var _mat4_temp$2 = new Mat4();
      var _vec3u_temp = new Vec3();
      var _leftDown = {
        row: 0,
        col: 0
      };
      var _uva = {
        x: 0,
        y: 0
      };
      var _uvb = {
        x: 0,
        y: 0
      };
      var _uvc = {
        x: 0,
        y: 0
      };
      var _uvd = {
        x: 0,
        y: 0
      };
      var _vfOffset = 0;
      var _moveX = 0;
      var _moveY = 0;
      var _fillCount = 0;
      var _curTexture = null;
      var _tempBuffers;
      var _curLayer;
      var flipTexture;
      var _accessor = null;
      var simple = {
        ensureAccessor: function ensureAccessor() {
          if (!_accessor) {
            var device = director.root.device;
            director.root.batcher2D;
            _accessor = new StaticVBAccessor(device, vfmtPosUvColor, this.vCount);
            director.on(Director.EVENT_BEFORE_DRAW, function () {
              _accessor.reset();
            });
          }
        },
        createData: function createData(layer) {
        },
        fillBuffers: function fillBuffers(layer, renderer) {
          if (!layer || layer.tiledDataArray.length === 0) return;
          var dataArray = layer.tiledDataArray;
          var data = dataArray[layer._tiledDataArrayIdx];
          var renderData = data.renderData;
          var iBuf = renderData.chunk.meshBuffer.iData;
          var indexOffset = renderData.chunk.meshBuffer.indexOffset;
          var vertexId = renderData.chunk.vertexOffset;
          var quadCount = renderData.vertexCount / 4;
          for (var _i = 0; _i < quadCount; _i += 1) {
            iBuf[indexOffset] = vertexId;
            iBuf[indexOffset + 1] = vertexId + 1;
            iBuf[indexOffset + 2] = vertexId + 2;
            iBuf[indexOffset + 3] = vertexId + 2;
            iBuf[indexOffset + 4] = vertexId + 1;
            iBuf[indexOffset + 5] = vertexId + 3;
            indexOffset += 6;
            vertexId += 4;
          }
          renderData.chunk.meshBuffer.indexOffset = indexOffset;
        },
        updateRenderData: function updateRenderData(comp) {
          comp.updateCulling();
          _moveX = comp.leftDownToCenterX;
          _moveY = comp.leftDownToCenterY;
          if (comp.colorChanged || comp.isCullingDirty() || comp.isUserNodeDirty() || comp.hasAnimation() || comp.hasTiledNode() || comp.node.hasChangedFlags) {
            comp.colorChanged = false;
            comp.destroyRenderData();
            var leftDown;
            var rightTop;
            if (comp.enableCulling) {
              var cullingRect = comp.cullingRect;
              leftDown = cullingRect.leftDown;
              rightTop = cullingRect.rightTop;
            } else {
              leftDown = _leftDown;
              rightTop = comp.rightTop;
            }
            switch (comp.renderOrder) {
              case RenderOrder.RightDown:
                traverseGrids(leftDown, rightTop, -1, 1, comp);
                break;
              case RenderOrder.LeftDown:
                traverseGrids(leftDown, rightTop, -1, -1, comp);
                break;
              case RenderOrder.RightUp:
                traverseGrids(leftDown, rightTop, 1, 1, comp);
                break;
              case RenderOrder.LeftUp:
              default:
                traverseGrids(leftDown, rightTop, 1, -1, comp);
                break;
            }
            comp.setCullingDirty(false);
            comp.setUserNodeDirty(false);
          }
        },
        updateColor: function updateColor(tiled) {
          var color = tiled.color;
          var colorV = new Float32Array(4);
          colorV[0] = color.r / 255;
          colorV[1] = color.g / 255;
          colorV[2] = color.b / 255;
          colorV[3] = color.a / 255;
          var rs = tiled.tiledDataArray;
          for (var _iterator = _createForOfIteratorHelperLoose(rs), _step; !(_step = _iterator()).done;) {
            var r = _step.value;
            if (!r.renderData) continue;
            var renderData = r.renderData;
            var vs = renderData.vData;
            for (var _i2 = renderData.vertexStart, l = renderData.vertexCount; _i2 < l; _i2++) {
              vs.set(colorV, _i2 * 9 + 5);
            }
          }
        }
      };
      function _flipTexture(inGrid, gid) {
        if (inGrid._rotated) {
          _uva.x = inGrid.r;
          _uva.y = inGrid.t;
          _uvb.x = inGrid.l;
          _uvb.y = inGrid.t;
          _uvc.x = inGrid.r;
          _uvc.y = inGrid.b;
          _uvd.x = inGrid.l;
          _uvd.y = inGrid.b;
        } else {
          _uva.x = inGrid.l;
          _uva.y = inGrid.t;
          _uvb.x = inGrid.l;
          _uvb.y = inGrid.b;
          _uvc.x = inGrid.r;
          _uvc.y = inGrid.t;
          _uvd.x = inGrid.r;
          _uvd.y = inGrid.b;
        }
        var tempVal;
        if ((gid & TileFlag.DIAGONAL) >>> 0) {
          tempVal = _uvb;
          _uvb = _uvc;
          _uvc = tempVal;
        }
        if ((gid & TileFlag.HORIZONTAL) >>> 0) {
          tempVal = _uva;
          _uva = _uvc;
          _uvc = tempVal;
          tempVal = _uvb;
          _uvb = _uvd;
          _uvd = tempVal;
        }
        if ((gid & TileFlag.VERTICAL) >>> 0) {
          tempVal = _uva;
          _uva = _uvb;
          _uvb = tempVal;
          tempVal = _uvc;
          _uvc = _uvd;
          _uvd = tempVal;
        }
      }
      function packRenderData() {
        if (_fillCount < 1 || !_curTexture) return;
        var vbCount = 4 * _fillCount;
        var ibCount = 6 * _fillCount;
        var tiledData = _curLayer.requestTiledRenderData();
        {
          tiledData.renderData = RenderData.add(vfmtPosUvColor);
        }
        tiledData.texture = _curTexture;
        var rd = tiledData.renderData;
        rd.resize(vbCount, ibCount);
        var vb = rd.chunk.vb;
        vb.set(_tempBuffers.subarray(0, vbCount * 9), 0);
        _fillCount = 0;
        _curTexture = null;
      }
      function traverseGrids(leftDown, rightTop, rowMoveDir, colMoveDir, comp) {
        if (rightTop.row < 0 || rightTop.col < 0) return;
        _curLayer = comp;
        var matrix = comp.node.worldMatrix;
        _vfOffset = 0;
        var tiledTiles = comp.tiledTiles;
        var texGrids = comp.texGrids;
        var tiles = comp.tiles;
        var vertStep = 9;
        var vertStep2 = vertStep * 2;
        var vertStep3 = vertStep * 3;
        var vertices = comp.vertices;
        var rowData;
        var col;
        var cols;
        var row;
        var rows;
        var colData;
        var tileSize;
        var grid;
        var gid = 0;
        var left = 0;
        var bottom = 0;
        var right = 0;
        var top = 0;
        var tiledNode;
        var colNodesCount = 0;
        var isCheckColRange = true;
        var diamondTile = false;
        flipTexture = _flipTexture;
        var color = new Float32Array(4);
        color[0] = comp.color.r / 255;
        color[1] = comp.color.g / 255;
        color[2] = comp.color.b / 255;
        color[3] = comp.color.a / 255;
        if (rowMoveDir === -1) {
          row = rightTop.row;
          rows = leftDown.row;
        } else {
          row = leftDown.row;
          rows = rightTop.row;
        }
        var _tempRows = Math.abs(leftDown.row - rightTop.row) + 1;
        var _tempClos = Math.abs(rightTop.col - leftDown.col) + 1;
        _tempBuffers = new Float32Array(_tempRows * _tempClos * 9 * 4);
        _fillCount = 0;
        var vertexBuf = _tempBuffers;
        for (; (rows - row) * rowMoveDir >= 0; row += rowMoveDir) {
          rowData = vertices[row];
          colNodesCount = comp.getNodesCountByRow(row);
          isCheckColRange = rowData && colNodesCount === 0;
          if (colMoveDir === 1) {
            col = isCheckColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col;
            cols = isCheckColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col;
          } else {
            col = isCheckColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col;
            cols = isCheckColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col;
          }
          for (; (cols - col) * colMoveDir >= 0; col += colMoveDir) {
            colData = rowData && rowData[col];
            if (colNodesCount > 0) {
              packRenderData();
              var nodes = comp.requestSubNodesData();
              var celData = comp.getNodesByRowCol(row, col);
              if (celData && celData.count > 0) {
                nodes.subNodes = celData.list;
              }
            }
            if (!colData) {
              continue;
            }
            gid = tiles[colData.index];
            grid = texGrids.get((gid & TileFlag.FLIPPED_MASK) >>> 0);
            if (!grid) continue;
            if (_curTexture !== grid.texture) {
              packRenderData();
              _curTexture = grid.texture;
            }
            tileSize = grid.tileset._tileSize;
            left = colData.left - _moveX;
            bottom = colData.bottom - _moveY;
            right = left + tileSize.width;
            top = bottom + tileSize.height;
            tiledNode = tiledTiles[colData.index];
            _vfOffset = _fillCount * 4 * 9;
            if (!tiledNode) {
              {
                vec3_temps[0].x = left;
                vec3_temps[0].y = top;
                vec3_temps[1].x = left;
                vec3_temps[1].y = bottom;
                vec3_temps[2].x = right;
                vec3_temps[2].y = top;
                vec3_temps[3].x = right;
                vec3_temps[3].y = bottom;
              }
              vec3_temps[0].transformMat4(matrix);
              vertexBuf[_vfOffset] = vec3_temps[0].x;
              vertexBuf[_vfOffset + 1] = vec3_temps[0].y;
              vertexBuf[_vfOffset + 2] = vec3_temps[0].z;
              vec3_temps[1].transformMat4(matrix);
              vertexBuf[_vfOffset + vertStep] = vec3_temps[1].x;
              vertexBuf[_vfOffset + vertStep + 1] = vec3_temps[1].y;
              vertexBuf[_vfOffset + vertStep + 2] = vec3_temps[1].z;
              vec3_temps[2].transformMat4(matrix);
              vertexBuf[_vfOffset + vertStep2] = vec3_temps[2].x;
              vertexBuf[_vfOffset + vertStep2 + 1] = vec3_temps[2].y;
              vertexBuf[_vfOffset + vertStep2 + 2] = vec3_temps[2].z;
              vec3_temps[3].transformMat4(matrix);
              vertexBuf[_vfOffset + vertStep3] = vec3_temps[3].x;
              vertexBuf[_vfOffset + vertStep3 + 1] = vec3_temps[3].y;
              vertexBuf[_vfOffset + vertStep3 + 2] = vec3_temps[3].z;
              vertexBuf.set(color, _vfOffset + 5);
              vertexBuf.set(color, _vfOffset + vertStep + 5);
              vertexBuf.set(color, _vfOffset + vertStep2 + 5);
              vertexBuf.set(color, _vfOffset + vertStep3 + 5);
            } else if (tiledNode.node.active) {
              fillByTiledNode(tiledNode.node, color, vertexBuf, left, right, top, bottom, diamondTile);
            }
            flipTexture(grid, gid);
            vertexBuf[_vfOffset + 3] = _uva.x;
            vertexBuf[_vfOffset + 4] = _uva.y;
            vertexBuf[_vfOffset + vertStep + 3] = _uvb.x;
            vertexBuf[_vfOffset + vertStep + 4] = _uvb.y;
            vertexBuf[_vfOffset + vertStep2 + 3] = _uvc.x;
            vertexBuf[_vfOffset + vertStep2 + 4] = _uvc.y;
            vertexBuf[_vfOffset + vertStep3 + 3] = _uvd.x;
            vertexBuf[_vfOffset + vertStep3 + 4] = _uvd.y;
            _fillCount++;
            if (_fillCount >= MaxGridsLimit) {
              packRenderData();
            }
          }
        }
        packRenderData();
      }
      function fillByTiledNode(tiledNode, color, vbuf, left, right, top, bottom, diamondTile) {
        var vertStep = 9;
        var vertStep2 = vertStep * 2;
        var vertStep3 = vertStep * 3;
        tiledNode.updateWorldTransform();
        Mat4.fromRTS(_mat4_temp$2, tiledNode.rotation, tiledNode.position, tiledNode.scale);
        Vec3.set(_vec3u_temp, -(left + _moveX), -(bottom + _moveY), 0);
        Mat4.transform(_mat4_temp$2, _mat4_temp$2, _vec3u_temp);
        Mat4.multiply(_mat4_temp$2, tiledNode.parent.worldMatrix, _mat4_temp$2);
        var m = _mat4_temp$2;
        var tx = m.m12;
        var ty = m.m13;
        var a = m.m00;
        var b = m.m01;
        var c = m.m04;
        var d = m.m05;
        var justTranslate = a === 1 && b === 0 && c === 0 && d === 1;
        if (diamondTile) {
          var centerX = (left + right) / 2;
          var centerY = (top + bottom) / 2;
          if (justTranslate) {
            vbuf[_vfOffset] = centerX + tx;
            vbuf[_vfOffset + 1] = top + ty;
            vbuf[_vfOffset + vertStep] = left + tx;
            vbuf[_vfOffset + vertStep + 1] = centerY + ty;
            vbuf[_vfOffset + vertStep2] = right + tx;
            vbuf[_vfOffset + vertStep2 + 1] = centerY + ty;
            vbuf[_vfOffset + vertStep3] = centerX + tx;
            vbuf[_vfOffset + vertStep3 + 1] = bottom + ty;
          } else {
            vbuf[_vfOffset] = centerX * a + top * c + tx;
            vbuf[_vfOffset + 1] = centerX * b + top * d + ty;
            vbuf[_vfOffset + vertStep] = left * a + centerY * c + tx;
            vbuf[_vfOffset + vertStep + 1] = left * b + centerY * d + ty;
            vbuf[_vfOffset + vertStep2] = right * a + centerY * c + tx;
            vbuf[_vfOffset + vertStep2 + 1] = right * b + centerY * d + ty;
            vbuf[_vfOffset + vertStep3] = centerX * a + bottom * c + tx;
            vbuf[_vfOffset + vertStep3 + 1] = centerX * b + bottom * d + ty;
          }
        } else if (justTranslate) {
          vbuf[_vfOffset] = left + tx;
          vbuf[_vfOffset + 1] = top + ty;
          vbuf[_vfOffset + vertStep] = left + tx;
          vbuf[_vfOffset + vertStep + 1] = bottom + ty;
          vbuf[_vfOffset + vertStep2] = right + tx;
          vbuf[_vfOffset + vertStep2 + 1] = top + ty;
          vbuf[_vfOffset + vertStep3] = right + tx;
          vbuf[_vfOffset + vertStep3 + 1] = bottom + ty;
        } else {
          vbuf[_vfOffset] = left * a + top * c + tx;
          vbuf[_vfOffset + 1] = left * b + top * d + ty;
          vbuf[_vfOffset + vertStep] = left * a + bottom * c + tx;
          vbuf[_vfOffset + vertStep + 1] = left * b + bottom * d + ty;
          vbuf[_vfOffset + vertStep2] = right * a + top * c + tx;
          vbuf[_vfOffset + vertStep2 + 1] = right * b + top * d + ty;
          vbuf[_vfOffset + vertStep3] = right * a + bottom * c + tx;
          vbuf[_vfOffset + vertStep3 + 1] = right * b + bottom * d + ty;
        }
        vbuf.set(color, _vfOffset + 5);
        vbuf.set(color, _vfOffset + vertStep + 5);
        vbuf.set(color, _vfOffset + vertStep2 + 5);
        vbuf.set(color, _vfOffset + vertStep3 + 5);
      }

      var tiledLayerAssembler = exports('gT', {
        getAssembler: function getAssembler() {
          return simple;
        }
      });
      TiledLayer.Assembler = tiledLayerAssembler;

      var Action = function () {
        function Action() {
          this.originalTarget = null;
          this.target = null;
          this.tag = Action.TAG_INVALID;
        }
        var _proto = Action.prototype;
        _proto.clone = function clone() {
          var action = new Action();
          action.originalTarget = null;
          action.target = null;
          action.tag = this.tag;
          return action;
        };
        _proto.isDone = function isDone() {
          return true;
        };
        _proto.startWithTarget = function startWithTarget(target) {
          this.originalTarget = target;
          this.target = target;
        };
        _proto.stop = function stop() {
          this.target = null;
        };
        _proto.step = function step(dt) {
          logID(1006);
        };
        _proto.update = function update(dt) {
          logID(1007);
        };
        _proto.getTarget = function getTarget() {
          return this.target;
        };
        _proto.setTarget = function setTarget(target) {
          this.target = target;
        };
        _proto.getOriginalTarget = function getOriginalTarget() {
          return this.originalTarget;
        };
        _proto.setOriginalTarget = function setOriginalTarget(originalTarget) {
          this.originalTarget = originalTarget;
        };
        _proto.getTag = function getTag() {
          return this.tag;
        };
        _proto.setTag = function setTag(tag) {
          this.tag = tag;
        };
        _proto.reverse = function reverse() {
          logID(1008);
          return null;
        };
        _proto.retain = function retain() {};
        _proto.release = function release() {};
        return Action;
      }();
      Action.TAG_INVALID = -1;
      var FiniteTimeAction = function (_Action) {
        _inheritsLoose(FiniteTimeAction, _Action);
        function FiniteTimeAction() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Action.call.apply(_Action, [this].concat(args)) || this;
          _this._duration = 0;
          _this._timesForRepeat = 1;
          return _this;
        }
        var _proto2 = FiniteTimeAction.prototype;
        _proto2.getDuration = function getDuration() {
          return this._duration * (this._timesForRepeat || 1);
        };
        _proto2.setDuration = function setDuration(duration) {
          this._duration = duration;
        };
        _proto2.clone = function clone() {
          return new FiniteTimeAction();
        };
        return FiniteTimeAction;
      }(Action);
      (function (_Action2) {
        _inheritsLoose(Speed, _Action2);
        function Speed(action, speed) {
          var _this2;
          if (speed === void 0) {
            speed = 1;
          }
          _this2 = _Action2.call(this) || this;
          _this2._speed = 0;
          _this2._innerAction = null;
          action && _this2.initWithAction(action, speed);
          return _this2;
        }
        var _proto3 = Speed.prototype;
        _proto3.getSpeed = function getSpeed() {
          return this._speed;
        };
        _proto3.setSpeed = function setSpeed(speed) {
          this._speed = speed;
        };
        _proto3.initWithAction = function initWithAction(action, speed) {
          if (!action) {
            errorID(1021);
            return false;
          }
          this._innerAction = action;
          this._speed = speed;
          return true;
        };
        _proto3.clone = function clone() {
          var action = new Speed();
          action.initWithAction(this._innerAction.clone(), this._speed);
          return action;
        };
        _proto3.startWithTarget = function startWithTarget(target) {
          Action.prototype.startWithTarget.call(this, target);
          this._innerAction.startWithTarget(target);
        };
        _proto3.stop = function stop() {
          this._innerAction.stop();
          Action.prototype.stop.call(this);
        };
        _proto3.step = function step(dt) {
          this._innerAction.step(dt * this._speed);
        };
        _proto3.isDone = function isDone() {
          return this._innerAction.isDone();
        };
        _proto3.reverse = function reverse() {
          return new Speed(this._innerAction.reverse(), this._speed);
        };
        _proto3.setInnerAction = function setInnerAction(action) {
          if (this._innerAction !== action) {
            this._innerAction = action;
          }
        };
        _proto3.getInnerAction = function getInnerAction() {
          return this._innerAction;
        };
        return Speed;
      })(Action);

      var ID_COUNTER = 0;
      var HashElement = function HashElement() {
        this.actions = [];
        this.target = null;
        this.actionIndex = 0;
        this.currentAction = null;
        this.paused = false;
        this.lock = false;
      };
      var ActionManager = function () {
        function ActionManager() {
          this._hashTargets = new Map();
          this._arrayTargets = [];
          this._currentTarget = void 0;
          this._elementPool = [];
        }
        var _proto = ActionManager.prototype;
        _proto._searchElementByTarget = function _searchElementByTarget(arr, target) {
          for (var k = 0; k < arr.length; k++) {
            if (target === arr[k].target) return arr[k];
          }
          return null;
        };
        _proto._getElement = function _getElement(target, paused) {
          var element = this._elementPool.pop();
          if (!element) {
            element = new HashElement();
          }
          element.target = target;
          element.paused = !!paused;
          return element;
        };
        _proto._putElement = function _putElement(element) {
          element.actions.length = 0;
          element.actionIndex = 0;
          element.currentAction = null;
          element.paused = false;
          element.target = null;
          element.lock = false;
          this._elementPool.push(element);
        };
        _proto.addAction = function addAction(action, target, paused) {
          if (!action || !target) {
            errorID(1000);
            return;
          }
          if (target.uuid == null) {
            target.uuid = "_TWEEN_UUID_" + ID_COUNTER++;
          }
          var element = this._hashTargets.get(target);
          if (!element) {
            element = this._getElement(target, paused);
            this._hashTargets.set(target, element);
            this._arrayTargets.push(element);
          } else if (!element.actions) {
            element.actions = [];
          }
          element.target = target;
          element.actions.push(action);
          action.startWithTarget(target);
        };
        _proto.removeAllActions = function removeAllActions() {
          var locTargets = this._arrayTargets;
          for (var i = 0; i < locTargets.length; i++) {
            var element = locTargets[i];
            if (element) this._putElement(element);
          }
          this._arrayTargets.length = 0;
          this._hashTargets = new Map();
        };
        _proto.removeAllActionsFromTarget = function removeAllActionsFromTarget(target) {
          if (target == null) return;
          var element = this._hashTargets.get(target);
          if (element) {
            element.actions.length = 0;
            this._deleteHashElement(element);
          }
        };
        _proto.removeAction = function removeAction(action) {
          if (action == null) return;
          var target = action.getOriginalTarget();
          var element = this._hashTargets.get(target);
          if (element) {
            for (var i = 0; i < element.actions.length; i++) {
              if (element.actions[i] === action) {
                element.actions.splice(i, 1);
                if (element.actionIndex >= i) element.actionIndex--;
                break;
              }
            }
          }
        };
        _proto._removeActionByTag = function _removeActionByTag(tag, element, target) {
          for (var i = 0, l = element.actions.length; i < l; ++i) {
            var action = element.actions[i];
            if (action && action.getTag() === tag) {
              if (target && action.getOriginalTarget() !== target) {
                continue;
              }
              this._removeActionAtIndex(i, element);
              break;
            }
          }
        };
        _proto._removeAllActionsByTag = function _removeAllActionsByTag(tag, element, target) {
          for (var i = element.actions.length - 1; i >= 0; --i) {
            var action = element.actions[i];
            if (action && action.getTag() === tag) {
              if (target && action.getOriginalTarget() !== target) {
                continue;
              }
              this._removeActionAtIndex(i, element);
            }
          }
        };
        _proto.removeActionByTag = function removeActionByTag(tag, target) {
          var _this = this;
          if (tag === Action.TAG_INVALID) logID(1002);
          var hashTargets = this._hashTargets;
          if (target) {
            var element = hashTargets.get(target);
            if (element) {
              this._removeActionByTag(tag, element, target);
            }
          } else {
            hashTargets.forEach(function (element) {
              _this._removeActionByTag(tag, element);
            });
          }
        };
        _proto.removeAllActionsByTag = function removeAllActionsByTag(tag, target) {
          var _this2 = this;
          if (tag === Action.TAG_INVALID) logID(1002);
          var hashTargets = this._hashTargets;
          if (target) {
            var element = hashTargets.get(target);
            if (element) {
              this._removeAllActionsByTag(tag, element, target);
            }
          } else {
            hashTargets.forEach(function (element) {
              _this2._removeAllActionsByTag(tag, element);
            });
          }
        };
        _proto.getActionByTag = function getActionByTag(tag, target) {
          if (tag === Action.TAG_INVALID) logID(1004);
          var element = this._hashTargets.get(target);
          if (element) {
            if (element.actions != null) {
              for (var i = 0; i < element.actions.length; ++i) {
                var action = element.actions[i];
                if (action && action.getTag() === tag) {
                  return action;
                }
              }
            }
            logID(1005, tag);
          }
          return null;
        };
        _proto.getNumberOfRunningActionsInTarget = function getNumberOfRunningActionsInTarget(target) {
          var element = this._hashTargets.get(target);
          if (element) {
            return element.actions ? element.actions.length : 0;
          }
          return 0;
        };
        _proto.pauseTarget = function pauseTarget(target) {
          var element = this._hashTargets.get(target);
          if (element) element.paused = true;
        };
        _proto.resumeTarget = function resumeTarget(target) {
          var element = this._hashTargets.get(target);
          if (element) element.paused = false;
        };
        _proto.pauseAllRunningActions = function pauseAllRunningActions() {
          var idsWithActions = [];
          var locTargets = this._arrayTargets;
          for (var i = 0; i < locTargets.length; i++) {
            var element = locTargets[i];
            if (element && !element.paused) {
              element.paused = true;
              idsWithActions.push(element.target);
            }
          }
          return idsWithActions;
        };
        _proto.resumeTargets = function resumeTargets(targetsToResume) {
          if (!targetsToResume) return;
          for (var i = 0; i < targetsToResume.length; i++) {
            if (targetsToResume[i]) this.resumeTarget(targetsToResume[i]);
          }
        };
        _proto.pauseTargets = function pauseTargets(targetsToPause) {
          if (!targetsToPause) return;
          for (var i = 0; i < targetsToPause.length; i++) {
            if (targetsToPause[i]) this.pauseTarget(targetsToPause[i]);
          }
        };
        _proto.purgeSharedManager = function purgeSharedManager() {
          legacyCC.director.getScheduler().unscheduleUpdate(this);
        };
        _proto._removeActionAtIndex = function _removeActionAtIndex(index, element) {
          element.actions[index];
          element.actions.splice(index, 1);
          if (element.actionIndex >= index) element.actionIndex--;
          if (element.actions.length === 0) {
            this._deleteHashElement(element);
          }
        };
        _proto._deleteHashElement = function _deleteHashElement(element) {
          var ret = false;
          if (element && !element.lock) {
            if (this._hashTargets.get(element.target)) {
              this._hashTargets["delete"](element.target);
              var targets = this._arrayTargets;
              for (var i = 0, l = targets.length; i < l; i++) {
                if (targets[i] === element) {
                  targets.splice(i, 1);
                  break;
                }
              }
              this._putElement(element);
              ret = true;
            }
          }
          return ret;
        };
        _proto.update = function update(dt) {
          var locTargets = this._arrayTargets;
          var locCurrTarget;
          for (var elt = 0; elt < locTargets.length; elt++) {
            this._currentTarget = locTargets[elt];
            locCurrTarget = this._currentTarget;
            var target = locCurrTarget.target;
            if (isCCObject(target) && !target.isValid) {
              this.removeAllActionsFromTarget(target);
              elt--;
              continue;
            }
            if (!locCurrTarget.paused && locCurrTarget.actions) {
              locCurrTarget.lock = true;
              for (locCurrTarget.actionIndex = 0; locCurrTarget.actionIndex < locCurrTarget.actions.length; locCurrTarget.actionIndex++) {
                locCurrTarget.currentAction = locCurrTarget.actions[locCurrTarget.actionIndex];
                if (!locCurrTarget.currentAction) continue;
                locCurrTarget.currentAction.step(dt * (this._isActionInternal(locCurrTarget.currentAction) ? locCurrTarget.currentAction.getSpeed() : 1));
                if (locCurrTarget.currentAction && locCurrTarget.currentAction.isDone()) {
                  locCurrTarget.currentAction.stop();
                  var action = locCurrTarget.currentAction;
                  locCurrTarget.currentAction = null;
                  this.removeAction(action);
                }
                locCurrTarget.currentAction = null;
              }
              locCurrTarget.lock = false;
            }
            if (locCurrTarget.actions.length === 0) {
              if (this._deleteHashElement(locCurrTarget)) {
                elt--;
              }
            }
          }
        };
        _proto._isActionInternal = function _isActionInternal(action) {
          return typeof action._speedMethod !== 'undefined';
        };
        return ActionManager;
      }();

      var TweenSystem = exports('gU', function (_System) {
        _inheritsLoose(TweenSystem, _System);
        function TweenSystem() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _System.call.apply(_System, [this].concat(args)) || this;
          _this.actionMgr = new ActionManager();
          return _this;
        }
        var _proto = TweenSystem.prototype;
        _proto.update = function update(dt) {
          {
            this.actionMgr.update(dt);
          }
        };
        _createClass(TweenSystem, [{
          key: "ActionManager",
          get: function get() {
            return this.actionMgr;
          }
        }]);
        return TweenSystem;
      }(System));
      TweenSystem.ID = 'TWEEN';
      TweenSystem.instance = void 0;
      director.on(Director.EVENT_INIT, function () {
        var sys = new TweenSystem();
        TweenSystem.instance = sys;
        director.registerSystem(TweenSystem.ID, sys, System.Priority.MEDIUM);
      });

      var ActionInstant = function (_FiniteTimeAction) {
        _inheritsLoose(ActionInstant, _FiniteTimeAction);
        function ActionInstant() {
          return _FiniteTimeAction.apply(this, arguments) || this;
        }
        var _proto = ActionInstant.prototype;
        _proto.isDone = function isDone() {
          return true;
        };
        _proto.step = function step(dt) {
          this.update(1);
        };
        _proto.update = function update(dt) {};
        _proto.reverse = function reverse() {
          return this.clone();
        };
        _proto.clone = function clone() {
          return new ActionInstant();
        };
        return ActionInstant;
      }(FiniteTimeAction);
      var Show = function (_ActionInstant) {
        _inheritsLoose(Show, _ActionInstant);
        function Show() {
          return _ActionInstant.apply(this, arguments) || this;
        }
        var _proto2 = Show.prototype;
        _proto2.update = function update(dt) {
          var _renderComps = this.target.getComponentsInChildren(Renderer);
          for (var i = 0; i < _renderComps.length; ++i) {
            var render = _renderComps[i];
            render.enabled = true;
          }
        };
        _proto2.reverse = function reverse() {
          return new Hide();
        };
        _proto2.clone = function clone() {
          return new Show();
        };
        return Show;
      }(ActionInstant);
      function show() {
        return new Show();
      }
      var Hide = function (_ActionInstant2) {
        _inheritsLoose(Hide, _ActionInstant2);
        function Hide() {
          return _ActionInstant2.apply(this, arguments) || this;
        }
        var _proto3 = Hide.prototype;
        _proto3.update = function update(dt) {
          var _renderComps = this.target.getComponentsInChildren(Renderer);
          for (var i = 0; i < _renderComps.length; ++i) {
            var render = _renderComps[i];
            render.enabled = false;
          }
        };
        _proto3.reverse = function reverse() {
          return new Show();
        };
        _proto3.clone = function clone() {
          return new Hide();
        };
        return Hide;
      }(ActionInstant);
      function hide() {
        return new Hide();
      }
      (function (_ActionInstant3) {
        _inheritsLoose(ToggleVisibility, _ActionInstant3);
        function ToggleVisibility() {
          return _ActionInstant3.apply(this, arguments) || this;
        }
        var _proto4 = ToggleVisibility.prototype;
        _proto4.update = function update(dt) {
          var _renderComps = this.target.getComponentsInChildren(Renderer);
          for (var i = 0; i < _renderComps.length; ++i) {
            var render = _renderComps[i];
            render.enabled = !render.enabled;
          }
        };
        _proto4.reverse = function reverse() {
          return new ToggleVisibility();
        };
        _proto4.clone = function clone() {
          return new ToggleVisibility();
        };
        return ToggleVisibility;
      })(ActionInstant);
      var RemoveSelf = function (_ActionInstant4) {
        _inheritsLoose(RemoveSelf, _ActionInstant4);
        function RemoveSelf(isNeedCleanUp) {
          var _this;
          _this = _ActionInstant4.call(this) || this;
          _this._isNeedCleanUp = true;
          isNeedCleanUp !== undefined && _this.init(isNeedCleanUp);
          return _this;
        }
        var _proto5 = RemoveSelf.prototype;
        _proto5.update = function update(dt) {
          this.target.removeFromParent();
          if (this._isNeedCleanUp) {
            this.target.destroy();
          }
        };
        _proto5.init = function init(isNeedCleanUp) {
          this._isNeedCleanUp = isNeedCleanUp;
          return true;
        };
        _proto5.reverse = function reverse() {
          return new RemoveSelf(this._isNeedCleanUp);
        };
        _proto5.clone = function clone() {
          return new RemoveSelf(this._isNeedCleanUp);
        };
        return RemoveSelf;
      }(ActionInstant);
      function removeSelf(isNeedCleanUp) {
        return new RemoveSelf(isNeedCleanUp);
      }
      var CallFunc = function (_ActionInstant5) {
        _inheritsLoose(CallFunc, _ActionInstant5);
        function CallFunc(selector, selectorTarget, data) {
          var _this2;
          _this2 = _ActionInstant5.call(this) || this;
          _this2._selectorTarget = null;
          _this2._function = null;
          _this2._data = null;
          _this2.initWithFunction(selector, selectorTarget, data);
          return _this2;
        }
        var _proto6 = CallFunc.prototype;
        _proto6.initWithFunction = function initWithFunction(selector, selectorTarget, data) {
          if (selector) {
            this._function = selector;
          }
          if (selectorTarget) {
            this._selectorTarget = selectorTarget;
          }
          if (data !== undefined) {
            this._data = data;
          }
          return true;
        };
        _proto6.execute = function execute() {
          if (this._function) {
            this._function.call(this._selectorTarget, this.target, this._data);
          }
        };
        _proto6.update = function update(dt) {
          this.execute();
        };
        _proto6.getTargetCallback = function getTargetCallback() {
          return this._selectorTarget;
        };
        _proto6.setTargetCallback = function setTargetCallback(sel) {
          if (sel !== this._selectorTarget) {
            if (this._selectorTarget) {
              this._selectorTarget = null;
            }
            this._selectorTarget = sel;
          }
        };
        _proto6.clone = function clone() {
          var action = new CallFunc();
          action.initWithFunction(this._function, this._selectorTarget, this._data);
          return action;
        };
        return CallFunc;
      }(ActionInstant);
      function callFunc(selector, selectorTarget, data) {
        return new CallFunc(selector, selectorTarget, data);
      }

      var _class2$h, _class5;
      var ActionInterval = function (_FiniteTimeAction) {
        _inheritsLoose(ActionInterval, _FiniteTimeAction);
        function ActionInterval(d) {
          var _this;
          _this = _FiniteTimeAction.call(this) || this;
          _this.MAX_VALUE = 2;
          _this._elapsed = 0;
          _this._firstTick = false;
          _this._easeList = [];
          _this._speed = 1;
          _this._repeatForever = false;
          _this._repeatMethod = false;
          _this._speedMethod = false;
          if (d !== undefined && !Number.isNaN(d)) {
            _this.initWithDuration(d);
          }
          return _this;
        }
        var _proto = ActionInterval.prototype;
        _proto.getElapsed = function getElapsed() {
          return this._elapsed;
        };
        _proto.initWithDuration = function initWithDuration(d) {
          this._duration = d === 0 ? macro.FLT_EPSILON : d;
          this._elapsed = 0;
          this._firstTick = true;
          return true;
        };
        _proto.isDone = function isDone() {
          return this._elapsed >= this._duration;
        };
        _proto._cloneDecoration = function _cloneDecoration(action) {
          action._repeatForever = this._repeatForever;
          action._speed = this._speed;
          action._timesForRepeat = this._timesForRepeat;
          action._easeList = this._easeList;
          action._speedMethod = this._speedMethod;
          action._repeatMethod = this._repeatMethod;
        };
        _proto._reverseEaseList = function _reverseEaseList(action) {
          if (this._easeList) {
            action._easeList = [];
            for (var i = 0; i < this._easeList.length; i++) {
              action._easeList.push(this._easeList[i]);
            }
          }
        };
        _proto.clone = function clone() {
          var action = new ActionInterval(this._duration);
          this._cloneDecoration(action);
          return action;
        };
        _proto.easing = function easing(easeObj) {
          if (this._easeList) this._easeList.length = 0;else this._easeList = [];
          for (var i = 0; i < arguments.length; i++) this._easeList.push(arguments[i]);
          return this;
        };
        _proto._computeEaseTime = function _computeEaseTime(dt) {
          return dt;
        };
        _proto.step = function step(dt) {
          if (this._firstTick) {
            this._firstTick = false;
            this._elapsed = 0;
          } else this._elapsed += dt;
          var t = this._elapsed / (this._duration > 0.0000001192092896 ? this._duration : 0.0000001192092896);
          t = t < 1 ? t : 1;
          this.update(t > 0 ? t : 0);
          if (this._repeatMethod && this._timesForRepeat > 1 && this.isDone()) {
            if (!this._repeatForever) {
              this._timesForRepeat--;
            }
            this.startWithTarget(this.target);
            this.step(this._elapsed - this._duration);
          }
        };
        _proto.startWithTarget = function startWithTarget(target) {
          Action.prototype.startWithTarget.call(this, target);
          this._elapsed = 0;
          this._firstTick = true;
        };
        _proto.reverse = function reverse() {
          logID(1010);
          return this;
        };
        _proto.setAmplitudeRate = function setAmplitudeRate(amp) {
          logID(1011);
        };
        _proto.getAmplitudeRate = function getAmplitudeRate() {
          logID(1012);
          return 0;
        };
        _proto.speed = function speed(_speed) {
          if (_speed <= 0) {
            logID(1013);
            return this;
          }
          this._speedMethod = true;
          this._speed *= _speed;
          return this;
        };
        _proto.getSpeed = function getSpeed() {
          return this._speed;
        };
        _proto.setSpeed = function setSpeed(speed) {
          this._speed = speed;
          return this;
        };
        _proto.repeat = function repeat(times) {
          times = Math.round(times);
          if (Number.isNaN(times) || times < 1) {
            logID(1014);
            return this;
          }
          this._repeatMethod = true;
          this._timesForRepeat *= times;
          return this;
        };
        _proto.repeatForever = function repeatForever() {
          this._repeatMethod = true;
          this._timesForRepeat = this.MAX_VALUE;
          this._repeatForever = true;
          return this;
        };
        return ActionInterval;
      }(FiniteTimeAction);
      var Sequence = function (_ActionInterval) {
        _inheritsLoose(Sequence, _ActionInterval);
        function Sequence(tempArray) {
          var _this2;
          _this2 = _ActionInterval.call(this) || this;
          _this2._actions = [];
          _this2._split = 0;
          _this2._last = 0;
          _this2._reversed = false;
          var paramArray = tempArray instanceof Array ? tempArray : arguments;
          if (paramArray.length === 1) {
            errorID(1019);
            return _assertThisInitialized(_this2);
          }
          var last = paramArray.length - 1;
          if (last >= 0 && paramArray[last] == null) logID(1015);
          if (last >= 0) {
            var prev = paramArray[0];
            var action1;
            for (var i = 1; i < last; i++) {
              if (paramArray[i]) {
                action1 = prev;
                prev = Sequence._actionOneTwo(action1, paramArray[i]);
              }
            }
            _this2.initWithTwoActions(prev, paramArray[last]);
          }
          return _this2;
        }
        var _proto2 = Sequence.prototype;
        _proto2.initWithTwoActions = function initWithTwoActions(actionOne, actionTwo) {
          if (!actionOne || !actionTwo) {
            errorID(1025);
            return false;
          }
          var durationOne = actionOne._duration;
          var durationTwo = actionTwo._duration;
          durationOne *= actionOne._repeatMethod ? actionOne._timesForRepeat : 1;
          durationTwo *= actionTwo._repeatMethod ? actionTwo._timesForRepeat : 1;
          var d = durationOne + durationTwo;
          this.initWithDuration(d);
          this._actions[0] = actionOne;
          this._actions[1] = actionTwo;
          return true;
        };
        _proto2.clone = function clone() {
          var action = new Sequence();
          this._cloneDecoration(action);
          action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone());
          return action;
        };
        _proto2.startWithTarget = function startWithTarget(target) {
          ActionInterval.prototype.startWithTarget.call(this, target);
          this._split = this._actions[0]._duration / this._duration;
          this._split *= this._actions[0]._repeatMethod ? this._actions[0]._timesForRepeat : 1;
          this._last = -1;
        };
        _proto2.stop = function stop() {
          if (this._last !== -1) this._actions[this._last].stop();
          Action.prototype.stop.call(this);
        };
        _proto2.update = function update(dt) {
          var new_t;
          var found = 0;
          var locSplit = this._split;
          var locActions = this._actions;
          var locLast = this._last;
          var actionFound;
          dt = this._computeEaseTime(dt);
          if (dt < locSplit) {
            new_t = locSplit !== 0 ? dt / locSplit : 1;
            if (found === 0 && locLast === 1 && this._reversed) {
              locActions[1].update(0);
              locActions[1].stop();
            }
          } else {
            found = 1;
            new_t = locSplit === 1 ? 1 : (dt - locSplit) / (1 - locSplit);
            if (locLast === -1) {
              locActions[0].startWithTarget(this.target);
              locActions[0].update(1);
              locActions[0].stop();
            }
            if (locLast === 0) {
              locActions[0].update(1);
              locActions[0].stop();
            }
          }
          actionFound = locActions[found];
          if (locLast === found && actionFound.isDone()) return;
          if (locLast !== found) actionFound.startWithTarget(this.target);
          new_t *= actionFound._timesForRepeat;
          actionFound.update(new_t > 1 ? new_t % 1 : new_t);
          this._last = found;
        };
        _proto2.reverse = function reverse() {
          var action = Sequence._actionOneTwo(this._actions[1].reverse(), this._actions[0].reverse());
          this._cloneDecoration(action);
          this._reverseEaseList(action);
          action._reversed = true;
          return action;
        };
        return Sequence;
      }(ActionInterval);
      _class2$h = Sequence;
      Sequence._actionOneTwo = function (actionOne, actionTwo) {
        var sequence = new _class2$h();
        sequence.initWithTwoActions(actionOne, actionTwo);
        return sequence;
      };
      function sequence(tempArray) {
        var paramArray = tempArray instanceof Array ? tempArray : arguments;
        if (paramArray.length === 1) {
          return paramArray[0];
        }
        var last = paramArray.length - 1;
        if (last >= 0 && paramArray[last] == null) logID(1015);
        var result = null;
        if (last >= 0) {
          result = paramArray[0];
          for (var i = 1; i <= last; i++) {
            if (paramArray[i]) {
              result = Sequence._actionOneTwo(result, paramArray[i]);
            }
          }
        }
        return result;
      }
      var Repeat = function (_ActionInterval2) {
        _inheritsLoose(Repeat, _ActionInterval2);
        function Repeat(action, times) {
          var _this3;
          _this3 = _ActionInterval2.call(this) || this;
          _this3._times = 0;
          _this3._total = 0;
          _this3._nextDt = 0;
          _this3._actionInstant = false;
          _this3._innerAction = null;
          times !== undefined && _this3.initWithAction(action, times);
          return _this3;
        }
        var _proto3 = Repeat.prototype;
        _proto3.initWithAction = function initWithAction(action, times) {
          var duration = action._duration * times;
          if (this.initWithDuration(duration)) {
            this._times = times;
            this._innerAction = action;
            if (action instanceof ActionInstant) {
              this._actionInstant = true;
              this._times -= 1;
            }
            this._total = 0;
            return true;
          }
          return false;
        };
        _proto3.clone = function clone() {
          var action = new Repeat();
          this._cloneDecoration(action);
          action.initWithAction(this._innerAction.clone(), this._times);
          return action;
        };
        _proto3.startWithTarget = function startWithTarget(target) {
          this._total = 0;
          this._nextDt = this._innerAction._duration / this._duration;
          ActionInterval.prototype.startWithTarget.call(this, target);
          this._innerAction.startWithTarget(target);
        };
        _proto3.stop = function stop() {
          this._innerAction.stop();
          Action.prototype.stop.call(this);
        };
        _proto3.update = function update(dt) {
          dt = this._computeEaseTime(dt);
          var locInnerAction = this._innerAction;
          var locDuration = this._duration;
          var locTimes = this._times;
          var locNextDt = this._nextDt;
          if (dt >= locNextDt) {
            while (dt > locNextDt && this._total < locTimes) {
              locInnerAction.update(1);
              this._total++;
              locInnerAction.stop();
              locInnerAction.startWithTarget(this.target);
              locNextDt += locInnerAction._duration / locDuration;
              this._nextDt = locNextDt > 1 ? 1 : locNextDt;
            }
            if (dt >= 1.0 && this._total < locTimes) {
              locInnerAction.update(1);
              this._total++;
            }
            if (!this._actionInstant) {
              if (this._total === locTimes) {
                locInnerAction.stop();
              } else {
                locInnerAction.update(dt - (locNextDt - locInnerAction._duration / locDuration));
              }
            }
          } else {
            locInnerAction.update(dt * locTimes % 1.0);
          }
        };
        _proto3.isDone = function isDone() {
          return this._total === this._times;
        };
        _proto3.reverse = function reverse() {
          var action = new Repeat(this._innerAction.reverse(), this._times);
          this._cloneDecoration(action);
          this._reverseEaseList(action);
          return action;
        };
        _proto3.setInnerAction = function setInnerAction(action) {
          if (this._innerAction !== action) {
            this._innerAction = action;
          }
        };
        _proto3.getInnerAction = function getInnerAction() {
          return this._innerAction;
        };
        return Repeat;
      }(ActionInterval);
      function repeat(action, times) {
        return new Repeat(action, times);
      }
      var RepeatForever = function (_ActionInterval3) {
        _inheritsLoose(RepeatForever, _ActionInterval3);
        function RepeatForever(action) {
          var _this4;
          _this4 = _ActionInterval3.call(this) || this;
          _this4._innerAction = null;
          action && _this4.initWithAction(action);
          return _this4;
        }
        var _proto4 = RepeatForever.prototype;
        _proto4.initWithAction = function initWithAction(action) {
          if (!action) {
            errorID(1026);
            return false;
          }
          this._innerAction = action;
          return true;
        };
        _proto4.clone = function clone() {
          var action = new RepeatForever();
          this._cloneDecoration(action);
          action.initWithAction(this._innerAction.clone());
          return action;
        };
        _proto4.startWithTarget = function startWithTarget(target) {
          ActionInterval.prototype.startWithTarget.call(this, target);
          this._innerAction.startWithTarget(target);
        };
        _proto4.step = function step(dt) {
          var locInnerAction = this._innerAction;
          locInnerAction.step(dt);
          if (locInnerAction.isDone()) {
            locInnerAction.startWithTarget(this.target);
            locInnerAction.step(locInnerAction.getElapsed() - locInnerAction._duration);
          }
        };
        _proto4.isDone = function isDone() {
          return false;
        };
        _proto4.reverse = function reverse() {
          var action = new RepeatForever(this._innerAction.reverse());
          this._cloneDecoration(action);
          this._reverseEaseList(action);
          return action;
        };
        _proto4.setInnerAction = function setInnerAction(action) {
          if (this._innerAction !== action) {
            this._innerAction = action;
          }
        };
        _proto4.getInnerAction = function getInnerAction() {
          return this._innerAction;
        };
        return RepeatForever;
      }(ActionInterval);
      function repeatForever(action) {
        return new RepeatForever(action);
      }
      var Spawn = function (_ActionInterval4) {
        _inheritsLoose(Spawn, _ActionInterval4);
        function Spawn(tempArray) {
          var _this5;
          _this5 = _ActionInterval4.call(this) || this;
          _this5._one = null;
          _this5._two = null;
          var paramArray = tempArray instanceof Array ? tempArray : arguments;
          if (paramArray.length === 1) {
            errorID(1020);
            return _assertThisInitialized(_this5);
          }
          var last = paramArray.length - 1;
          if (last >= 0 && paramArray[last] == null) logID(1015);
          if (last >= 0) {
            var prev = paramArray[0];
            var action1;
            for (var i = 1; i < last; i++) {
              if (paramArray[i]) {
                action1 = prev;
                prev = Spawn._actionOneTwo(action1, paramArray[i]);
              }
            }
            _this5.initWithTwoActions(prev, paramArray[last]);
          }
          return _this5;
        }
        var _proto5 = Spawn.prototype;
        _proto5.initWithTwoActions = function initWithTwoActions(action1, action2) {
          if (!action1 || !action2) {
            errorID(1027);
            return false;
          }
          var ret = false;
          var d1 = action1._duration;
          var d2 = action2._duration;
          if (this.initWithDuration(Math.max(d1, d2))) {
            this._one = action1;
            this._two = action2;
            if (d1 > d2) {
              this._two = Sequence._actionOneTwo(action2, delayTime(d1 - d2));
            } else if (d1 < d2) {
              this._one = Sequence._actionOneTwo(action1, delayTime(d2 - d1));
            }
            ret = true;
          }
          return ret;
        };
        _proto5.clone = function clone() {
          var action = new Spawn();
          this._cloneDecoration(action);
          action.initWithTwoActions(this._one.clone(), this._two.clone());
          return action;
        };
        _proto5.startWithTarget = function startWithTarget(target) {
          ActionInterval.prototype.startWithTarget.call(this, target);
          this._one.startWithTarget(target);
          this._two.startWithTarget(target);
        };
        _proto5.stop = function stop() {
          this._one.stop();
          this._two.stop();
          Action.prototype.stop.call(this);
        };
        _proto5.update = function update(dt) {
          dt = this._computeEaseTime(dt);
          if (this._one) this._one.update(dt);
          if (this._two) this._two.update(dt);
        };
        _proto5.reverse = function reverse() {
          var action = Spawn._actionOneTwo(this._one.reverse(), this._two.reverse());
          this._cloneDecoration(action);
          this._reverseEaseList(action);
          return action;
        };
        return Spawn;
      }(ActionInterval);
      _class5 = Spawn;
      Spawn._actionOneTwo = function (action1, action2) {
        var pSpawn = new _class5();
        pSpawn.initWithTwoActions(action1, action2);
        return pSpawn;
      };
      function spawn(tempArray) {
        var paramArray = tempArray instanceof Array ? tempArray : arguments;
        if (paramArray.length === 1) {
          errorID(1020);
          return null;
        }
        if (paramArray.length > 0 && paramArray[paramArray.length - 1] == null) logID(1015);
        var prev = paramArray[0];
        for (var i = 1; i < paramArray.length; i++) {
          if (paramArray[i] != null) prev = Spawn._actionOneTwo(prev, paramArray[i]);
        }
        return prev;
      }
      var DelayTime = function (_ActionInterval5) {
        _inheritsLoose(DelayTime, _ActionInterval5);
        function DelayTime() {
          return _ActionInterval5.apply(this, arguments) || this;
        }
        var _proto6 = DelayTime.prototype;
        _proto6.update = function update(dt) {};
        _proto6.reverse = function reverse() {
          var action = new DelayTime(this._duration);
          this._cloneDecoration(action);
          this._reverseEaseList(action);
          return action;
        };
        _proto6.clone = function clone() {
          var action = new DelayTime();
          this._cloneDecoration(action);
          action.initWithDuration(this._duration);
          return action;
        };
        return DelayTime;
      }(ActionInterval);
      function delayTime(d) {
        return new DelayTime(d);
      }
      var ReverseTime = function (_ActionInterval6) {
        _inheritsLoose(ReverseTime, _ActionInterval6);
        function ReverseTime(action) {
          var _this6;
          _this6 = _ActionInterval6.call(this) || this;
          _this6._other = null;
          action && _this6.initWithAction(action);
          return _this6;
        }
        var _proto7 = ReverseTime.prototype;
        _proto7.initWithAction = function initWithAction(action) {
          if (!action) {
            errorID(1028);
            return false;
          }
          if (action === this._other) {
            errorID(1029);
            return false;
          }
          if (ActionInterval.prototype.initWithDuration.call(this, action._duration)) {
            this._other = action;
            return true;
          }
          return false;
        };
        _proto7.clone = function clone() {
          var action = new ReverseTime();
          this._cloneDecoration(action);
          action.initWithAction(this._other.clone());
          return action;
        };
        _proto7.startWithTarget = function startWithTarget(target) {
          ActionInterval.prototype.startWithTarget.call(this, target);
          this._other.startWithTarget(target);
        };
        _proto7.update = function update(dt) {
          dt = this._computeEaseTime(dt);
          if (this._other) this._other.update(1 - dt);
        };
        _proto7.reverse = function reverse() {
          return this._other.clone();
        };
        _proto7.stop = function stop() {
          this._other.stop();
          Action.prototype.stop.call(this);
        };
        return ReverseTime;
      }(ActionInterval);
      function reverseTime(action) {
        return new ReverseTime(action);
      }

      function TweenEasingAdapter(easingName) {
        var initialChar = easingName.charAt(0);
        if (/[A-Z]/.test(initialChar)) {
          easingName = easingName.replace(initialChar, initialChar.toLowerCase());
          var arr = easingName.split('-');
          if (arr.length === 2) {
            var str0 = arr[0];
            if (str0 === 'linear') {
              easingName = 'linear';
            } else {
              var str1 = arr[1];
              switch (str0) {
                case 'quadratic':
                  easingName = "quad" + str1;
                  break;
                case 'quartic':
                  easingName = "quart" + str1;
                  break;
                case 'quintic':
                  easingName = "quint" + str1;
                  break;
                case 'sinusoidal':
                  easingName = "sine" + str1;
                  break;
                case 'exponential':
                  easingName = "expo" + str1;
                  break;
                case 'circular':
                  easingName = "circ" + str1;
                  break;
                default:
                  easingName = str0 + str1;
                  break;
              }
            }
          }
        }
        return easingName;
      }
      function TweenOptionChecker(opts) {
        var header = ' [Tween:] ';
        var message = " option is not support in v + " + engineVersion;
        var _opts = opts;
        if (_opts.delay) {
          warn(header + "delay" + message);
        }
        if (_opts.repeat) {
          warn(header + "repeat" + message);
        }
        if (_opts.repeatDelay) {
          warn(header + "repeatDelay" + message);
        }
        if (_opts.interpolation) {
          warn(header + "interpolation" + message);
        }
        if (_opts.onStop) {
          warn(header + "onStop" + message);
        }
      }
      var TweenAction = exports('gY', function (_ActionInterval) {
        _inheritsLoose(TweenAction, _ActionInterval);
        function TweenAction(duration, props, opts) {
          var _this;
          _this = _ActionInterval.call(this) || this;
          _this._opts = void 0;
          _this._props = void 0;
          _this._originProps = void 0;
          if (opts == null) {
            opts = Object.create(null);
          } else {
            TweenOptionChecker(opts);
            if (opts.easing && typeof opts.easing === 'string') {
              opts.easing = TweenEasingAdapter(opts.easing);
            }
            if (!opts.progress) {
              opts.progress = _this.progress;
            }
            if (opts.easing && typeof opts.easing === 'string') {
              var easingName = opts.easing;
              opts.easing = easing[easingName];
              if (!opts.easing) {
                warnID(1031, easingName);
              }
            }
          }
          _this._opts = opts;
          _this._props = Object.create(null);
          for (var name in props) {
            if (!props.hasOwnProperty(name)) continue;
            var value = props[name];
            if (typeof value === 'function') {
              value = value();
            }
            if (value == null || typeof value === 'string') continue;
            var customEasing = void 0;
            var progress = void 0;
            if (value.value !== undefined && (value.easing || value.progress)) {
              if (typeof value.easing === 'string') {
                customEasing = easing[value.easing];
                if (!customEasing) warnID(1031, value.easing);
              } else {
                customEasing = value.easing;
              }
              progress = value.progress;
              value = value.value;
            }
            var prop = Object.create(null);
            prop.value = value;
            prop.easing = customEasing;
            prop.progress = progress;
            _this._props[name] = prop;
          }
          _this._originProps = props;
          _this.initWithDuration(duration);
          return _this;
        }
        var _proto = TweenAction.prototype;
        _proto.clone = function clone() {
          var action = new TweenAction(this._duration, this._originProps, this._opts);
          this._cloneDecoration(action);
          return action;
        };
        _proto.startWithTarget = function startWithTarget(target) {
          ActionInterval.prototype.startWithTarget.call(this, target);
          var relative = !!this._opts.relative;
          var props = this._props;
          for (var property in props) {
            var _t = target[property];
            if (_t === undefined) {
              continue;
            }
            var prop = props[property];
            var value = prop.value;
            if (typeof _t === 'number') {
              prop.start = _t;
              prop.current = _t;
              prop.end = relative ? _t + value : value;
            } else if (typeof _t === 'object') {
              if (prop.start == null) {
                prop.start = {};
                prop.current = {};
                prop.end = {};
              }
              for (var k in value) {
                if (isNaN(_t[k])) continue;
                prop.start[k] = _t[k];
                prop.current[k] = _t[k];
                prop.end[k] = relative ? _t[k] + value[k] : value[k];
              }
            }
          }
          if (this._opts.onStart) {
            this._opts.onStart(this.target);
          }
        };
        _proto.update = function update(t) {
          var target = this.target;
          if (!target) return;
          var props = this._props;
          var opts = this._opts;
          var easingTime = t;
          if (opts.easing) easingTime = opts.easing(t);
          var progress = opts.progress;
          for (var name in props) {
            var prop = props[name];
            var time = prop.easing ? prop.easing(t) : easingTime;
            var interpolation = prop.progress ? prop.progress : progress;
            var start = prop.start;
            var end = prop.end;
            if (typeof start === 'number') {
              prop.current = interpolation(start, end, prop.current, time);
            } else if (typeof start === 'object') {
              for (var k in start) {
                prop.current[k] = interpolation(start[k], end[k], prop.current[k], time);
              }
            }
            target[name] = prop.current;
          }
          if (opts.onUpdate) {
            opts.onUpdate(this.target, t);
          }
          if (t === 1 && opts.onComplete) {
            opts.onComplete(this.target);
          }
        };
        _proto.progress = function progress(start, end, current, t) {
          return start + (end - start) * t;
        };
        return TweenAction;
      }(ActionInterval));

      var SetAction = function (_ActionInstant) {
        _inheritsLoose(SetAction, _ActionInstant);
        function SetAction(props) {
          var _this;
          _this = _ActionInstant.call(this) || this;
          _this._props = void 0;
          _this._props = {};
          props !== undefined && _this.init(props);
          return _this;
        }
        var _proto = SetAction.prototype;
        _proto.init = function init(props) {
          for (var name in props) {
            this._props[name] = props[name];
          }
          return true;
        };
        _proto.update = function update() {
          var props = this._props;
          var target = this.target;
          for (var name in props) {
            target[name] = props[name];
          }
        };
        _proto.clone = function clone() {
          var action = new SetAction();
          action.init(this._props);
          return action;
        };
        return SetAction;
      }(ActionInstant);

      var Tween = exports('gX', function () {
        function Tween(target) {
          this._actions = [];
          this._finalAction = null;
          this._target = null;
          this._tag = Action.TAG_INVALID;
          this._target = target === undefined ? null : target;
        }
        var _proto = Tween.prototype;
        _proto.tag = function tag(_tag) {
          this._tag = _tag;
          return this;
        };
        _proto.then = function then(other) {
          if (other instanceof Action) {
            this._actions.push(other.clone());
          } else {
            this._actions.push(other._union());
          }
          return this;
        };
        _proto.target = function target(_target) {
          this._target = _target;
          return this;
        };
        _proto.start = function start() {
          if (!this._target) {
            warn('Please set target to tween first');
            return this;
          }
          if (this._finalAction) {
            TweenSystem.instance.ActionManager.removeAction(this._finalAction);
          }
          this._finalAction = this._union();
          this._finalAction.setTag(this._tag);
          TweenSystem.instance.ActionManager.addAction(this._finalAction, this._target, false);
          return this;
        };
        _proto.stop = function stop() {
          if (this._finalAction) {
            TweenSystem.instance.ActionManager.removeAction(this._finalAction);
          }
          return this;
        };
        _proto.clone = function clone(target) {
          var action = this._union();
          return tween(target).then(action.clone());
        };
        _proto.union = function union() {
          var action = this._union();
          this._actions.length = 0;
          this._actions.push(action);
          return this;
        };
        _proto.to = function to(duration, props, opts) {
          opts = opts || Object.create(null);
          opts.relative = false;
          var action = new TweenAction(duration, props, opts);
          this._actions.push(action);
          return this;
        };
        _proto.by = function by(duration, props, opts) {
          opts = opts || Object.create(null);
          opts.relative = true;
          var action = new TweenAction(duration, props, opts);
          this._actions.push(action);
          return this;
        };
        _proto.set = function set(props) {
          var action = new SetAction(props);
          this._actions.push(action);
          return this;
        };
        _proto.delay = function delay(duration) {
          var action = delayTime(duration);
          this._actions.push(action);
          return this;
        };
        _proto.call = function call(callback) {
          var action = callFunc(callback);
          this._actions.push(action);
          return this;
        };
        _proto.sequence = function sequence() {
          var action = Tween._wrappedSequence.apply(Tween, arguments);
          this._actions.push(action);
          return this;
        };
        _proto.parallel = function parallel() {
          var action = Tween._wrappedParallel.apply(Tween, arguments);
          this._actions.push(action);
          return this;
        };
        _proto.repeat = function repeat$1(repeatTimes, embedTween) {
          if (repeatTimes === Infinity) {
            return this.repeatForever(embedTween);
          }
          var actions = this._actions;
          var action;
          if (embedTween instanceof Tween) {
            action = embedTween._union();
          } else {
            action = actions.pop();
          }
          actions.push(repeat(action, repeatTimes));
          return this;
        };
        _proto.repeatForever = function repeatForever$1(embedTween) {
          var actions = this._actions;
          var action;
          if (embedTween instanceof Tween) {
            action = embedTween._union();
          } else {
            action = actions.pop();
          }
          actions.push(repeatForever(action));
          return this;
        };
        _proto.reverseTime = function reverseTime$1(embedTween) {
          var actions = this._actions;
          var action;
          if (embedTween instanceof Tween) {
            action = embedTween._union();
          } else {
            action = actions.pop();
          }
          actions.push(reverseTime(action));
          return this;
        };
        _proto.hide = function hide$1() {
          var action = hide();
          this._actions.push(action);
          return this;
        };
        _proto.show = function show$1() {
          var action = show();
          this._actions.push(action);
          return this;
        };
        _proto.removeSelf = function removeSelf$1() {
          var action = removeSelf(false);
          this._actions.push(action);
          return this;
        };
        _proto.destroySelf = function destroySelf() {
          var action = removeSelf(true);
          this._actions.push(action);
          return this;
        };
        Tween.stopAll = function stopAll() {
          TweenSystem.instance.ActionManager.removeAllActions();
        };
        Tween.stopAllByTag = function stopAllByTag(tag, target) {
          TweenSystem.instance.ActionManager.removeAllActionsByTag(tag, target);
        };
        Tween.stopAllByTarget = function stopAllByTarget(target) {
          TweenSystem.instance.ActionManager.removeAllActionsFromTarget(target);
        };
        _proto._union = function _union() {
          var actions = this._actions;
          var action;
          if (actions.length === 1) {
            action = actions[0];
          } else {
            action = sequence(actions);
          }
          return action;
        };
        _proto._destroy = function _destroy() {
          this.stop();
        };
        Tween._wrappedSequence = function _wrappedSequence() {
          var tmp_args = Tween._tmp_args;
          tmp_args.length = 0;
          for (var l = arguments.length, i = 0; i < l; i++) {
            var arg = tmp_args[i] = i < 0 || arguments.length <= i ? undefined : arguments[i];
            if (arg instanceof Tween) {
              tmp_args[i] = arg._union();
            }
          }
          return sequence.apply(sequence, tmp_args);
        };
        Tween._wrappedParallel = function _wrappedParallel() {
          var tmp_args = Tween._tmp_args;
          tmp_args.length = 0;
          for (var l = arguments.length, i = 0; i < l; i++) {
            var arg = tmp_args[i] = i < 0 || arguments.length <= i ? undefined : arguments[i];
            if (arg instanceof Tween) {
              tmp_args[i] = arg._union();
            }
          }
          return spawn.apply(spawn, tmp_args);
        };
        return Tween;
      }());
      Tween._tmp_args = [];
      legacyCC.Tween = Tween;
      function tween(target) {
        return new Tween(target);
      }
      legacyCC.tween = tween;
      function tweenUtil(target) {
        warn('tweenUtil\' is deprecated, please use \'tween\' instead ');
        return new Tween(target);
      }
      legacyCC.tweenUtil = tweenUtil;

      var DeviceType;
      (function (DeviceType) {
        DeviceType[DeviceType["Other"] = 0] = "Other";
        DeviceType[DeviceType["Left"] = 1] = "Left";
        DeviceType[DeviceType["Right"] = 2] = "Right";
      })(DeviceType || (DeviceType = {}));
      var XrUIPressEventType;
      (function (XrUIPressEventType) {
        XrUIPressEventType["XRUI_HOVER_ENTERED"] = "xrui-hover-entered";
        XrUIPressEventType["XRUI_HOVER_EXITED"] = "xrui-hover-exited";
        XrUIPressEventType["XRUI_HOVER_STAY"] = "xrui-hover-stay";
        XrUIPressEventType["XRUI_CLICK"] = "xrui-click";
        XrUIPressEventType["XRUI_UNCLICK"] = "xrui-unclick";
      })(XrUIPressEventType || (XrUIPressEventType = {}));
      var XrKeyboardEventType;
      (function (XrKeyboardEventType) {
        XrKeyboardEventType["XR_CAPS_LOCK"] = "xr-caps-lock";
        XrKeyboardEventType["XR_KEYBOARD_INIT"] = "xr-keyboard-init";
        XrKeyboardEventType["XR_KEYBOARD_INPUT"] = "xr-keyboard-input";
        XrKeyboardEventType["TO_LATIN"] = "to-latin";
        XrKeyboardEventType["TO_SYMBOL"] = "to-symbol";
        XrKeyboardEventType["TO_MATH_SYMBOL"] = "to-math-symbol";
      })(XrKeyboardEventType || (XrKeyboardEventType = {}));
      (function (_Event) {
        _inheritsLoose(XrUIPressEvent, _Event);
        function XrUIPressEvent() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Event.call.apply(_Event, [this].concat(args)) || this;
          _this.deviceType = DeviceType.Other;
          _this.hitPoint = new Vec3();
          return _this;
        }
        return XrUIPressEvent;
      })(Event);

      var _dec$k, _dec2$h, _dec3$g, _dec4$c, _dec5$c, _dec6$6, _dec7$4, _dec8$3, _dec9$3, _dec10$1, _class$k, _class2$g, _initializer$g, _initializer2$f, _initializer3$c, _initializer4$b, _initializer5$9, _initializer6$6, _initializer7$6, _initializer8$6, _initializer9$6, _initializer10$6, _initializer11$6, _initializer12$5, _initializer13$3, _initializer14$2, _class3$c;
      var _tempColor$1 = new Color$1();
      var Transition;
      (function (Transition) {
        Transition[Transition["NONE"] = 0] = "NONE";
        Transition[Transition["COLOR"] = 1] = "COLOR";
        Transition[Transition["SPRITE"] = 2] = "SPRITE";
        Transition[Transition["SCALE"] = 3] = "SCALE";
      })(Transition || (Transition = {}));
      ccenum(Transition);
      var State;
      (function (State) {
        State["NORMAL"] = "normal";
        State["HOVER"] = "hover";
        State["PRESSED"] = "pressed";
        State["DISABLED"] = "disabled";
      })(State || (State = {}));
      var EventType$6;
      (function (EventType) {
        EventType["CLICK"] = "click";
      })(EventType$6 || (EventType$6 = {}));
      var Button = exports('gZ', (_dec$k = ccclass$M('cc.Button'), _dec2$h = executionOrder$1(110), _dec3$g = requireComponent(UITransform), _dec4$c = type$d(Node$1), _dec5$c = type$d(Transition), _dec6$6 = type$d(SpriteFrame), _dec7$4 = type$d(SpriteFrame), _dec8$3 = type$d(SpriteFrame), _dec9$3 = type$d(SpriteFrame), _dec10$1 = type$d([EventHandler]), _dec$k(_class$k = _dec2$h(_class$k = _dec3$g(_class$k = (_class2$g = (_class3$c = function (_Component) {
        _inheritsLoose(Button, _Component);
        function Button() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.clickEvents = _initializer$g && _initializer$g();
          _this._interactable = _initializer2$f && _initializer2$f();
          _this._transition = _initializer3$c && _initializer3$c();
          _this._normalColor = _initializer4$b && _initializer4$b();
          _this._hoverColor = _initializer5$9 && _initializer5$9();
          _this._pressedColor = _initializer6$6 && _initializer6$6();
          _this._disabledColor = _initializer7$6 && _initializer7$6();
          _this._normalSprite = _initializer8$6 && _initializer8$6();
          _this._hoverSprite = _initializer9$6 && _initializer9$6();
          _this._pressedSprite = _initializer10$6 && _initializer10$6();
          _this._disabledSprite = _initializer11$6 && _initializer11$6();
          _this._duration = _initializer12$5 && _initializer12$5();
          _this._zoomScale = _initializer13$3 && _initializer13$3();
          _this._target = _initializer14$2 && _initializer14$2();
          _this._pressed = false;
          _this._hovered = false;
          _this._fromColor = new Color$1();
          _this._toColor = new Color$1();
          _this._time = 0;
          _this._transitionFinished = true;
          _this._fromScale = new Vec3();
          _this._toScale = new Vec3();
          _this._originalScale = null;
          _this._sprite = null;
          _this._targetScale = new Vec3();
          return _this;
        }
        var _proto = Button.prototype;
        _proto.__preload = function __preload() {
          if (!this.target) {
            this.target = this.node;
          }
          this._applyTarget();
          this._resetState();
        };
        _proto.onEnable = function onEnable() {
          {
            this._registerNodeEvent();
          }
        };
        _proto.onDisable = function onDisable() {
          this._resetState();
          {
            this._unregisterNodeEvent();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this.target.isValid) {
            this._unregisterTargetEvent(this.target);
          }
        };
        _proto.update = function update(dt) {
          var target = this.target;
          if (this._transitionFinished || !target) {
            return;
          }
          if (this._transition !== Transition.COLOR && this._transition !== Transition.SCALE) {
            return;
          }
          this._time += dt;
          var ratio = 1.0;
          if (this._duration > 0) {
            ratio = this._time / this._duration;
          }
          if (ratio >= 1) {
            ratio = 1;
          }
          if (this._transition === Transition.COLOR) {
            var renderComp = target._uiProps.uiComp;
            Color$1.lerp(_tempColor$1, this._fromColor, this._toColor, ratio);
            if (renderComp) {
              renderComp.color = _tempColor$1;
            }
          } else if (this.transition === Transition.SCALE) {
            target.getScale(this._targetScale);
            this._targetScale.x = lerp(this._fromScale.x, this._toScale.x, ratio);
            this._targetScale.y = lerp(this._fromScale.y, this._toScale.y, ratio);
            target.setScale(this._targetScale);
          }
          if (ratio === 1) {
            this._transitionFinished = true;
          }
        };
        _proto._resizeNodeToTargetNode = function _resizeNodeToTargetNode() {
          if (!this.target) {
            return;
          }
          this.target._uiProps.uiTransformComp;
        };
        _proto._resetState = function _resetState() {
          this._pressed = false;
          this._hovered = false;
          var target = this.target;
          if (!target) {
            return;
          }
          var transition = this._transition;
          if (transition === Transition.COLOR && this._interactable) {
            var renderComp = target.getComponent(UIRenderer);
            if (renderComp) {
              renderComp.color = this._normalColor;
            }
          } else if (transition === Transition.SCALE && this._originalScale) {
            target.setScale(this._originalScale);
          }
          this._transitionFinished = true;
        };
        _proto._registerNodeEvent = function _registerNodeEvent() {
          this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMove, this);
          this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.on(NodeEventType.TOUCH_CANCEL, this._onTouchCancel, this);
          this.node.on(NodeEventType.MOUSE_ENTER, this._onMouseMoveIn, this);
          this.node.on(NodeEventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
          this.node.on(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this);
          this.node.on(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this);
          this.node.on(XrUIPressEventType.XRUI_CLICK, this._xrClick, this);
          this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
        };
        _proto._registerTargetEvent = function _registerTargetEvent(target) {
          target.on(NodeEventType.TRANSFORM_CHANGED, this._onTargetTransformChanged, this);
        };
        _proto._unregisterNodeEvent = function _unregisterNodeEvent() {
          this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMove, this);
          this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.off(NodeEventType.TOUCH_CANCEL, this._onTouchCancel, this);
          this.node.off(NodeEventType.MOUSE_ENTER, this._onMouseMoveIn, this);
          this.node.off(NodeEventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
          this.node.off(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this);
          this.node.off(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this);
          this.node.off(XrUIPressEventType.XRUI_CLICK, this._xrClick, this);
          this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
        };
        _proto._unregisterTargetEvent = function _unregisterTargetEvent(target) {
          target.off(NodeEventType.TRANSFORM_CHANGED);
        };
        _proto._getTargetSprite = function _getTargetSprite(target) {
          var sprite = null;
          if (target) {
            sprite = target.getComponent(Sprite);
          }
          return sprite;
        };
        _proto._applyTarget = function _applyTarget() {
          if (this.target) {
            this._sprite = this._getTargetSprite(this.target);
            if (!this._originalScale) {
              this._originalScale = new Vec3();
            }
            Vec3.copy(this._originalScale, this.target.getScale());
            this._registerTargetEvent(this.target);
          }
        };
        _proto._onTargetSpriteFrameChanged = function _onTargetSpriteFrameChanged(comp) {
          if (this._transition === Transition.SPRITE) {
            this._setCurrentStateSpriteFrame(comp.spriteFrame);
          }
        };
        _proto._setCurrentStateSpriteFrame = function _setCurrentStateSpriteFrame(spriteFrame) {
          if (!spriteFrame) {
            return;
          }
          switch (this._getButtonState()) {
            case State.NORMAL:
              this._normalSprite = spriteFrame;
              break;
            case State.HOVER:
              this._hoverSprite = spriteFrame;
              break;
            case State.PRESSED:
              this._pressedSprite = spriteFrame;
              break;
            case State.DISABLED:
              this._disabledSprite = spriteFrame;
              break;
          }
        };
        _proto._onTargetColorChanged = function _onTargetColorChanged(color) {
          if (this._transition === Transition.COLOR) {
            this._setCurrentStateColor(color);
          }
        };
        _proto._setCurrentStateColor = function _setCurrentStateColor(color) {
          switch (this._getButtonState()) {
            case State.NORMAL:
              this._normalColor = color;
              break;
            case State.HOVER:
              this._hoverColor = color;
              break;
            case State.PRESSED:
              this._pressedColor = color;
              break;
            case State.DISABLED:
              this._disabledColor = color;
              break;
          }
        };
        _proto._onTargetTransformChanged = function _onTargetTransformChanged(transformBit) {
          if (transformBit & TransformBit.SCALE && this._originalScale && this._transition === Transition.SCALE && this._transitionFinished) {
            Vec3.copy(this._originalScale, this.target.getScale());
          }
        };
        _proto._onTouchBegan = function _onTouchBegan(event) {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          this._pressed = true;
          this._updateState();
          if (event) {
            event.propagationStopped = true;
          }
        };
        _proto._onTouchMove = function _onTouchMove(event) {
          if (!this._interactable || !this.enabledInHierarchy || !this._pressed) {
            return;
          }
          if (!event) {
            return;
          }
          var touch = event.touch;
          if (!touch) {
            return;
          }
          var hit = this.node._uiProps.uiTransformComp.hitTest(touch.getLocation(), event.windowId);
          if (this._transition === Transition.SCALE && this.target && this._originalScale) {
            if (hit) {
              Vec3.copy(this._fromScale, this._originalScale);
              Vec3.multiplyScalar(this._toScale, this._originalScale, this._zoomScale);
              this._transitionFinished = false;
            } else {
              this._time = 0;
              this._transitionFinished = true;
              this.target.setScale(this._originalScale);
            }
          } else {
            var state;
            if (hit) {
              state = State.PRESSED;
            } else {
              state = State.NORMAL;
            }
            this._applyTransition(state);
          }
          if (event) {
            event.propagationStopped = true;
          }
        };
        _proto._onTouchEnded = function _onTouchEnded(event) {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          if (this._pressed) {
            EventHandler.emitEvents(this.clickEvents, event);
            this.node.emit(EventType$6.CLICK, this);
          }
          this._pressed = false;
          this._updateState();
          if (event) {
            event.propagationStopped = true;
          }
        };
        _proto._onTouchCancel = function _onTouchCancel(event) {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          this._pressed = false;
          this._updateState();
        };
        _proto._onMouseMoveIn = function _onMouseMoveIn(event) {
          if (this._pressed || !this.interactable || !this.enabledInHierarchy) {
            return;
          }
          if (this._transition === Transition.SPRITE && !this._hoverSprite) {
            return;
          }
          if (!this._hovered) {
            this._hovered = true;
            this._updateState();
          }
        };
        _proto._onMouseMoveOut = function _onMouseMoveOut(event) {
          if (this._hovered) {
            this._hovered = false;
            this._updateState();
          }
        };
        _proto._updateState = function _updateState() {
          var state = this._getButtonState();
          this._applyTransition(state);
        };
        _proto._getButtonState = function _getButtonState() {
          var state = State.NORMAL;
          if (!this._interactable) {
            state = State.DISABLED;
          } else if (this._pressed) {
            state = State.PRESSED;
          } else if (this._hovered) {
            state = State.HOVER;
          }
          return state.toString();
        };
        _proto._updateColorTransition = function _updateColorTransition(state) {
          var _this$target;
          var color = this[state + "Color"];
          var renderComp = (_this$target = this.target) === null || _this$target === void 0 ? void 0 : _this$target.getComponent(UIRenderer);
          if (!renderComp) {
            return;
          }
          if (state === State.DISABLED.toString()) {
            renderComp.color = color;
          } else {
            this._fromColor = renderComp.color.clone();
            this._toColor = color;
            this._time = 0;
            this._transitionFinished = false;
          }
        };
        _proto._updateSpriteTransition = function _updateSpriteTransition(state) {
          var sprite = this[state + "Sprite"];
          if (this._sprite && sprite) {
            this._sprite.spriteFrame = sprite;
          }
        };
        _proto._updateScaleTransition = function _updateScaleTransition(state) {
          if (!this._interactable) {
            return;
          }
          if (state === State.PRESSED.toString()) {
            this._zoomUp();
          } else {
            this._zoomBack();
          }
        };
        _proto._zoomUp = function _zoomUp() {
          if (!this._originalScale) {
            return;
          }
          Vec3.copy(this._fromScale, this._originalScale);
          Vec3.multiplyScalar(this._toScale, this._originalScale, this._zoomScale);
          this._time = 0;
          this._transitionFinished = false;
        };
        _proto._zoomBack = function _zoomBack() {
          if (!this.target || !this._originalScale) {
            return;
          }
          Vec3.copy(this._fromScale, this.target.getScale());
          Vec3.copy(this._toScale, this._originalScale);
          this._time = 0;
          this._transitionFinished = false;
        };
        _proto._applyTransition = function _applyTransition(state) {
          var transition = this._transition;
          if (transition === Transition.COLOR) {
            this._updateColorTransition(state);
          } else if (transition === Transition.SPRITE) {
            this._updateSpriteTransition(state);
          } else if (transition === Transition.SCALE) {
            this._updateScaleTransition(state);
          }
        };
        _proto._xrHoverEnter = function _xrHoverEnter() {
          this._onMouseMoveIn();
          this._updateState();
        };
        _proto._xrHoverExit = function _xrHoverExit() {
          this._onMouseMoveOut();
          if (this._pressed) {
            this._pressed = false;
            this._updateState();
          }
        };
        _proto._xrClick = function _xrClick() {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          this._pressed = true;
          this._updateState();
        };
        _proto._xrUnClick = function _xrUnClick() {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          if (this._pressed) {
            EventHandler.emitEvents(this.clickEvents, this);
            this.node.emit(EventType$6.CLICK, this);
          }
          this._pressed = false;
          this._updateState();
        };
        _createClass(Button, [{
          key: "target",
          get: function get() {
            return this._target || this.node;
          },
          set: function set(value) {
            if (this._target === value) {
              return;
            }
            if (this._target) {
              this._unregisterTargetEvent(this._target);
            }
            this._target = value;
            this._applyTarget();
          }
        }, {
          key: "interactable",
          get: function get() {
            return this._interactable;
          },
          set: function set(value) {
            if (this._interactable === value) {
              return;
            }
            this._interactable = value;
            this._updateState();
            if (!this._interactable) {
              this._resetState();
            }
          }
        }, {
          key: "_resizeToTarget",
          set: function set(value) {
            if (value) {
              this._resizeNodeToTargetNode();
            }
          }
        }, {
          key: "transition",
          get: function get() {
            return this._transition;
          },
          set: function set(value) {
            if (this._transition === value) {
              return;
            }
            if (this._transition === Transition.COLOR) {
              this._updateColorTransition(State.NORMAL);
            } else if (this._transition === Transition.SPRITE) {
              this._updateSpriteTransition(State.NORMAL);
            }
            this._transition = value;
            this._updateState();
          }
        }, {
          key: "normalColor",
          get: function get() {
            return this._normalColor;
          },
          set: function set(value) {
            if (this._normalColor === value) {
              return;
            }
            this._normalColor.set(value);
            this._updateState();
          }
        }, {
          key: "pressedColor",
          get: function get() {
            return this._pressedColor;
          },
          set: function set(value) {
            if (this._pressedColor === value) {
              return;
            }
            this._pressedColor.set(value);
          }
        }, {
          key: "hoverColor",
          get: function get() {
            return this._hoverColor;
          },
          set: function set(value) {
            if (this._hoverColor === value) {
              return;
            }
            this._hoverColor.set(value);
          }
        }, {
          key: "disabledColor",
          get: function get() {
            return this._disabledColor;
          },
          set: function set(value) {
            if (this._disabledColor === value) {
              return;
            }
            this._disabledColor.set(value);
            this._updateState();
          }
        }, {
          key: "duration",
          get: function get() {
            return this._duration;
          },
          set: function set(value) {
            if (this._duration === value) {
              return;
            }
            this._duration = value;
          }
        }, {
          key: "zoomScale",
          get: function get() {
            return this._zoomScale;
          },
          set: function set(value) {
            if (this._zoomScale === value) {
              return;
            }
            this._zoomScale = value;
          }
        }, {
          key: "normalSprite",
          get: function get() {
            return this._normalSprite;
          },
          set: function set(value) {
            if (this._normalSprite === value) {
              return;
            }
            this._normalSprite = value;
            var sprite = this.node.getComponent(Sprite);
            if (sprite) {
              sprite.spriteFrame = value;
            }
            this._updateState();
          }
        }, {
          key: "pressedSprite",
          get: function get() {
            return this._pressedSprite;
          },
          set: function set(value) {
            if (this._pressedSprite === value) {
              return;
            }
            this._pressedSprite = value;
            this._updateState();
          }
        }, {
          key: "hoverSprite",
          get: function get() {
            return this._hoverSprite;
          },
          set: function set(value) {
            if (this._hoverSprite === value) {
              return;
            }
            this._hoverSprite = value;
            this._updateState();
          }
        }, {
          key: "disabledSprite",
          get: function get() {
            return this._disabledSprite;
          },
          set: function set(value) {
            if (this._disabledSprite === value) {
              return;
            }
            this._disabledSprite = value;
            this._updateState();
          }
        }]);
        return Button;
      }(Component), _class3$c.Transition = Transition, _class3$c.EventType = EventType$6, _class3$c), (_applyDecoratedDescriptor(_class2$g.prototype, "target", [_dec4$c], Object.getOwnPropertyDescriptor(_class2$g.prototype, "target"), _class2$g.prototype), _applyDecoratedDescriptor(_class2$g.prototype, "transition", [_dec5$c], Object.getOwnPropertyDescriptor(_class2$g.prototype, "transition"), _class2$g.prototype), _applyDecoratedDescriptor(_class2$g.prototype, "normalSprite", [_dec6$6], Object.getOwnPropertyDescriptor(_class2$g.prototype, "normalSprite"), _class2$g.prototype), _applyDecoratedDescriptor(_class2$g.prototype, "pressedSprite", [_dec7$4], Object.getOwnPropertyDescriptor(_class2$g.prototype, "pressedSprite"), _class2$g.prototype), _applyDecoratedDescriptor(_class2$g.prototype, "hoverSprite", [_dec8$3], Object.getOwnPropertyDescriptor(_class2$g.prototype, "hoverSprite"), _class2$g.prototype), _applyDecoratedDescriptor(_class2$g.prototype, "disabledSprite", [_dec9$3], Object.getOwnPropertyDescriptor(_class2$g.prototype, "disabledSprite"), _class2$g.prototype), _initializer$g = applyDecoratedInitializer(_class2$g.prototype, "clickEvents", [_dec10$1, serializable$p], function () {
        return [];
      }), _initializer2$f = applyDecoratedInitializer(_class2$g.prototype, "_interactable", [serializable$p], function () {
        return true;
      }), _initializer3$c = applyDecoratedInitializer(_class2$g.prototype, "_transition", [serializable$p], function () {
        return Transition.NONE;
      }), _initializer4$b = applyDecoratedInitializer(_class2$g.prototype, "_normalColor", [serializable$p], function () {
        return Color$1.WHITE.clone();
      }), _initializer5$9 = applyDecoratedInitializer(_class2$g.prototype, "_hoverColor", [serializable$p], function () {
        return new Color$1(211, 211, 211, 255);
      }), _initializer6$6 = applyDecoratedInitializer(_class2$g.prototype, "_pressedColor", [serializable$p], function () {
        return Color$1.WHITE.clone();
      }), _initializer7$6 = applyDecoratedInitializer(_class2$g.prototype, "_disabledColor", [serializable$p], function () {
        return new Color$1(124, 124, 124, 255);
      }), _initializer8$6 = applyDecoratedInitializer(_class2$g.prototype, "_normalSprite", [serializable$p], function () {
        return null;
      }), _initializer9$6 = applyDecoratedInitializer(_class2$g.prototype, "_hoverSprite", [serializable$p], function () {
        return null;
      }), _initializer10$6 = applyDecoratedInitializer(_class2$g.prototype, "_pressedSprite", [serializable$p], function () {
        return null;
      }), _initializer11$6 = applyDecoratedInitializer(_class2$g.prototype, "_disabledSprite", [serializable$p], function () {
        return null;
      }), _initializer12$5 = applyDecoratedInitializer(_class2$g.prototype, "_duration", [serializable$p], function () {
        return 0.1;
      }), _initializer13$3 = applyDecoratedInitializer(_class2$g.prototype, "_zoomScale", [serializable$p], function () {
        return 1.2;
      }), _initializer14$2 = applyDecoratedInitializer(_class2$g.prototype, "_target", [serializable$p], function () {
        return null;
      })), _class2$g)) || _class$k) || _class$k) || _class$k));
      legacyCC.Button = Button;

      var tabIndexUtil = function () {
        function tabIndexUtil() {}
        tabIndexUtil.add = function add(editBoxImpl) {
          var list = this._tabIndexList;
          var index = list.indexOf(editBoxImpl);
          if (index === -1) {
            list.push(editBoxImpl);
          }
        };
        tabIndexUtil.remove = function remove(editBoxImpl) {
          var list = this._tabIndexList;
          var index = list.indexOf(editBoxImpl);
          if (index !== -1) {
            list.splice(index, 1);
          }
        };
        tabIndexUtil.resort = function resort() {
          this._tabIndexList.sort(function (a, b) {
            return a._delegate.tabIndex - b._delegate.tabIndex;
          });
        };
        tabIndexUtil.next = function next(editBoxImpl) {
          var list = this._tabIndexList;
          var index = list.indexOf(editBoxImpl);
          editBoxImpl.setFocus(false);
          if (index !== -1) {
            var nextImpl = list[index + 1];
            if (nextImpl && nextImpl._delegate.tabIndex >= 0) {
              nextImpl.setFocus(true);
            }
          }
        };
        return tabIndexUtil;
      }();
      tabIndexUtil._tabIndexList = [];

      var KeyboardReturnType;
      (function (KeyboardReturnType) {
        KeyboardReturnType[KeyboardReturnType["DEFAULT"] = 0] = "DEFAULT";
        KeyboardReturnType[KeyboardReturnType["DONE"] = 1] = "DONE";
        KeyboardReturnType[KeyboardReturnType["SEND"] = 2] = "SEND";
        KeyboardReturnType[KeyboardReturnType["SEARCH"] = 3] = "SEARCH";
        KeyboardReturnType[KeyboardReturnType["GO"] = 4] = "GO";
        KeyboardReturnType[KeyboardReturnType["NEXT"] = 5] = "NEXT";
      })(KeyboardReturnType || (KeyboardReturnType = {}));
      Enum(KeyboardReturnType);
      var InputMode;
      (function (InputMode) {
        InputMode[InputMode["ANY"] = 0] = "ANY";
        InputMode[InputMode["EMAIL_ADDR"] = 1] = "EMAIL_ADDR";
        InputMode[InputMode["NUMERIC"] = 2] = "NUMERIC";
        InputMode[InputMode["PHONE_NUMBER"] = 3] = "PHONE_NUMBER";
        InputMode[InputMode["URL"] = 4] = "URL";
        InputMode[InputMode["DECIMAL"] = 5] = "DECIMAL";
        InputMode[InputMode["SINGLE_LINE"] = 6] = "SINGLE_LINE";
      })(InputMode || (InputMode = {}));
      Enum(InputMode);
      var InputFlag;
      (function (InputFlag) {
        InputFlag[InputFlag["PASSWORD"] = 0] = "PASSWORD";
        InputFlag[InputFlag["SENSITIVE"] = 1] = "SENSITIVE";
        InputFlag[InputFlag["INITIAL_CAPS_WORD"] = 2] = "INITIAL_CAPS_WORD";
        InputFlag[InputFlag["INITIAL_CAPS_SENTENCE"] = 3] = "INITIAL_CAPS_SENTENCE";
        InputFlag[InputFlag["INITIAL_CAPS_ALL_CHARACTERS"] = 4] = "INITIAL_CAPS_ALL_CHARACTERS";
        InputFlag[InputFlag["DEFAULT"] = 5] = "DEFAULT";
      })(InputFlag || (InputFlag = {}));
      Enum(InputFlag);

      var EditBoxImplBase = function () {
        function EditBoxImplBase() {
          this._editing = false;
          this._delegate = null;
        }
        var _proto = EditBoxImplBase.prototype;
        _proto.init = function init(delegate) {};
        _proto.onEnable = function onEnable() {};
        _proto.beforeDraw = function beforeDraw() {};
        _proto.onDisable = function onDisable() {
          if (this._editing) {
            this.endEditing();
          }
        };
        _proto.clear = function clear() {
          this._delegate = null;
        };
        _proto.setTabIndex = function setTabIndex(index) {};
        _proto.setSize = function setSize(width, height) {};
        _proto.setFocus = function setFocus(value) {
          if (value) {
            this.beginEditing();
          } else {
            this.endEditing();
          }
        };
        _proto.isFocused = function isFocused() {
          return this._editing;
        };
        _proto.beginEditing = function beginEditing() {};
        _proto.endEditing = function endEditing() {};
        return EditBoxImplBase;
      }();

      var ccdocument$3 = ccwindow.document;
      var SCROLLY = 40;
      var LEFT_PADDING$1 = 2;
      var DELAY_TIME = 400;
      var _matrix = new Mat4();
      var _matrix_temp = new Mat4();
      var _vec3 = new Vec3();
      var _currentEditBoxImpl = null;
      var _domCount = 0;
      var EditBoxImpl = function (_EditBoxImplBase) {
        _inheritsLoose(EditBoxImpl, _EditBoxImplBase);
        function EditBoxImpl() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EditBoxImplBase.call.apply(_EditBoxImplBase, [this].concat(args)) || this;
          _this._delegate = null;
          _this._inputMode = -1;
          _this._inputFlag = -1;
          _this._returnType = -1;
          _this.__eventListeners = {};
          _this.__autoResize = false;
          _this.__orientationChanged = void 0;
          _this._edTxt = null;
          _this._isTextArea = false;
          _this._textLabelFont = null;
          _this._textLabelFontSize = null;
          _this._textLabelFontColor = null;
          _this._textLabelAlign = null;
          _this._placeholderLabelFont = null;
          _this._placeholderLabelFontSize = null;
          _this._placeholderLabelFontColor = null;
          _this._placeholderLabelAlign = null;
          _this._placeholderLineHeight = null;
          _this._placeholderStyleSheet = null;
          _this._domId = "EditBoxId_" + ++_domCount;
          _this._forceUpdate = false;
          return _this;
        }
        var _proto = EditBoxImpl.prototype;
        _proto.init = function init(delegate) {
          if (!delegate) {
            return;
          }
          this._delegate = delegate;
          if (delegate.inputMode === InputMode.ANY) {
            this._createTextArea();
          } else {
            this._createInput();
          }
          tabIndexUtil.add(this);
          this.setTabIndex(delegate.tabIndex);
          this._initStyleSheet();
          this._registerEventListeners();
          this._addDomToGameContainer();
          View.instance.on('canvas-resize', this._resize, this);
          screenAdapter.on('window-resize', this._resize, this);
        };
        _proto.clear = function clear() {
          View.instance.off('canvas-resize', this._resize, this);
          screenAdapter.off('window-resize', this._resize, this);
          this._removeEventListeners();
          this._removeDomFromGameContainer();
          tabIndexUtil.remove(this);
          if (_currentEditBoxImpl === this) {
            _currentEditBoxImpl = null;
          }
          this._delegate = null;
        };
        _proto._resize = function _resize() {
          this._forceUpdate = true;
        };
        _proto.beforeDraw = function beforeDraw() {
          var node = this._delegate.node;
          if (!node.hasChangedFlags && !this._forceUpdate) {
            return;
          }
          this._forceUpdate = false;
          this._updateMatrix();
        };
        _proto.setTabIndex = function setTabIndex(index) {
          this._edTxt.tabIndex = index;
          tabIndexUtil.resort();
        };
        _proto.setSize = function setSize(width, height) {
          var elem = this._edTxt;
          if (elem) {
            elem.style.width = width + "px";
            elem.style.height = height + "px";
          }
        };
        _proto.beginEditing = function beginEditing() {
          if (_currentEditBoxImpl && _currentEditBoxImpl !== this) {
            _currentEditBoxImpl.setFocus(false);
          }
          this._editing = true;
          _currentEditBoxImpl = this;
          this._delegate._editBoxEditingDidBegan();
          this._showDom();
          this._edTxt.focus();
        };
        _proto.endEditing = function endEditing() {
          this._edTxt.blur();
        };
        _proto._createInput = function _createInput() {
          this._isTextArea = false;
          this._edTxt = ccdocument$3.createElement('input');
        };
        _proto._createTextArea = function _createTextArea() {
          this._isTextArea = true;
          this._edTxt = ccdocument$3.createElement('textarea');
        };
        _proto._addDomToGameContainer = function _addDomToGameContainer() {
          if (game.container && this._edTxt) {
            game.container.appendChild(this._edTxt);
            ccdocument$3.head.appendChild(this._placeholderStyleSheet);
          }
        };
        _proto._removeDomFromGameContainer = function _removeDomFromGameContainer() {
          var hasElem = contains$1(game.container, this._edTxt);
          if (hasElem && this._edTxt) {
            game.container.removeChild(this._edTxt);
          }
          var hasStyleSheet = contains$1(ccdocument$3.head, this._placeholderStyleSheet);
          if (hasStyleSheet) {
            ccdocument$3.head.removeChild(this._placeholderStyleSheet);
          }
          this._edTxt = null;
          this._placeholderStyleSheet = null;
        };
        _proto._showDom = function _showDom() {
          this._updateMaxLength();
          this._updateInputType();
          this._updateStyleSheet();
          if (this._edTxt && this._delegate) {
            this._edTxt.style.display = '';
            this._delegate._hideLabels();
          }
          if (sys.isMobile) {
            this._showDomOnMobile();
          }
        };
        _proto._hideDom = function _hideDom() {
          var elem = this._edTxt;
          if (elem && this._delegate) {
            elem.style.display = 'none';
            this._delegate._showLabels();
          }
          if (sys.isMobile) {
            this._hideDomOnMobile();
          }
        };
        _proto._showDomOnMobile = function _showDomOnMobile() {
          if (sys.os !== OS.ANDROID && sys.os !== OS.OHOS) {
            return;
          }
          screenAdapter.handleResizeEvent = false;
          this._adjustWindowScroll();
        };
        _proto._hideDomOnMobile = function _hideDomOnMobile() {
          if (sys.os === OS.ANDROID || sys.os === OS.OHOS) {
            screenAdapter.handleResizeEvent = true;
          }
          this._scrollBackWindow();
        };
        _proto._isElementInViewport = function _isElementInViewport() {
          if (this._edTxt) {
            var rect = this._edTxt.getBoundingClientRect();
            return rect.top >= 0 && rect.left >= 0 && rect.bottom <= (ccwindow.innerHeight || ccdocument$3.documentElement.clientHeight) && rect.right <= (ccwindow.innerWidth || ccdocument$3.documentElement.clientWidth);
          }
          return false;
        };
        _proto._adjustWindowScroll = function _adjustWindowScroll() {
          var _this2 = this;
          setTimeout(function () {
            if (ccwindow.scrollY < SCROLLY && !_this2._isElementInViewport()) {
              _this2._edTxt.scrollIntoView({
                block: 'start',
                inline: 'nearest',
                behavior: 'smooth'
              });
            }
          }, DELAY_TIME);
        };
        _proto._scrollBackWindow = function _scrollBackWindow() {
          setTimeout(function () {
            if (sys.browserType === BrowserType.WECHAT && sys.os === OS.IOS) {
              if (ccwindow.top) {
                ccwindow.top.scrollTo(0, 0);
              }
              return;
            }
            ccwindow.scrollTo(0, 0);
          }, DELAY_TIME);
        };
        _proto._updateMatrix = function _updateMatrix() {
          if (!this._edTxt) {
            return;
          }
          var node = this._delegate.node;
          var scaleX = view.getScaleX();
          var scaleY = view.getScaleY();
          var viewport = view.getViewportRect();
          var dpr = screenAdapter.devicePixelRatio;
          node.getWorldMatrix(_matrix);
          var transform = node._uiProps.uiTransformComp;
          if (transform) {
            Vec3.set(_vec3, -transform.anchorX * transform.width, -transform.anchorY * transform.height, _vec3.z);
            Mat4.transform(_matrix, _matrix, _vec3);
          }
          if (!node._uiProps.uiTransformComp) {
            return;
          }
          var camera = director.root.batcher2D.getFirstRenderCamera(node);
          if (!camera) return;
          camera.node.getWorldRT(_matrix_temp);
          var m12 = _matrix_temp.m12;
          var m13 = _matrix_temp.m13;
          var center = visibleRect.center;
          _matrix_temp.m12 = center.x - (_matrix_temp.m00 * m12 + _matrix_temp.m04 * m13);
          _matrix_temp.m13 = center.y - (_matrix_temp.m01 * m12 + _matrix_temp.m05 * m13);
          scaleX /= dpr;
          scaleY /= dpr;
          Vec3.set(_vec3, scaleX, scaleY, 1);
          Mat4.scale(_matrix_temp, _matrix_temp, _vec3);
          var container = game.container;
          var offsetX = parseInt(container && container.style.paddingLeft || '0');
          offsetX += viewport.x / dpr;
          var offsetY = parseInt(container && container.style.paddingBottom || '0');
          offsetY += viewport.y / dpr;
          _matrix_temp.m12 += offsetX;
          _matrix_temp.m13 += offsetY;
          Mat4.multiply(_matrix_temp, _matrix_temp, _matrix);
          var a = _matrix_temp.m00;
          var b = _matrix_temp.m01;
          var c = _matrix_temp.m04;
          var d = _matrix_temp.m05;
          var tx = _matrix_temp.m12;
          var ty = _matrix_temp.m13;
          var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")";
          this._edTxt.style.transform = matrix;
          this._edTxt.style['-webkit-transform'] = matrix;
          this._edTxt.style['transform-origin'] = '0px 100% 0px';
          this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px';
        };
        _proto._updateInputType = function _updateInputType() {
          var delegate = this._delegate;
          var inputMode = delegate.inputMode;
          var inputFlag = delegate.inputFlag;
          var returnType = delegate.returnType;
          var elem = this._edTxt;
          if (this._inputMode === inputMode && this._inputFlag === inputFlag && this._returnType === returnType) {
            return;
          }
          this._inputMode = inputMode;
          this._inputFlag = inputFlag;
          this._returnType = returnType;
          if (this._isTextArea) {
            var transform = 'none';
            if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
              transform = 'uppercase';
            } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
              transform = 'capitalize';
            }
            elem.style.textTransform = transform;
            return;
          }
          elem = elem;
          if (inputFlag === InputFlag.PASSWORD) {
            elem.type = 'password';
            elem.style.textTransform = 'none';
            return;
          }
          var type = elem.type;
          if (inputMode === InputMode.EMAIL_ADDR) {
            type = 'email';
          } else if (inputMode === InputMode.NUMERIC) {
            type = 'number';
          } else if (inputMode === InputMode.DECIMAL) {
            type = 'digit';
          } else if (inputMode === InputMode.PHONE_NUMBER) {
            type = 'tel';
            elem.addEventListener('wheel', function () {
              return false;
            });
          } else if (inputMode === InputMode.URL) {
            type = 'url';
          } else {
            type = 'text';
            if (returnType === KeyboardReturnType.SEARCH) {
              type = 'search';
            }
          }
          elem.type = type;
          var textTransform = 'none';
          if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
            textTransform = 'uppercase';
          } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
            textTransform = 'capitalize';
          }
          elem.style.textTransform = textTransform;
        };
        _proto._updateMaxLength = function _updateMaxLength() {
          var maxLength = this._delegate.maxLength;
          if (maxLength < 0) {
            maxLength = 65535;
          }
          this._edTxt.maxLength = maxLength;
        };
        _proto._initStyleSheet = function _initStyleSheet() {
          if (!this._edTxt) {
            return;
          }
          var elem = this._edTxt;
          elem.style.color = '#000000';
          elem.style.border = '0px';
          elem.style.background = 'transparent';
          elem.style.width = '100%';
          elem.style.height = '100%';
          elem.style.outline = 'medium';
          elem.style.padding = '0';
          elem.style.textTransform = 'none';
          elem.style.display = 'none';
          elem.style.position = 'absolute';
          elem.style.bottom = '0px';
          elem.style.left = LEFT_PADDING$1 + "px";
          elem.className = 'cocosEditBox';
          elem.style.fontFamily = 'Arial';
          elem.id = this._domId;
          if (!this._isTextArea) {
            elem = elem;
            elem.type = 'text';
            elem.style['-moz-appearance'] = 'textfield';
          } else {
            elem.style.resize = 'none';
            elem.style.overflowY = 'scroll';
          }
          this._placeholderStyleSheet = ccdocument$3.createElement('style');
        };
        _proto._updateStyleSheet = function _updateStyleSheet() {
          var delegate = this._delegate;
          var elem = this._edTxt;
          if (elem && delegate) {
            elem.value = delegate.string;
            this._updateTextLabel(delegate.textLabel);
          }
        };
        _proto._updateTextLabel = function _updateTextLabel(textLabel) {
          if (!textLabel) {
            return;
          }
          var font = textLabel.font;
          if (font && !(font instanceof BitmapFont)) {
            font = font._fontFamily;
          } else {
            font = textLabel.fontFamily;
          }
          var fontSize = textLabel.fontSize * textLabel.node.scale.y;
          if (this._textLabelFont === font && this._textLabelFontSize === fontSize && this._textLabelFontColor === textLabel.fontColor && this._textLabelAlign === textLabel.horizontalAlign) {
            return;
          }
          this._textLabelFont = font;
          this._textLabelFontSize = fontSize;
          this._textLabelFontColor = textLabel.fontColor;
          this._textLabelAlign = textLabel.horizontalAlign;
          if (!this._edTxt) {
            return;
          }
          var elem = this._edTxt;
          elem.style.fontSize = fontSize + "px";
          elem.style.color = textLabel.color.toCSS();
          elem.style.fontFamily = font;
          switch (textLabel.horizontalAlign) {
            case Label.HorizontalAlign.LEFT:
              elem.style.textAlign = 'left';
              break;
            case Label.HorizontalAlign.CENTER:
              elem.style.textAlign = 'center';
              break;
            case Label.HorizontalAlign.RIGHT:
              elem.style.textAlign = 'right';
              break;
          }
        };
        _proto._updatePlaceholderLabel = function _updatePlaceholderLabel(placeholderLabel) {
          if (!placeholderLabel) {
            return;
          }
          var font = placeholderLabel.font;
          if (font && !(font instanceof BitmapFont)) {
            font = placeholderLabel.font._fontFamily;
          } else {
            font = placeholderLabel.fontFamily;
          }
          var fontSize = placeholderLabel.fontSize * placeholderLabel.node.scale.y;
          if (this._placeholderLabelFont === font && this._placeholderLabelFontSize === fontSize && this._placeholderLabelFontColor === placeholderLabel.fontColor && this._placeholderLabelAlign === placeholderLabel.horizontalAlign && this._placeholderLineHeight === placeholderLabel.fontSize) {
            return;
          }
          this._placeholderLabelFont = font;
          this._placeholderLabelFontSize = fontSize;
          this._placeholderLabelFontColor = placeholderLabel.fontColor;
          this._placeholderLabelAlign = placeholderLabel.horizontalAlign;
          this._placeholderLineHeight = placeholderLabel.fontSize;
          var styleEl = this._placeholderStyleSheet;
          var fontColor = placeholderLabel.color.toCSS();
          var lineHeight = placeholderLabel.fontSize;
          var horizontalAlign = '';
          switch (placeholderLabel.horizontalAlign) {
            case Label.HorizontalAlign.LEFT:
              horizontalAlign = 'left';
              break;
            case Label.HorizontalAlign.CENTER:
              horizontalAlign = 'center';
              break;
            case Label.HorizontalAlign.RIGHT:
              horizontalAlign = 'right';
              break;
          }
          styleEl.innerHTML = "#" + this._domId + "::-webkit-input-placeholder{text-transform: initial;-family: " + font + ";font-size: " + fontSize + "px;color: " + fontColor + ";line-height: " + lineHeight + "px;text-align: " + horizontalAlign + ";}" + ("#" + this._domId + "::-moz-placeholder{text-transform: initial;-family: " + font + ";font-size: " + fontSize + "px;color: " + fontColor + ";line-height: " + lineHeight + "px;text-align: " + horizontalAlign + ";}") + ("#" + this._domId + "::-ms-input-placeholder{text-transform: initial;-family: " + font + ";font-size: " + fontSize + "px;color: " + fontColor + ";line-height: " + lineHeight + "px;text-align: " + horizontalAlign + ";}");
          if (sys.browserType === BrowserType.EDGE) {
            styleEl.innerHTML += "#" + this._domId + "::-ms-clear{display: none;}";
          }
        };
        _proto._registerEventListeners = function _registerEventListeners() {
          var _this3 = this;
          if (!this._edTxt) {
            return;
          }
          var elem = this._edTxt;
          var inputLock = false;
          var cbs = this.__eventListeners;
          cbs.compositionStart = function () {
            inputLock = true;
          };
          cbs.compositionEnd = function () {
            inputLock = false;
            _this3._delegate._editBoxTextChanged(elem.value);
          };
          cbs.onInput = function () {
            if (inputLock) {
              return;
            }
            var delegate = _this3._delegate;
            var maxLength = delegate.maxLength;
            if (maxLength >= 0) {
              elem.value = elem.value.slice(0, maxLength);
            }
            delegate._editBoxTextChanged(elem.value);
          };
          cbs.onClick = function () {
            if (_this3._editing) {
              if (sys.isMobile) {
                _this3._adjustWindowScroll();
              }
            }
          };
          cbs.onKeydown = function (e) {
            if (e.keyCode === KeyCode.ENTER) {
              e.propagationStopped = true;
              _this3._delegate._editBoxEditingReturn();
              if (!_this3._isTextArea) {
                elem.blur();
              }
            } else if (e.keyCode === KeyCode.TAB) {
              e.propagationStopped = true;
              e.preventDefault();
              tabIndexUtil.next(_this3);
            }
          };
          cbs.onBlur = function () {
            if (sys.isMobile && inputLock) {
              cbs.compositionEnd();
            }
            _this3._editing = false;
            _currentEditBoxImpl = null;
            _this3._hideDom();
            _this3._delegate._editBoxEditingDidEnded();
          };
          elem.addEventListener('compositionstart', cbs.compositionStart);
          elem.addEventListener('compositionend', cbs.compositionEnd);
          elem.addEventListener('input', cbs.onInput);
          elem.addEventListener('keydown', cbs.onKeydown);
          elem.addEventListener('blur', cbs.onBlur);
          elem.addEventListener('touchstart', cbs.onClick);
        };
        _proto._removeEventListeners = function _removeEventListeners() {
          if (!this._edTxt) {
            return;
          }
          var elem = this._edTxt;
          var cbs = this.__eventListeners;
          elem.removeEventListener('compositionstart', cbs.compositionStart);
          elem.removeEventListener('compositionend', cbs.compositionEnd);
          elem.removeEventListener('input', cbs.onInput);
          elem.removeEventListener('keydown', cbs.onKeydown);
          elem.removeEventListener('blur', cbs.onBlur);
          elem.removeEventListener('touchstart', cbs.onClick);
          cbs.compositionStart = null;
          cbs.compositionEnd = null;
          cbs.onInput = null;
          cbs.onKeydown = null;
          cbs.onBlur = null;
          cbs.onClick = null;
        };
        return EditBoxImpl;
      }(EditBoxImplBase);

      var _dec$j, _dec2$g, _dec3$f, _dec4$b, _dec5$b, _dec6$5, _dec7$3, _dec8$2, _dec9$2, _dec10, _dec11, _dec12, _dec13, _class$j, _class2$f, _initializer$f, _initializer2$e, _initializer3$b, _initializer4$a, _initializer5$8, _initializer6$5, _initializer7$5, _initializer8$5, _initializer9$5, _initializer10$5, _initializer11$5, _initializer12$4, _initializer13$2, _class3$b;
      var LEFT_PADDING = 2;
      function capitalize(str) {
        return str.replace(/(?:^|\s)\S/g, function (a) {
          return a.toUpperCase();
        });
      }
      function capitalizeFirstLetter(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
      }
      var EventType$5;
      (function (EventType) {
        EventType["EDITING_DID_BEGAN"] = "editing-did-began";
        EventType["EDITING_DID_ENDED"] = "editing-did-ended";
        EventType["TEXT_CHANGED"] = "text-changed";
        EventType["EDITING_RETURN"] = "editing-return";
        EventType["XR_EDITING_DID_BEGAN"] = "xr-editing-did-began";
        EventType["XR_EDITING_DID_ENDED"] = "xr-editing-did-ended";
      })(EventType$5 || (EventType$5 = {}));
      var EditBox = exports('g_', (_dec$j = ccclass$M('cc.EditBox'), _dec2$g = executionOrder$1(110), _dec3$f = requireComponent(UITransform), _dec4$b = type$d(Label), _dec5$b = type$d(Label), _dec6$5 = type$d(SpriteFrame), _dec7$3 = type$d(InputFlag), _dec8$2 = type$d(InputMode), _dec9$2 = type$d(KeyboardReturnType), _dec10 = type$d([EventHandler]), _dec11 = type$d([EventHandler]), _dec12 = type$d([EventHandler]), _dec13 = type$d([EventHandler]), _dec$j(_class$j = _dec2$g(_class$j = _dec3$f(_class$j = (_class2$f = (_class3$b = function (_Component) {
        _inheritsLoose(EditBox, _Component);
        function EditBox() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.editingDidBegan = _initializer$f && _initializer$f();
          _this.textChanged = _initializer2$e && _initializer2$e();
          _this.editingDidEnded = _initializer3$b && _initializer3$b();
          _this.editingReturn = _initializer4$a && _initializer4$a();
          _this._impl = null;
          _this._background = null;
          _this._textLabel = _initializer5$8 && _initializer5$8();
          _this._placeholderLabel = _initializer6$5 && _initializer6$5();
          _this._returnType = _initializer7$5 && _initializer7$5();
          _this._string = _initializer8$5 && _initializer8$5();
          _this._tabIndex = _initializer9$5 && _initializer9$5();
          _this._backgroundImage = _initializer10$5 && _initializer10$5();
          _this._inputFlag = _initializer11$5 && _initializer11$5();
          _this._inputMode = _initializer12$4 && _initializer12$4();
          _this._maxLength = _initializer13$2 && _initializer13$2();
          _this._isLabelVisible = false;
          return _this;
        }
        var _proto = EditBox.prototype;
        _proto.__preload = function __preload() {
          this._init();
        };
        _proto.onEnable = function onEnable() {
          {
            this._registerEvent();
          }
          this._ensureBackgroundSprite();
          if (this._impl) {
            this._impl.onEnable();
          }
        };
        _proto._beforeDraw = function _beforeDraw() {
          if (this._impl) {
            this._impl.beforeDraw();
          }
        };
        _proto.onDisable = function onDisable() {
          {
            this._unregisterEvent();
          }
          this._unregisterBackgroundEvent();
          if (this._impl) {
            this._impl.onDisable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          director.off(Director.EVENT_BEFORE_DRAW, this._beforeDraw, this);
          if (this._impl) {
            this._impl.clear();
          }
        };
        _proto.setFocus = function setFocus() {
          if (this._impl) {
            this._impl.setFocus(true);
          }
        };
        _proto.focus = function focus() {
          if (this._impl) {
            this._impl.setFocus(true);
          }
        };
        _proto.blur = function blur() {
          if (this._impl) {
            this._impl.setFocus(false);
          }
        };
        _proto.isFocused = function isFocused() {
          if (this._impl) {
            return this._impl.isFocused();
          }
          return false;
        };
        _proto._editBoxEditingDidBegan = function _editBoxEditingDidBegan() {
          EventHandler.emitEvents(this.editingDidBegan, this);
          this.node.emit(EventType$5.EDITING_DID_BEGAN, this);
        };
        _proto._editBoxEditingDidEnded = function _editBoxEditingDidEnded(text) {
          EventHandler.emitEvents(this.editingDidEnded, this);
          this.node.emit(EventType$5.EDITING_DID_ENDED, this, text);
        };
        _proto._editBoxTextChanged = function _editBoxTextChanged(text) {
          text = this._updateLabelStringStyle(text, true);
          this.string = text;
          EventHandler.emitEvents(this.textChanged, text, this);
          this.node.emit(EventType$5.TEXT_CHANGED, this);
        };
        _proto._editBoxEditingReturn = function _editBoxEditingReturn(text) {
          EventHandler.emitEvents(this.editingReturn, this);
          this.node.emit(EventType$5.EDITING_RETURN, this, text);
        };
        _proto._showLabels = function _showLabels() {
          this._isLabelVisible = true;
          this._updateLabels();
        };
        _proto._hideLabels = function _hideLabels() {
          this._isLabelVisible = false;
          if (this._textLabel) {
            this._textLabel.node.active = false;
          }
          if (this._placeholderLabel) {
            this._placeholderLabel.node.active = false;
          }
        };
        _proto._onTouchBegan = function _onTouchBegan(event) {
          event.propagationStopped = true;
        };
        _proto._onTouchCancel = function _onTouchCancel(event) {
          event.propagationStopped = true;
        };
        _proto._onTouchEnded = function _onTouchEnded(event) {
          if (this._impl) {
            this._impl.beginEditing();
          }
          event.propagationStopped = true;
        };
        _proto._init = function _init() {
          this._updatePlaceholderLabel();
          this._updateTextLabel();
          this._isLabelVisible = true;
          this.node.on(NodeEventType.SIZE_CHANGED, this._resizeChildNodes, this);
          director.on(Director.EVENT_BEFORE_DRAW, this._beforeDraw, this);
          var impl = this._impl = new EditBox._EditBoxImpl();
          impl.init(this);
          this._updateString(this._string);
          this._syncSize();
        };
        _proto._ensureBackgroundSprite = function _ensureBackgroundSprite() {
          if (!this._background) {
            var background = this.node.getComponent(Sprite);
            if (!background) {
              background = this.node.addComponent(Sprite);
            }
            if (background !== this._background) {
              background.type = Sprite.Type.SLICED;
              background.spriteFrame = this._backgroundImage;
              this._background = background;
              this._registerBackgroundEvent();
            }
          }
        };
        _proto._updateTextLabel = function _updateTextLabel() {
          var textLabel = this._textLabel;
          if (!textLabel) {
            var node = this.node.getChildByName('TEXT_LABEL');
            if (!node) {
              node = new Node$1('TEXT_LABEL');
              node.layer = this.node.layer;
            }
            textLabel = node.getComponent(Label);
            if (!textLabel) {
              textLabel = node.addComponent(Label);
            }
            node.parent = this.node;
            this._textLabel = textLabel;
          }
          if (this._inputMode === InputMode.ANY) {
            textLabel.verticalAlign = VerticalTextAlignment.TOP;
            textLabel.enableWrapText = true;
          } else {
            textLabel.enableWrapText = false;
          }
          textLabel.string = this._updateLabelStringStyle(this._string);
        };
        _proto._updatePlaceholderLabel = function _updatePlaceholderLabel() {
          var placeholderLabel = this._placeholderLabel;
          if (!placeholderLabel) {
            var node = this.node.getChildByName('PLACEHOLDER_LABEL');
            if (!node) {
              node = new Node$1('PLACEHOLDER_LABEL');
              node.layer = this.node.layer;
            }
            placeholderLabel = node.getComponent(Label);
            if (!placeholderLabel) {
              placeholderLabel = node.addComponent(Label);
            }
            node.parent = this.node;
            this._placeholderLabel = placeholderLabel;
          }
          if (this._inputMode === InputMode.ANY) {
            placeholderLabel.enableWrapText = true;
          } else {
            placeholderLabel.enableWrapText = false;
          }
          placeholderLabel.string = this.placeholder;
        };
        _proto._syncSize = function _syncSize() {
          var trans = this.node._uiProps.uiTransformComp;
          var size = trans.contentSize;
          if (this._background) {
            var bgTrans = this._background.node._uiProps.uiTransformComp;
            bgTrans.anchorPoint = trans.anchorPoint;
            bgTrans.setContentSize(size);
          }
          this._updateLabelPosition(size);
          if (this._impl) {
            this._impl.setSize(size.width, size.height);
          }
        };
        _proto._updateLabels = function _updateLabels() {
          if (this._isLabelVisible) {
            var content = this._string;
            if (this._textLabel) {
              this._textLabel.node.active = content !== '';
            }
            if (this._placeholderLabel) {
              this._placeholderLabel.node.active = content === '';
            }
          }
        };
        _proto._updateString = function _updateString(text) {
          var textLabel = this._textLabel;
          if (!textLabel) {
            return;
          }
          var displayText = text;
          if (displayText) {
            displayText = this._updateLabelStringStyle(displayText);
          }
          textLabel.string = displayText;
          this._updateLabels();
        };
        _proto._updateLabelStringStyle = function _updateLabelStringStyle(text, ignorePassword) {
          if (ignorePassword === void 0) {
            ignorePassword = false;
          }
          var inputFlag = this._inputFlag;
          if (!ignorePassword && inputFlag === InputFlag.PASSWORD) {
            var passwordString = '';
            var len = text.length;
            for (var i = 0; i < len; ++i) {
              passwordString += "\u25CF";
            }
            text = passwordString;
          } else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
            text = text.toUpperCase();
          } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
            text = capitalize(text);
          } else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) {
            text = capitalizeFirstLetter(text);
          }
          return text;
        };
        _proto._registerEvent = function _registerEvent() {
          this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
          this.node.on(XrKeyboardEventType.XR_KEYBOARD_INPUT, this._xrKeyBoardInput, this);
        };
        _proto._unregisterEvent = function _unregisterEvent() {
          this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
          this.node.off(XrKeyboardEventType.XR_KEYBOARD_INPUT, this._xrKeyBoardInput, this);
        };
        _proto._onBackgroundSpriteFrameChanged = function _onBackgroundSpriteFrameChanged() {
          if (!this._background) {
            return;
          }
          this.backgroundImage = this._background.spriteFrame;
        };
        _proto._registerBackgroundEvent = function _registerBackgroundEvent() {
          var node = this._background && this._background.node;
          node === null || node === void 0 ? void 0 : node.on(Sprite.EventType.SPRITE_FRAME_CHANGED, this._onBackgroundSpriteFrameChanged, this);
        };
        _proto._unregisterBackgroundEvent = function _unregisterBackgroundEvent() {
          var node = this._background && this._background.node;
          node === null || node === void 0 ? void 0 : node.off(Sprite.EventType.SPRITE_FRAME_CHANGED, this._onBackgroundSpriteFrameChanged, this);
        };
        _proto._updateLabelPosition = function _updateLabelPosition(size) {
          var trans = this.node._uiProps.uiTransformComp;
          var offX = -trans.anchorX * trans.width;
          var offY = -trans.anchorY * trans.height;
          var placeholderLabel = this._placeholderLabel;
          var textLabel = this._textLabel;
          if (textLabel) {
            textLabel.node._uiProps.uiTransformComp.setContentSize(size.width - LEFT_PADDING, size.height);
            textLabel.node.setPosition(offX + LEFT_PADDING, offY + size.height, textLabel.node.position.z);
            if (this._inputMode === InputMode.ANY) {
              textLabel.verticalAlign = VerticalTextAlignment.TOP;
            }
            textLabel.enableWrapText = this._inputMode === InputMode.ANY;
          }
          if (placeholderLabel) {
            placeholderLabel.node._uiProps.uiTransformComp.setContentSize(size.width - LEFT_PADDING, size.height);
            placeholderLabel.node.setPosition(offX + LEFT_PADDING, offY + size.height, placeholderLabel.node.position.z);
            placeholderLabel.enableWrapText = this._inputMode === InputMode.ANY;
          }
        };
        _proto._resizeChildNodes = function _resizeChildNodes() {
          var trans = this.node._uiProps.uiTransformComp;
          var textLabelNode = this._textLabel && this._textLabel.node;
          if (textLabelNode) {
            textLabelNode.setPosition(-trans.width / 2, trans.height / 2, textLabelNode.position.z);
            textLabelNode._uiProps.uiTransformComp.setContentSize(trans.contentSize);
          }
          var placeholderLabelNode = this._placeholderLabel && this._placeholderLabel.node;
          if (placeholderLabelNode) {
            placeholderLabelNode.setPosition(-trans.width / 2, trans.height / 2, placeholderLabelNode.position.z);
            placeholderLabelNode._uiProps.uiTransformComp.setContentSize(trans.contentSize);
          }
          var backgroundNode = this._background && this._background.node;
          if (backgroundNode) {
            backgroundNode._uiProps.uiTransformComp.setContentSize(trans.contentSize);
          }
          this._syncSize();
        };
        _proto._xrUnClick = function _xrUnClick() {
          this.node.emit(EventType$5.XR_EDITING_DID_BEGAN, this._maxLength, this.string);
        };
        _proto._xrKeyBoardInput = function _xrKeyBoardInput(str) {
          this.string = str;
        };
        _createClass(EditBox, [{
          key: "string",
          get: function get() {
            return this._string;
          },
          set: function set(value) {
            if (this._maxLength >= 0 && value.length >= this._maxLength) {
              value = value.slice(0, this._maxLength);
            }
            if (this._string === value) {
              return;
            }
            this._string = value;
            this._updateString(value);
          }
        }, {
          key: "placeholder",
          get: function get() {
            if (!this._placeholderLabel) {
              return '';
            }
            return this._placeholderLabel.string;
          },
          set: function set(value) {
            if (this._placeholderLabel) {
              this._placeholderLabel.string = value;
            }
          }
        }, {
          key: "textLabel",
          get: function get() {
            return this._textLabel;
          },
          set: function set(oldValue) {
            if (this._textLabel !== oldValue) {
              this._textLabel = oldValue;
              if (this._textLabel) {
                this._updateTextLabel();
                this._updateLabels();
              }
            }
          }
        }, {
          key: "placeholderLabel",
          get: function get() {
            return this._placeholderLabel;
          },
          set: function set(oldValue) {
            if (this._placeholderLabel !== oldValue) {
              this._placeholderLabel = oldValue;
              if (this._placeholderLabel) {
                this._updatePlaceholderLabel();
                this._updateLabels();
              }
            }
          }
        }, {
          key: "backgroundImage",
          get: function get() {
            return this._backgroundImage;
          },
          set: function set(value) {
            if (this._backgroundImage === value) {
              return;
            }
            this._backgroundImage = value;
            this._ensureBackgroundSprite();
            this._background.spriteFrame = value;
          }
        }, {
          key: "inputFlag",
          get: function get() {
            return this._inputFlag;
          },
          set: function set(value) {
            if (this._inputFlag === value) {
              return;
            }
            this._inputFlag = value;
            this._updateString(this._string);
          }
        }, {
          key: "inputMode",
          get: function get() {
            return this._inputMode;
          },
          set: function set(oldValue) {
            if (this._inputMode !== oldValue) {
              this._inputMode = oldValue;
              this._updateTextLabel();
              this._updatePlaceholderLabel();
            }
          }
        }, {
          key: "returnType",
          get: function get() {
            return this._returnType;
          },
          set: function set(value) {
            this._returnType = value;
          }
        }, {
          key: "maxLength",
          get: function get() {
            return this._maxLength;
          },
          set: function set(value) {
            this._maxLength = value;
          }
        }, {
          key: "tabIndex",
          get: function get() {
            return this._tabIndex;
          },
          set: function set(value) {
            if (this._tabIndex !== value) {
              this._tabIndex = value;
              if (this._impl) {
                this._impl.setTabIndex(value);
              }
            }
          }
        }]);
        return EditBox;
      }(Component), _class3$b._EditBoxImpl = EditBoxImplBase, _class3$b.KeyboardReturnType = KeyboardReturnType, _class3$b.InputFlag = InputFlag, _class3$b.InputMode = InputMode, _class3$b.EventType = EventType$5, _class3$b), (_applyDecoratedDescriptor(_class2$f.prototype, "textLabel", [_dec4$b], Object.getOwnPropertyDescriptor(_class2$f.prototype, "textLabel"), _class2$f.prototype), _applyDecoratedDescriptor(_class2$f.prototype, "placeholderLabel", [_dec5$b], Object.getOwnPropertyDescriptor(_class2$f.prototype, "placeholderLabel"), _class2$f.prototype), _applyDecoratedDescriptor(_class2$f.prototype, "backgroundImage", [_dec6$5], Object.getOwnPropertyDescriptor(_class2$f.prototype, "backgroundImage"), _class2$f.prototype), _applyDecoratedDescriptor(_class2$f.prototype, "inputFlag", [_dec7$3], Object.getOwnPropertyDescriptor(_class2$f.prototype, "inputFlag"), _class2$f.prototype), _applyDecoratedDescriptor(_class2$f.prototype, "inputMode", [_dec8$2], Object.getOwnPropertyDescriptor(_class2$f.prototype, "inputMode"), _class2$f.prototype), _applyDecoratedDescriptor(_class2$f.prototype, "returnType", [_dec9$2], Object.getOwnPropertyDescriptor(_class2$f.prototype, "returnType"), _class2$f.prototype), _initializer$f = applyDecoratedInitializer(_class2$f.prototype, "editingDidBegan", [_dec10, serializable$p], function () {
        return [];
      }), _initializer2$e = applyDecoratedInitializer(_class2$f.prototype, "textChanged", [_dec11, serializable$p], function () {
        return [];
      }), _initializer3$b = applyDecoratedInitializer(_class2$f.prototype, "editingDidEnded", [_dec12, serializable$p], function () {
        return [];
      }), _initializer4$a = applyDecoratedInitializer(_class2$f.prototype, "editingReturn", [_dec13, serializable$p], function () {
        return [];
      }), _initializer5$8 = applyDecoratedInitializer(_class2$f.prototype, "_textLabel", [serializable$p], function () {
        return null;
      }), _initializer6$5 = applyDecoratedInitializer(_class2$f.prototype, "_placeholderLabel", [serializable$p], function () {
        return null;
      }), _initializer7$5 = applyDecoratedInitializer(_class2$f.prototype, "_returnType", [serializable$p], function () {
        return KeyboardReturnType.DEFAULT;
      }), _initializer8$5 = applyDecoratedInitializer(_class2$f.prototype, "_string", [serializable$p], function () {
        return '';
      }), _initializer9$5 = applyDecoratedInitializer(_class2$f.prototype, "_tabIndex", [serializable$p], function () {
        return 0;
      }), _initializer10$5 = applyDecoratedInitializer(_class2$f.prototype, "_backgroundImage", [serializable$p], function () {
        return null;
      }), _initializer11$5 = applyDecoratedInitializer(_class2$f.prototype, "_inputFlag", [serializable$p], function () {
        return InputFlag.DEFAULT;
      }), _initializer12$4 = applyDecoratedInitializer(_class2$f.prototype, "_inputMode", [serializable$p], function () {
        return InputMode.ANY;
      }), _initializer13$2 = applyDecoratedInitializer(_class2$f.prototype, "_maxLength", [serializable$p], function () {
        return 20;
      })), _class2$f)) || _class$j) || _class$j) || _class$j));
      if (typeof window === 'object' && typeof document === 'object' && !MINIGAME && !JSB && !RUNTIME_BASED) {
        EditBox._EditBoxImpl = EditBoxImpl;
      }
      legacyCC.internal.EditBox = EditBox;

      var _dec$i, _dec2$f, _dec3$e, _dec4$a, _dec5$a, _dec6$4, _dec7$2, _dec8$1, _dec9$1, _class$i, _class2$e, _initializer$e, _initializer2$d, _initializer3$a, _initializer4$9, _initializer5$7, _initializer6$4, _initializer7$4, _initializer8$4, _initializer9$4, _initializer10$4, _initializer11$4, _initializer12$3, _initializer13$1, _initializer14$1, _initializer15$1, _initializer16$1, _class3$a;
      var Type;
      (function (Type) {
        Type[Type["NONE"] = 0] = "NONE";
        Type[Type["HORIZONTAL"] = 1] = "HORIZONTAL";
        Type[Type["VERTICAL"] = 2] = "VERTICAL";
        Type[Type["GRID"] = 3] = "GRID";
      })(Type || (Type = {}));
      ccenum(Type);
      var ResizeMode;
      (function (ResizeMode) {
        ResizeMode[ResizeMode["NONE"] = 0] = "NONE";
        ResizeMode[ResizeMode["CONTAINER"] = 1] = "CONTAINER";
        ResizeMode[ResizeMode["CHILDREN"] = 2] = "CHILDREN";
      })(ResizeMode || (ResizeMode = {}));
      ccenum(ResizeMode);
      var AxisDirection;
      (function (AxisDirection) {
        AxisDirection[AxisDirection["HORIZONTAL"] = 0] = "HORIZONTAL";
        AxisDirection[AxisDirection["VERTICAL"] = 1] = "VERTICAL";
      })(AxisDirection || (AxisDirection = {}));
      ccenum(AxisDirection);
      var VerticalDirection;
      (function (VerticalDirection) {
        VerticalDirection[VerticalDirection["BOTTOM_TO_TOP"] = 0] = "BOTTOM_TO_TOP";
        VerticalDirection[VerticalDirection["TOP_TO_BOTTOM"] = 1] = "TOP_TO_BOTTOM";
      })(VerticalDirection || (VerticalDirection = {}));
      ccenum(VerticalDirection);
      var HorizontalDirection;
      (function (HorizontalDirection) {
        HorizontalDirection[HorizontalDirection["LEFT_TO_RIGHT"] = 0] = "LEFT_TO_RIGHT";
        HorizontalDirection[HorizontalDirection["RIGHT_TO_LEFT"] = 1] = "RIGHT_TO_LEFT";
      })(HorizontalDirection || (HorizontalDirection = {}));
      ccenum(HorizontalDirection);
      var Constraint;
      (function (Constraint) {
        Constraint[Constraint["NONE"] = 0] = "NONE";
        Constraint[Constraint["FIXED_ROW"] = 1] = "FIXED_ROW";
        Constraint[Constraint["FIXED_COL"] = 2] = "FIXED_COL";
      })(Constraint || (Constraint = {}));
      ccenum(Constraint);
      var _tempVec3$2 = new Vec3();
      var Layout = exports('g$', (_dec$i = ccclass$M('cc.Layout'), _dec2$f = executionOrder$1(110), _dec3$e = requireComponent(UITransform), _dec4$a = type$d(Type), _dec5$a = type$d(ResizeMode), _dec6$4 = type$d(AxisDirection), _dec7$2 = type$d(VerticalDirection), _dec8$1 = type$d(HorizontalDirection), _dec9$1 = type$d(Constraint), _dec$i(_class$i = _dec2$f(_class$i = _dec3$e(_class$i = (_class2$e = (_class3$a = function (_Component) {
        _inheritsLoose(Layout, _Component);
        function Layout() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._resizeMode = _initializer$e && _initializer$e();
          _this._layoutType = _initializer2$d && _initializer2$d();
          _this._cellSize = _initializer3$a && _initializer3$a();
          _this._startAxis = _initializer4$9 && _initializer4$9();
          _this._paddingLeft = _initializer5$7 && _initializer5$7();
          _this._paddingRight = _initializer6$4 && _initializer6$4();
          _this._paddingTop = _initializer7$4 && _initializer7$4();
          _this._paddingBottom = _initializer8$4 && _initializer8$4();
          _this._spacingX = _initializer9$4 && _initializer9$4();
          _this._spacingY = _initializer10$4 && _initializer10$4();
          _this._verticalDirection = _initializer11$4 && _initializer11$4();
          _this._horizontalDirection = _initializer12$3 && _initializer12$3();
          _this._constraint = _initializer13$1 && _initializer13$1();
          _this._constraintNum = _initializer14$1 && _initializer14$1();
          _this._affectedByScale = _initializer15$1 && _initializer15$1();
          _this._isAlign = _initializer16$1 && _initializer16$1();
          _this._layoutSize = new Size$1(300, 200);
          _this._layoutDirty = true;
          _this._childrenDirty = false;
          _this._usefulLayoutObj = [];
          _this._init = false;
          return _this;
        }
        var _proto = Layout.prototype;
        _proto.updateLayout = function updateLayout(force) {
          if (force === void 0) {
            force = false;
          }
          if (this._layoutDirty || force) {
            this._doLayout();
            this._layoutDirty = false;
          }
        };
        _proto.onEnable = function onEnable() {
          this._addEventListeners();
          var trans = this.node._uiProps.uiTransformComp;
          if (trans.contentSize.equals(Size$1.ZERO)) {
            trans.setContentSize(this._layoutSize);
          }
          this._childrenChanged();
        };
        _proto.onDisable = function onDisable() {
          this._usefulLayoutObj.length = 0;
          this._removeEventListeners();
        };
        _proto._checkUsefulObj = function _checkUsefulObj() {
          this._usefulLayoutObj.length = 0;
          var children = this.node.children;
          for (var i = 0; i < children.length; ++i) {
            var child = children[i];
            var uiTrans = child._uiProps.uiTransformComp;
            if (child.activeInHierarchy && uiTrans) {
              this._usefulLayoutObj.push(uiTrans);
            }
          }
        };
        _proto._addEventListeners = function _addEventListeners() {
          director.on(Director.EVENT_AFTER_UPDATE, this.updateLayout, this);
          this.node.on(NodeEventType.SIZE_CHANGED, this._resized, this);
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
          this.node.on(NodeEventType.CHILD_ADDED, this._childAdded, this);
          this.node.on(NodeEventType.CHILD_REMOVED, this._childRemoved, this);
          this.node.on(NodeEventType.CHILDREN_ORDER_CHANGED, this._childrenChanged, this);
          this.node.on('childrenSiblingOrderChanged', this.updateLayout, this);
          this._addChildrenEventListeners();
        };
        _proto._removeEventListeners = function _removeEventListeners() {
          director.off(Director.EVENT_AFTER_UPDATE, this.updateLayout, this);
          this.node.off(NodeEventType.SIZE_CHANGED, this._resized, this);
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
          this.node.off(NodeEventType.CHILD_ADDED, this._childAdded, this);
          this.node.off(NodeEventType.CHILD_REMOVED, this._childRemoved, this);
          this.node.off(NodeEventType.CHILDREN_ORDER_CHANGED, this._childrenChanged, this);
          this.node.off('childrenSiblingOrderChanged', this.updateLayout, this);
          this._removeChildrenEventListeners();
        };
        _proto._addChildrenEventListeners = function _addChildrenEventListeners() {
          var children = this.node.children;
          for (var i = 0; i < children.length; ++i) {
            var child = children[i];
            child.on(NodeEventType.SIZE_CHANGED, this._doLayoutDirty, this);
            child.on(NodeEventType.TRANSFORM_CHANGED, this._transformDirty, this);
            child.on(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
            child.on(NodeEventType.ACTIVE_IN_HIERARCHY_CHANGED, this._childrenChanged, this);
          }
        };
        _proto._removeChildrenEventListeners = function _removeChildrenEventListeners() {
          var children = this.node.children;
          for (var i = 0; i < children.length; ++i) {
            var child = children[i];
            child.off(NodeEventType.SIZE_CHANGED, this._doLayoutDirty, this);
            child.off(NodeEventType.TRANSFORM_CHANGED, this._transformDirty, this);
            child.off(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
            child.off(NodeEventType.ACTIVE_IN_HIERARCHY_CHANGED, this._childrenChanged, this);
          }
        };
        _proto._childAdded = function _childAdded(child) {
          child.on(NodeEventType.SIZE_CHANGED, this._doLayoutDirty, this);
          child.on(NodeEventType.TRANSFORM_CHANGED, this._transformDirty, this);
          child.on(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
          child.on(NodeEventType.ACTIVE_IN_HIERARCHY_CHANGED, this._childrenChanged, this);
          this._childrenChanged();
        };
        _proto._childRemoved = function _childRemoved(child) {
          child.off(NodeEventType.SIZE_CHANGED, this._doLayoutDirty, this);
          child.off(NodeEventType.TRANSFORM_CHANGED, this._transformDirty, this);
          child.off(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
          child.off(NodeEventType.ACTIVE_IN_HIERARCHY_CHANGED, this._childrenChanged, this);
          this._childrenChanged();
        };
        _proto._resized = function _resized() {
          this._layoutSize.set(this.node._uiProps.uiTransformComp.contentSize);
          this._doLayoutDirty();
        };
        _proto._doLayoutHorizontally = function _doLayoutHorizontally(baseWidth, rowBreak, fnPositionY, applyChildren) {
          var trans = this.node._uiProps.uiTransformComp;
          var layoutAnchor = trans.anchorPoint;
          var limit = this._getFixedBreakingNum();
          var sign = 1;
          var paddingX = this._paddingLeft;
          if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
            sign = -1;
            paddingX = this._paddingRight;
          }
          var startPos = (this._horizontalDirection - layoutAnchor.x) * baseWidth + sign * paddingX;
          var nextX = startPos - sign * this._spacingX;
          var totalHeight = 0;
          var rowMaxHeight = 0;
          var tempMaxHeight = 0;
          var maxHeight = 0;
          var isBreak = false;
          var activeChildCount = this._usefulLayoutObj.length;
          var newChildWidth = this._cellSize.width;
          var paddingH = this._getPaddingH();
          if (this._layoutType !== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) {
            newChildWidth = (baseWidth - paddingH - (activeChildCount - 1) * this._spacingX) / activeChildCount;
          }
          var children = this._usefulLayoutObj;
          for (var i = 0; i < children.length; ++i) {
            var childTrans = children[i];
            var child = childTrans.node;
            var scale = child.scale;
            var childScaleX = this._getUsedScaleValue(scale.x);
            var childScaleY = this._getUsedScaleValue(scale.y);
            if (this._resizeMode === ResizeMode.CHILDREN) {
              childTrans.width = newChildWidth / childScaleX;
              if (this._layoutType === Type.GRID) {
                childTrans.height = this._cellSize.height / childScaleY;
              }
            }
            var anchorX = Math.abs(this._horizontalDirection - childTrans.anchorX);
            var childBoundingBoxWidth = childTrans.width * childScaleX;
            var childBoundingBoxHeight = childTrans.height * childScaleY;
            if (childBoundingBoxHeight > tempMaxHeight) {
              maxHeight = Math.max(tempMaxHeight, maxHeight);
              rowMaxHeight = tempMaxHeight || childBoundingBoxHeight;
              tempMaxHeight = childBoundingBoxHeight;
            }
            nextX += sign * (anchorX * childBoundingBoxWidth + this._spacingX);
            var rightBoundaryOfChild = sign * (1 - anchorX) * childBoundingBoxWidth;
            if (rowBreak) {
              if (limit > 0) {
                isBreak = i / limit > 0 && i % limit === 0;
                if (isBreak) {
                  rowMaxHeight = tempMaxHeight > childBoundingBoxHeight ? tempMaxHeight : rowMaxHeight;
                }
              } else if (childBoundingBoxWidth > baseWidth - paddingH) {
                if (nextX > startPos + sign * (anchorX * childBoundingBoxWidth)) {
                  isBreak = true;
                }
              } else {
                var boundary = (1 - this._horizontalDirection - layoutAnchor.x) * baseWidth;
                var rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this._paddingRight : this._paddingLeft);
                isBreak = Math.abs(rowBreakBoundary) > Math.abs(boundary);
              }
              if (isBreak) {
                nextX = startPos + sign * (anchorX * childBoundingBoxWidth);
                if (childBoundingBoxHeight !== tempMaxHeight) {
                  rowMaxHeight = tempMaxHeight;
                }
                totalHeight += rowMaxHeight + this._spacingY;
                rowMaxHeight = tempMaxHeight = childBoundingBoxHeight;
              }
            }
            var finalPositionY = fnPositionY(child, childTrans, totalHeight);
            if (applyChildren) {
              child.setPosition(nextX, finalPositionY);
            }
            nextX += rightBoundaryOfChild;
          }
          rowMaxHeight = Math.max(rowMaxHeight, tempMaxHeight);
          var containerResizeBoundary = Math.max(maxHeight, totalHeight + rowMaxHeight) + this._getPaddingV();
          return containerResizeBoundary;
        };
        _proto._doLayoutVertically = function _doLayoutVertically(baseHeight, columnBreak, fnPositionX, applyChildren) {
          var trans = this.node._uiProps.uiTransformComp;
          var layoutAnchor = trans.anchorPoint;
          var limit = this._getFixedBreakingNum();
          var sign = 1;
          var paddingY = this._paddingBottom;
          if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
            sign = -1;
            paddingY = this._paddingTop;
          }
          var startPos = (this._verticalDirection - layoutAnchor.y) * baseHeight + sign * paddingY;
          var nextY = startPos - sign * this._spacingY;
          var tempMaxWidth = 0;
          var maxWidth = 0;
          var colMaxWidth = 0;
          var totalWidth = 0;
          var isBreak = false;
          var activeChildCount = this._usefulLayoutObj.length;
          var newChildHeight = this._cellSize.height;
          var paddingV = this._getPaddingV();
          if (this._layoutType !== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) {
            newChildHeight = (baseHeight - paddingV - (activeChildCount - 1) * this._spacingY) / activeChildCount;
          }
          var children = this._usefulLayoutObj;
          for (var i = 0; i < children.length; ++i) {
            var childTrans = children[i];
            var child = childTrans.node;
            var scale = child.scale;
            var childScaleX = this._getUsedScaleValue(scale.x);
            var childScaleY = this._getUsedScaleValue(scale.y);
            if (this._resizeMode === ResizeMode.CHILDREN) {
              childTrans.height = newChildHeight / childScaleY;
              if (this._layoutType === Type.GRID) {
                childTrans.width = this._cellSize.width / childScaleX;
              }
            }
            var anchorY = Math.abs(this._verticalDirection - childTrans.anchorY);
            var childBoundingBoxWidth = childTrans.width * childScaleX;
            var childBoundingBoxHeight = childTrans.height * childScaleY;
            if (childBoundingBoxWidth > tempMaxWidth) {
              maxWidth = Math.max(tempMaxWidth, maxWidth);
              colMaxWidth = tempMaxWidth || childBoundingBoxWidth;
              tempMaxWidth = childBoundingBoxWidth;
            }
            nextY += sign * (anchorY * childBoundingBoxHeight + this._spacingY);
            var topBoundaryOfChild = sign * (1 - anchorY) * childBoundingBoxHeight;
            if (columnBreak) {
              if (limit > 0) {
                isBreak = i / limit > 0 && i % limit === 0;
                if (isBreak) {
                  colMaxWidth = tempMaxWidth > childBoundingBoxHeight ? tempMaxWidth : colMaxWidth;
                }
              } else if (childBoundingBoxHeight > baseHeight - paddingV) {
                if (nextY > startPos + sign * (anchorY * childBoundingBoxHeight)) {
                  isBreak = true;
                }
              } else {
                var boundary = (1 - this._verticalDirection - layoutAnchor.y) * baseHeight;
                var columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this._paddingTop : this._paddingBottom);
                isBreak = Math.abs(columnBreakBoundary) > Math.abs(boundary);
              }
              if (isBreak) {
                nextY = startPos + sign * (anchorY * childBoundingBoxHeight);
                if (childBoundingBoxWidth !== tempMaxWidth) {
                  colMaxWidth = tempMaxWidth;
                }
                totalWidth += colMaxWidth + this._spacingX;
                colMaxWidth = tempMaxWidth = childBoundingBoxWidth;
              }
            }
            var finalPositionX = fnPositionX(child, childTrans, totalWidth);
            if (applyChildren) {
              child.getPosition(_tempVec3$2);
              child.setPosition(finalPositionX, nextY, _tempVec3$2.z);
            }
            nextY += topBoundaryOfChild;
          }
          colMaxWidth = Math.max(colMaxWidth, tempMaxWidth);
          var containerResizeBoundary = Math.max(maxWidth, totalWidth + colMaxWidth) + this._getPaddingH();
          return containerResizeBoundary;
        };
        _proto._doLayoutGridAxisHorizontal = function _doLayoutGridAxisHorizontal(layoutAnchor, layoutSize) {
          var _this2 = this;
          var baseWidth = layoutSize.width;
          var sign = 1;
          var bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height;
          var paddingY = this._paddingBottom;
          if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
            sign = -1;
            bottomBoundaryOfLayout = (1 - layoutAnchor.y) * layoutSize.height;
            paddingY = this._paddingTop;
          }
          var fnPositionY = function fnPositionY(child, childTrans, topOffset) {
            return bottomBoundaryOfLayout + sign * (topOffset + (1 - childTrans.anchorY) * childTrans.height * _this2._getUsedScaleValue(child.scale.y) + paddingY);
          };
          var newHeight = 0;
          if (this._resizeMode === ResizeMode.CONTAINER) {
            newHeight = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false);
            bottomBoundaryOfLayout = -layoutAnchor.y * newHeight;
            if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
              sign = -1;
              bottomBoundaryOfLayout = (1 - layoutAnchor.y) * newHeight;
            }
          }
          this._doLayoutHorizontally(baseWidth, true, fnPositionY, true);
          if (this._resizeMode === ResizeMode.CONTAINER) {
            this.node._uiProps.uiTransformComp.setContentSize(baseWidth, newHeight);
          }
        };
        _proto._doLayoutGridAxisVertical = function _doLayoutGridAxisVertical(layoutAnchor, layoutSize) {
          var _this3 = this;
          var baseHeight = layoutSize.height;
          var sign = 1;
          var leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width;
          var paddingX = this._paddingLeft;
          if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
            sign = -1;
            leftBoundaryOfLayout = (1 - layoutAnchor.x) * layoutSize.width;
            paddingX = this._paddingRight;
          }
          var fnPositionX = function fnPositionX(child, childTrans, leftOffset) {
            return leftBoundaryOfLayout + sign * (leftOffset + (1 - childTrans.anchorX) * childTrans.width * _this3._getUsedScaleValue(child.scale.x) + paddingX);
          };
          var newWidth = 0;
          if (this._resizeMode === ResizeMode.CONTAINER) {
            newWidth = this._doLayoutVertically(baseHeight, true, fnPositionX, false);
            leftBoundaryOfLayout = -layoutAnchor.x * newWidth;
            if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
              sign = -1;
              leftBoundaryOfLayout = (1 - layoutAnchor.x) * newWidth;
            }
          }
          this._doLayoutVertically(baseHeight, true, fnPositionX, true);
          if (this._resizeMode === ResizeMode.CONTAINER) {
            this.node._uiProps.uiTransformComp.setContentSize(newWidth, baseHeight);
          }
        };
        _proto._doLayoutGrid = function _doLayoutGrid() {
          var trans = this.node._uiProps.uiTransformComp;
          var layoutAnchor = trans.anchorPoint;
          var layoutSize = trans.contentSize;
          if (this.startAxis === AxisDirection.HORIZONTAL) {
            this._doLayoutGridAxisHorizontal(layoutAnchor, layoutSize);
          } else if (this.startAxis === AxisDirection.VERTICAL) {
            this._doLayoutGridAxisVertical(layoutAnchor, layoutSize);
          }
        };
        _proto._getHorizontalBaseWidth = function _getHorizontalBaseWidth(horizontal) {
          var children = this._usefulLayoutObj;
          var baseSize = 0;
          var activeChildCount = children.length;
          if (this._resizeMode === ResizeMode.CONTAINER) {
            for (var i = 0; i < children.length; ++i) {
              var childTrans = children[i];
              var child = childTrans.node;
              var scale = child.scale;
              baseSize += childTrans.width * this._getUsedScaleValue(scale.x);
            }
            baseSize += (activeChildCount - 1) * this._spacingX + this._getPaddingH();
          } else {
            baseSize = this.node._uiProps.uiTransformComp.width;
          }
          return baseSize;
        };
        _proto._getVerticalBaseHeight = function _getVerticalBaseHeight() {
          var children = this._usefulLayoutObj;
          var baseSize = 0;
          var activeChildCount = children.length;
          if (this._resizeMode === ResizeMode.CONTAINER) {
            for (var i = 0; i < children.length; ++i) {
              var childTrans = children[i];
              var child = childTrans.node;
              var scale = child.scale;
              baseSize += childTrans.height * this._getUsedScaleValue(scale.y);
            }
            baseSize += (activeChildCount - 1) * this._spacingY + this._getPaddingV();
          } else {
            baseSize = this.node._uiProps.uiTransformComp.height;
          }
          return baseSize;
        };
        _proto._doLayout = function _doLayout() {
          var _this4 = this;
          if (!this._init || this._childrenDirty) {
            this._checkUsefulObj();
            this._init = true;
            this._childrenDirty = false;
          }
          if (this._layoutType === Type.HORIZONTAL) {
            var newWidth = this._getHorizontalBaseWidth();
            var fnPositionY = function fnPositionY(child) {
              var pos = _this4._isAlign ? Vec3.ZERO : child.position;
              return pos.y;
            };
            this._doLayoutHorizontally(newWidth, false, fnPositionY, true);
            this.node._uiProps.uiTransformComp.width = newWidth;
          } else if (this._layoutType === Type.VERTICAL) {
            var newHeight = this._getVerticalBaseHeight();
            var fnPositionX = function fnPositionX(child) {
              var pos = _this4._isAlign ? Vec3.ZERO : child.position;
              return pos.x;
            };
            this._doLayoutVertically(newHeight, false, fnPositionX, true);
            this.node._uiProps.uiTransformComp.height = newHeight;
          } else if (this._layoutType === Type.GRID) {
            this._doLayoutGrid();
          }
        };
        _proto._getUsedScaleValue = function _getUsedScaleValue(value) {
          return this._affectedByScale ? Math.abs(value) : 1;
        };
        _proto._transformDirty = function _transformDirty(type) {
          if (!(type & TransformBit.SCALE) || !(type & TransformBit.POSITION) || !this._affectedByScale) {
            return;
          }
          this._doLayoutDirty();
        };
        _proto._doLayoutDirty = function _doLayoutDirty() {
          this._layoutDirty = true;
        };
        _proto._childrenChanged = function _childrenChanged() {
          this._childrenDirty = true;
          this._doLayoutDirty();
        };
        _proto._getPaddingH = function _getPaddingH() {
          return this._paddingLeft + this._paddingRight;
        };
        _proto._getPaddingV = function _getPaddingV() {
          return this._paddingTop + this._paddingBottom;
        };
        _proto._getFixedBreakingNum = function _getFixedBreakingNum() {
          if (this._layoutType !== Type.GRID || this._constraint === Constraint.NONE || this._constraintNum <= 0) {
            return 0;
          }
          var num = this._constraint === Constraint.FIXED_ROW ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum;
          if (this._startAxis === AxisDirection.VERTICAL) {
            num = this._constraint === Constraint.FIXED_COL ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum;
          }
          return num;
        };
        _createClass(Layout, [{
          key: "alignHorizontal",
          get: function get() {
            return this._isAlign;
          },
          set: function set(value) {
            if (this._layoutType !== Type.HORIZONTAL) {
              return;
            }
            this._isAlign = value;
            this._doLayoutDirty();
          }
        }, {
          key: "alignVertical",
          get: function get() {
            return this._isAlign;
          },
          set: function set(value) {
            if (this._layoutType !== Type.VERTICAL) {
              return;
            }
            this._isAlign = value;
            this._doLayoutDirty();
          }
        }, {
          key: "type",
          get: function get() {
            return this._layoutType;
          },
          set: function set(value) {
            this._layoutType = value;
            this._doLayoutDirty();
          }
        }, {
          key: "resizeMode",
          get: function get() {
            return this._resizeMode;
          },
          set: function set(value) {
            if (this._layoutType === Type.NONE) {
              return;
            }
            this._resizeMode = value;
            this._doLayoutDirty();
          }
        }, {
          key: "cellSize",
          get: function get() {
            return this._cellSize;
          },
          set: function set(value) {
            if (this._cellSize === value) {
              return;
            }
            this._cellSize.set(value);
            this._doLayoutDirty();
          }
        }, {
          key: "startAxis",
          get: function get() {
            return this._startAxis;
          },
          set: function set(value) {
            if (this._startAxis === value) {
              return;
            }
            this._startAxis = value;
            this._doLayoutDirty();
          }
        }, {
          key: "paddingLeft",
          get: function get() {
            return this._paddingLeft;
          },
          set: function set(value) {
            if (this._paddingLeft === value) {
              return;
            }
            this._paddingLeft = value;
            this._doLayoutDirty();
          }
        }, {
          key: "paddingRight",
          get: function get() {
            return this._paddingRight;
          },
          set: function set(value) {
            if (this._paddingRight === value) {
              return;
            }
            this._paddingRight = value;
            this._doLayoutDirty();
          }
        }, {
          key: "paddingTop",
          get: function get() {
            return this._paddingTop;
          },
          set: function set(value) {
            if (this._paddingTop === value) {
              return;
            }
            this._paddingTop = value;
            this._doLayoutDirty();
          }
        }, {
          key: "paddingBottom",
          get: function get() {
            return this._paddingBottom;
          },
          set: function set(value) {
            if (this._paddingBottom === value) {
              return;
            }
            this._paddingBottom = value;
            this._doLayoutDirty();
          }
        }, {
          key: "spacingX",
          get: function get() {
            return this._spacingX;
          },
          set: function set(value) {
            if (this._spacingX === value) {
              return;
            }
            this._spacingX = value;
            this._doLayoutDirty();
          }
        }, {
          key: "spacingY",
          get: function get() {
            return this._spacingY;
          },
          set: function set(value) {
            if (this._spacingY === value) {
              return;
            }
            this._spacingY = value;
            this._doLayoutDirty();
          }
        }, {
          key: "verticalDirection",
          get: function get() {
            return this._verticalDirection;
          },
          set: function set(value) {
            if (this._verticalDirection === value) {
              return;
            }
            this._verticalDirection = value;
            this._doLayoutDirty();
          }
        }, {
          key: "horizontalDirection",
          get: function get() {
            return this._horizontalDirection;
          },
          set: function set(value) {
            if (this._horizontalDirection === value) {
              return;
            }
            this._horizontalDirection = value;
            this._doLayoutDirty();
          }
        }, {
          key: "padding",
          get: function get() {
            return this._paddingLeft;
          },
          set: function set(value) {
            if (this.paddingLeft !== value || this._paddingRight !== value || this._paddingTop !== value || this._paddingBottom !== value) {
              this._paddingLeft = this._paddingRight = this._paddingTop = this._paddingBottom = value;
              this._doLayoutDirty();
            }
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._constraint;
          },
          set: function set(value) {
            if (this._layoutType === Type.NONE || this._constraint === value) {
              return;
            }
            this._constraint = value;
            this._doLayoutDirty();
          }
        }, {
          key: "constraintNum",
          get: function get() {
            return this._constraintNum;
          },
          set: function set(value) {
            if (this._constraint === Constraint.NONE || this._constraintNum === value) {
              return;
            }
            if (value <= 0) {
              warn('Limit values to be greater than 0');
            }
            this._constraintNum = value;
            this._doLayoutDirty();
          }
        }, {
          key: "affectedByScale",
          get: function get() {
            return this._affectedByScale;
          },
          set: function set(value) {
            this._affectedByScale = value;
            this._doLayoutDirty();
          }
        }]);
        return Layout;
      }(Component), _class3$a.Type = Type, _class3$a.VerticalDirection = VerticalDirection, _class3$a.HorizontalDirection = HorizontalDirection, _class3$a.ResizeMode = ResizeMode, _class3$a.AxisDirection = AxisDirection, _class3$a.Constraint = Constraint, _class3$a), (_applyDecoratedDescriptor(_class2$e.prototype, "type", [_dec4$a], Object.getOwnPropertyDescriptor(_class2$e.prototype, "type"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "resizeMode", [_dec5$a], Object.getOwnPropertyDescriptor(_class2$e.prototype, "resizeMode"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "startAxis", [_dec6$4], Object.getOwnPropertyDescriptor(_class2$e.prototype, "startAxis"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "verticalDirection", [_dec7$2], Object.getOwnPropertyDescriptor(_class2$e.prototype, "verticalDirection"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "horizontalDirection", [_dec8$1], Object.getOwnPropertyDescriptor(_class2$e.prototype, "horizontalDirection"), _class2$e.prototype), _applyDecoratedDescriptor(_class2$e.prototype, "constraint", [_dec9$1], Object.getOwnPropertyDescriptor(_class2$e.prototype, "constraint"), _class2$e.prototype), _initializer$e = applyDecoratedInitializer(_class2$e.prototype, "_resizeMode", [serializable$p], function () {
        return ResizeMode.NONE;
      }), _initializer2$d = applyDecoratedInitializer(_class2$e.prototype, "_layoutType", [serializable$p], function () {
        return Type.NONE;
      }), _initializer3$a = applyDecoratedInitializer(_class2$e.prototype, "_cellSize", [serializable$p], function () {
        return new Size$1(40, 40);
      }), _initializer4$9 = applyDecoratedInitializer(_class2$e.prototype, "_startAxis", [serializable$p], function () {
        return AxisDirection.HORIZONTAL;
      }), _initializer5$7 = applyDecoratedInitializer(_class2$e.prototype, "_paddingLeft", [serializable$p], function () {
        return 0;
      }), _initializer6$4 = applyDecoratedInitializer(_class2$e.prototype, "_paddingRight", [serializable$p], function () {
        return 0;
      }), _initializer7$4 = applyDecoratedInitializer(_class2$e.prototype, "_paddingTop", [serializable$p], function () {
        return 0;
      }), _initializer8$4 = applyDecoratedInitializer(_class2$e.prototype, "_paddingBottom", [serializable$p], function () {
        return 0;
      }), _initializer9$4 = applyDecoratedInitializer(_class2$e.prototype, "_spacingX", [serializable$p], function () {
        return 0;
      }), _initializer10$4 = applyDecoratedInitializer(_class2$e.prototype, "_spacingY", [serializable$p], function () {
        return 0;
      }), _initializer11$4 = applyDecoratedInitializer(_class2$e.prototype, "_verticalDirection", [serializable$p], function () {
        return VerticalDirection.TOP_TO_BOTTOM;
      }), _initializer12$3 = applyDecoratedInitializer(_class2$e.prototype, "_horizontalDirection", [serializable$p], function () {
        return HorizontalDirection.LEFT_TO_RIGHT;
      }), _initializer13$1 = applyDecoratedInitializer(_class2$e.prototype, "_constraint", [serializable$p], function () {
        return Constraint.NONE;
      }), _initializer14$1 = applyDecoratedInitializer(_class2$e.prototype, "_constraintNum", [serializable$p], function () {
        return 2;
      }), _initializer15$1 = applyDecoratedInitializer(_class2$e.prototype, "_affectedByScale", [serializable$p], function () {
        return false;
      }), _initializer16$1 = applyDecoratedInitializer(_class2$e.prototype, "_isAlign", [serializable$p], function () {
        return false;
      })), _class2$e)) || _class$i) || _class$i) || _class$i));
      legacyCC.Layout = Layout;

      var _dec$h, _dec2$e, _dec3$d, _dec4$9, _dec5$9, _class$h, _class2$d, _initializer$d, _initializer2$c, _initializer3$9, _initializer4$8, _initializer5$6, _class3$9;
      var Mode;
      (function (Mode) {
        Mode[Mode["HORIZONTAL"] = 0] = "HORIZONTAL";
        Mode[Mode["VERTICAL"] = 1] = "VERTICAL";
        Mode[Mode["FILLED"] = 2] = "FILLED";
      })(Mode || (Mode = {}));
      Enum(Mode);
      var ProgressBar = exports('h0', (_dec$h = ccclass$M('cc.ProgressBar'), _dec2$e = executionOrder$1(110), _dec3$d = requireComponent(UITransform), _dec4$9 = type$d(Sprite), _dec5$9 = type$d(Mode), _dec$h(_class$h = _dec2$e(_class$h = _dec3$d(_class$h = (_class2$d = (_class3$9 = function (_Component) {
        _inheritsLoose(ProgressBar, _Component);
        function ProgressBar() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._barSprite = _initializer$d && _initializer$d();
          _this._mode = _initializer2$c && _initializer2$c();
          _this._totalLength = _initializer3$9 && _initializer3$9();
          _this._progress = _initializer4$8 && _initializer4$8();
          _this._reverse = _initializer5$6 && _initializer5$6();
          return _this;
        }
        var _proto = ProgressBar.prototype;
        _proto.onLoad = function onLoad() {
          this._updateBarStatus();
        };
        _proto._initBarSprite = function _initBarSprite() {
          if (this._barSprite) {
            var entity = this._barSprite.node;
            if (!entity) {
              return;
            }
            var trans = this.node._uiProps.uiTransformComp;
            var nodeSize = trans.contentSize;
            var nodeAnchor = trans.anchorPoint;
            var barSpriteSize = entity._uiProps.uiTransformComp.contentSize;
            if (this._barSprite.fillType === Sprite.FillType.RADIAL) {
              this._mode = Mode.FILLED;
            }
            if (this._mode === Mode.HORIZONTAL) {
              this.totalLength = barSpriteSize.width;
            } else if (this._mode === Mode.VERTICAL) {
              this.totalLength = barSpriteSize.height;
            } else {
              this.totalLength = this._barSprite.fillRange;
            }
            if (entity.parent === this.node) {
              var x = -nodeSize.width * nodeAnchor.x;
              entity.setPosition(x, 0, 0);
            }
          }
        };
        _proto._updateBarStatus = function _updateBarStatus() {
          if (this._barSprite) {
            var entity = this._barSprite.node;
            if (!entity) {
              return;
            }
            var entTrans = entity._uiProps.uiTransformComp;
            var entityAnchorPoint = entTrans.anchorPoint;
            var entitySize = entTrans.contentSize;
            var entityPosition = entity.getPosition();
            var anchorPoint = new Vec2(0, 0.5);
            var progress = clamp01(this._progress);
            var actualLenth = this._totalLength * progress;
            var finalContentSize = entitySize;
            var totalWidth = 0;
            var totalHeight = 0;
            switch (this._mode) {
              case Mode.HORIZONTAL:
                if (this._reverse) {
                  anchorPoint = new Vec2(1, 0.5);
                }
                finalContentSize = new Size$1(actualLenth, entitySize.height);
                totalWidth = this._totalLength;
                totalHeight = entitySize.height;
                break;
              case Mode.VERTICAL:
                if (this._reverse) {
                  anchorPoint = new Vec2(0.5, 1);
                } else {
                  anchorPoint = new Vec2(0.5, 0);
                }
                finalContentSize = new Size$1(entitySize.width, actualLenth);
                totalWidth = entitySize.width;
                totalHeight = this._totalLength;
                break;
            }
            if (this._mode === Mode.FILLED) {
              if (this._barSprite.type !== Sprite.Type.FILLED) {
                warn('ProgressBar FILLED mode only works when barSprite\'s Type is FILLED!');
              } else {
                if (this._reverse) {
                  actualLenth *= -1;
                }
                this._barSprite.fillRange = actualLenth;
              }
            } else if (this._barSprite.type !== Sprite.Type.FILLED) {
              var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x;
              var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y;
              var finalPosition = new Vec3(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY, 0);
              entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y, entityPosition.z);
              entTrans.setAnchorPoint(anchorPoint);
              entTrans.setContentSize(finalContentSize);
            } else {
              warn('ProgressBar non-FILLED mode only works when barSprite\'s Type is non-FILLED!');
            }
          }
        };
        _createClass(ProgressBar, [{
          key: "barSprite",
          get: function get() {
            return this._barSprite;
          },
          set: function set(value) {
            if (this._barSprite === value) {
              return;
            }
            this._barSprite = value;
            this._initBarSprite();
          }
        }, {
          key: "mode",
          get: function get() {
            return this._mode;
          },
          set: function set(value) {
            if (this._mode === value) {
              return;
            }
            this._mode = value;
            if (this._barSprite) {
              var entity = this._barSprite.node;
              if (!entity) {
                return;
              }
              var entitySize = entity._uiProps.uiTransformComp.contentSize;
              if (this._mode === Mode.HORIZONTAL) {
                this.totalLength = entitySize.width;
              } else if (this._mode === Mode.VERTICAL) {
                this.totalLength = entitySize.height;
              } else if (this._mode === Mode.FILLED) {
                this.totalLength = this._barSprite.fillRange;
              }
            }
          }
        }, {
          key: "totalLength",
          get: function get() {
            return this._totalLength;
          },
          set: function set(value) {
            if (this._mode === Mode.FILLED) {
              value = clamp01(value);
            }
            if (this._totalLength === value) {
              return;
            }
            this._totalLength = value;
            this._updateBarStatus();
          }
        }, {
          key: "progress",
          get: function get() {
            return this._progress;
          },
          set: function set(value) {
            if (this._progress === value) {
              return;
            }
            this._progress = value;
            this._updateBarStatus();
          }
        }, {
          key: "reverse",
          get: function get() {
            return this._reverse;
          },
          set: function set(value) {
            if (this._reverse === value) {
              return;
            }
            this._reverse = value;
            if (this._barSprite) {
              this._barSprite.fillStart = 1 - this._barSprite.fillStart;
            }
            this._updateBarStatus();
          }
        }]);
        return ProgressBar;
      }(Component), _class3$9.Mode = Mode, _class3$9), (_applyDecoratedDescriptor(_class2$d.prototype, "barSprite", [_dec4$9], Object.getOwnPropertyDescriptor(_class2$d.prototype, "barSprite"), _class2$d.prototype), _applyDecoratedDescriptor(_class2$d.prototype, "mode", [_dec5$9], Object.getOwnPropertyDescriptor(_class2$d.prototype, "mode"), _class2$d.prototype), _initializer$d = applyDecoratedInitializer(_class2$d.prototype, "_barSprite", [serializable$p], function () {
        return null;
      }), _initializer2$c = applyDecoratedInitializer(_class2$d.prototype, "_mode", [serializable$p], function () {
        return Mode.HORIZONTAL;
      }), _initializer3$9 = applyDecoratedInitializer(_class2$d.prototype, "_totalLength", [serializable$p], function () {
        return 1;
      }), _initializer4$8 = applyDecoratedInitializer(_class2$d.prototype, "_progress", [serializable$p], function () {
        return 0.1;
      }), _initializer5$6 = applyDecoratedInitializer(_class2$d.prototype, "_reverse", [serializable$p], function () {
        return false;
      })), _class2$d)) || _class$h) || _class$h) || _class$h));
      legacyCC.ProgressBar = ProgressBar;

      var _dec$g, _dec2$d, _dec3$c, _dec4$8, _dec5$8, _class$g, _class2$c, _initializer$c, _initializer2$b, _initializer3$8, _initializer4$7, _initializer5$5, _class3$8;
      var GETTING_SHORTER_FACTOR = 20;
      var _tempPos_1 = new Vec3();
      var _tempPos_2 = new Vec3();
      var _tempVec3$1 = new Vec3();
      var defaultAnchor = new Vec2();
      var _tempColor = new Color$1();
      var _tempVec2$2 = new Vec2();
      var Direction$3;
      (function (Direction) {
        Direction[Direction["HORIZONTAL"] = 0] = "HORIZONTAL";
        Direction[Direction["VERTICAL"] = 1] = "VERTICAL";
      })(Direction$3 || (Direction$3 = {}));
      ccenum(Direction$3);
      var ScrollBar = exports('h1', (_dec$g = ccclass$M('cc.ScrollBar'), _dec2$d = executionOrder$1(110), _dec3$c = requireComponent(UITransform), _dec4$8 = type$d(Sprite), _dec5$8 = type$d(Direction$3), _dec$g(_class$g = _dec2$d(_class$g = _dec3$c(_class$g = (_class2$c = (_class3$8 = function (_Component) {
        _inheritsLoose(ScrollBar, _Component);
        function ScrollBar() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._scrollView = _initializer$c && _initializer$c();
          _this._handle = _initializer2$b && _initializer2$b();
          _this._direction = _initializer3$8 && _initializer3$8();
          _this._enableAutoHide = _initializer4$7 && _initializer4$7();
          _this._autoHideTime = _initializer5$5 && _initializer5$5();
          _this._touching = false;
          _this._opacity = 255;
          _this._autoHideRemainingTime = 0;
          return _this;
        }
        var _proto = ScrollBar.prototype;
        _proto.hide = function hide() {
          this._autoHideRemainingTime = 0;
          this._setOpacity(0);
        };
        _proto.show = function show() {
          this._autoHideRemainingTime = this._autoHideTime;
          this._opacity = 255;
          this._setOpacity(this._opacity);
        };
        _proto.onScroll = function onScroll(outOfBoundary) {
          if (!this._scrollView) {
            return;
          }
          var content = this._scrollView.content;
          if (!content) {
            return;
          }
          var contentSize = content._uiProps.uiTransformComp.contentSize;
          var scrollViewSize = this._scrollView.node._uiProps.uiTransformComp.contentSize;
          var barSize = this.node._uiProps.uiTransformComp.contentSize;
          if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
            return;
          }
          if (this._enableAutoHide) {
            this._autoHideRemainingTime = this._autoHideTime;
            this._setOpacity(this._opacity);
          }
          var contentMeasure = 0;
          var scrollViewMeasure = 0;
          var outOfBoundaryValue = 0;
          var contentPosition = 0;
          var handleNodeMeasure = 0;
          var outOfContentPosition = _tempVec2$2;
          outOfContentPosition.set(0, 0);
          if (this._direction === Direction$3.HORIZONTAL) {
            contentMeasure = contentSize.width;
            scrollViewMeasure = scrollViewSize.width;
            handleNodeMeasure = barSize.width;
            outOfBoundaryValue = outOfBoundary.x;
            this._convertToScrollViewSpace(outOfContentPosition, content);
            contentPosition = -outOfContentPosition.x;
          } else if (this._direction === Direction$3.VERTICAL) {
            contentMeasure = contentSize.height;
            scrollViewMeasure = scrollViewSize.height;
            handleNodeMeasure = barSize.height;
            outOfBoundaryValue = outOfBoundary.y;
            this._convertToScrollViewSpace(outOfContentPosition, content);
            contentPosition = -outOfContentPosition.y;
          }
          var length = this._calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundaryValue);
          var position = _tempVec2$2;
          this._calculatePosition(position, contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundaryValue, length);
          this._updateLength(length);
          this._updateHandlerPosition(position);
        };
        _proto.setScrollView = function setScrollView(scrollView) {
          this._scrollView = scrollView;
        };
        _proto.onTouchBegan = function onTouchBegan() {
          if (!this._enableAutoHide) {
            return;
          }
          this._touching = true;
        };
        _proto.onTouchEnded = function onTouchEnded() {
          if (!this._enableAutoHide) {
            return;
          }
          this._touching = false;
          if (this._autoHideTime <= 0) {
            return;
          }
          if (this._scrollView) {
            var content = this._scrollView.content;
            if (content) {
              var contentSize = content._uiProps.uiTransformComp.contentSize;
              var scrollViewSize = this._scrollView.node._uiProps.uiTransformComp.contentSize;
              if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
                return;
              }
            }
          }
          this._autoHideRemainingTime = this._autoHideTime;
        };
        _proto.onEnable = function onEnable() {
          var renderComp = this.node.getComponent(Sprite);
          if (renderComp) {
            this._opacity = renderComp.color.a;
          }
        };
        _proto.start = function start() {
          if (this._enableAutoHide) {
            this._setOpacity(0);
          }
        };
        _proto.update = function update(dt) {
          this._processAutoHide(dt);
        };
        _proto._convertToScrollViewSpace = function _convertToScrollViewSpace(out, content) {
          var scrollTrans = this._scrollView && this._scrollView.node._uiProps.uiTransformComp;
          var contentTrans = content._uiProps.uiTransformComp;
          if (!scrollTrans || !contentTrans) {
            out.set(Vec2.ZERO);
          } else {
            _tempPos_1.set(-contentTrans.anchorX * contentTrans.width, -contentTrans.anchorY * contentTrans.height, 0);
            contentTrans.convertToWorldSpaceAR(_tempPos_1, _tempPos_2);
            var scrollViewSpacePos = scrollTrans.convertToNodeSpaceAR(_tempPos_2);
            scrollViewSpacePos.x += scrollTrans.anchorX * scrollTrans.width;
            scrollViewSpacePos.y += scrollTrans.anchorY * scrollTrans.height;
            out.set(scrollViewSpacePos.x, scrollViewSpacePos.y);
          }
        };
        _proto._setOpacity = function _setOpacity(opacity) {
          if (this._handle) {
            var renderComp = this.node.getComponent(Sprite);
            if (renderComp) {
              _tempColor.set(renderComp.color);
              _tempColor.a = opacity;
              renderComp.color = _tempColor;
            }
            renderComp = this._handle.getComponent(Sprite);
            if (renderComp) {
              _tempColor.set(renderComp.color);
              _tempColor.a = opacity;
              renderComp.color = _tempColor;
            }
          }
        };
        _proto._updateHandlerPosition = function _updateHandlerPosition(position) {
          if (this._handle) {
            var oldPosition = _tempVec3$1;
            this._fixupHandlerPosition(oldPosition);
            this._handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y, oldPosition.z);
          }
        };
        _proto._fixupHandlerPosition = function _fixupHandlerPosition(out) {
          var uiTrans = this.node._uiProps.uiTransformComp;
          var barSize = uiTrans.contentSize;
          var barAnchor = uiTrans.anchorPoint;
          var handleSize = this.handle.node._uiProps.uiTransformComp.contentSize;
          var handleParent = this.handle.node.parent;
          Vec3.set(_tempPos_1, -barSize.width * barAnchor.x, -barSize.height * barAnchor.y, 0);
          var leftBottomWorldPosition = this.node._uiProps.uiTransformComp.convertToWorldSpaceAR(_tempPos_1, _tempPos_2);
          var fixupPosition = out;
          fixupPosition.set(0, 0, 0);
          handleParent._uiProps.uiTransformComp.convertToNodeSpaceAR(leftBottomWorldPosition, fixupPosition);
          if (this.direction === Direction$3.HORIZONTAL) {
            fixupPosition.set(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2, fixupPosition.z);
          } else if (this.direction === Direction$3.VERTICAL) {
            fixupPosition.set(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y, fixupPosition.z);
          }
          this.handle.node.setPosition(fixupPosition);
        };
        _proto._conditionalDisableScrollBar = function _conditionalDisableScrollBar(contentSize, scrollViewSize) {
          if (contentSize.width <= scrollViewSize.width && this._direction === Direction$3.HORIZONTAL) {
            return true;
          }
          if (contentSize.height <= scrollViewSize.height && this._direction === Direction$3.VERTICAL) {
            return true;
          }
          return false;
        };
        _proto._calculateLength = function _calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) {
          var denominatorValue = contentMeasure;
          if (outOfBoundary) {
            denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTING_SHORTER_FACTOR;
          }
          var lengthRation = scrollViewMeasure / denominatorValue;
          return handleNodeMeasure * lengthRation;
        };
        _proto._calculatePosition = function _calculatePosition(out, contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) {
          var denominatorValue = contentMeasure - scrollViewMeasure;
          if (outOfBoundary) {
            denominatorValue += Math.abs(outOfBoundary);
          }
          var positionRatio = 0;
          if (denominatorValue) {
            positionRatio = contentPosition / denominatorValue;
            positionRatio = clamp01(positionRatio);
          }
          var position = (handleNodeMeasure - actualLenth) * positionRatio;
          if (this._direction === Direction$3.VERTICAL) {
            out.set(0, position);
          } else {
            out.set(position, 0);
          }
        };
        _proto._updateLength = function _updateLength(length) {
          if (this._handle) {
            var handleNode = this._handle.node;
            var handleTrans = handleNode._uiProps.uiTransformComp;
            var handleNodeSize = handleTrans.contentSize;
            var anchor = handleTrans.anchorPoint;
            if (anchor.x !== defaultAnchor.x || anchor.y !== defaultAnchor.y) {
              handleTrans.setAnchorPoint(defaultAnchor);
            }
            if (this._direction === Direction$3.HORIZONTAL) {
              handleTrans.setContentSize(length, handleNodeSize.height);
            } else {
              handleTrans.setContentSize(handleNodeSize.width, length);
            }
          }
        };
        _proto._processAutoHide = function _processAutoHide(deltaTime) {
          if (!this._enableAutoHide || this._autoHideRemainingTime <= 0) {
            return;
          } else if (this._touching) {
            return;
          }
          this._autoHideRemainingTime -= deltaTime;
          if (this._autoHideRemainingTime <= this._autoHideTime) {
            this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime);
            var opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime);
            this._setOpacity(opacity);
          }
        };
        _createClass(ScrollBar, [{
          key: "handle",
          get: function get() {
            return this._handle;
          },
          set: function set(value) {
            if (this._handle === value) {
              return;
            }
            this._handle = value;
            this.onScroll(Vec2.ZERO);
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) {
              return;
            }
            this._direction = value;
            this.onScroll(Vec2.ZERO);
          }
        }, {
          key: "enableAutoHide",
          get: function get() {
            return this._enableAutoHide;
          },
          set: function set(value) {
            if (this._enableAutoHide === value) {
              return;
            }
            this._enableAutoHide = value;
            if (this._enableAutoHide) {
              this._setOpacity(0);
            }
          }
        }, {
          key: "autoHideTime",
          get: function get() {
            return this._autoHideTime;
          },
          set: function set(value) {
            if (this._autoHideTime === value) {
              return;
            }
            this._autoHideTime = value;
          }
        }]);
        return ScrollBar;
      }(Component), _class3$8.Direction = Direction$3, _class3$8), (_applyDecoratedDescriptor(_class2$c.prototype, "handle", [_dec4$8], Object.getOwnPropertyDescriptor(_class2$c.prototype, "handle"), _class2$c.prototype), _applyDecoratedDescriptor(_class2$c.prototype, "direction", [_dec5$8], Object.getOwnPropertyDescriptor(_class2$c.prototype, "direction"), _class2$c.prototype), _initializer$c = applyDecoratedInitializer(_class2$c.prototype, "_scrollView", [serializable$p], function () {
        return null;
      }), _initializer2$b = applyDecoratedInitializer(_class2$c.prototype, "_handle", [serializable$p], function () {
        return null;
      }), _initializer3$8 = applyDecoratedInitializer(_class2$c.prototype, "_direction", [serializable$p], function () {
        return Direction$3.HORIZONTAL;
      }), _initializer4$7 = applyDecoratedInitializer(_class2$c.prototype, "_enableAutoHide", [serializable$p], function () {
        return false;
      }), _initializer5$5 = applyDecoratedInitializer(_class2$c.prototype, "_autoHideTime", [serializable$p], function () {
        return 1.0;
      })), _class2$c)) || _class$g) || _class$g) || _class$g));
      legacyCC.ScrollBar = ScrollBar;

      var _dec$f, _dec2$c, _class$f;
      var ViewGroup = exports('h6', (_dec$f = ccclass$M('cc.ViewGroup'), _dec2$c = executionOrder$1(110), _dec$f(_class$f = _dec2$c(_class$f = function (_Component) {
        _inheritsLoose(ViewGroup, _Component);
        function ViewGroup() {
          return _Component.apply(this, arguments) || this;
        }
        return ViewGroup;
      }(Component)) || _class$f) || _class$f));
      legacyCC.ViewGroup = ViewGroup;

      var _dec$e, _dec2$b, _dec3$b, _dec4$7, _dec5$7, _dec6$3, _dec7$1, _class$e, _class2$b, _initializer$b, _initializer2$a, _initializer3$7, _initializer4$6, _initializer5$4, _initializer6$3, _initializer7$3, _initializer8$3, _initializer9$3, _initializer10$3, _initializer11$3, _class3$7;
      var NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5;
      var OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05;
      var EPSILON = 1e-4;
      var TOLERANCE = 1e4;
      var MOVEMENT_FACTOR = 0.7;
      var _tempVec3 = new Vec3();
      var _tempVec3_1 = new Vec3();
      var _tempVec2$1 = new Vec2();
      var _tempVec2_1$1 = new Vec2();
      var quintEaseOut = function quintEaseOut(time) {
        time -= 1;
        return time * time * time * time * time + 1;
      };
      var getTimeInMilliseconds = function getTimeInMilliseconds() {
        var currentTime = new Date();
        return currentTime.getMilliseconds();
      };
      var eventMap = {
        'scroll-to-top': 0,
        'scroll-to-bottom': 1,
        'scroll-to-left': 2,
        'scroll-to-right': 3,
        'scrolling': 4,
        'bounce-bottom': 6,
        'bounce-left': 7,
        'bounce-right': 8,
        'bounce-top': 5,
        'scroll-ended': 9,
        'touch-up': 10,
        'scroll-ended-with-threshold': 11,
        'scroll-began': 12
      };
      var EventType$4;
      (function (EventType) {
        EventType["NONE"] = "";
        EventType["SCROLL_TO_TOP"] = "scroll-to-top";
        EventType["SCROLL_TO_BOTTOM"] = "scroll-to-bottom";
        EventType["SCROLL_TO_LEFT"] = "scroll-to-left";
        EventType["SCROLL_TO_RIGHT"] = "scroll-to-right";
        EventType["SCROLL_BEGAN"] = "scroll-began";
        EventType["SCROLL_ENDED"] = "scroll-ended";
        EventType["BOUNCE_TOP"] = "bounce-top";
        EventType["BOUNCE_BOTTOM"] = "bounce-bottom";
        EventType["BOUNCE_LEFT"] = "bounce-left";
        EventType["BOUNCE_RIGHT"] = "bounce-right";
        EventType["SCROLLING"] = "scrolling";
        EventType["SCROLL_ENG_WITH_THRESHOLD"] = "scroll-ended-with-threshold";
        EventType["TOUCH_UP"] = "touch-up";
      })(EventType$4 || (EventType$4 = {}));
      var XrhoverType;
      (function (XrhoverType) {
        XrhoverType[XrhoverType["NONE"] = 0] = "NONE";
        XrhoverType[XrhoverType["LEFT"] = 1] = "LEFT";
        XrhoverType[XrhoverType["RIGHT"] = 2] = "RIGHT";
      })(XrhoverType || (XrhoverType = {}));
      var ScrollView = exports('h2', (_dec$e = ccclass$M('cc.ScrollView'), _dec2$b = executionOrder$1(110), _dec3$b = requireComponent(UITransform), _dec4$7 = type$d(Node$1), _dec5$7 = type$d(ScrollBar), _dec6$3 = type$d(ScrollBar), _dec7$1 = type$d([EventHandler]), _dec$e(_class$e = _dec2$b(_class$e = _dec3$b(_class$e = (_class2$b = (_class3$7 = function (_ViewGroup) {
        _inheritsLoose(ScrollView, _ViewGroup);
        function ScrollView() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ViewGroup.call.apply(_ViewGroup, [this].concat(args)) || this;
          _this.bounceDuration = _initializer$b && _initializer$b();
          _this.brake = _initializer2$a && _initializer2$a();
          _this.elastic = _initializer3$7 && _initializer3$7();
          _this.inertia = _initializer4$6 && _initializer4$6();
          _this.horizontal = _initializer5$4 && _initializer5$4();
          _this.vertical = _initializer6$3 && _initializer6$3();
          _this.cancelInnerEvents = _initializer7$3 && _initializer7$3();
          _this.scrollEvents = _initializer8$3 && _initializer8$3();
          _this._autoScrolling = false;
          _this._scrolling = false;
          _this._content = _initializer9$3 && _initializer9$3();
          _this._horizontalScrollBar = _initializer10$3 && _initializer10$3();
          _this._verticalScrollBar = _initializer11$3 && _initializer11$3();
          _this._topBoundary = 0;
          _this._bottomBoundary = 0;
          _this._leftBoundary = 0;
          _this._rightBoundary = 0;
          _this._touchMoveDisplacements = [];
          _this._touchMoveTimeDeltas = [];
          _this._touchMovePreviousTimestamp = 0;
          _this._touchMoved = false;
          _this._autoScrollAttenuate = false;
          _this._autoScrollStartPosition = new Vec3();
          _this._autoScrollTargetDelta = new Vec3();
          _this._autoScrollTotalTime = 0;
          _this._autoScrollAccumulatedTime = 0;
          _this._autoScrollCurrentlyOutOfBoundary = false;
          _this._autoScrollBraking = false;
          _this._autoScrollBrakingStartPosition = new Vec3();
          _this._outOfBoundaryAmount = new Vec3();
          _this._outOfBoundaryAmountDirty = true;
          _this._stopMouseWheel = false;
          _this._mouseWheelEventElapsedTime = 0.0;
          _this._isScrollEndedWithThresholdEventFired = false;
          _this._scrollEventEmitMask = 0;
          _this._isBouncing = false;
          _this._contentPos = new Vec3();
          _this._deltaPos = new Vec3();
          _this._deltaAmount = new Vec3();
          _this._hoverIn = XrhoverType.NONE;
          return _this;
        }
        var _proto = ScrollView.prototype;
        _proto.scrollToBottom = function scrollToBottom(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, 0),
            applyToHorizontal: false,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta, true);
          }
        };
        _proto.scrollToTop = function scrollToTop(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, 1),
            applyToHorizontal: false,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToLeft = function scrollToLeft(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, 0),
            applyToHorizontal: true,
            applyToVertical: false
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToRight = function scrollToRight(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(1, 0),
            applyToHorizontal: true,
            applyToVertical: false
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToTopLeft = function scrollToTopLeft(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, 1),
            applyToHorizontal: true,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToTopRight = function scrollToTopRight(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(1, 1),
            applyToHorizontal: true,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToBottomLeft = function scrollToBottomLeft(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, 0),
            applyToHorizontal: true,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToBottomRight = function scrollToBottomRight(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(1, 0),
            applyToHorizontal: true,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToOffset = function scrollToOffset(offset, timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var maxScrollOffset = this.getMaxScrollOffset();
          var anchor = new Vec2(0, 0);
          if (maxScrollOffset.x === 0) {
            anchor.x = 0;
          } else {
            anchor.x = offset.x / maxScrollOffset.x;
          }
          if (maxScrollOffset.y === 0) {
            anchor.y = 1;
          } else {
            anchor.y = (maxScrollOffset.y - offset.y) / maxScrollOffset.y;
          }
          this.scrollTo(anchor, timeInSecond, attenuated);
        };
        _proto.getScrollOffset = function getScrollOffset() {
          var topDelta = this._getContentTopBoundary() - this._topBoundary;
          var leftDelta = this._getContentLeftBoundary() - this._leftBoundary;
          return new Vec2(leftDelta, topDelta);
        };
        _proto.getMaxScrollOffset = function getMaxScrollOffset() {
          if (!this._content || !this.view) {
            return Vec2.ZERO;
          }
          var contentSize = this._content._uiProps.uiTransformComp.contentSize;
          var horizontalMaximizeOffset = contentSize.width - this.view.width;
          var verticalMaximizeOffset = contentSize.height - this.view.height;
          horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0;
          verticalMaximizeOffset = verticalMaximizeOffset >= 0 ? verticalMaximizeOffset : 0;
          return new Vec2(horizontalMaximizeOffset, verticalMaximizeOffset);
        };
        _proto.scrollToPercentHorizontal = function scrollToPercentHorizontal(percent, timeInSecond, attenuated) {
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(percent, 0),
            applyToHorizontal: true,
            applyToVertical: false
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollTo = function scrollTo(anchor, timeInSecond, attenuated) {
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(anchor),
            applyToHorizontal: true,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToPercentVertical = function scrollToPercentVertical(percent, timeInSecond, attenuated) {
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, percent),
            applyToHorizontal: false,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.stopAutoScroll = function stopAutoScroll() {
          this._autoScrolling = false;
          this._autoScrollAccumulatedTime = this._autoScrollTotalTime;
        };
        _proto.setContentPosition = function setContentPosition(position) {
          this._setContentPosition(position);
        };
        _proto._setContentPosition = function _setContentPosition(position) {
          if (!this._content) {
            return;
          }
          var contentPos = this._getContentPosition();
          if (Math.abs(position.x - contentPos.x) < EPSILON && Math.abs(position.y - contentPos.y) < EPSILON) {
            return;
          }
          this._content.setPosition(position);
          this._outOfBoundaryAmountDirty = true;
        };
        _proto.getContentPosition = function getContentPosition() {
          return this._getContentPosition();
        };
        _proto._getContentPosition = function _getContentPosition() {
          if (!this._content) {
            return Vec3.ZERO.clone();
          }
          this._contentPos.set(this._content.position);
          return this._contentPos;
        };
        _proto.isScrolling = function isScrolling() {
          return this._scrolling;
        };
        _proto.isAutoScrolling = function isAutoScrolling() {
          return this._autoScrolling;
        };
        _proto.getScrollEndedEventTiming = function getScrollEndedEventTiming() {
          return EPSILON;
        };
        _proto.start = function start() {
          this._calculateBoundary();
          if (this._content) {
            director.once(Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this);
          }
        };
        _proto.onEnable = function onEnable() {
          {
            this._registerEvent();
            if (this._content) {
              this._content.on(NodeEventType.SIZE_CHANGED, this._calculateBoundary, this);
              this._content.on(NodeEventType.TRANSFORM_CHANGED, this._scaleChanged, this);
              if (this.view) {
                this.view.node.on(NodeEventType.TRANSFORM_CHANGED, this._scaleChanged, this);
                this.view.node.on(NodeEventType.SIZE_CHANGED, this._calculateBoundary, this);
              }
            }
            this._calculateBoundary();
          }
          this._updateScrollBarState();
        };
        _proto.update = function update(dt) {
          var deltaAmount = this._deltaAmount;
          if (this._autoScrolling) {
            this._processAutoScrolling(dt);
            deltaAmount.x = 0;
            deltaAmount.y = 0;
          } else if (deltaAmount.x !== 0 || deltaAmount.y !== 0) {
            this._processDeltaMove(deltaAmount);
            deltaAmount.x = 0;
            deltaAmount.y = 0;
          }
        };
        _proto.onDisable = function onDisable() {
          {
            this._unregisterEvent();
            if (this._content) {
              this._content.off(NodeEventType.SIZE_CHANGED, this._calculateBoundary, this);
              this._content.off(NodeEventType.TRANSFORM_CHANGED, this._scaleChanged, this);
              if (this.view) {
                this.view.node.off(NodeEventType.TRANSFORM_CHANGED, this._scaleChanged, this);
                this.view.node.off(NodeEventType.SIZE_CHANGED, this._calculateBoundary, this);
              }
            }
          }
          this._deltaAmount.set(0, 0);
          this._hideScrollBar();
          this.stopAutoScroll();
        };
        _proto._registerEvent = function _registerEvent() {
          this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this, true);
          this.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this, true);
          this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this, true);
          this.node.on(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
          this.node.on(NodeEventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
          this.node.on(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this);
          this.node.on(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this);
          input$1.on(Input.EventType.HANDLE_INPUT, this._dispatchEventHandleInput, this);
          input$1.on(Input.EventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this);
        };
        _proto._unregisterEvent = function _unregisterEvent() {
          this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this, true);
          this.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this, true);
          this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this, true);
          this.node.off(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
          this.node.off(NodeEventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
          this.node.off(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this);
          this.node.off(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this);
          input$1.off(Input.EventType.HANDLE_INPUT, this._dispatchEventHandleInput, this);
          input$1.off(Input.EventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this);
        };
        _proto._onMouseWheel = function _onMouseWheel(event, captureListeners) {
          if (!this.enabledInHierarchy) {
            return;
          }
          if (this._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          var deltaMove = new Vec3();
          var wheelPrecision = -0.1;
          var scrollY = event.getScrollY();
          if (this.vertical) {
            deltaMove.set(0, scrollY * wheelPrecision, 0);
          } else if (this.horizontal) {
            deltaMove.set(scrollY * wheelPrecision, 0, 0);
          }
          this._mouseWheelEventElapsedTime = 0;
          this._deltaAmount.add(deltaMove);
          if (!this._stopMouseWheel) {
            this._handlePressLogic();
            this.schedule(this._checkMouseWheel, 1.0 / 60);
            this._stopMouseWheel = true;
          }
          this._stopPropagationIfTargetIsMe(event);
        };
        _proto._onTouchBegan = function _onTouchBegan(event, captureListeners) {
          if (!this.enabledInHierarchy || !this._content) {
            return;
          }
          if (this._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          this._handlePressLogic();
          this._touchMoved = false;
          this._stopPropagationIfTargetIsMe(event);
        };
        _proto._onTouchMoved = function _onTouchMoved(event, captureListeners) {
          if (!this.enabledInHierarchy || !this._content) {
            return;
          }
          if (this._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          var touch = event.touch;
          this._handleMoveLogic(touch);
          if (!this.cancelInnerEvents) {
            return;
          }
          var deltaMove = touch.getUILocation(_tempVec2$1);
          deltaMove.subtract(touch.getUIStartLocation(_tempVec2_1$1));
          if (deltaMove.length() > 7) {
            if (!this._touchMoved && event.target !== this.node) {
              var cancelEvent = new EventTouch(event.getTouches(), event.bubbles, SystemEventType.TOUCH_CANCEL);
              cancelEvent.touch = event.touch;
              cancelEvent.simulate = true;
              event.target.dispatchEvent(cancelEvent);
              this._touchMoved = true;
            }
          }
          this._stopPropagationIfTargetIsMe(event);
        };
        _proto._onTouchEnded = function _onTouchEnded(event, captureListeners) {
          if (!this.enabledInHierarchy || !this._content || !event) {
            return;
          }
          if (this._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          this._dispatchEvent(EventType$4.TOUCH_UP);
          var touch = event.touch;
          this._handleReleaseLogic(touch);
          if (this._touchMoved) {
            event.propagationStopped = true;
          } else {
            this._stopPropagationIfTargetIsMe(event);
          }
        };
        _proto._onTouchCancelled = function _onTouchCancelled(event, captureListeners) {
          if (!this.enabledInHierarchy || !this._content) {
            return;
          }
          if (this._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          if (event && !event.simulate) {
            var touch = event.touch;
            this._handleReleaseLogic(touch);
          }
          this._stopPropagationIfTargetIsMe(event);
        };
        _proto._calculateBoundary = function _calculateBoundary() {
          if (this._content && this.view) {
            var layout = this._content.getComponent(Layout);
            if (layout && layout.enabledInHierarchy) {
              layout.updateLayout();
            }
            var viewTrans = this.view;
            var anchorX = viewTrans.width * viewTrans.anchorX;
            var anchorY = viewTrans.height * viewTrans.anchorY;
            this._leftBoundary = -anchorX;
            this._bottomBoundary = -anchorY;
            this._rightBoundary = this._leftBoundary + viewTrans.width;
            this._topBoundary = this._bottomBoundary + viewTrans.height;
            this._moveContentToTopLeft(viewTrans.contentSize);
          }
        };
        _proto._hasNestedViewGroup = function _hasNestedViewGroup(event, captureListeners) {
          if (!event || event.eventPhase !== Event.CAPTURING_PHASE) {
            return false;
          }
          if (captureListeners) {
            for (var _iterator = _createForOfIteratorHelperLoose(captureListeners), _step; !(_step = _iterator()).done;) {
              var listener = _step.value;
              var item = listener;
              if (this.node === item) {
                if (event.target && event.target.getComponent(ViewGroup)) {
                  return true;
                }
                return false;
              }
              if (item.getComponent(ViewGroup)) {
                return true;
              }
            }
          }
          return false;
        };
        _proto._startInertiaScroll = function _startInertiaScroll(touchMoveVelocity) {
          var inertiaTotalMovement = new Vec3(touchMoveVelocity);
          inertiaTotalMovement.multiplyScalar(MOVEMENT_FACTOR);
          this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity);
        };
        _proto._calculateAttenuatedFactor = function _calculateAttenuatedFactor(distance) {
          if (this.brake <= 0) {
            return 1 - this.brake;
          }
          return (1 - this.brake) * (1 / (1 + distance * 0.000014 + distance * distance * 0.000000008));
        };
        _proto._startAttenuatingAutoScroll = function _startAttenuatingAutoScroll(deltaMove, initialVelocity) {
          var targetDelta = deltaMove.clone();
          targetDelta.normalize();
          if (this._content && this.view) {
            var contentSize = this._content._uiProps.uiTransformComp.contentSize;
            var scrollViewSize = this.view.contentSize;
            var totalMoveWidth = contentSize.width - scrollViewSize.width;
            var totalMoveHeight = contentSize.height - scrollViewSize.height;
            var attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth);
            var attenuatedFactorY = this._calculateAttenuatedFactor(totalMoveHeight);
            targetDelta.x = targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX;
            targetDelta.y = targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake);
            targetDelta.z = 0;
          }
          var originalMoveLength = deltaMove.length();
          var factor = targetDelta.length() / originalMoveLength;
          targetDelta.add(deltaMove);
          if (this.brake > 0 && factor > 7) {
            factor = Math.sqrt(factor);
            var clonedDeltaMove = deltaMove.clone();
            clonedDeltaMove.multiplyScalar(factor);
            targetDelta.set(clonedDeltaMove);
            targetDelta.add(deltaMove);
          }
          var time = this._calculateAutoScrollTimeByInitialSpeed(initialVelocity.length());
          if (this.brake > 0 && factor > 3) {
            factor = 3;
            time *= factor;
          }
          if (this.brake === 0 && factor > 1) {
            time *= factor;
          }
          this._startAutoScroll(targetDelta, time, true);
        };
        _proto._calculateAutoScrollTimeByInitialSpeed = function _calculateAutoScrollTimeByInitialSpeed(initialSpeed) {
          return Math.sqrt(Math.sqrt(initialSpeed / 5));
        };
        _proto._startAutoScroll = function _startAutoScroll(deltaMove, timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = false;
          }
          var adjustedDeltaMove = this._flattenVectorByDirection(deltaMove);
          this._autoScrolling = true;
          this._autoScrollTargetDelta = adjustedDeltaMove;
          this._autoScrollAttenuate = attenuated;
          Vec3.copy(this._autoScrollStartPosition, this._getContentPosition());
          this._autoScrollTotalTime = timeInSecond;
          this._autoScrollAccumulatedTime = 0;
          this._autoScrollBraking = false;
          this._isScrollEndedWithThresholdEventFired = false;
          this._autoScrollBrakingStartPosition.set(0, 0, 0);
          var currentOutOfBoundary = this._getHowMuchOutOfBoundary();
          if (!currentOutOfBoundary.equals(Vec3.ZERO, EPSILON)) {
            this._autoScrollCurrentlyOutOfBoundary = true;
          }
        };
        _proto._calculateTouchMoveVelocity = function _calculateTouchMoveVelocity() {
          var out = new Vec3();
          var totalTime = 0;
          totalTime = this._touchMoveTimeDeltas.reduce(function (a, b) {
            return a + b;
          }, totalTime);
          if (totalTime <= 0 || totalTime >= 0.5) {
            out.set(Vec3.ZERO);
          } else {
            var totalMovement = new Vec3();
            totalMovement = this._touchMoveDisplacements.reduce(function (a, b) {
              a.add(b);
              return a;
            }, totalMovement);
            out.set(totalMovement.x * (1 - this.brake) / totalTime, totalMovement.y * (1 - this.brake) / totalTime, totalMovement.z);
          }
          return out;
        };
        _proto._flattenVectorByDirection = function _flattenVectorByDirection(vector) {
          var result = vector;
          result.x = this.horizontal ? result.x : 0;
          result.y = this.vertical ? result.y : 0;
          return result;
        };
        _proto._moveContent = function _moveContent(deltaMove, canStartBounceBack) {
          var adjustedMove = this._flattenVectorByDirection(deltaMove);
          _tempVec3.set(this._getContentPosition());
          _tempVec3.add(adjustedMove);
          _tempVec3.set(Math.round(_tempVec3.x * TOLERANCE) * EPSILON, Math.round(_tempVec3.y * TOLERANCE) * EPSILON, _tempVec3.z);
          this._setContentPosition(_tempVec3);
          var outOfBoundary = this._getHowMuchOutOfBoundary();
          _tempVec2$1.set(outOfBoundary.x, outOfBoundary.y);
          this._updateScrollBar(_tempVec2$1);
          if (this.elastic && canStartBounceBack) {
            this._startBounceBackIfNeeded();
          }
        };
        _proto._getContentLeftBoundary = function _getContentLeftBoundary() {
          if (!this._content) {
            return -1;
          }
          var contentPos = this._getContentPosition();
          var uiTrans = this._content._uiProps.uiTransformComp;
          return contentPos.x - uiTrans.anchorX * uiTrans.width;
        };
        _proto._getContentRightBoundary = function _getContentRightBoundary() {
          if (!this._content) {
            return -1;
          }
          var uiTrans = this._content._uiProps.uiTransformComp;
          return this._getContentLeftBoundary() + uiTrans.width;
        };
        _proto._getContentTopBoundary = function _getContentTopBoundary() {
          if (!this._content) {
            return -1;
          }
          var uiTrans = this._content._uiProps.uiTransformComp;
          return this._getContentBottomBoundary() + uiTrans.height;
        };
        _proto._getContentBottomBoundary = function _getContentBottomBoundary() {
          if (!this._content) {
            return -1;
          }
          var contentPos = this._getContentPosition();
          var uiTrans = this._content._uiProps.uiTransformComp;
          return contentPos.y - uiTrans.anchorY * uiTrans.height;
        };
        _proto._getHowMuchOutOfBoundary = function _getHowMuchOutOfBoundary(addition) {
          addition = addition || new Vec3();
          if (addition.equals(Vec3.ZERO, EPSILON) && !this._outOfBoundaryAmountDirty) {
            return this._outOfBoundaryAmount;
          }
          var outOfBoundaryAmount = new Vec3();
          var tempLeftBoundary = this._getContentLeftBoundary();
          var tempRightBoundary = this._getContentRightBoundary();
          if (tempLeftBoundary + addition.x > this._leftBoundary) {
            outOfBoundaryAmount.x = this._leftBoundary - (tempLeftBoundary + addition.x);
          } else if (tempRightBoundary + addition.x < this._rightBoundary) {
            outOfBoundaryAmount.x = this._rightBoundary - (tempRightBoundary + addition.x);
          }
          var tempTopBoundary = this._getContentTopBoundary();
          var tempBottomBoundary = this._getContentBottomBoundary();
          if (tempTopBoundary + addition.y < this._topBoundary) {
            outOfBoundaryAmount.y = this._topBoundary - (tempTopBoundary + addition.y);
          } else if (tempBottomBoundary + addition.y > this._bottomBoundary) {
            outOfBoundaryAmount.y = this._bottomBoundary - (tempBottomBoundary + addition.y);
          }
          if (addition.equals(Vec3.ZERO, EPSILON)) {
            this._outOfBoundaryAmount = outOfBoundaryAmount;
            this._outOfBoundaryAmountDirty = false;
          }
          this._clampDelta(outOfBoundaryAmount);
          return outOfBoundaryAmount;
        };
        _proto._updateScrollBar = function _updateScrollBar(outOfBoundary) {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.onScroll(outOfBoundary);
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.onScroll(outOfBoundary);
          }
        };
        _proto._onScrollBarTouchBegan = function _onScrollBarTouchBegan() {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.onTouchBegan();
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.onTouchBegan();
          }
        };
        _proto._onScrollBarTouchEnded = function _onScrollBarTouchEnded() {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.onTouchEnded();
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.onTouchEnded();
          }
        };
        _proto._dispatchEvent = function _dispatchEvent(event) {
          if (event === EventType$4.SCROLL_ENDED) {
            this._scrollEventEmitMask = 0;
          } else if (event === EventType$4.SCROLL_TO_TOP || event === EventType$4.SCROLL_TO_BOTTOM || event === EventType$4.SCROLL_TO_LEFT || event === EventType$4.SCROLL_TO_RIGHT) {
            var flag = 1 << eventMap[event];
            if (this._scrollEventEmitMask & flag) {
              return;
            } else {
              this._scrollEventEmitMask |= flag;
            }
          }
          EventHandler.emitEvents(this.scrollEvents, this, eventMap[event]);
          this.node.emit(event, this);
        };
        _proto._adjustContentOutOfBoundary = function _adjustContentOutOfBoundary() {
          if (!this._content) {
            return;
          }
          this._outOfBoundaryAmountDirty = true;
          var outOfBoundary = this._getHowMuchOutOfBoundary();
          var _isOutOfBoundary = !outOfBoundary.equals(Vec3.ZERO, EPSILON);
          if (_isOutOfBoundary) {
            _tempVec3.set(this._getContentPosition());
            _tempVec3.add(outOfBoundary);
            this._setContentPosition(_tempVec3);
            this._updateScrollBar(Vec2.ZERO);
          }
        };
        _proto._hideScrollBar = function _hideScrollBar() {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.hide();
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.hide();
          }
        };
        _proto._updateScrollBarState = function _updateScrollBarState() {
          if (!this._content || !this.view) {
            return;
          }
          var viewTrans = this.view;
          var uiTrans = this._content._uiProps.uiTransformComp;
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            if (uiTrans.height < viewTrans.height || approx(uiTrans.height, viewTrans.height)) {
              this._verticalScrollBar.hide();
            } else {
              this._verticalScrollBar.show();
            }
          }
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            if (uiTrans.width < viewTrans.width || approx(uiTrans.width, viewTrans.width)) {
              this._horizontalScrollBar.hide();
            } else {
              this._horizontalScrollBar.show();
            }
          }
        };
        _proto._stopPropagationIfTargetIsMe = function _stopPropagationIfTargetIsMe(event) {
          if (event.eventPhase === Event.AT_TARGET && event.target === this.node) {
            event.propagationStopped = true;
          }
        };
        _proto._processDeltaMove = function _processDeltaMove(deltaMove) {
          this._scrollChildren(deltaMove);
          this._gatherTouchMove(deltaMove);
        };
        _proto._handleMoveLogic = function _handleMoveLogic(touch) {
          this._getLocalAxisAlignDelta(this._deltaPos, touch);
          this._deltaAmount.add(this._deltaPos);
        };
        _proto._handleReleaseLogic = function _handleReleaseLogic(touch) {
          this._getLocalAxisAlignDelta(this._deltaPos, touch);
          this._gatherTouchMove(this._deltaPos);
          this._processInertiaScroll();
          if (this._scrolling) {
            this._scrolling = false;
            if (!this._autoScrolling) {
              this._dispatchEvent(EventType$4.SCROLL_ENDED);
            }
          }
        };
        _proto._getLocalAxisAlignDelta = function _getLocalAxisAlignDelta(out, touch) {
          var uiTransformComp = this.node._uiProps.uiTransformComp;
          var vec = new Vec3();
          if (uiTransformComp) {
            touch.getUILocation(_tempVec2$1);
            touch.getUIPreviousLocation(_tempVec2_1$1);
            _tempVec3.set(_tempVec2$1.x, _tempVec2$1.y, 0);
            _tempVec3_1.set(_tempVec2_1$1.x, _tempVec2_1$1.y, 0);
            uiTransformComp.convertToNodeSpaceAR(_tempVec3, _tempVec3);
            uiTransformComp.convertToNodeSpaceAR(_tempVec3_1, _tempVec3_1);
            Vec3.subtract(vec, _tempVec3, _tempVec3_1);
          }
          out.set(vec);
        };
        _proto._scrollChildren = function _scrollChildren(deltaMove) {
          this._clampDelta(deltaMove);
          var realMove = deltaMove;
          var outOfBoundary;
          if (this.elastic) {
            outOfBoundary = this._getHowMuchOutOfBoundary();
            realMove.x *= outOfBoundary.x === 0 ? 1 : 0.5;
            realMove.y *= outOfBoundary.y === 0 ? 1 : 0.5;
          }
          if (!this.elastic) {
            outOfBoundary = this._getHowMuchOutOfBoundary(realMove);
            realMove.add(outOfBoundary);
          }
          var verticalScrollEventType = EventType$4.NONE;
          var horizontalScrollEventType = EventType$4.NONE;
          if (this._content) {
            var _ref = this._content._uiProps.uiTransformComp,
              anchorX = _ref.anchorX,
              anchorY = _ref.anchorY,
              width = _ref.width,
              height = _ref.height;
            var pos = this._content.position || Vec3.ZERO;
            if (this.vertical) {
              if (realMove.y > 0) {
                var icBottomPos = pos.y - anchorY * height;
                if (icBottomPos + realMove.y >= this._bottomBoundary) {
                  verticalScrollEventType = EventType$4.SCROLL_TO_BOTTOM;
                }
              } else if (realMove.y < 0) {
                var icTopPos = pos.y - anchorY * height + height;
                if (icTopPos + realMove.y <= this._topBoundary) {
                  verticalScrollEventType = EventType$4.SCROLL_TO_TOP;
                }
              }
            }
            if (this.horizontal) {
              if (realMove.x < 0) {
                var icRightPos = pos.x - anchorX * width + width;
                if (icRightPos + realMove.x <= this._rightBoundary) {
                  horizontalScrollEventType = EventType$4.SCROLL_TO_RIGHT;
                }
              } else if (realMove.x > 0) {
                var icLeftPos = pos.x - anchorX * width;
                if (icLeftPos + realMove.x >= this._leftBoundary) {
                  horizontalScrollEventType = EventType$4.SCROLL_TO_LEFT;
                }
              }
            }
          }
          this._moveContent(realMove, false);
          if (this.horizontal && realMove.x !== 0 || this.vertical && realMove.y !== 0) {
            if (!this._scrolling) {
              this._scrolling = true;
              this._dispatchEvent(EventType$4.SCROLL_BEGAN);
            }
            this._dispatchEvent(EventType$4.SCROLLING);
          }
          if (verticalScrollEventType !== EventType$4.NONE) {
            this._dispatchEvent(verticalScrollEventType);
          }
          if (horizontalScrollEventType !== EventType$4.NONE) {
            this._dispatchEvent(horizontalScrollEventType);
          }
        };
        _proto._handlePressLogic = function _handlePressLogic() {
          if (this._autoScrolling) {
            this._dispatchEvent(EventType$4.SCROLL_ENDED);
          }
          this._autoScrolling = false;
          this._isBouncing = false;
          this._touchMovePreviousTimestamp = getTimeInMilliseconds();
          this._touchMoveDisplacements.length = 0;
          this._touchMoveTimeDeltas.length = 0;
          this._onScrollBarTouchBegan();
        };
        _proto._clampDelta = function _clampDelta(out) {
          if (this._content && this.view) {
            var scrollViewSize = this.view.contentSize;
            var uiTrans = this._content._uiProps.uiTransformComp;
            if (uiTrans.width < scrollViewSize.width) {
              out.x = 0;
            }
            if (uiTrans.height < scrollViewSize.height) {
              out.y = 0;
            }
          }
        };
        _proto._gatherTouchMove = function _gatherTouchMove(delta) {
          var clampDt = delta.clone();
          this._clampDelta(clampDt);
          while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) {
            this._touchMoveDisplacements.shift();
            this._touchMoveTimeDeltas.shift();
          }
          this._touchMoveDisplacements.push(clampDt);
          var timeStamp = getTimeInMilliseconds();
          this._touchMoveTimeDeltas.push((timeStamp - this._touchMovePreviousTimestamp) / 1000);
          this._touchMovePreviousTimestamp = timeStamp;
        };
        _proto._startBounceBackIfNeeded = function _startBounceBackIfNeeded() {
          if (!this.elastic) {
            return false;
          }
          var bounceBackAmount = this._getHowMuchOutOfBoundary();
          this._clampDelta(bounceBackAmount);
          if (bounceBackAmount.equals(Vec3.ZERO, EPSILON)) {
            return false;
          }
          var bounceBackTime = Math.max(this.bounceDuration, 0);
          this._startAutoScroll(bounceBackAmount, bounceBackTime, true);
          if (!this._isBouncing) {
            if (bounceBackAmount.y > 0) {
              this._dispatchEvent(EventType$4.BOUNCE_TOP);
            }
            if (bounceBackAmount.y < 0) {
              this._dispatchEvent(EventType$4.BOUNCE_BOTTOM);
            }
            if (bounceBackAmount.x > 0) {
              this._dispatchEvent(EventType$4.BOUNCE_RIGHT);
            }
            if (bounceBackAmount.x < 0) {
              this._dispatchEvent(EventType$4.BOUNCE_LEFT);
            }
            this._isBouncing = true;
          }
          return true;
        };
        _proto._processInertiaScroll = function _processInertiaScroll() {
          var bounceBackStarted = this._startBounceBackIfNeeded();
          if (!bounceBackStarted && this.inertia) {
            var touchMoveVelocity = this._calculateTouchMoveVelocity();
            if (!touchMoveVelocity.equals(_tempVec3, EPSILON) && this.brake < 1) {
              this._startInertiaScroll(touchMoveVelocity);
            }
          }
          this._onScrollBarTouchEnded();
        };
        _proto._isOutOfBoundary = function _isOutOfBoundary() {
          var outOfBoundary = this._getHowMuchOutOfBoundary();
          return !outOfBoundary.equals(Vec3.ZERO, EPSILON);
        };
        _proto._isNecessaryAutoScrollBrake = function _isNecessaryAutoScrollBrake() {
          if (this._autoScrollBraking) {
            return true;
          }
          if (this._isOutOfBoundary()) {
            if (!this._autoScrollCurrentlyOutOfBoundary) {
              this._autoScrollCurrentlyOutOfBoundary = true;
              this._autoScrollBraking = true;
              Vec3.copy(this._autoScrollBrakingStartPosition, this._getContentPosition());
              return true;
            }
          } else {
            this._autoScrollCurrentlyOutOfBoundary = false;
          }
          return false;
        };
        _proto._processAutoScrolling = function _processAutoScrolling(dt) {
          var isAutoScrollBrake = this._isNecessaryAutoScrollBrake();
          var brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1;
          this._autoScrollAccumulatedTime += dt * (1 / brakingFactor);
          var percentage = Math.min(1, this._autoScrollAccumulatedTime / this._autoScrollTotalTime);
          if (this._autoScrollAttenuate) {
            percentage = quintEaseOut(percentage);
          }
          var clonedAutoScrollTargetDelta = this._autoScrollTargetDelta.clone();
          clonedAutoScrollTargetDelta.multiplyScalar(percentage);
          var clonedAutoScrollStartPosition = this._autoScrollStartPosition.clone();
          clonedAutoScrollStartPosition.add(clonedAutoScrollTargetDelta);
          var reachedEnd = Math.abs(percentage - 1) <= EPSILON;
          var fireEvent = Math.abs(percentage - 1) <= this.getScrollEndedEventTiming();
          if (fireEvent && !this._isScrollEndedWithThresholdEventFired) {
            this._dispatchEvent(EventType$4.SCROLL_ENG_WITH_THRESHOLD);
            this._isScrollEndedWithThresholdEventFired = true;
          }
          if (this.elastic) {
            var brakeOffsetPosition = clonedAutoScrollStartPosition.clone();
            brakeOffsetPosition.subtract(this._autoScrollBrakingStartPosition);
            if (isAutoScrollBrake) {
              brakeOffsetPosition.multiplyScalar(brakingFactor);
            }
            clonedAutoScrollStartPosition.set(this._autoScrollBrakingStartPosition);
            clonedAutoScrollStartPosition.add(brakeOffsetPosition);
          } else {
            var moveDelta = clonedAutoScrollStartPosition.clone();
            moveDelta.subtract(this.getContentPosition());
            var outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta);
            if (!outOfBoundary.equals(Vec3.ZERO, EPSILON)) {
              clonedAutoScrollStartPosition.add(outOfBoundary);
              reachedEnd = true;
            }
          }
          if (reachedEnd) {
            this._autoScrolling = false;
          }
          var deltaMove = clonedAutoScrollStartPosition.clone();
          deltaMove.subtract(this._getContentPosition());
          this._clampDelta(deltaMove);
          this._moveContent(deltaMove, reachedEnd);
          this._dispatchEvent(EventType$4.SCROLLING);
          if (!this._autoScrolling) {
            this._isBouncing = false;
            this._scrolling = false;
            this._dispatchEvent(EventType$4.SCROLL_ENDED);
          }
        };
        _proto._checkMouseWheel = function _checkMouseWheel(dt) {
          var currentOutOfBoundary = this._getHowMuchOutOfBoundary();
          var maxElapsedTime = 0.1;
          if (!currentOutOfBoundary.equals(Vec3.ZERO, EPSILON)) {
            this._processInertiaScroll();
            if (this._scrolling) {
              this._scrolling = false;
              if (!this._autoScrolling) {
                this._dispatchEvent(EventType$4.SCROLL_ENDED);
              }
            }
            this.unschedule(this._checkMouseWheel);
            this._stopMouseWheel = false;
            return;
          }
          this._mouseWheelEventElapsedTime += dt;
          if (this._mouseWheelEventElapsedTime > maxElapsedTime) {
            this._onScrollBarTouchEnded();
            if (this._scrolling) {
              this._scrolling = false;
              if (!this._autoScrolling) {
                this._dispatchEvent(EventType$4.SCROLL_ENDED);
              }
            }
            this.unschedule(this._checkMouseWheel);
            this._stopMouseWheel = false;
          }
        };
        _proto._calculateMovePercentDelta = function _calculateMovePercentDelta(options) {
          var anchor = options.anchor;
          var applyToHorizontal = options.applyToHorizontal;
          var applyToVertical = options.applyToVertical;
          this._calculateBoundary();
          anchor.clampf(Vec2.ZERO, Vec2.ONE);
          var bottomDelta = this._getContentBottomBoundary() - this._bottomBoundary;
          bottomDelta = -bottomDelta;
          var leftDelta = this._getContentLeftBoundary() - this._leftBoundary;
          leftDelta = -leftDelta;
          var moveDelta = new Vec3();
          if (this._content && this.view) {
            var totalScrollDelta = 0;
            var uiTrans = this._content._uiProps.uiTransformComp;
            var contentSize = uiTrans.contentSize;
            var scrollSize = this.view.contentSize;
            if (applyToHorizontal) {
              totalScrollDelta = contentSize.width - scrollSize.width;
              moveDelta.x = leftDelta - totalScrollDelta * anchor.x;
            }
            if (applyToVertical) {
              totalScrollDelta = contentSize.height - scrollSize.height;
              moveDelta.y = bottomDelta - totalScrollDelta * anchor.y;
            }
          }
          return moveDelta;
        };
        _proto._moveContentToTopLeft = function _moveContentToTopLeft(scrollViewSize) {
          var bottomDelta = this._getContentBottomBoundary() - this._bottomBoundary;
          bottomDelta = -bottomDelta;
          var moveDelta = new Vec3();
          var totalScrollDelta = 0;
          var leftDelta = this._getContentLeftBoundary() - this._leftBoundary;
          leftDelta = -leftDelta;
          if (this._content) {
            var uiTrans = this._content._uiProps.uiTransformComp;
            var contentSize = uiTrans.contentSize;
            if (contentSize.height < scrollViewSize.height) {
              totalScrollDelta = contentSize.height - scrollViewSize.height;
              moveDelta.y = bottomDelta - totalScrollDelta;
            }
            if (contentSize.width < scrollViewSize.width) {
              totalScrollDelta = contentSize.width - scrollViewSize.width;
              moveDelta.x = leftDelta;
            }
          }
          this._updateScrollBarState();
          this._moveContent(moveDelta);
          this._adjustContentOutOfBoundary();
        };
        _proto._scaleChanged = function _scaleChanged(value) {
          if (value === TransformBit.SCALE) {
            this._calculateBoundary();
          }
        };
        _proto._xrHoverEnter = function _xrHoverEnter(event) {
          if (event.deviceType === DeviceType.Left) {
            this._hoverIn = XrhoverType.LEFT;
          } else if (event.deviceType === DeviceType.Right) {
            this._hoverIn = XrhoverType.RIGHT;
          }
        };
        _proto._xrHoverExit = function _xrHoverExit(event) {
          this._hoverIn = XrhoverType.NONE;
        };
        _proto._dispatchEventHandleInput = function _dispatchEventHandleInput(event) {
          var handleInputDevice;
          if (event instanceof EventGamepad) {
            handleInputDevice = event.gamepad;
          } else if (event instanceof EventHandle) {
            handleInputDevice = event.handleInputDevice;
          }
          var value;
          if (!this.enabledInHierarchy || this._hoverIn === XrhoverType.NONE) {
            return;
          }
          if (this._hoverIn === XrhoverType.LEFT) {
            value = handleInputDevice.leftStick.getValue();
            if (!value.equals(Vec2.ZERO)) {
              this._xrThumbStickMove(value);
            }
          } else if (this._hoverIn === XrhoverType.RIGHT) {
            value = handleInputDevice.rightStick.getValue();
            if (!value.equals(Vec2.ZERO)) {
              this._xrThumbStickMove(value);
            }
          }
        };
        _proto._xrThumbStickMove = function _xrThumbStickMove(event) {
          if (!this.enabledInHierarchy) {
            return;
          }
          var deltaMove = new Vec3();
          var wheelPrecision = -62.5;
          var scrollY = event.y;
          if (this.vertical) {
            deltaMove.set(0, scrollY * wheelPrecision, 0);
          } else if (this.horizontal) {
            deltaMove.set(scrollY * wheelPrecision, 0, 0);
          }
          this._mouseWheelEventElapsedTime = 0;
          this._deltaAmount.add(deltaMove);
          if (!this._stopMouseWheel) {
            this._handlePressLogic();
            this.schedule(this._checkMouseWheel, 1.0 / 60, NaN, 0);
            this._stopMouseWheel = true;
          }
        };
        _createClass(ScrollView, [{
          key: "content",
          get: function get() {
            return this._content;
          },
          set: function set(value) {
            if (this._content === value) {
              return;
            }
            var viewTrans = value && value.parent && value.parent._uiProps.uiTransformComp;
            if (value && (!value || !viewTrans)) {
              logID(4302);
              return;
            }
            this._content = value;
            this._calculateBoundary();
          }
        }, {
          key: "horizontalScrollBar",
          get: function get() {
            if (this._horizontalScrollBar && !this._horizontalScrollBar.isValid) {
              errorID(4303, 'horizontal', this.node.name);
            }
            return this._horizontalScrollBar;
          },
          set: function set(value) {
            if (this._horizontalScrollBar === value) {
              return;
            }
            this._horizontalScrollBar = value;
            if (this._horizontalScrollBar) {
              this._horizontalScrollBar.setScrollView(this);
              this._updateScrollBar(Vec2.ZERO);
            }
          }
        }, {
          key: "verticalScrollBar",
          get: function get() {
            if (this._verticalScrollBar && !this._verticalScrollBar.isValid) {
              errorID(4303, 'vertical', this.node.name);
            }
            return this._verticalScrollBar;
          },
          set: function set(value) {
            if (this._verticalScrollBar === value) {
              return;
            }
            this._verticalScrollBar = value;
            if (this._verticalScrollBar) {
              this._verticalScrollBar.setScrollView(this);
              this._updateScrollBar(Vec2.ZERO);
            }
          }
        }, {
          key: "view",
          get: function get() {
            var parent = this._content && this._content.parent;
            if (!parent) {
              return null;
            }
            return parent._uiProps.uiTransformComp;
          }
        }]);
        return ScrollView;
      }(ViewGroup), _class3$7.EventType = EventType$4, _class3$7), (_initializer$b = applyDecoratedInitializer(_class2$b.prototype, "bounceDuration", [serializable$p], function () {
        return 1;
      }), _initializer2$a = applyDecoratedInitializer(_class2$b.prototype, "brake", [serializable$p], function () {
        return 0.5;
      }), _initializer3$7 = applyDecoratedInitializer(_class2$b.prototype, "elastic", [serializable$p], function () {
        return true;
      }), _initializer4$6 = applyDecoratedInitializer(_class2$b.prototype, "inertia", [serializable$p], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$b.prototype, "content", [_dec4$7], Object.getOwnPropertyDescriptor(_class2$b.prototype, "content"), _class2$b.prototype), _initializer5$4 = applyDecoratedInitializer(_class2$b.prototype, "horizontal", [serializable$p], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$b.prototype, "horizontalScrollBar", [_dec5$7], Object.getOwnPropertyDescriptor(_class2$b.prototype, "horizontalScrollBar"), _class2$b.prototype), _initializer6$3 = applyDecoratedInitializer(_class2$b.prototype, "vertical", [serializable$p], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$b.prototype, "verticalScrollBar", [_dec6$3], Object.getOwnPropertyDescriptor(_class2$b.prototype, "verticalScrollBar"), _class2$b.prototype), _initializer7$3 = applyDecoratedInitializer(_class2$b.prototype, "cancelInnerEvents", [serializable$p], function () {
        return true;
      }), _initializer8$3 = applyDecoratedInitializer(_class2$b.prototype, "scrollEvents", [_dec7$1, serializable$p], function () {
        return [];
      }), _initializer9$3 = applyDecoratedInitializer(_class2$b.prototype, "_content", [serializable$p], function () {
        return null;
      }), _initializer10$3 = applyDecoratedInitializer(_class2$b.prototype, "_horizontalScrollBar", [serializable$p], function () {
        return null;
      }), _initializer11$3 = applyDecoratedInitializer(_class2$b.prototype, "_verticalScrollBar", [serializable$p], function () {
        return null;
      })), _class2$b)) || _class$e) || _class$e) || _class$e));
      legacyCC.ScrollView = ScrollView;

      var _dec$d, _dec2$a, _dec3$a, _dec4$6, _dec5$6, _dec6$2, _class$d, _class2$a, _initializer$a, _initializer2$9, _initializer3$6, _initializer4$5, _class3$6;
      var _tempPos$1 = new Vec3();
      var Direction$2;
      (function (Direction) {
        Direction[Direction["Horizontal"] = 0] = "Horizontal";
        Direction[Direction["Vertical"] = 1] = "Vertical";
      })(Direction$2 || (Direction$2 = {}));
      ccenum(Direction$2);
      var Slider = exports('h3', (_dec$d = ccclass$M('cc.Slider'), _dec2$a = executionOrder$1(110), _dec3$a = requireComponent(UITransform), _dec4$6 = type$d(Sprite), _dec5$6 = type$d(Direction$2), _dec6$2 = type$d([EventHandler]), _dec$d(_class$d = _dec2$a(_class$d = _dec3$a(_class$d = (_class2$a = (_class3$6 = function (_Component) {
        _inheritsLoose(Slider, _Component);
        function Slider() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.slideEvents = _initializer$a && _initializer$a();
          _this._handle = _initializer2$9 && _initializer2$9();
          _this._direction = _initializer3$6 && _initializer3$6();
          _this._progress = _initializer4$5 && _initializer4$5();
          _this._offset = new Vec3();
          _this._dragging = false;
          _this._touchHandle = false;
          _this._handleLocalPos = new Vec3();
          _this._touchPos = new Vec3();
          return _this;
        }
        var _proto = Slider.prototype;
        _proto.__preload = function __preload() {
          this._updateHandlePosition();
        };
        _proto.onEnable = function onEnable() {
          this._updateHandlePosition();
          this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this);
          this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.on(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this);
          this.node.on(XrUIPressEventType.XRUI_HOVER_STAY, this._xrHoverStay, this);
          this.node.on(XrUIPressEventType.XRUI_CLICK, this._xrClick, this);
          this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
          if (this._handle && this._handle.isValid) {
            this._handle.node.on(NodeEventType.TOUCH_START, this._onHandleDragStart, this);
            this._handle.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this);
            this._handle.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          }
        };
        _proto.onDisable = function onDisable() {
          this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this);
          this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.off(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this);
          this.node.off(XrUIPressEventType.XRUI_HOVER_STAY, this._xrHoverStay, this);
          this.node.off(XrUIPressEventType.XRUI_CLICK, this._xrClick, this);
          this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
          if (this._handle && this._handle.isValid) {
            this._handle.node.off(NodeEventType.TOUCH_START, this._onHandleDragStart, this);
            this._handle.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this);
            this._handle.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          }
        };
        _proto._onHandleDragStart = function _onHandleDragStart(event) {
          if (!event || !this._handle || !this._handle.node._uiProps.uiTransformComp) {
            return;
          }
          this._dragging = true;
          this._touchHandle = true;
          var touhPos = event.touch.getUILocation();
          Vec3.set(this._touchPos, touhPos.x, touhPos.y, 0);
          this._handle.node._uiProps.uiTransformComp.convertToNodeSpaceAR(this._touchPos, this._offset);
          event.propagationStopped = true;
        };
        _proto._onTouchBegan = function _onTouchBegan(event) {
          if (!this._handle || !event) {
            return;
          }
          this._dragging = true;
          if (!this._touchHandle) {
            this._handleSliderLogic(event.touch);
          }
          event.propagationStopped = true;
        };
        _proto._onTouchMoved = function _onTouchMoved(event) {
          if (!this._dragging || !event) {
            return;
          }
          this._handleSliderLogic(event.touch);
          event.propagationStopped = true;
        };
        _proto._onTouchEnded = function _onTouchEnded(event) {
          this._dragging = false;
          this._touchHandle = false;
          this._offset = new Vec3();
          if (event) {
            event.propagationStopped = true;
          }
        };
        _proto._onTouchCancelled = function _onTouchCancelled(event) {
          this._dragging = false;
          if (event) {
            event.propagationStopped = true;
          }
        };
        _proto._handleSliderLogic = function _handleSliderLogic(touch) {
          this._updateProgress(touch);
          this._emitSlideEvent();
        };
        _proto._emitSlideEvent = function _emitSlideEvent() {
          EventHandler.emitEvents(this.slideEvents, this);
          this.node.emit('slide', this);
        };
        _proto._updateProgress = function _updateProgress(touch) {
          if (!this._handle || !touch) {
            return;
          }
          var touchPos = touch.getUILocation();
          Vec3.set(this._touchPos, touchPos.x, touchPos.y, 0);
          var uiTrans = this.node._uiProps.uiTransformComp;
          var localTouchPos = uiTrans.convertToNodeSpaceAR(this._touchPos, _tempPos$1);
          if (this.direction === Direction$2.Horizontal) {
            this.progress = clamp01(0.5 + (localTouchPos.x - this._offset.x) / uiTrans.width);
          } else {
            this.progress = clamp01(0.5 + (localTouchPos.y - this._offset.y) / uiTrans.height);
          }
        };
        _proto._updateHandlePosition = function _updateHandlePosition() {
          if (!this._handle) {
            return;
          }
          this._handleLocalPos.set(this._handle.node.getPosition());
          var uiTrans = this.node._uiProps.uiTransformComp;
          if (this._direction === Direction$2.Horizontal) {
            this._handleLocalPos.x = -uiTrans.width * uiTrans.anchorX + this.progress * uiTrans.width;
          } else {
            this._handleLocalPos.y = -uiTrans.height * uiTrans.anchorY + this.progress * uiTrans.height;
          }
          this._handle.node.setPosition(this._handleLocalPos);
        };
        _proto._changeLayout = function _changeLayout() {
          var uiTrans = this.node._uiProps.uiTransformComp;
          var contentSize = uiTrans.contentSize;
          uiTrans.setContentSize(contentSize.height, contentSize.width);
          if (this._handle) {
            var pos = this._handle.node.position;
            if (this._direction === Direction$2.Horizontal) {
              this._handle.node.setPosition(pos.x, 0, pos.z);
            } else {
              this._handle.node.setPosition(0, pos.y, pos.z);
            }
            this._updateHandlePosition();
          }
        };
        _proto._xrHandleProgress = function _xrHandleProgress(point) {
          if (!this._touchHandle) {
            var uiTrans = this.node._uiProps.uiTransformComp;
            uiTrans.convertToNodeSpaceAR(point, _tempPos$1);
            if (this.direction === Direction$2.Horizontal) {
              this.progress = clamp01(0.5 + (_tempPos$1.x - this.node.position.x) / uiTrans.width);
            } else {
              this.progress = clamp01(0.5 + (_tempPos$1.y - this.node.position.y) / uiTrans.height);
            }
          }
        };
        _proto._xrClick = function _xrClick(event) {
          if (!this._handle) {
            return;
          }
          this._dragging = true;
          this._xrHandleProgress(event.hitPoint);
          this._emitSlideEvent();
        };
        _proto._xrUnClick = function _xrUnClick() {
          this._dragging = false;
          this._touchHandle = false;
        };
        _proto._xrHoverStay = function _xrHoverStay(event) {
          if (!this._dragging) {
            return;
          }
          this._xrHandleProgress(event.hitPoint);
          this._emitSlideEvent();
        };
        _createClass(Slider, [{
          key: "handle",
          get: function get() {
            return this._handle;
          },
          set: function set(value) {
            if (this._handle === value) {
              return;
            }
            this._handle = value;
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) {
              return;
            }
            this._direction = value;
            this._changeLayout();
          }
        }, {
          key: "progress",
          get: function get() {
            return this._progress;
          },
          set: function set(value) {
            if (this._progress === value) {
              return;
            }
            this._progress = value;
            this._updateHandlePosition();
          }
        }]);
        return Slider;
      }(Component), _class3$6.Direction = Direction$2, _class3$6), (_applyDecoratedDescriptor(_class2$a.prototype, "handle", [_dec4$6], Object.getOwnPropertyDescriptor(_class2$a.prototype, "handle"), _class2$a.prototype), _applyDecoratedDescriptor(_class2$a.prototype, "direction", [_dec5$6], Object.getOwnPropertyDescriptor(_class2$a.prototype, "direction"), _class2$a.prototype), _initializer$a = applyDecoratedInitializer(_class2$a.prototype, "slideEvents", [_dec6$2, serializable$p], function () {
        return [];
      }), _initializer2$9 = applyDecoratedInitializer(_class2$a.prototype, "_handle", [serializable$p], function () {
        return null;
      }), _initializer3$6 = applyDecoratedInitializer(_class2$a.prototype, "_direction", [serializable$p], function () {
        return Direction$2.Horizontal;
      }), _initializer4$5 = applyDecoratedInitializer(_class2$a.prototype, "_progress", [serializable$p], function () {
        return 0.1;
      })), _class2$a)) || _class$d) || _class$d) || _class$d));
      legacyCC.Slider = Slider;

      function extendsEnum() {
        for (var _len = arguments.length, enums = new Array(_len), _key = 0; _key < _len; _key++) {
          enums[_key] = arguments[_key];
        }
        return Object.assign.apply(Object, [{}].concat(enums));
      }

      var _dec$c, _dec2$9, _dec3$9, _dec4$5, _dec5$5, _class$c, _class2$9, _initializer$9, _initializer2$8, _initializer3$5, _class3$5;
      var EventType$3;
      (function (EventType) {
        EventType["TOGGLE"] = "toggle";
      })(EventType$3 || (EventType$3 = {}));
      var Toggle = exports('h4', (_dec$c = ccclass$M('cc.Toggle'), _dec2$9 = executionOrder$1(110), _dec3$9 = requireComponent(UITransform), _dec4$5 = type$d(Sprite), _dec5$5 = type$d([EventHandler]), _dec$c(_class$c = _dec2$9(_class$c = _dec3$9(_class$c = (_class2$9 = (_class3$5 = function (_Button) {
        _inheritsLoose(Toggle, _Button);
        function Toggle() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Button.call.apply(_Button, [this].concat(args)) || this;
          _this.checkEvents = _initializer$9 && _initializer$9();
          _this._isChecked = _initializer2$8 && _initializer2$8();
          _this._checkMark = _initializer3$5 && _initializer3$5();
          return _this;
        }
        var _proto = Toggle.prototype;
        _proto._internalToggle = function _internalToggle() {
          this.isChecked = !this.isChecked;
        };
        _proto._set = function _set(value, emitEvent) {
          if (emitEvent === void 0) {
            emitEvent = true;
          }
          if (this._isChecked == value) return;
          this._isChecked = value;
          var group = this._toggleContainer;
          if (group && group.enabled && this.enabled) {
            if (value || !group.anyTogglesChecked() && !group.allowSwitchOff) {
              this._isChecked = true;
              group.notifyToggleCheck(this, emitEvent);
            }
          }
          this.playEffect();
          if (emitEvent) {
            this._emitToggleEvents();
          }
        };
        _proto.playEffect = function playEffect() {
          if (this._checkMark) {
            this._checkMark.node.active = this._isChecked;
          }
        };
        _proto.setIsCheckedWithoutNotify = function setIsCheckedWithoutNotify(value) {
          this._set(value, false);
        };
        _proto.onEnable = function onEnable() {
          _Button.prototype.onEnable.call(this);
          this.playEffect();
          {
            this.node.on(Toggle.EventType.CLICK, this._internalToggle, this);
          }
        };
        _proto.onDisable = function onDisable() {
          _Button.prototype.onDisable.call(this);
          {
            this.node.off(Toggle.EventType.CLICK, this._internalToggle, this);
          }
        };
        _proto._emitToggleEvents = function _emitToggleEvents() {
          this.node.emit(Toggle.EventType.TOGGLE, this);
          if (this.checkEvents) {
            EventHandler.emitEvents(this.checkEvents, this);
          }
        };
        _createClass(Toggle, [{
          key: "isChecked",
          get: function get() {
            return this._isChecked;
          },
          set: function set(value) {
            this._set(value);
          }
        }, {
          key: "checkMark",
          get: function get() {
            return this._checkMark;
          },
          set: function set(value) {
            if (this._checkMark === value) {
              return;
            }
            this._checkMark = value;
          }
        }, {
          key: "_resizeToTarget",
          set: function set(value) {
            if (value) {
              this._resizeNodeToTargetNode();
            }
          }
        }, {
          key: "_toggleContainer",
          get: function get() {
            var parent = this.node.parent;
            if (legacyCC.Node.isNode(parent)) {
              return parent.getComponent('cc.ToggleContainer');
            }
            return null;
          }
        }]);
        return Toggle;
      }(Button), _class3$5.EventType = extendsEnum(EventType$3, EventType$6), _class3$5), (_applyDecoratedDescriptor(_class2$9.prototype, "checkMark", [_dec4$5], Object.getOwnPropertyDescriptor(_class2$9.prototype, "checkMark"), _class2$9.prototype), _initializer$9 = applyDecoratedInitializer(_class2$9.prototype, "checkEvents", [_dec5$5, serializable$p], function () {
        return [];
      }), _initializer2$8 = applyDecoratedInitializer(_class2$9.prototype, "_isChecked", [serializable$p], function () {
        return true;
      }), _initializer3$5 = applyDecoratedInitializer(_class2$9.prototype, "_checkMark", [serializable$p], function () {
        return null;
      })), _class2$9)) || _class$c) || _class$c) || _class$c));
      legacyCC.Toggle = Toggle;

      var _dec$b, _dec2$8, _dec3$8, _class$b, _class2$8, _initializer$8, _initializer2$7;
      var ToggleContainer = exports('h5', (_dec$b = ccclass$M('cc.ToggleContainer'), _dec2$8 = executionOrder$1(110), _dec3$8 = type$d([EventHandler]), _dec$b(_class$b = _dec2$8(_class$b = (_class2$8 = function (_Component) {
        _inheritsLoose(ToggleContainer, _Component);
        function ToggleContainer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._allowSwitchOff = _initializer$8 && _initializer$8();
          _this.checkEvents = _initializer2$7 && _initializer2$7();
          return _this;
        }
        var _proto = ToggleContainer.prototype;
        _proto.onEnable = function onEnable() {
          this.ensureValidState();
          this.node.on(NodeEventType.CHILD_ADDED, this.ensureValidState, this);
          this.node.on(NodeEventType.CHILD_REMOVED, this.ensureValidState, this);
        };
        _proto.onDisable = function onDisable() {
          this.node.off(NodeEventType.CHILD_ADDED, this.ensureValidState, this);
          this.node.off(NodeEventType.CHILD_REMOVED, this.ensureValidState, this);
        };
        _proto.activeToggles = function activeToggles() {
          return this.toggleItems.filter(function (x) {
            return x.isChecked;
          });
        };
        _proto.anyTogglesChecked = function anyTogglesChecked() {
          return !!this.toggleItems.find(function (x) {
            return x.isChecked;
          });
        };
        _proto.notifyToggleCheck = function notifyToggleCheck(toggle, emitEvent) {
          if (emitEvent === void 0) {
            emitEvent = true;
          }
          if (!this.enabledInHierarchy) {
            return;
          }
          for (var i = 0; i < this.toggleItems.length; i++) {
            var item = this.toggleItems[i];
            if (item === toggle) {
              continue;
            }
            if (emitEvent) {
              item.isChecked = false;
            } else {
              item.setIsCheckedWithoutNotify(false);
            }
          }
          if (this.checkEvents) {
            legacyCC.Component.EventHandler.emitEvents(this.checkEvents, toggle);
          }
        };
        _proto.ensureValidState = function ensureValidState() {
          var toggles = this.toggleItems;
          if (!this._allowSwitchOff && !this.anyTogglesChecked() && toggles.length !== 0) {
            var toggle = toggles[0];
            toggle.isChecked = true;
            this.notifyToggleCheck(toggle);
          }
          var activeToggles = this.activeToggles();
          if (activeToggles.length > 1) {
            var firstToggle = activeToggles[0];
            for (var i = 0; i < activeToggles.length; ++i) {
              var _toggle = activeToggles[i];
              if (_toggle === firstToggle) {
                continue;
              }
              _toggle.isChecked = false;
            }
          }
        };
        _createClass(ToggleContainer, [{
          key: "allowSwitchOff",
          get: function get() {
            return this._allowSwitchOff;
          },
          set: function set(value) {
            this._allowSwitchOff = value;
          }
        }, {
          key: "toggleItems",
          get: function get() {
            return this.node.children.map(function (item) {
              var toggle = item.getComponent('cc.Toggle');
              if (toggle && toggle.enabled) {
                return toggle;
              }
              return null;
            }).filter(Boolean);
          }
        }]);
        return ToggleContainer;
      }(Component), (_initializer$8 = applyDecoratedInitializer(_class2$8.prototype, "_allowSwitchOff", [serializable$p], function () {
        return false;
      }), _initializer2$7 = applyDecoratedInitializer(_class2$8.prototype, "checkEvents", [_dec3$8, serializable$p], function () {
        return [];
      })), _class2$8)) || _class$b) || _class$b));
      legacyCC.ToggleContainer = ToggleContainer;

      var _dec$a, _dec2$7, _dec3$7, _dec4$4, _dec5$4, _class$a, _class2$7, _initializer$7, _initializer2$6, _initializer3$4, _initializer4$4, _initializer5$3, _initializer6$2, _initializer7$2, _initializer8$2, _initializer9$2, _initializer10$2, _initializer11$2, _initializer12$2, _initializer13, _initializer14, _initializer15, _initializer16, _initializer17, _initializer18, _class3$4;
      var _tempScale = new Vec2();
      function getReadonlyNodeSize(parent) {
        if (parent instanceof Scene) {
          return visibleRect;
        } else if (parent._uiProps.uiTransformComp) {
          return parent._uiProps.uiTransformComp.contentSize;
        } else {
          return Size$1.ZERO;
        }
      }
      function computeInverseTransForTarget(widgetNode, target, out_inverseTranslate, out_inverseScale) {
        if (widgetNode.parent) {
          _tempScale.set(widgetNode.parent.getScale().x, widgetNode.parent.getScale().y);
        } else {
          _tempScale.set(0, 0);
        }
        var scaleX = _tempScale.x;
        var scaleY = _tempScale.y;
        var translateX = 0;
        var translateY = 0;
        for (var node = widgetNode.parent;;) {
          if (!node) {
            out_inverseTranslate.x = out_inverseTranslate.y = 0;
            out_inverseScale.x = out_inverseScale.y = 1;
            return;
          }
          var pos = node.getPosition();
          translateX += pos.x;
          translateY += pos.y;
          node = node.parent;
          if (node !== target) {
            if (node) {
              _tempScale.set(node.getScale().x, node.getScale().y);
            } else {
              _tempScale.set(0, 0);
            }
            var sx = _tempScale.x;
            var sy = _tempScale.y;
            translateX *= sx;
            translateY *= sy;
            scaleX *= sx;
            scaleY *= sy;
          } else {
            break;
          }
        }
        out_inverseScale.x = scaleX !== 0 ? 1 / scaleX : 1;
        out_inverseScale.y = scaleY !== 0 ? 1 / scaleY : 1;
        out_inverseTranslate.x = -translateX;
        out_inverseTranslate.y = -translateY;
      }
      var AlignMode;
      (function (AlignMode) {
        AlignMode[AlignMode["ONCE"] = 0] = "ONCE";
        AlignMode[AlignMode["ALWAYS"] = 1] = "ALWAYS";
        AlignMode[AlignMode["ON_WINDOW_RESIZE"] = 2] = "ON_WINDOW_RESIZE";
      })(AlignMode || (AlignMode = {}));
      ccenum(AlignMode);
      var AlignFlags;
      (function (AlignFlags) {
        AlignFlags[AlignFlags["TOP"] = 1] = "TOP";
        AlignFlags[AlignFlags["MID"] = 2] = "MID";
        AlignFlags[AlignFlags["BOT"] = 4] = "BOT";
        AlignFlags[AlignFlags["LEFT"] = 8] = "LEFT";
        AlignFlags[AlignFlags["CENTER"] = 16] = "CENTER";
        AlignFlags[AlignFlags["RIGHT"] = 32] = "RIGHT";
        AlignFlags[AlignFlags["HORIZONTAL"] = 56] = "HORIZONTAL";
        AlignFlags[AlignFlags["VERTICAL"] = 7] = "VERTICAL";
      })(AlignFlags || (AlignFlags = {}));
      var TOP_BOT = AlignFlags.TOP | AlignFlags.BOT;
      var LEFT_RIGHT = AlignFlags.LEFT | AlignFlags.RIGHT;
      var Widget = exports('h7', (_dec$a = ccclass$M('cc.Widget'), _dec2$7 = executionOrder$1(110), _dec3$7 = requireComponent(UITransform), _dec4$4 = type$d(Node$1), _dec5$4 = type$d(AlignMode), _dec$a(_class$a = _dec2$7(_class$a = _dec3$7(_class$a = (_class2$7 = (_class3$4 = function (_Component) {
        _inheritsLoose(Widget, _Component);
        function Widget() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._lastPos = new Vec3();
          _this._lastSize = new Size$1();
          _this._dirty = true;
          _this._hadAlignOnce = false;
          _this._alignFlags = _initializer$7 && _initializer$7();
          _this._target = _initializer2$6 && _initializer2$6();
          _this._left = _initializer3$4 && _initializer3$4();
          _this._right = _initializer4$4 && _initializer4$4();
          _this._top = _initializer5$3 && _initializer5$3();
          _this._bottom = _initializer6$2 && _initializer6$2();
          _this._horizontalCenter = _initializer7$2 && _initializer7$2();
          _this._verticalCenter = _initializer8$2 && _initializer8$2();
          _this._isAbsLeft = _initializer9$2 && _initializer9$2();
          _this._isAbsRight = _initializer10$2 && _initializer10$2();
          _this._isAbsTop = _initializer11$2 && _initializer11$2();
          _this._isAbsBottom = _initializer12$2 && _initializer12$2();
          _this._isAbsHorizontalCenter = _initializer13 && _initializer13();
          _this._isAbsVerticalCenter = _initializer14 && _initializer14();
          _this._originalWidth = _initializer15 && _initializer15();
          _this._originalHeight = _initializer16 && _initializer16();
          _this._alignMode = _initializer17 && _initializer17();
          _this._lockFlags = _initializer18 && _initializer18();
          return _this;
        }
        var _proto = Widget.prototype;
        _proto.updateAlignment = function updateAlignment() {
          legacyCC._widgetManager.updateAlignment(this.node);
        };
        _proto._validateTargetInDEV = function _validateTargetInDEV() {
          {
            return;
          }
        };
        _proto.setDirty = function setDirty() {
          this._recursiveDirty();
        };
        _proto.onEnable = function onEnable() {
          this.node.getPosition(this._lastPos);
          this._lastSize.set(this.node._uiProps.uiTransformComp.contentSize);
          legacyCC._widgetManager.add(this);
          this._hadAlignOnce = false;
          this._registerEvent();
          this._registerTargetEvents();
        };
        _proto.onDisable = function onDisable() {
          legacyCC._widgetManager.remove(this);
          this._unregisterEvent();
          this._unregisterTargetEvents();
        };
        _proto.onDestroy = function onDestroy() {
          this._removeParentEvent();
        };
        _proto._adjustWidgetToAllowMovingInEditor = function _adjustWidgetToAllowMovingInEditor(eventType) {};
        _proto._adjustWidgetToAllowResizingInEditor = function _adjustWidgetToAllowResizingInEditor() {};
        _proto._adjustWidgetToAnchorChanged = function _adjustWidgetToAnchorChanged() {
          this.setDirty();
        };
        _proto._adjustTargetToParentChanged = function _adjustTargetToParentChanged(oldParent) {
          if (oldParent) {
            this._unregisterOldParentEvents(oldParent);
          }
          if (this.node.getParent()) {
            this._registerTargetEvents();
          }
          this._setDirtyByMode();
        };
        _proto._registerEvent = function _registerEvent() {
          {
            this.node.on(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
            this.node.on(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
          }
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._adjustWidgetToAnchorChanged, this);
          this.node.on(NodeEventType.PARENT_CHANGED, this._adjustTargetToParentChanged, this);
        };
        _proto._unregisterEvent = function _unregisterEvent() {
          {
            this.node.off(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
            this.node.off(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
          }
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._adjustWidgetToAnchorChanged, this);
        };
        _proto._removeParentEvent = function _removeParentEvent() {
          this.node.off(NodeEventType.PARENT_CHANGED, this._adjustTargetToParentChanged, this);
        };
        _proto._autoChangedValue = function _autoChangedValue(flag, isAbs) {
          var current = (this._alignFlags & flag) > 0;
          if (!current) {
            return;
          }
          var parentUiProps = this.node.parent && this.node.parent._uiProps;
          var parentTrans = parentUiProps && parentUiProps.uiTransformComp;
          var size = parentTrans ? parentTrans.contentSize : visibleRect;
          if (this.isAlignLeft && flag === AlignFlags.LEFT) {
            this._left = isAbs ? this._left * size.width : this._left / size.width;
          } else if (this.isAlignRight && flag === AlignFlags.RIGHT) {
            this._right = isAbs ? this._right * size.width : this._right / size.width;
          } else if (this.isAlignHorizontalCenter && flag === AlignFlags.CENTER) {
            this._horizontalCenter = isAbs ? this._horizontalCenter * size.width : this._horizontalCenter / size.width;
          } else if (this.isAlignTop && flag === AlignFlags.TOP) {
            this._top = isAbs ? this._top * size.height : this._top / size.height;
          } else if (this.isAlignBottom && flag === AlignFlags.BOT) {
            this._bottom = isAbs ? this._bottom * size.height : this._bottom / size.height;
          } else if (this.isAbsoluteVerticalCenter && flag === AlignFlags.MID) {
            this._verticalCenter = isAbs ? this._verticalCenter / size.height : this._verticalCenter / size.height;
          }
          this._recursiveDirty();
        };
        _proto._registerTargetEvents = function _registerTargetEvents() {
          var target = this._target || this.node.parent;
          if (target) {
            if (target.getComponent(UITransform)) {
              target.on(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
              target.on(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
              target.on(NodeEventType.ANCHOR_CHANGED, this._setDirtyByMode, this);
            }
          }
        };
        _proto._unregisterTargetEvents = function _unregisterTargetEvents() {
          var target = this._target || this.node.parent;
          if (target) {
            target.off(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
            target.off(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
            target.off(NodeEventType.ANCHOR_CHANGED, this._setDirtyByMode, this);
          }
        };
        _proto._unregisterOldParentEvents = function _unregisterOldParentEvents(oldParent) {
          var target = this._target || oldParent;
          if (target) {
            target.off(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
            target.off(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
          }
        };
        _proto._setDirtyByMode = function _setDirtyByMode() {
          if (this.alignMode === AlignMode.ALWAYS || EDITOR_NOT_IN_PREVIEW) {
            this._recursiveDirty();
          }
        };
        _proto._setAlign = function _setAlign(flag, isAlign) {
          var current = (this._alignFlags & flag) > 0;
          if (isAlign === current) {
            return;
          }
          var isHorizontal = (flag & LEFT_RIGHT) > 0;
          var trans = this.node._uiProps.uiTransformComp;
          if (isAlign) {
            this._alignFlags |= flag;
            if (isHorizontal) {
              this.isAlignHorizontalCenter = false;
              if (this.isStretchWidth) {
                this._originalWidth = trans.width;
              }
            } else {
              this.isAlignVerticalCenter = false;
              if (this.isStretchHeight) {
                this._originalHeight = trans.height;
              }
            }
          } else {
            if (isHorizontal) {
              if (this.isStretchWidth) {
                trans.width = this._originalWidth;
              }
            } else if (this.isStretchHeight) {
              trans.height = this._originalHeight;
            }
            this._alignFlags &= ~flag;
          }
        };
        _proto._recursiveDirty = function _recursiveDirty() {
          if (this._dirty) {
            return;
          }
          this._dirty = true;
        };
        _createClass(Widget, [{
          key: "target",
          get: function get() {
            return this._target;
          },
          set: function set(value) {
            if (this._target === value) {
              return;
            }
            this._unregisterTargetEvents();
            this._target = value;
            this._registerTargetEvents();
            this._validateTargetInDEV();
            this._recursiveDirty();
          }
        }, {
          key: "isAlignTop",
          get: function get() {
            return (this._alignFlags & AlignFlags.TOP) > 0;
          },
          set: function set(value) {
            this._setAlign(AlignFlags.TOP, value);
            this._recursiveDirty();
          }
        }, {
          key: "isAlignBottom",
          get: function get() {
            return (this._alignFlags & AlignFlags.BOT) > 0;
          },
          set: function set(value) {
            this._setAlign(AlignFlags.BOT, value);
            this._recursiveDirty();
          }
        }, {
          key: "isAlignLeft",
          get: function get() {
            return (this._alignFlags & AlignFlags.LEFT) > 0;
          },
          set: function set(value) {
            this._setAlign(AlignFlags.LEFT, value);
            this._recursiveDirty();
          }
        }, {
          key: "isAlignRight",
          get: function get() {
            return (this._alignFlags & AlignFlags.RIGHT) > 0;
          },
          set: function set(value) {
            this._setAlign(AlignFlags.RIGHT, value);
            this._recursiveDirty();
          }
        }, {
          key: "isAlignVerticalCenter",
          get: function get() {
            return (this._alignFlags & AlignFlags.MID) > 0;
          },
          set: function set(value) {
            if (value) {
              this.isAlignTop = false;
              this.isAlignBottom = false;
              this._alignFlags |= AlignFlags.MID;
            } else {
              this._alignFlags &= ~AlignFlags.MID;
            }
            this._recursiveDirty();
          }
        }, {
          key: "isAlignHorizontalCenter",
          get: function get() {
            return (this._alignFlags & AlignFlags.CENTER) > 0;
          },
          set: function set(value) {
            if (value) {
              this.isAlignLeft = false;
              this.isAlignRight = false;
              this._alignFlags |= AlignFlags.CENTER;
            } else {
              this._alignFlags &= ~AlignFlags.CENTER;
            }
            this._recursiveDirty();
          }
        }, {
          key: "isStretchWidth",
          get: function get() {
            return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT;
          }
        }, {
          key: "isStretchHeight",
          get: function get() {
            return (this._alignFlags & TOP_BOT) === TOP_BOT;
          }
        }, {
          key: "top",
          get: function get() {
            return this._top;
          },
          set: function set(value) {
            this._top = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorTop",
          get: function get() {
            return this._isAbsTop ? this._top : this._top * 100;
          },
          set: function set(value) {
            this._top = this._isAbsTop ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "bottom",
          get: function get() {
            return this._bottom;
          },
          set: function set(value) {
            this._bottom = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorBottom",
          get: function get() {
            return this._isAbsBottom ? this._bottom : this._bottom * 100;
          },
          set: function set(value) {
            this._bottom = this._isAbsBottom ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "left",
          get: function get() {
            return this._left;
          },
          set: function set(value) {
            this._left = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorLeft",
          get: function get() {
            return this._isAbsLeft ? this._left : this._left * 100;
          },
          set: function set(value) {
            this._left = this._isAbsLeft ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "right",
          get: function get() {
            return this._right;
          },
          set: function set(value) {
            this._right = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorRight",
          get: function get() {
            return this._isAbsRight ? this._right : this._right * 100;
          },
          set: function set(value) {
            this._right = this._isAbsRight ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "horizontalCenter",
          get: function get() {
            return this._horizontalCenter;
          },
          set: function set(value) {
            this._horizontalCenter = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorHorizontalCenter",
          get: function get() {
            return this._isAbsHorizontalCenter ? this._horizontalCenter : this._horizontalCenter * 100;
          },
          set: function set(value) {
            this._horizontalCenter = this._isAbsHorizontalCenter ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "verticalCenter",
          get: function get() {
            return this._verticalCenter;
          },
          set: function set(value) {
            this._verticalCenter = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorVerticalCenter",
          get: function get() {
            return this._isAbsVerticalCenter ? this._verticalCenter : this._verticalCenter * 100;
          },
          set: function set(value) {
            this._verticalCenter = this._isAbsVerticalCenter ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "isAbsoluteTop",
          get: function get() {
            return this._isAbsTop;
          },
          set: function set(value) {
            if (this._isAbsTop === value) {
              return;
            }
            this._isAbsTop = value;
            this._autoChangedValue(AlignFlags.TOP, this._isAbsTop);
          }
        }, {
          key: "isAbsoluteBottom",
          get: function get() {
            return this._isAbsBottom;
          },
          set: function set(value) {
            if (this._isAbsBottom === value) {
              return;
            }
            this._isAbsBottom = value;
            this._autoChangedValue(AlignFlags.BOT, this._isAbsBottom);
          }
        }, {
          key: "isAbsoluteLeft",
          get: function get() {
            return this._isAbsLeft;
          },
          set: function set(value) {
            if (this._isAbsLeft === value) {
              return;
            }
            this._isAbsLeft = value;
            this._autoChangedValue(AlignFlags.LEFT, this._isAbsLeft);
          }
        }, {
          key: "isAbsoluteRight",
          get: function get() {
            return this._isAbsRight;
          },
          set: function set(value) {
            if (this._isAbsRight === value) {
              return;
            }
            this._isAbsRight = value;
            this._autoChangedValue(AlignFlags.RIGHT, this._isAbsRight);
          }
        }, {
          key: "isAbsoluteHorizontalCenter",
          get: function get() {
            return this._isAbsHorizontalCenter;
          },
          set: function set(value) {
            if (this._isAbsHorizontalCenter === value) {
              return;
            }
            this._isAbsHorizontalCenter = value;
            this._autoChangedValue(AlignFlags.CENTER, this._isAbsHorizontalCenter);
          }
        }, {
          key: "isAbsoluteVerticalCenter",
          get: function get() {
            return this._isAbsVerticalCenter;
          },
          set: function set(value) {
            if (this._isAbsVerticalCenter === value) {
              return;
            }
            this._isAbsVerticalCenter = value;
            this._autoChangedValue(AlignFlags.MID, this._isAbsVerticalCenter);
          }
        }, {
          key: "alignMode",
          get: function get() {
            return this._alignMode;
          },
          set: function set(value) {
            this._alignMode = value;
            this._recursiveDirty();
          }
        }, {
          key: "alignFlags",
          get: function get() {
            return this._alignFlags;
          },
          set: function set(value) {
            if (this._alignFlags === value) {
              return;
            }
            this._alignFlags = value;
            this._recursiveDirty();
          }
        }]);
        return Widget;
      }(Component), _class3$4.AlignMode = AlignMode, _class3$4), (_applyDecoratedDescriptor(_class2$7.prototype, "target", [_dec4$4], Object.getOwnPropertyDescriptor(_class2$7.prototype, "target"), _class2$7.prototype), _applyDecoratedDescriptor(_class2$7.prototype, "alignMode", [_dec5$4], Object.getOwnPropertyDescriptor(_class2$7.prototype, "alignMode"), _class2$7.prototype), _initializer$7 = applyDecoratedInitializer(_class2$7.prototype, "_alignFlags", [serializable$p], function () {
        return 0;
      }), _initializer2$6 = applyDecoratedInitializer(_class2$7.prototype, "_target", [serializable$p], function () {
        return null;
      }), _initializer3$4 = applyDecoratedInitializer(_class2$7.prototype, "_left", [serializable$p], function () {
        return 0;
      }), _initializer4$4 = applyDecoratedInitializer(_class2$7.prototype, "_right", [serializable$p], function () {
        return 0;
      }), _initializer5$3 = applyDecoratedInitializer(_class2$7.prototype, "_top", [serializable$p], function () {
        return 0;
      }), _initializer6$2 = applyDecoratedInitializer(_class2$7.prototype, "_bottom", [serializable$p], function () {
        return 0;
      }), _initializer7$2 = applyDecoratedInitializer(_class2$7.prototype, "_horizontalCenter", [serializable$p], function () {
        return 0;
      }), _initializer8$2 = applyDecoratedInitializer(_class2$7.prototype, "_verticalCenter", [serializable$p], function () {
        return 0;
      }), _initializer9$2 = applyDecoratedInitializer(_class2$7.prototype, "_isAbsLeft", [serializable$p], function () {
        return true;
      }), _initializer10$2 = applyDecoratedInitializer(_class2$7.prototype, "_isAbsRight", [serializable$p], function () {
        return true;
      }), _initializer11$2 = applyDecoratedInitializer(_class2$7.prototype, "_isAbsTop", [serializable$p], function () {
        return true;
      }), _initializer12$2 = applyDecoratedInitializer(_class2$7.prototype, "_isAbsBottom", [serializable$p], function () {
        return true;
      }), _initializer13 = applyDecoratedInitializer(_class2$7.prototype, "_isAbsHorizontalCenter", [serializable$p], function () {
        return true;
      }), _initializer14 = applyDecoratedInitializer(_class2$7.prototype, "_isAbsVerticalCenter", [serializable$p], function () {
        return true;
      }), _initializer15 = applyDecoratedInitializer(_class2$7.prototype, "_originalWidth", [serializable$p], function () {
        return 0;
      }), _initializer16 = applyDecoratedInitializer(_class2$7.prototype, "_originalHeight", [serializable$p], function () {
        return 0;
      }), _initializer17 = applyDecoratedInitializer(_class2$7.prototype, "_alignMode", [serializable$p], function () {
        return AlignMode.ON_WINDOW_RESIZE;
      }), _initializer18 = applyDecoratedInitializer(_class2$7.prototype, "_lockFlags", [serializable$p, editorOnly], function () {
        return 0;
      })), _class2$7)) || _class$a) || _class$a) || _class$a));
      legacyCC.internal.computeInverseTransForTarget = computeInverseTransForTarget;
      legacyCC.internal.getReadonlyNodeSize = getReadonlyNodeSize;
      legacyCC.Widget = Widget;

      var _dec$9, _dec2$6, _dec3$6, _dec4$3, _dec5$3, _class$9, _class2$6, _initializer$6, _initializer2$5, _initializer3$3, _initializer4$3, _class3$3;
      var _color = new Color$1();
      var Direction$1;
      (function (Direction) {
        Direction[Direction["HORIZONTAL"] = 0] = "HORIZONTAL";
        Direction[Direction["VERTICAL"] = 1] = "VERTICAL";
      })(Direction$1 || (Direction$1 = {}));
      ccenum(Direction$1);
      var PageViewIndicator = exports('h9', (_dec$9 = ccclass$M('cc.PageViewIndicator'), _dec2$6 = executionOrder$1(110), _dec3$6 = type$d(SpriteFrame), _dec4$3 = type$d(Direction$1), _dec5$3 = type$d(Size$1), _dec$9(_class$9 = _dec2$6(_class$9 = (_class2$6 = (_class3$3 = function (_Component) {
        _inheritsLoose(PageViewIndicator, _Component);
        function PageViewIndicator() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.spacing = _initializer$6 && _initializer$6();
          _this._spriteFrame = _initializer2$5 && _initializer2$5();
          _this._direction = _initializer3$3 && _initializer3$3();
          _this._cellSize = _initializer4$3 && _initializer4$3();
          _this._layout = null;
          _this._pageView = null;
          _this._indicators = [];
          return _this;
        }
        var _proto = PageViewIndicator.prototype;
        _proto.onLoad = function onLoad() {
          this._updateLayout();
        };
        _proto.setPageView = function setPageView(target) {
          this._pageView = target;
          this._refresh();
        };
        _proto._updateLayout = function _updateLayout() {
          this._layout = this.getComponent(Layout);
          if (!this._layout) {
            this._layout = this.addComponent(Layout);
          }
          var layout = this._layout;
          if (this.direction === Direction$1.HORIZONTAL) {
            layout.type = Layout.Type.HORIZONTAL;
            layout.spacingX = this.spacing;
          } else if (this.direction === Direction$1.VERTICAL) {
            layout.type = Layout.Type.VERTICAL;
            layout.spacingY = this.spacing;
          }
          layout.resizeMode = Layout.ResizeMode.CONTAINER;
        };
        _proto._createIndicator = function _createIndicator() {
          var node = new Node$1();
          node.layer = this.node.layer;
          var sprite = node.addComponent(Sprite);
          sprite.spriteFrame = this.spriteFrame;
          sprite.sizeMode = Sprite.SizeMode.CUSTOM;
          node.parent = this.node;
          node._uiProps.uiTransformComp.setContentSize(this._cellSize);
          return node;
        };
        _proto._changedState = function _changedState() {
          var indicators = this._indicators;
          if (indicators.length === 0 || !this._pageView) {
            return;
          }
          var idx = this._pageView.curPageIdx;
          if (idx >= indicators.length) {
            return;
          }
          for (var i = 0; i < indicators.length; ++i) {
            var node = indicators[i];
            if (!node._uiProps.uiComp) {
              continue;
            }
            var uiComp = node._uiProps.uiComp;
            _color.set(uiComp.color);
            _color.a = 255 / 2;
            uiComp.color = _color;
          }
          if (indicators[idx]._uiProps.uiComp) {
            var comp = indicators[idx]._uiProps.uiComp;
            _color.set(comp.color);
            _color.a = 255;
            comp.color = _color;
          }
        };
        _proto._refresh = function _refresh() {
          if (!this._pageView) {
            return;
          }
          var indicators = this._indicators;
          var pages = this._pageView.getPages();
          if (pages.length === indicators.length) {
            return;
          }
          var i = 0;
          if (pages.length > indicators.length) {
            for (i = 0; i < pages.length; ++i) {
              if (!indicators[i]) {
                indicators[i] = this._createIndicator();
              }
            }
          } else {
            var count = indicators.length - pages.length;
            for (i = count; i > 0; --i) {
              var node = indicators[i - 1];
              this.node.removeChild(node);
              indicators.splice(i - 1, 1);
            }
          }
          if (this._layout && this._layout.enabledInHierarchy) {
            this._layout.updateLayout();
          }
          this._changedState();
        };
        _createClass(PageViewIndicator, [{
          key: "spriteFrame",
          get: function get() {
            return this._spriteFrame;
          },
          set: function set(value) {
            if (this._spriteFrame === value) {
              return;
            }
            this._spriteFrame = value;
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) {
              return;
            }
            this._direction = value;
          }
        }, {
          key: "cellSize",
          get: function get() {
            return this._cellSize;
          },
          set: function set(value) {
            if (this._cellSize === value) {
              return;
            }
            this._cellSize = value;
          }
        }]);
        return PageViewIndicator;
      }(Component), _class3$3.Direction = Direction$1, _class3$3), (_applyDecoratedDescriptor(_class2$6.prototype, "spriteFrame", [_dec3$6], Object.getOwnPropertyDescriptor(_class2$6.prototype, "spriteFrame"), _class2$6.prototype), _applyDecoratedDescriptor(_class2$6.prototype, "direction", [_dec4$3], Object.getOwnPropertyDescriptor(_class2$6.prototype, "direction"), _class2$6.prototype), _applyDecoratedDescriptor(_class2$6.prototype, "cellSize", [_dec5$3], Object.getOwnPropertyDescriptor(_class2$6.prototype, "cellSize"), _class2$6.prototype), _initializer$6 = applyDecoratedInitializer(_class2$6.prototype, "spacing", [serializable$p], function () {
        return 0;
      }), _initializer2$5 = applyDecoratedInitializer(_class2$6.prototype, "_spriteFrame", [serializable$p], function () {
        return null;
      }), _initializer3$3 = applyDecoratedInitializer(_class2$6.prototype, "_direction", [serializable$p], function () {
        return Direction$1.HORIZONTAL;
      }), _initializer4$3 = applyDecoratedInitializer(_class2$6.prototype, "_cellSize", [serializable$p], function () {
        return new Size$1(20, 20);
      })), _class2$6)) || _class$9) || _class$9));
      legacyCC.PageViewIndicator = PageViewIndicator;

      var _dec$8, _dec2$5, _dec3$5, _dec4$2, _dec5$2, _dec6$1, _dec7, _dec8, _dec9, _class$8, _class2$5, _initializer$5, _initializer2$4, _initializer3$2, _initializer4$2, _initializer5$2, _initializer6$1, _initializer7$1, _initializer8$1, _initializer9$1, _initializer10$1, _initializer11$1, _initializer12$1, _class3$2;
      var _tempVec2 = new Vec2();
      var SizeMode;
      (function (SizeMode) {
        SizeMode[SizeMode["Unified"] = 0] = "Unified";
        SizeMode[SizeMode["Free"] = 1] = "Free";
      })(SizeMode || (SizeMode = {}));
      ccenum(SizeMode);
      var Direction;
      (function (Direction) {
        Direction[Direction["Horizontal"] = 0] = "Horizontal";
        Direction[Direction["Vertical"] = 1] = "Vertical";
      })(Direction || (Direction = {}));
      ccenum(Direction);
      var EventType$2;
      (function (EventType) {
        EventType["PAGE_TURNING"] = "page-turning";
      })(EventType$2 || (EventType$2 = {}));
      var PageView = exports('h8', (_dec$8 = ccclass$M('cc.PageView'), _dec2$5 = executionOrder$1(110), _dec3$5 = type$d(SizeMode), _dec4$2 = type$d(Direction), _dec5$2 = type$d(PageViewIndicator), _dec6$1 = type$d(ScrollBar), _dec7 = type$d(ScrollBar), _dec8 = type$d([EventHandler]), _dec9 = type$d([EventHandler]), _dec$8(_class$8 = _dec2$5(_class$8 = (_class2$5 = (_class3$2 = function (_ScrollView) {
        _inheritsLoose(PageView, _ScrollView);
        function PageView() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ScrollView.call.apply(_ScrollView, [this].concat(args)) || this;
          _this.autoPageTurningThreshold = _initializer$5 && _initializer$5();
          _this.horizontal = _initializer2$4 && _initializer2$4();
          _this.vertical = _initializer3$2 && _initializer3$2();
          _this.cancelInnerEvents = _initializer4$2 && _initializer4$2();
          _this.scrollEvents = _initializer5$2 && _initializer5$2();
          _this.pageTurningSpeed = _initializer6$1 && _initializer6$1();
          _this.pageEvents = _initializer7$1 && _initializer7$1();
          _this._sizeMode = _initializer8$1 && _initializer8$1();
          _this._direction = _initializer9$1 && _initializer9$1();
          _this._scrollThreshold = _initializer10$1 && _initializer10$1();
          _this._pageTurningEventTiming = _initializer11$1 && _initializer11$1();
          _this._indicator = _initializer12$1 && _initializer12$1();
          _this._curPageIdx = 0;
          _this._lastPageIdx = 0;
          _this._pages = [];
          _this._initContentPos = new Vec3();
          _this._scrollCenterOffsetX = [];
          _this._scrollCenterOffsetY = [];
          _this._touchBeganPosition = new Vec2();
          _this._touchEndPosition = new Vec2();
          return _this;
        }
        var _proto = PageView.prototype;
        _proto.onEnable = function onEnable() {
          _ScrollView.prototype.onEnable.call(this);
          this.node.on(NodeEventType.SIZE_CHANGED, this._updateAllPagesSize, this);
          {
            this.node.on(PageView.EventType.SCROLL_ENG_WITH_THRESHOLD, this._dispatchPageTurningEvent, this);
          }
        };
        _proto.onDisable = function onDisable() {
          _ScrollView.prototype.onDisable.call(this);
          this.node.off(NodeEventType.SIZE_CHANGED, this._updateAllPagesSize, this);
          {
            this.node.off(PageView.EventType.SCROLL_ENG_WITH_THRESHOLD, this._dispatchPageTurningEvent, this);
          }
        };
        _proto.onLoad = function onLoad() {
          this._initPages();
          if (this.indicator) {
            this.indicator.setPageView(this);
          }
        };
        _proto.getCurrentPageIndex = function getCurrentPageIndex() {
          return this._curPageIdx;
        };
        _proto.setCurrentPageIndex = function setCurrentPageIndex(index) {
          this.scrollToPage(index, 1);
        };
        _proto.getPages = function getPages() {
          return this._pages;
        };
        _proto.addPage = function addPage(page) {
          if (!page || this._pages.indexOf(page) !== -1 || !this.content) {
            return;
          }
          if (!page._uiProps.uiTransformComp) {
            logID(4301);
            return;
          }
          this.content.addChild(page);
          this._pages.push(page);
          this._updatePageView();
        };
        _proto.insertPage = function insertPage(page, index) {
          if (index < 0 || !page || this._pages.indexOf(page) !== -1 || !this.content) {
            return;
          }
          var pageCount = this._pages.length;
          if (index >= pageCount) {
            this.addPage(page);
          } else {
            if (!page._uiProps.uiTransformComp) {
              logID(4301);
              return;
            }
            this._pages.splice(index, 0, page);
            this.content.insertChild(page, index);
            this._updatePageView();
          }
        };
        _proto.removePage = function removePage(page) {
          if (!page || !this.content) {
            return;
          }
          var index = this._pages.indexOf(page);
          if (index === -1) {
            warnID(4300, page.name);
            return;
          }
          this.removePageAtIndex(index);
        };
        _proto.removePageAtIndex = function removePageAtIndex(index) {
          var pageList = this._pages;
          if (index < 0 || index >= pageList.length) {
            return;
          }
          var page = pageList[index];
          if (!page || !this.content) {
            return;
          }
          this.content.removeChild(page);
          pageList.splice(index, 1);
          this._updatePageView();
        };
        _proto.removeAllPages = function removeAllPages() {
          if (!this.content) {
            return;
          }
          var locPages = this._pages;
          for (var i = 0, len = locPages.length; i < len; i++) {
            this.content.removeChild(locPages[i]);
          }
          this._pages.length = 0;
          this._updatePageView();
        };
        _proto.scrollToPage = function scrollToPage(idx, timeInSecond) {
          if (timeInSecond === void 0) {
            timeInSecond = 0.3;
          }
          if (idx < 0 || idx >= this._pages.length) {
            return;
          }
          this._curPageIdx = idx;
          this.scrollToOffset(this._moveOffsetValue(idx), timeInSecond, true);
          if (this.indicator) {
            this.indicator._changedState();
          }
        };
        _proto.getScrollEndedEventTiming = function getScrollEndedEventTiming() {
          return this.pageTurningEventTiming;
        };
        _proto._updatePageView = function _updatePageView() {
          if (!this.content) {
            return;
          }
          var layout = this.content.getComponent(Layout);
          if (layout && layout.enabled) {
            layout.updateLayout();
          }
          var pageCount = this._pages.length;
          if (this._curPageIdx >= pageCount) {
            this._curPageIdx = pageCount === 0 ? 0 : pageCount - 1;
            this._lastPageIdx = this._curPageIdx;
          }
          var contentPos = this._initContentPos;
          for (var i = 0; i < pageCount; ++i) {
            var page = this._pages[i];
            var pos = page.position;
            if (this.direction === Direction.Horizontal) {
              this._scrollCenterOffsetX[i] = Math.abs(contentPos.x + pos.x);
            } else {
              this._scrollCenterOffsetY[i] = Math.abs(contentPos.y + pos.y);
            }
          }
          if (this.indicator) {
            this.indicator._refresh();
          }
        };
        _proto._updateAllPagesSize = function _updateAllPagesSize() {
          var viewTrans = this.view;
          if (!this.content || !viewTrans) {
            return;
          }
          if (this._sizeMode !== SizeMode.Unified) {
            return;
          }
          var locPages = this._pages;
          var selfSize = viewTrans.contentSize;
          for (var i = 0, len = locPages.length; i < len; i++) {
            locPages[i]._uiProps.uiTransformComp.setContentSize(selfSize);
          }
        };
        _proto._handleReleaseLogic = function _handleReleaseLogic() {
          this._autoScrollToPage();
          if (this._scrolling) {
            this._scrolling = false;
            if (!this._autoScrolling) {
              this._dispatchEvent(PageView.EventType.SCROLL_ENDED);
            }
          }
        };
        _proto._onTouchBegan = function _onTouchBegan(event, captureListeners) {
          event.touch.getUILocation(_tempVec2);
          Vec2.set(this._touchBeganPosition, _tempVec2.x, _tempVec2.y);
          _ScrollView.prototype._onTouchBegan.call(this, event, captureListeners);
        };
        _proto._onTouchMoved = function _onTouchMoved(event, captureListeners) {
          _ScrollView.prototype._onTouchMoved.call(this, event, captureListeners);
        };
        _proto._onTouchEnded = function _onTouchEnded(event, captureListeners) {
          event.touch.getUILocation(_tempVec2);
          Vec2.set(this._touchEndPosition, _tempVec2.x, _tempVec2.y);
          _ScrollView.prototype._onTouchEnded.call(this, event, captureListeners);
        };
        _proto._onTouchCancelled = function _onTouchCancelled(event, captureListeners) {
          event.touch.getUILocation(_tempVec2);
          Vec2.set(this._touchEndPosition, _tempVec2.x, _tempVec2.y);
          _ScrollView.prototype._onTouchCancelled.call(this, event, captureListeners);
        };
        _proto._onMouseWheel = function _onMouseWheel() {};
        _proto._syncScrollDirection = function _syncScrollDirection() {
          this.horizontal = this.direction === Direction.Horizontal;
          this.vertical = this.direction === Direction.Vertical;
        };
        _proto._syncSizeMode = function _syncSizeMode() {
          var viewTrans = this.view;
          if (!this.content || !viewTrans) {
            return;
          }
          var layout = this.content.getComponent(Layout);
          if (layout) {
            if (this._sizeMode === SizeMode.Free && this._pages.length > 0) {
              var firstPageTrans = this._pages[0]._uiProps.uiTransformComp;
              var lastPageTrans = this._pages[this._pages.length - 1]._uiProps.uiTransformComp;
              if (this.direction === Direction.Horizontal) {
                layout.paddingLeft = (viewTrans.width - firstPageTrans.width) / 2;
                layout.paddingRight = (viewTrans.width - lastPageTrans.width) / 2;
              } else if (this.direction === Direction.Vertical) {
                layout.paddingTop = (viewTrans.height - firstPageTrans.height) / 2;
                layout.paddingBottom = (viewTrans.height - lastPageTrans.height) / 2;
              }
            }
            layout.updateLayout();
          }
        };
        _proto._initPages = function _initPages() {
          if (!this.content) {
            return;
          }
          this._initContentPos = this.content.position;
          var children = this.content.children;
          for (var i = 0; i < children.length; ++i) {
            var page = children[i];
            if (this._pages.indexOf(page) >= 0) {
              continue;
            }
            this._pages.push(page);
          }
          this._syncScrollDirection();
          this._syncSizeMode();
          this._updatePageView();
        };
        _proto._dispatchPageTurningEvent = function _dispatchPageTurningEvent() {
          if (this._lastPageIdx === this._curPageIdx) {
            return;
          }
          this._lastPageIdx = this._curPageIdx;
          EventHandler.emitEvents(this.pageEvents, this, EventType$2.PAGE_TURNING);
          this.node.emit(EventType$2.PAGE_TURNING, this);
        };
        _proto._isQuicklyScrollable = function _isQuicklyScrollable(touchMoveVelocity) {
          if (this.direction === Direction.Horizontal) {
            if (Math.abs(touchMoveVelocity.x) > this.autoPageTurningThreshold) {
              return true;
            }
          } else if (this.direction === Direction.Vertical) {
            if (Math.abs(touchMoveVelocity.y) > this.autoPageTurningThreshold) {
              return true;
            }
          }
          return false;
        };
        _proto._moveOffsetValue = function _moveOffsetValue(idx) {
          var offset = new Vec2();
          if (this._sizeMode === SizeMode.Free) {
            if (this.direction === Direction.Horizontal) {
              offset.x = this._scrollCenterOffsetX[idx];
            } else if (this.direction === Direction.Vertical) {
              offset.y = this._scrollCenterOffsetY[idx];
            }
          } else {
            var viewTrans = this.view;
            if (!viewTrans) {
              return offset;
            }
            if (this.direction === Direction.Horizontal) {
              offset.x = idx * viewTrans.width;
            } else if (this.direction === Direction.Vertical) {
              offset.y = idx * viewTrans.height;
            }
          }
          return offset;
        };
        _proto._getDragDirection = function _getDragDirection(moveOffset) {
          if (this._direction === Direction.Horizontal) {
            if (moveOffset.x === 0) {
              return 0;
            }
            return moveOffset.x > 0 ? 1 : -1;
          } else {
            if (moveOffset.y === 0) {
              return 0;
            }
            return moveOffset.y < 0 ? 1 : -1;
          }
        };
        _proto._isScrollable = function _isScrollable(offset, index, nextIndex) {
          if (this._sizeMode === SizeMode.Free) {
            var curPageCenter = 0;
            var nextPageCenter = 0;
            if (this.direction === Direction.Horizontal) {
              curPageCenter = this._scrollCenterOffsetX[index];
              nextPageCenter = this._scrollCenterOffsetX[nextIndex];
              return Math.abs(offset.x) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold;
            } else if (this.direction === Direction.Vertical) {
              curPageCenter = this._scrollCenterOffsetY[index];
              nextPageCenter = this._scrollCenterOffsetY[nextIndex];
              return Math.abs(offset.y) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold;
            }
          } else {
            var viewTrans = this.view;
            if (!viewTrans) {
              return false;
            }
            if (this.direction === Direction.Horizontal) {
              return Math.abs(offset.x) >= viewTrans.width * this.scrollThreshold;
            } else if (this.direction === Direction.Vertical) {
              return Math.abs(offset.y) >= viewTrans.height * this.scrollThreshold;
            }
          }
          return false;
        };
        _proto._autoScrollToPage = function _autoScrollToPage() {
          var bounceBackStarted = this._startBounceBackIfNeeded();
          if (bounceBackStarted) {
            var bounceBackAmount = this._getHowMuchOutOfBoundary();
            this._clampDelta(bounceBackAmount);
            if (bounceBackAmount.x > 0 || bounceBackAmount.y < 0) {
              this._curPageIdx = this._pages.length === 0 ? 0 : this._pages.length - 1;
            }
            if (bounceBackAmount.x < 0 || bounceBackAmount.y > 0) {
              this._curPageIdx = 0;
            }
            if (this.indicator) {
              this.indicator._changedState();
            }
          } else {
            var moveOffset = new Vec2();
            Vec2.subtract(moveOffset, this._touchBeganPosition, this._touchEndPosition);
            var index = this._curPageIdx;
            var nextIndex = index + this._getDragDirection(moveOffset);
            var timeInSecond = this.pageTurningSpeed * Math.abs(index - nextIndex);
            if (nextIndex < this._pages.length) {
              if (this._isScrollable(moveOffset, index, nextIndex)) {
                this.scrollToPage(nextIndex, timeInSecond);
                return;
              } else {
                var touchMoveVelocity = this._calculateTouchMoveVelocity();
                if (this._isQuicklyScrollable(touchMoveVelocity)) {
                  this.scrollToPage(nextIndex, timeInSecond);
                  return;
                }
              }
            }
            this.scrollToPage(index, timeInSecond);
          }
        };
        _createClass(PageView, [{
          key: "sizeMode",
          get: function get() {
            return this._sizeMode;
          },
          set: function set(value) {
            if (this._sizeMode === value) {
              return;
            }
            this._sizeMode = value;
            this._syncSizeMode();
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) {
              return;
            }
            this._direction = value;
            this._syncScrollDirection();
          }
        }, {
          key: "scrollThreshold",
          get: function get() {
            return this._scrollThreshold;
          },
          set: function set(value) {
            if (this._scrollThreshold === value) {
              return;
            }
            this._scrollThreshold = value;
          }
        }, {
          key: "pageTurningEventTiming",
          get: function get() {
            return this._pageTurningEventTiming;
          },
          set: function set(value) {
            if (this._pageTurningEventTiming === value) {
              return;
            }
            this._pageTurningEventTiming = value;
          }
        }, {
          key: "indicator",
          get: function get() {
            return this._indicator;
          },
          set: function set(value) {
            if (this._indicator === value) {
              return;
            }
            this._indicator = value;
            if (this.indicator) {
              this.indicator.setPageView(this);
            }
          }
        }, {
          key: "curPageIdx",
          get: function get() {
            return this._curPageIdx;
          }
        }, {
          key: "verticalScrollBar",
          get: function get() {
            return _ScrollView.prototype.verticalScrollBar;
          },
          set: function set(value) {
            this.verticalScrollBar = value;
          }
        }, {
          key: "horizontalScrollBar",
          get: function get() {
            return _ScrollView.prototype.horizontalScrollBar;
          },
          set: function set(value) {
            this.horizontalScrollBar = value;
          }
        }]);
        return PageView;
      }(ScrollView), _class3$2.SizeMode = SizeMode, _class3$2.Direction = Direction, _class3$2.EventType = extendsEnum(EventType$2, EventType$4), _class3$2), (_applyDecoratedDescriptor(_class2$5.prototype, "sizeMode", [_dec3$5], Object.getOwnPropertyDescriptor(_class2$5.prototype, "sizeMode"), _class2$5.prototype), _applyDecoratedDescriptor(_class2$5.prototype, "direction", [_dec4$2], Object.getOwnPropertyDescriptor(_class2$5.prototype, "direction"), _class2$5.prototype), _applyDecoratedDescriptor(_class2$5.prototype, "indicator", [_dec5$2], Object.getOwnPropertyDescriptor(_class2$5.prototype, "indicator"), _class2$5.prototype), _initializer$5 = applyDecoratedInitializer(_class2$5.prototype, "autoPageTurningThreshold", [serializable$p], function () {
        return 100;
      }), _applyDecoratedDescriptor(_class2$5.prototype, "verticalScrollBar", [_dec6$1, override$1], Object.getOwnPropertyDescriptor(_class2$5.prototype, "verticalScrollBar"), _class2$5.prototype), _applyDecoratedDescriptor(_class2$5.prototype, "horizontalScrollBar", [_dec7, override$1], Object.getOwnPropertyDescriptor(_class2$5.prototype, "horizontalScrollBar"), _class2$5.prototype), _initializer2$4 = applyDecoratedInitializer(_class2$5.prototype, "horizontal", [override$1, serializable$p], function () {
        return true;
      }), _initializer3$2 = applyDecoratedInitializer(_class2$5.prototype, "vertical", [override$1, serializable$p], function () {
        return true;
      }), _initializer4$2 = applyDecoratedInitializer(_class2$5.prototype, "cancelInnerEvents", [override$1, serializable$p], function () {
        return true;
      }), _initializer5$2 = applyDecoratedInitializer(_class2$5.prototype, "scrollEvents", [_dec8, serializable$p, override$1], function () {
        return [];
      }), _initializer6$1 = applyDecoratedInitializer(_class2$5.prototype, "pageTurningSpeed", [serializable$p], function () {
        return 0.3;
      }), _initializer7$1 = applyDecoratedInitializer(_class2$5.prototype, "pageEvents", [_dec9, serializable$p], function () {
        return [];
      }), _initializer8$1 = applyDecoratedInitializer(_class2$5.prototype, "_sizeMode", [serializable$p], function () {
        return SizeMode.Unified;
      }), _initializer9$1 = applyDecoratedInitializer(_class2$5.prototype, "_direction", [serializable$p], function () {
        return Direction.Horizontal;
      }), _initializer10$1 = applyDecoratedInitializer(_class2$5.prototype, "_scrollThreshold", [serializable$p], function () {
        return 0.5;
      }), _initializer11$1 = applyDecoratedInitializer(_class2$5.prototype, "_pageTurningEventTiming", [serializable$p], function () {
        return 0.1;
      }), _initializer12$1 = applyDecoratedInitializer(_class2$5.prototype, "_indicator", [serializable$p], function () {
        return null;
      })), _class2$5)) || _class$8) || _class$8));
      legacyCC.PageView = PageView;

      var _tempPos = new Vec3();
      var _defaultAnchor = new Vec2();
      var tInverseTranslate = new Vec2();
      var tInverseScale = new Vec2(1, 1);
      var _tempVec2_1 = new Vec2();
      var _tempVec2_2 = new Vec2();
      function align(node, widget) {
        if (widget._hadAlignOnce) return;
        if (widget.alignMode === AlignMode.ONCE) {
          widget._hadAlignOnce = true;
        }
        var hasTarget = widget.target;
        var target;
        var inverseTranslate = tInverseTranslate;
        var inverseScale = tInverseScale;
        if (hasTarget) {
          target = hasTarget;
          computeInverseTransForTarget(node, target, inverseTranslate, inverseScale);
        } else {
          target = node.parent;
        }
        var targetSize = getReadonlyNodeSize(target);
        var useGlobal = target instanceof Scene || !target.getComponent(UITransform);
        var targetAnchor = useGlobal ? _defaultAnchor : target.getComponent(UITransform).anchorPoint;
        var isRoot = useGlobal;
        node.getPosition(_tempPos);
        var uiTrans = node._uiProps.uiTransformComp;
        var x = _tempPos.x;
        var y = _tempPos.y;
        var anchor = uiTrans.anchorPoint;
        var scale = node.getScale();
        if (widget.alignFlags & AlignFlags.HORIZONTAL) {
          var localLeft = 0;
          var localRight = 0;
          var targetWidth = targetSize.width;
          if (isRoot) {
            localLeft = visibleRect.left.x;
            localRight = visibleRect.right.x;
          } else {
            localLeft = -targetAnchor.x * targetWidth;
            localRight = localLeft + targetWidth;
          }
          localLeft += widget.isAbsoluteLeft ? widget.left : widget.left * targetWidth;
          localRight -= widget.isAbsoluteRight ? widget.right : widget.right * targetWidth;
          if (hasTarget) {
            localLeft += inverseTranslate.x;
            localLeft *= inverseScale.x;
            localRight += inverseTranslate.x;
            localRight *= inverseScale.x;
          }
          var width = 0;
          var anchorX = anchor.x;
          var scaleX = scale.x;
          if (scaleX < 0) {
            anchorX = 1.0 - anchorX;
            scaleX = -scaleX;
          }
          if (widget.isStretchWidth) {
            width = localRight - localLeft;
            if (scaleX !== 0) {
              uiTrans.width = width / scaleX;
            }
            x = localLeft + anchorX * width;
          } else {
            width = uiTrans.width * scaleX;
            if (widget.isAlignHorizontalCenter) {
              var localHorizontalCenter = widget.isAbsoluteHorizontalCenter ? widget.horizontalCenter : widget.horizontalCenter * targetWidth;
              var targetCenter = (0.5 - targetAnchor.x) * targetSize.width;
              if (hasTarget) {
                localHorizontalCenter *= inverseScale.x;
                targetCenter += inverseTranslate.x;
                targetCenter *= inverseScale.x;
              }
              x = targetCenter + (anchorX - 0.5) * width + localHorizontalCenter;
            } else if (widget.isAlignLeft) {
              x = localLeft + anchorX * width;
            } else {
              x = localRight + (anchorX - 1) * width;
            }
            if (!approx(scaleX, 0, EPSILON$3)) {
              width /= scaleX;
            } else {
              width = uiTrans.width;
            }
          }
          widget._lastSize.width = width;
        }
        if (widget.alignFlags & AlignFlags.VERTICAL) {
          var localTop = 0;
          var localBottom = 0;
          var targetHeight = targetSize.height;
          if (isRoot) {
            localBottom = visibleRect.bottom.y;
            localTop = visibleRect.top.y;
          } else {
            localBottom = -targetAnchor.y * targetHeight;
            localTop = localBottom + targetHeight;
          }
          localBottom += widget.isAbsoluteBottom ? widget.bottom : widget.bottom * targetHeight;
          localTop -= widget.isAbsoluteTop ? widget.top : widget.top * targetHeight;
          if (hasTarget) {
            localBottom += inverseTranslate.y;
            localBottom *= inverseScale.y;
            localTop += inverseTranslate.y;
            localTop *= inverseScale.y;
          }
          var height = 0;
          var anchorY = anchor.y;
          var scaleY = scale.y;
          if (scaleY < 0) {
            anchorY = 1.0 - anchorY;
            scaleY = -scaleY;
          }
          if (widget.isStretchHeight) {
            height = localTop - localBottom;
            if (scaleY !== 0) {
              uiTrans.height = height / scaleY;
            }
            y = localBottom + anchorY * height;
          } else {
            height = uiTrans.height * scaleY;
            if (widget.isAlignVerticalCenter) {
              var localVerticalCenter = widget.isAbsoluteVerticalCenter ? widget.verticalCenter : widget.verticalCenter * targetHeight;
              var targetMiddle = (0.5 - targetAnchor.y) * targetSize.height;
              if (hasTarget) {
                localVerticalCenter *= inverseScale.y;
                targetMiddle += inverseTranslate.y;
                targetMiddle *= inverseScale.y;
              }
              y = targetMiddle + (anchorY - 0.5) * height + localVerticalCenter;
            } else if (widget.isAlignBottom) {
              y = localBottom + anchorY * height;
            } else {
              y = localTop + (anchorY - 1) * height;
            }
            if (!approx(scaleY, 0, EPSILON$3)) {
              height /= scaleY;
            } else {
              height = uiTrans.height;
            }
          }
          widget._lastSize.height = height;
        }
        node.setPosition(x, y, _tempPos.z);
        Vec3.set(widget._lastPos, x, y, _tempPos.z);
      }
      function visitNode(node) {
        var widget = node.getComponent(Widget);
        if (widget && widget.enabled) {
          if (!legacyCC.isValid(node, true)) {
            return;
          }
          activeWidgets.push(widget);
        }
        var children = node.children;
        for (var _iterator = _createForOfIteratorHelperLoose(children), _step; !(_step = _iterator()).done;) {
          var child = _step.value;
          if (child.active) {
            visitNode(child);
          }
        }
      }
      function refreshScene() {
        var scene = director.getScene();
        if (scene) {
          widgetManager.isAligning = true;
          if (widgetManager._nodesOrderDirty) {
            activeWidgets.length = 0;
            visitNode(scene);
            widgetManager._nodesOrderDirty = false;
          }
          var widget = null;
          var iterator = widgetManager._activeWidgetsIterator;
          for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) {
            widget = activeWidgets[iterator.i];
            if (widget._dirty) {
              align(widget.node, widget);
              widget._dirty = false;
            }
          }
          widgetManager.isAligning = false;
        }
      }
      var activeWidgets = [];
      function updateAlignment(node) {
        var parent = node.parent;
        if (parent && Node$1.isNode(parent)) {
          updateAlignment(parent);
        }
        var widget = node.getComponent(Widget);
        if (widget && parent) {
          align(node, widget);
        }
      }
      var widgetManager = exports('he', legacyCC._widgetManager = {
        isAligning: false,
        _nodesOrderDirty: false,
        _activeWidgetsIterator: new MutableForwardIterator(activeWidgets),
        animationState: null,
        init: function init() {
          director.on(Director.EVENT_AFTER_SCENE_LAUNCH, refreshScene);
          director.on(Director.EVENT_AFTER_UPDATE, refreshScene);
          View.instance.on('design-resolution-changed', this.onResized, this);
          {
            var thisOnResized = this.onResized.bind(this);
            View.instance.on('canvas-resize', thisOnResized);
            screenAdapter.on('window-resize', thisOnResized);
          }
        },
        add: function add(widget) {
          this._nodesOrderDirty = true;
        },
        remove: function remove(widget) {
          this._activeWidgetsIterator.remove(widget);
        },
        onResized: function onResized() {
          var scene = director.getScene();
          if (scene) {
            this.refreshWidgetOnResized(scene);
          }
        },
        refreshWidgetOnResized: function refreshWidgetOnResized(node) {
          var widget = Node$1.isNode(node) && node.getComponent(Widget);
          if (widget && widget.enabled && (widget.alignMode === AlignMode.ON_WINDOW_RESIZE || widget.alignMode === AlignMode.ALWAYS)) {
            widget.setDirty();
          }
          var children = node.children;
          for (var _iterator2 = _createForOfIteratorHelperLoose(children), _step2; !(_step2 = _iterator2()).done;) {
            var child = _step2.value;
            this.refreshWidgetOnResized(child);
          }
        },
        updateOffsetsToStayPut: function updateOffsetsToStayPut(widget, e) {
          function i(t, c) {
            return Math.abs(t - c) > 1e-10 ? c : t;
          }
          var widgetNode = widget.node;
          var widgetParent = widgetNode.parent;
          if (widgetParent) {
            var zero = _tempVec2_1;
            zero.set(0, 0);
            var one = _tempVec2_2;
            one.set(1, 1);
            if (widget.target) {
              widgetParent = widget.target;
              computeInverseTransForTarget(widgetNode, widgetParent, zero, one);
            }
            if (!e) {
              return;
            }
            var parentTrans = widgetParent._uiProps && widgetParent._uiProps.uiTransformComp;
            var parentAP = parentTrans ? parentTrans.anchorPoint : _defaultAnchor;
            var trans = widgetNode._uiProps.uiTransformComp;
            var matchSize = getReadonlyNodeSize(widgetParent);
            var myAP = trans.anchorPoint;
            var pos = widgetNode.getPosition();
            var alignFlags = AlignFlags;
            var widgetNodeScale = widgetNode.getScale();
            var temp = 0;
            if (e & alignFlags.LEFT) {
              var l = -parentAP.x * matchSize.width;
              l += zero.x;
              l *= one.x;
              temp = pos.x - myAP.x * trans.width * Math.abs(widgetNodeScale.x) - l;
              if (!widget.isAbsoluteLeft) {
                temp /= matchSize.width;
              }
              temp /= one.x;
              widget.left = i(widget.left, temp);
            }
            if (e & alignFlags.RIGHT) {
              var r = (1 - parentAP.x) * matchSize.width;
              r += zero.x;
              temp = (r *= one.x) - (pos.x + (1 - myAP.x) * trans.width * Math.abs(widgetNodeScale.x));
              if (!widget.isAbsoluteRight) {
                temp /= matchSize.width;
              }
              temp /= one.x;
              widget.right = i(widget.right, temp);
            }
            if (e & alignFlags.TOP) {
              var t = (1 - parentAP.y) * matchSize.height;
              t += zero.y;
              temp = (t *= one.y) - (pos.y + (1 - myAP.y) * trans.height * Math.abs(widgetNodeScale.y));
              if (!widget.isAbsoluteTop) {
                temp /= matchSize.height;
              }
              temp /= one.y;
              widget.top = i(widget.top, temp);
            }
            if (e & alignFlags.BOT) {
              var b = -parentAP.y * matchSize.height;
              b += zero.y;
              b *= one.y;
              temp = pos.y - myAP.y * trans.height * Math.abs(widgetNodeScale.y) - b;
              if (!widget.isAbsoluteBottom) {
                temp /= matchSize.height;
              }
              temp /= one.y;
              widget.bottom = i(widget.bottom, temp);
            }
          }
        },
        updateAlignment: updateAlignment,
        AlignMode: AlignMode,
        AlignFlags: AlignFlags
      });
      director.on(Director.EVENT_INIT, function () {
        widgetManager.init();
      });

      var _dec$7, _dec2$4, _dec3$4, _class$7;
      var SafeArea = exports('ha', (_dec$7 = ccclass$M('cc.SafeArea'), _dec2$4 = executionOrder$1(110), _dec3$4 = requireComponent(Widget), _dec$7(_class$7 = _dec2$4(_class$7 = _dec3$4(_class$7 = function (_Component) {
        _inheritsLoose(SafeArea, _Component);
        function SafeArea() {
          return _Component.apply(this, arguments) || this;
        }
        var _proto = SafeArea.prototype;
        _proto.onEnable = function onEnable() {
          this.updateArea();
          screenAdapter.on('window-resize', this.updateArea, this);
          screenAdapter.on('orientation-change', this.updateArea, this);
        };
        _proto.onDisable = function onDisable() {
          screenAdapter.off('window-resize', this.updateArea, this);
          screenAdapter.off('orientation-change', this.updateArea, this);
        };
        _proto.updateArea = function updateArea() {
          var widget = this.node.getComponent(Widget);
          var uiTransComp = this.node.getComponent(UITransform);
          if (!widget || !uiTransComp) {
            return;
          }
          widget.updateAlignment();
          var lastPos = this.node.position.clone();
          var lastAnchorPoint = uiTransComp.anchorPoint.clone();
          widget.isAlignTop = widget.isAlignBottom = widget.isAlignLeft = widget.isAlignRight = true;
          var visibleSize = view.getVisibleSize();
          var screenWidth = visibleSize.width;
          var screenHeight = visibleSize.height;
          var safeArea = sys.getSafeAreaRect();
          widget.top = screenHeight - safeArea.y - safeArea.height;
          widget.bottom = safeArea.y;
          widget.left = safeArea.x;
          widget.right = screenWidth - safeArea.x - safeArea.width;
          widget.updateAlignment();
          var curPos = this.node.position.clone();
          var anchorX = lastAnchorPoint.x - (curPos.x - lastPos.x) / uiTransComp.width;
          var anchorY = lastAnchorPoint.y - (curPos.y - lastPos.y) / uiTransComp.height;
          uiTransComp.setAnchorPoint(anchorX, anchorY);
          widgetManager.add(widget);
        };
        return SafeArea;
      }(Component)) || _class$7) || _class$7) || _class$7));
      legacyCC.SafeArea = SafeArea;

      var _dec$6, _dec2$3, _dec3$3, _dec4$1, _dec5$1, _class$6, _class2$4, _initializer$4, _initializer2$3, _initializer3$1, _initializer4$1, _initializer5$1;
      var UICoordinateTracker = exports('hb', (_dec$6 = ccclass$M('cc.UICoordinateTracker'), _dec2$3 = executionOrder$1(110), _dec3$3 = type$d(Node$1), _dec4$1 = type$d(Camera), _dec5$1 = type$d([EventHandler]), _dec$6(_class$6 = _dec2$3(_class$6 = (_class2$4 = function (_Component) {
        _inheritsLoose(UICoordinateTracker, _Component);
        function UICoordinateTracker() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.syncEvents = _initializer$4 && _initializer$4();
          _this._target = _initializer2$3 && _initializer2$3();
          _this._camera = _initializer3$1 && _initializer3$1();
          _this._useScale = _initializer4$1 && _initializer4$1();
          _this._distance = _initializer5$1 && _initializer5$1();
          _this._transformPos = new Vec3();
          _this._viewPos = new Vec3();
          _this._canMove = true;
          _this._lastWPos = new Vec3();
          _this._lastCameraPos = new Vec3();
          return _this;
        }
        var _proto = UICoordinateTracker.prototype;
        _proto.onEnable = function onEnable() {
          this._checkCanMove();
        };
        _proto.update = function update() {
          var wPos = this.node.worldPosition;
          var camera = this._camera;
          if (!this._canMove || !camera || !camera.camera || this._lastWPos.equals(wPos) && this._lastCameraPos.equals(camera.node.worldPosition)) {
            return;
          }
          this._lastWPos.set(wPos);
          this._lastCameraPos.set(camera.node.worldPosition);
          camera.camera.update();
          camera.convertToUINode(wPos, this._target, this._transformPos);
          if (this._useScale) {
            Vec3.transformMat4(this._viewPos, this.node.worldPosition, camera.camera.matView);
          }
          if (this.syncEvents.length > 0) {
            var data = this._distance / Math.abs(this._viewPos.z);
            EventHandler.emitEvents(this.syncEvents, this._transformPos, data);
          }
        };
        _proto._checkCanMove = function _checkCanMove() {
          this._canMove = !!(this._camera && this._target);
        };
        _createClass(UICoordinateTracker, [{
          key: "target",
          get: function get() {
            return this._target;
          },
          set: function set(value) {
            if (this._target === value) {
              return;
            }
            this._target = value;
            this._checkCanMove();
          }
        }, {
          key: "camera",
          get: function get() {
            return this._camera;
          },
          set: function set(value) {
            if (this._camera === value) {
              return;
            }
            this._camera = value;
            this._checkCanMove();
          }
        }, {
          key: "useScale",
          get: function get() {
            return this._useScale;
          },
          set: function set(value) {
            if (this._useScale === value) {
              return;
            }
            this._useScale = value;
          }
        }, {
          key: "distance",
          get: function get() {
            return this._distance;
          },
          set: function set(value) {
            if (this._distance === value) {
              return;
            }
            this._distance = value;
          }
        }]);
        return UICoordinateTracker;
      }(Component), (_applyDecoratedDescriptor(_class2$4.prototype, "target", [_dec3$3], Object.getOwnPropertyDescriptor(_class2$4.prototype, "target"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "camera", [_dec4$1], Object.getOwnPropertyDescriptor(_class2$4.prototype, "camera"), _class2$4.prototype), _initializer$4 = applyDecoratedInitializer(_class2$4.prototype, "syncEvents", [_dec5$1, serializable$p], function () {
        return [];
      }), _initializer2$3 = applyDecoratedInitializer(_class2$4.prototype, "_target", [serializable$p], function () {
        return null;
      }), _initializer3$1 = applyDecoratedInitializer(_class2$4.prototype, "_camera", [serializable$p], function () {
        return null;
      }), _initializer4$1 = applyDecoratedInitializer(_class2$4.prototype, "_useScale", [serializable$p], function () {
        return true;
      }), _initializer5$1 = applyDecoratedInitializer(_class2$4.prototype, "_distance", [serializable$p], function () {
        return 1;
      })), _class2$4)) || _class$6) || _class$6));

      var _dec$5, _class$5;
      var BlockEvents = [NodeEventType.TOUCH_START, NodeEventType.TOUCH_END, NodeEventType.TOUCH_MOVE, NodeEventType.MOUSE_DOWN, NodeEventType.MOUSE_MOVE, NodeEventType.MOUSE_UP, NodeEventType.MOUSE_ENTER, NodeEventType.MOUSE_LEAVE, NodeEventType.MOUSE_WHEEL];
      function stopPropagation(event) {
        event.propagationStopped = true;
      }
      var BlockInputEvents = exports('hc', (_dec$5 = ccclass$M('cc.BlockInputEvents'), _dec$5(_class$5 = function (_Component) {
        _inheritsLoose(BlockInputEvents, _Component);
        function BlockInputEvents() {
          return _Component.apply(this, arguments) || this;
        }
        var _proto = BlockInputEvents.prototype;
        _proto.onEnable = function onEnable() {
          for (var i = 0; i < BlockEvents.length; i++) {
            this.node.on(BlockEvents[i], stopPropagation, this);
          }
        };
        _proto.onDisable = function onDisable() {
          for (var i = 0; i < BlockEvents.length; i++) {
            this.node.off(BlockEvents[i], stopPropagation, this);
          }
        };
        return BlockInputEvents;
      }(Component)) || _class$5));

      var _dec$4, _dec2$2, _dec3$2, _class$4, _class2$3, _initializer$3, _initializer2$2;
      var SubContextView = exports('hd', (_dec$4 = ccclass$M('cc.SubContextView'), _dec2$2 = executionOrder$1(110), _dec3$2 = requireComponent(UITransform), _dec$4(_class$4 = _dec2$2(_class$4 = _dec3$2(_class$4 = (_class2$3 = function (_Component) {
        _inheritsLoose(SubContextView, _Component);
        function SubContextView() {
          var _this;
          _this = _Component.call(this) || this;
          _this._fps = _initializer$3 && _initializer$3();
          _this._sprite = void 0;
          _this._imageAsset = void 0;
          _this._texture = void 0;
          _this._updatedTime = 0;
          _this._updateInterval = 0;
          _this._openDataContext = void 0;
          _this._content = void 0;
          _this._designResolutionSize = _initializer2$2 && _initializer2$2();
          _this._content = new Node$1('content');
          _this._content.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
          _this._sprite = null;
          _this._imageAsset = new ImageAsset();
          _this._openDataContext = null;
          _this._updatedTime = performance.now();
          _this._texture = new Texture2D();
          return _this;
        }
        var _proto = SubContextView.prototype;
        _proto.onLoad = function onLoad() {
          if (minigame.getOpenDataContext) {
            this._updateInterval = 1000 / this._fps;
            this._openDataContext = minigame.getOpenDataContext();
            this._initSharedCanvas();
            this._initContentNode();
            this._updateSubContextView();
            this._updateContentLayer();
          } else {
            this.enabled = false;
          }
        };
        _proto.onEnable = function onEnable() {
          this._registerNodeEvent();
        };
        _proto.onDisable = function onDisable() {
          this._unregisterNodeEvent();
        };
        _proto._initSharedCanvas = function _initSharedCanvas() {
          if (this._openDataContext) {
            var sharedCanvas = this._openDataContext.canvas;
            var designWidth = this._designResolutionSize.width;
            var designHeight = this._designResolutionSize.height;
            sharedCanvas.width = designWidth;
            sharedCanvas.height = designHeight;
          }
        };
        _proto._initContentNode = function _initContentNode() {
          if (this._openDataContext) {
            var sharedCanvas = this._openDataContext.canvas;
            var image = this._imageAsset;
            image.reset(sharedCanvas);
            this._texture.image = image;
            this._texture.create(sharedCanvas.width, sharedCanvas.height);
            this._sprite = this._content.getComponent(Sprite);
            if (!this._sprite) {
              this._sprite = this._content.addComponent(Sprite);
            }
            if (this._sprite.spriteFrame) {
              this._sprite.spriteFrame.texture = this._texture;
            } else {
              var sp = new SpriteFrame();
              sp.texture = this._texture;
              this._sprite.spriteFrame = sp;
            }
            this._content.parent = this.node;
          }
        };
        _proto._updateSubContextView = function _updateSubContextView() {
          if (!this._openDataContext) {
            return;
          }
          var nodeTrans = this.node.getComponent(UITransform);
          var contentTrans = this._content.getComponent(UITransform);
          var scaleX = nodeTrans.width / contentTrans.width;
          var scaleY = nodeTrans.height / contentTrans.height;
          var scale = scaleX > scaleY ? scaleY : scaleX;
          contentTrans.width *= scale;
          contentTrans.height *= scale;
          var viewportRect = view.getViewportRect();
          var box = contentTrans.getBoundingBoxToWorld();
          var visibleSize = view.getVisibleSize();
          var dpr = screenAdapter.devicePixelRatio;
          var x = (viewportRect.width * (box.x / visibleSize.width) + viewportRect.x) / dpr;
          var y = (viewportRect.height * (box.y / visibleSize.height) + viewportRect.y) / dpr;
          var width = viewportRect.width * (box.width / visibleSize.width) / dpr;
          var height = viewportRect.height * (box.height / visibleSize.height) / dpr;
          this._openDataContext.postMessage({
            fromEngine: true,
            type: 'engine',
            event: 'viewport',
            x: x,
            y: y,
            width: width,
            height: height
          });
        };
        _proto._updateSubContextTexture = function _updateSubContextTexture() {
          var img = this._imageAsset;
          if (!img || !this._openDataContext) {
            return;
          }
          if (img.width <= 0 || img.height <= 0) {
            return;
          }
          var sharedCanvas = this._openDataContext.canvas;
          img.reset(sharedCanvas);
          if (sharedCanvas.width > img.width || sharedCanvas.height > img.height) {
            this._texture.create(sharedCanvas.width, sharedCanvas.height);
          }
          this._texture.uploadData(sharedCanvas);
        };
        _proto._registerNodeEvent = function _registerNodeEvent() {
          this.node.on(NodeEventType.TRANSFORM_CHANGED, this._updateSubContextView, this);
          this.node.on(NodeEventType.SIZE_CHANGED, this._updateSubContextView, this);
          this.node.on(NodeEventType.LAYER_CHANGED, this._updateContentLayer, this);
        };
        _proto._unregisterNodeEvent = function _unregisterNodeEvent() {
          this.node.off(NodeEventType.TRANSFORM_CHANGED, this._updateSubContextView, this);
          this.node.off(NodeEventType.SIZE_CHANGED, this._updateSubContextView, this);
          this.node.off(NodeEventType.LAYER_CHANGED, this._updateContentLayer, this);
        };
        _proto._updateContentLayer = function _updateContentLayer() {
          this._content.layer = this.node.layer;
        };
        _proto.update = function update(dt) {
          var calledUpdateManually = dt === undefined;
          if (calledUpdateManually) {
            this._updateSubContextTexture();
            return;
          }
          var now = performance.now();
          var deltaTime = now - this._updatedTime;
          if (deltaTime >= this._updateInterval) {
            this._updatedTime += this._updateInterval;
            this._updateSubContextTexture();
          }
        };
        _proto.onDestroy = function onDestroy() {
          this._content.destroy();
          this._texture.destroy();
          if (this._sprite) {
            this._sprite.destroy();
          }
          this._imageAsset.destroy();
          this._openDataContext = null;
        };
        _createClass(SubContextView, [{
          key: "designResolutionSize",
          get: function get() {
            return this._designResolutionSize;
          },
          set: function set(value) {
            {
              return;
            }
          }
        }, {
          key: "fps",
          get: function get() {
            return this._fps;
          },
          set: function set(value) {
            if (this._fps === value) {
              return;
            }
            this._fps = value;
            this._updateInterval = 1000 / value;
          }
        }]);
        return SubContextView;
      }(Component), (_initializer$3 = applyDecoratedInitializer(_class2$3.prototype, "_fps", [serializable$p], function () {
        return 60;
      }), _initializer2$2 = applyDecoratedInitializer(_class2$3.prototype, "_designResolutionSize", [serializable$p], function () {
        return new Size$1(640, 960);
      })), _class2$3)) || _class$4) || _class$4) || _class$4));
      legacyCC.SubContextView = SubContextView;

      deprecateModuleExportedName({
        ButtonComponent: {
          newName: 'Button',
          since: '1.2.0',
          removed: false
        },
        EditBoxComponent: {
          newName: 'EditBox',
          since: '1.2.0',
          removed: false
        },
        LayoutComponent: {
          newName: 'Layout',
          since: '1.2.0',
          removed: false
        },
        ProgressBarComponent: {
          newName: 'ProgressBar',
          since: '1.2.0',
          removed: false
        },
        ScrollViewComponent: {
          newName: 'ScrollView',
          since: '1.2.0',
          removed: false
        },
        ScrollBarComponent: {
          newName: 'ScrollBar',
          since: '1.2.0',
          removed: false
        },
        SliderComponent: {
          newName: 'Slider',
          since: '1.2.0',
          removed: false
        },
        ToggleComponent: {
          newName: 'Toggle',
          since: '1.2.0',
          removed: false
        },
        ToggleContainerComponent: {
          newName: 'ToggleContainer',
          since: '1.2.0',
          removed: false
        },
        WidgetComponent: {
          newName: 'Widget',
          since: '1.2.0',
          removed: false
        },
        PageViewComponent: {
          newName: 'PageView',
          since: '1.2.0',
          removed: false
        },
        PageViewIndicatorComponent: {
          newName: 'PageViewIndicator',
          since: '1.2.0',
          removed: false
        },
        SafeAreaComponent: {
          newName: 'SafeArea',
          since: '1.2.0',
          removed: false
        },
        UICoordinateTrackerComponent: {
          newName: 'UICoordinateTracker',
          since: '1.2.0',
          removed: false
        },
        BlockInputEventsComponent: {
          newName: 'BlockInputEvents',
          since: '1.2.0',
          removed: false
        }
      });

      var _dec$3, _class$3;
      var UIReorderComponent = exports('hi', (_dec$3 = ccclass$M('cc.UIReorderComponent'), _dec$3(_class$3 = function UIReorderComponent() {
        warnID(1408, 'UIReorderComponent');
      }) || _class$3));
      legacyCC.UIReorderComponent = UIReorderComponent;
      legacyCC.ButtonComponent = Button;
      setClassAlias(Button, 'cc.ButtonComponent');
      legacyCC.EditBoxComponent = EditBox;
      setClassAlias(EditBox, 'cc.EditBoxComponent');
      legacyCC.LayoutComponent = Layout;
      setClassAlias(Layout, 'cc.LayoutComponent');
      legacyCC.ProgressBarComponent = ProgressBar;
      setClassAlias(ProgressBar, 'cc.ProgressBarComponent');
      legacyCC.ScrollViewComponent = ScrollView;
      setClassAlias(ScrollView, 'cc.ScrollViewComponent');
      legacyCC.ScrollBarComponent = ScrollBar;
      setClassAlias(ScrollBar, 'cc.ScrollBarComponent');
      legacyCC.SliderComponent = Slider;
      setClassAlias(Slider, 'cc.SliderComponent');
      legacyCC.ToggleComponent = Toggle;
      setClassAlias(Toggle, 'cc.ToggleComponent');
      legacyCC.ToggleContainerComponent = ToggleContainer;
      setClassAlias(ToggleContainer, 'cc.ToggleContainerComponent');
      legacyCC.WidgetComponent = Widget;
      setClassAlias(Widget, 'cc.WidgetComponent');
      legacyCC.PageViewComponent = PageView;
      setClassAlias(PageView, 'cc.PageViewComponent');
      legacyCC.PageViewIndicatorComponent = PageViewIndicator;
      setClassAlias(PageViewIndicator, 'cc.PageViewIndicatorComponent');
      legacyCC.SafeAreaComponent = SafeArea;
      setClassAlias(SafeArea, 'cc.SafeAreaComponent');
      setClassAlias(UICoordinateTracker, 'cc.UICoordinateTrackerComponent');
      legacyCC.BlockInputEventsComponent = BlockInputEvents;
      setClassAlias(BlockInputEvents, 'cc.BlockInputEventsComponent');
      removeProperty(View.prototype, 'View.prototype', [{
        name: 'isAntiAliasEnabled',
        suggest: 'The API of Texture2d have been largely modified, no alternative'
      }, {
        name: 'enableAntiAlias',
        suggest: 'The API of Texture2d have been largely modified, no alternative'
      }]);
      markAsWarning(View.prototype, 'View.prototype', [{
        name: 'adjustViewportMeta'
      }, {
        name: 'enableAutoFullScreen',
        suggest: 'use screen.requestFullScreen() instead.'
      }, {
        name: 'isAutoFullScreenEnabled'
      }, {
        name: 'setCanvasSize',
        suggest: 'setting size in CSS pixels is not recommended, please use screen.windowSize instead.'
      }, {
        name: 'getCanvasSize',
        suggest: 'please use screen.windowSize instead.'
      }, {
        name: 'getFrameSize',
        suggest: 'getting size in CSS pixels is not recommended, please use screen.windowSize instead.'
      }, {
        name: 'setFrameSize',
        suggest: 'setting size in CSS pixels is not recommended, please use screen.windowSize instead.'
      }, {
        name: 'getDevicePixelRatio',
        suggest: 'use screen.devicePixelRatio instead.'
      }, {
        name: 'convertToLocationInView'
      }, {
        name: 'enableRetina'
      }, {
        name: 'isRetinaEnabled'
      }, {
        name: 'setRealPixelResolution'
      }]);

      var _dec$2, _class$2, _class2$2, _initializer$2;
      var VideoClip = exports('hj', (_dec$2 = ccclass$M('cc.VideoClip'), _dec$2(_class$2 = (_class2$2 = function (_Asset) {
        _inheritsLoose(VideoClip, _Asset);
        function VideoClip() {
          var _this;
          _this = _Asset.call(this) || this;
          _this._duration = _initializer$2 && _initializer$2();
          _this._video = null;
          return _this;
        }
        _createClass(VideoClip, [{
          key: "_nativeAsset",
          get: function get() {
            return this._video;
          },
          set: function set(clip) {
            this._video = clip;
            if (clip) {
              this._duration = clip.duration;
            } else {
              this._duration = 0;
            }
          }
        }]);
        return VideoClip;
      }(Asset), (_initializer$2 = applyDecoratedInitializer(_class2$2.prototype, "_duration", [serializable$p], function () {
        return 0;
      })), _class2$2)) || _class$2));

      var ccdocument$2 = ccwindow.document;
      function downloadVideo(url, options, onComplete) {
        var video = ccdocument$2.createElement('video');
        var source = ccdocument$2.createElement('source');
        video.appendChild(source);
        var req = new XMLHttpRequest();
        req.open('GET', url, true);
        req.responseType = 'blob';
        req.onload = function onload() {
          if (this.status === 200 || this.status === 0) {
            source.src = URL.createObjectURL(this.response);
            onComplete(null, video);
          } else {
            onComplete(new Error(req.status + "(no response)"));
          }
        };
        req.onerror = function onerror() {
          var message = "load video failure - " + url;
          log(message);
          onComplete(new Error(message));
        };
        req.send();
      }
      function createVideoClip(id, data, options, onComplete) {
        var out = new VideoClip();
        out._nativeUrl = id;
        out._nativeAsset = data;
        onComplete(null, out);
      }
      downloader$1.register({
        '.mp4': downloadVideo,
        '.avi': downloadVideo,
        '.mov': downloadVideo,
        '.mpg': downloadVideo,
        '.mpeg': downloadVideo,
        '.rm': downloadVideo,
        '.rmvb': downloadVideo
      });
      factory.register({
        '.mp4': createVideoClip,
        '.avi': createVideoClip,
        '.mov': createVideoClip,
        '.mpg': createVideoClip,
        '.mpeg': createVideoClip,
        '.rm': createVideoClip,
        '.rmvb': createVideoClip
      });

      var ResourceType = Enum({
        REMOTE: 0,
        LOCAL: 1
      });
      var EventType$1;
      (function (EventType) {
        EventType["NONE"] = "none";
        EventType["PLAYING"] = "playing";
        EventType["PAUSED"] = "paused";
        EventType["STOPPED"] = "stopped";
        EventType["COMPLETED"] = "completed";
        EventType["META_LOADED"] = "meta-loaded";
        EventType["READY_TO_PLAY"] = "ready-to-play";
        EventType["ERROR"] = "error";
        EventType["CLICKED"] = "clicked";
      })(EventType$1 || (EventType$1 = {}));
      var READY_STATE;
      (function (READY_STATE) {
        READY_STATE[READY_STATE["HAVE_NOTHING"] = 0] = "HAVE_NOTHING";
        READY_STATE[READY_STATE["HAVE_METADATA"] = 1] = "HAVE_METADATA";
        READY_STATE[READY_STATE["HAVE_CURRENT_DATA"] = 2] = "HAVE_CURRENT_DATA";
        READY_STATE[READY_STATE["HAVE_FUTURE_DATA"] = 3] = "HAVE_FUTURE_DATA";
        READY_STATE[READY_STATE["HAVE_ENOUGH_DATA"] = 4] = "HAVE_ENOUGH_DATA";
      })(READY_STATE || (READY_STATE = {}));

      var VideoPlayerImpl = function () {
        function VideoPlayerImpl(component) {
          var _this = this;
          this._componentEventList = new Map();
          this._state = EventType$1.NONE;
          this._video = null;
          this._onInterruptedBegin = void 0;
          this._onInterruptedEnd = void 0;
          this._interrupted = false;
          this._loaded = false;
          this._loadedMeta = false;
          this._ignorePause = false;
          this._fullScreenOnAwake = false;
          this._visible = true;
          this._playing = false;
          this._cachedCurrentTime = -1;
          this._waitingFullscreen = false;
          this._waitingPlay = false;
          this._keepAspectRatio = false;
          this._component = null;
          this._uiTrans = null;
          this._node = null;
          this._stayOnBottom = false;
          this._dirty = false;
          this._forceUpdate = false;
          this._w = 0;
          this._h = 0;
          this._m00 = 0;
          this._m01 = 0;
          this._m04 = 0;
          this._m05 = 0;
          this._m12 = 0;
          this._m13 = 0;
          this._component = component;
          this._node = component.node;
          this._uiTrans = component.node.getComponent(UITransform);
          this._onInterruptedBegin = function () {
            if (!_this.video || _this._state !== EventType$1.PLAYING) {
              return;
            }
            _this.video.pause();
            _this._interrupted = true;
          };
          this._onInterruptedEnd = function () {
            if (!_this._interrupted || !_this.video) {
              return;
            }
            _this.video.play();
            _this._interrupted = false;
          };
          legacyCC.game.on(legacyCC.Game.EVENT_PAUSE, this._onInterruptedBegin);
          legacyCC.game.on(legacyCC.Game.EVENT_RESUME, this._onInterruptedEnd);
        }
        var _proto = VideoPlayerImpl.prototype;
        _proto.onLoadedMetadata = function onLoadedMetadata(e) {
          this._loadedMeta = true;
          this._forceUpdate = true;
          if (this._visible) {
            this.enable();
          } else {
            this.disable();
          }
          this.dispatchEvent(EventType$1.META_LOADED);
          var video = e.target;
          if (this._keepAspectRatio && video) {
            this.syncUITransform(video.videoWidth, video.videoHeight);
          }
          this.delayedFullScreen();
          this.delayedPlay();
        };
        _proto.onCanPlay = function onCanPlay(e) {
          this._loaded = true;
          this.dispatchEvent(EventType$1.READY_TO_PLAY);
        };
        _proto.onPlay = function onPlay(e) {
          this._playing = true;
          this.dispatchEvent(EventType$1.PLAYING);
        };
        _proto.onPlaying = function onPlaying(e) {
          this.dispatchEvent(EventType$1.PLAYING);
        };
        _proto.onPause = function onPause(e) {
          this._playing = false;
          if (this._ignorePause) {
            this._ignorePause = false;
            return;
          }
          this.dispatchEvent(EventType$1.PAUSED);
        };
        _proto.onStoped = function onStoped(e) {
          this._playing = false;
          this._ignorePause = false;
          this.dispatchEvent(EventType$1.STOPPED);
        };
        _proto.onEnded = function onEnded(e) {
          this._playing = false;
          this.dispatchEvent(EventType$1.COMPLETED);
        };
        _proto.onClick = function onClick(e) {
          this.dispatchEvent(EventType$1.CLICKED);
        };
        _proto.onError = function onError(e) {
          this.dispatchEvent(EventType$1.ERROR);
          var video = e.target;
          if (video && video.error) {
            error("Error " + video.error.code + "; details: " + video.error.message);
          }
        };
        _proto.play = function play() {
          if (this._loadedMeta || this._loaded) {
            this.canPlay();
          } else {
            this._waitingPlay = true;
          }
        };
        _proto.delayedPlay = function delayedPlay() {
          if (this._waitingPlay) {
            this.canPlay();
            this._waitingPlay = false;
          }
        };
        _proto.syncFullScreenOnAwake = function syncFullScreenOnAwake(enabled) {
          this._fullScreenOnAwake = enabled;
          if (this._loadedMeta || this._loaded) {
            this.canFullScreen(enabled);
          } else {
            this._waitingFullscreen = true;
          }
        };
        _proto.delayedFullScreen = function delayedFullScreen() {
          if (this._waitingFullscreen) {
            this.canFullScreen(this._fullScreenOnAwake);
            this._waitingFullscreen = false;
          }
        };
        _proto.dispatchEvent = function dispatchEvent(key) {
          var callback = this._componentEventList.get(key);
          if (callback) {
            this._state = key;
            callback.call(this);
          }
        };
        _proto.syncUITransform = function syncUITransform(width, height) {
          if (this._uiTrans) {
            this._uiTrans.width = width;
            this._uiTrans.height = height;
          }
        };
        _proto.syncCurrentTime = function syncCurrentTime() {
          if (!this.video) {
            return;
          }
          if (this._cachedCurrentTime !== -1 && this.video.currentTime !== this._cachedCurrentTime) {
            this.seekTo(this._cachedCurrentTime);
            this._cachedCurrentTime = -1;
          }
        };
        _proto.destroy = function destroy() {
          this.removeVideoPlayer();
          this._componentEventList.clear();
          legacyCC.game.off(legacyCC.Game.EVENT_PAUSE, this._onInterruptedBegin);
          legacyCC.game.off(legacyCC.Game.EVENT_RESUME, this._onInterruptedEnd);
        };
        _createClass(VideoPlayerImpl, [{
          key: "fullScreenOnAwake",
          get: function get() {
            return this._fullScreenOnAwake;
          }
        }, {
          key: "loaded",
          get: function get() {
            return this._loaded;
          }
        }, {
          key: "componentEventList",
          get: function get() {
            return this._componentEventList;
          }
        }, {
          key: "video",
          get: function get() {
            return this._video;
          }
        }, {
          key: "state",
          get: function get() {
            return this._state;
          }
        }, {
          key: "isPlaying",
          get: function get() {
            return this._playing;
          }
        }, {
          key: "UICamera",
          get: function get() {
            return director.root.batcher2D.getFirstRenderCamera(this._node);
          }
        }]);
        return VideoPlayerImpl;
      }();
      legacyCC.internal.VideoPlayerImpl = VideoPlayerImpl;

      var ccdocument$1 = ccwindow.document;
      var MIN_ZINDEX = -Math.pow(2, 15);
      var _mat4_temp$1 = mat4();
      var VideoPlayerImplWeb = function (_VideoPlayerImpl) {
        _inheritsLoose(VideoPlayerImplWeb, _VideoPlayerImpl);
        function VideoPlayerImplWeb(component) {
          var _this;
          _this = _VideoPlayerImpl.call(this, component) || this;
          _this._eventList = new Map();
          _this._clearColorA = -1;
          _this._clearFlag = void 0;
          return _this;
        }
        var _proto = VideoPlayerImplWeb.prototype;
        _proto.addListener = function addListener(type, handler) {
          if (!this._video) {
            return;
          }
          this._eventList.set(type, handler);
          this._video.addEventListener(type, handler);
        };
        _proto.removeAllListeners = function removeAllListeners() {
          var _this2 = this;
          this._eventList.forEach(function (handler, type) {
            if (!_this2._video) {
              return;
            }
            _this2._video.removeEventListener(type, handler);
          });
          this._eventList.clear();
        };
        _proto.canPlay = function canPlay() {
          var _this3 = this;
          if (this.video) {
            var promise = this.video.play();
            if (ccwindow.Promise && promise instanceof Promise) {
              promise["catch"](function (error) {}).then(function () {
                _this3.syncCurrentTime();
              });
            }
          }
        };
        _proto.pause = function pause() {
          if (this.video) {
            this.video.pause();
            this._cachedCurrentTime = this.video.currentTime;
          }
        };
        _proto.resume = function resume() {
          this.play();
        };
        _proto.stop = function stop() {
          var _this4 = this;
          if (this.video) {
            this._ignorePause = true;
            this.video.currentTime = 0;
            this.video.pause();
            this._cachedCurrentTime = 0;
            setTimeout(function () {
              _this4._ignorePause = false;
              _this4.dispatchEvent(EventType$1.STOPPED);
            }, 0);
          }
        };
        _proto.syncClip = function syncClip(clip) {
          this.removeVideoPlayer();
          if (!clip) {
            return;
          }
          this.createVideoPlayer(clip.nativeUrl);
        };
        _proto.syncURL = function syncURL(url) {
          this.removeVideoPlayer();
          if (!url) {
            return;
          }
          this.createVideoPlayer(url);
        };
        _proto.syncPlaybackRate = function syncPlaybackRate(val) {
          if (sys.browserType === BrowserType.UC) {
            warn('playbackRate is not supported by the uc mobile browser.');
            return;
          }
          if (this.video) {
            this.video.playbackRate = val;
          }
        };
        _proto.syncVolume = function syncVolume(val) {
          if (this.video) {
            this.video.volume = val;
          }
        };
        _proto.syncMute = function syncMute(enabled) {
          if (this.video) {
            this.video.muted = enabled;
          }
        };
        _proto.syncLoop = function syncLoop(enabled) {
          if (this.video) {
            this.video.loop = enabled;
          }
        };
        _proto.getDuration = function getDuration() {
          if (!this.video) {
            return 0;
          }
          return this.video.duration;
        };
        _proto.getCurrentTime = function getCurrentTime() {
          if (this.video) {
            return this.video.currentTime;
          }
          return -1;
        };
        _proto.seekTo = function seekTo(val) {
          if (this.video) {
            this.video.currentTime = val;
            this._cachedCurrentTime = this.video.currentTime;
          }
        };
        _proto.canFullScreen = function canFullScreen(enabled) {
          var _this5 = this;
          var video = this._video;
          if (!video || video.readyState !== READY_STATE.HAVE_ENOUGH_DATA) {
            return;
          }
          if (sys.os === OS.IOS && sys.isBrowser) {
            if (enabled) {
              if (video.webkitEnterFullscreen) {
                video.webkitEnterFullscreen();
              }
            } else if (video.webkitExitFullscreen) {
              video.webkitExitFullscreen();
            }
            this._fullScreenOnAwake = video.webkitDisplayingFullscreen;
            return;
          }
          if (!screen$1.supportsFullScreen) {
            this._fullScreenOnAwake = enabled;
            this._forceUpdate = true;
            this.syncMatrix();
            return;
          }
          if (enabled) {
            if (sys.browserType === BrowserType.IE) {
              video.style.transform = '';
            }
            video.setAttribute('x5-video-player-fullscreen', 'true');
            screen$1.requestFullScreen(video, function (document) {
              var fullscreenElement = sys.browserType === BrowserType.IE ? document.msFullscreenElement : document.fullscreenElement;
              _this5._fullScreenOnAwake = fullscreenElement === video;
            }, function () {
              _this5._fullScreenOnAwake = false;
            });
          } else {
            video.removeAttribute('x5-video-player-fullscreen');
            screen$1.exitFullScreen();
          }
        };
        _proto.syncStayOnBottom = function syncStayOnBottom(enabled) {
          if (this._video) {
            this._video.style['z-index'] = enabled ? MIN_ZINDEX : 0;
            this._stayOnBottom = enabled;
          }
          this._dirty = true;
        };
        _proto.syncKeepAspectRatio = function syncKeepAspectRatio(enabled) {
          this._keepAspectRatio = enabled;
          if (enabled && this._loadedMeta && this._video) {
            this.syncUITransform(this._video.videoWidth, this._video.videoHeight);
          }
        };
        _proto.removeVideoPlayer = function removeVideoPlayer() {
          var video = this._video;
          if (video) {
            if (contains$1(game.container, video)) {
              game.container.removeChild(video);
              this.removeAllListeners();
            }
          }
          this._cachedCurrentTime = 0;
          this._playing = false;
          this._loaded = false;
          this._loadedMeta = false;
          this._video = null;
        };
        _proto.createVideoPlayer = function createVideoPlayer(url) {
          var video = this._video = ccdocument$1.createElement('video');
          video.className = 'cocosVideo';
          video.style.visibility = 'hidden';
          video.style.position = 'absolute';
          video.style.bottom = '0px';
          video.style.left = '0px';
          video.style['transform-origin'] = '0px 100% 0px';
          video.style['-webkit-transform-origin'] = '0px 100% 0px';
          video.setAttribute('preload', 'auto');
          video.setAttribute('webkit-playsinline', '');
          video.setAttribute('x5-playsinline', '');
          video.setAttribute('playsinline', '');
          this._bindDomEvent();
          game.container.appendChild(video);
          var source = ccdocument$1.createElement('source');
          video.appendChild(source);
          source.src = url;
        };
        _proto._bindDomEvent = function _bindDomEvent() {
          this._video;
          this.addListener('loadedmetadata', this.onLoadedMetadata.bind(this));
          this.addListener('canplay', this.onCanPlay.bind(this));
          this.addListener('canplaythrough', this.onCanPlay.bind(this));
          this.addListener('play', this.onPlay.bind(this));
          this.addListener('playing', this.onPlaying.bind(this));
          this.addListener('pause', this.onPause.bind(this));
          this.addListener('click', this.onClick.bind(this));
          this.addListener('ended', this.onEnded.bind(this));
          this.addListener('error', this.onError.bind(this));
        };
        _proto.onCanPlay = function onCanPlay(e) {
          var video = e.target;
          if (this._loaded && video) {
            return;
          }
          switch (video.readyState) {
            case READY_STATE.HAVE_METADATA:
            case READY_STATE.HAVE_ENOUGH_DATA:
              {
                _VideoPlayerImpl.prototype.onCanPlay.call(this, e);
                break;
              }
          }
        };
        _proto.enable = function enable() {
          if (this._video) {
            this._visible = true;
            if (this._video.style.visibility === 'visible') {
              return;
            }
            this._video.style.visibility = 'visible';
          }
        };
        _proto.disable = function disable(noPause) {
          if (this._video) {
            if (!noPause && this._playing) {
              this._video.pause();
            }
            this._visible = false;
            if (this._video.style.visibility === 'hidden') {
              return;
            }
            this._video.style.visibility = 'hidden';
          }
        };
        _proto.syncMatrix = function syncMatrix() {
          if (!this._video || !this._visible || !this._component) return;
          var camera = this.UICamera;
          if (!camera) {
            return;
          }
          if (screen$1.fullScreen()) {
            return;
          }
          if (this._dirty) {
            this._dirty = false;
            if (this._stayOnBottom) {
              this._clearColorA = camera.clearColor.w;
              this._clearFlag = camera.clearFlag;
              camera.clearColor.w = 0;
              camera.clearFlag = ClearFlagBit.ALL;
            } else if (this._clearFlag) {
              camera.clearColor.w = this._clearColorA;
              camera.clearFlag = this._clearFlag;
              this._clearColorA = -1;
              this._clearFlag = null;
            }
          }
          this._component.node.getWorldMatrix(_mat4_temp$1);
          camera.update(true);
          camera.worldMatrixToScreen(_mat4_temp$1, _mat4_temp$1, game.canvas.width, game.canvas.height);
          var width = 0;
          var height = 0;
          if (this._fullScreenOnAwake) {
            width = visibleRect.width;
            height = visibleRect.height;
          } else {
            width = this._uiTrans.contentSize.width;
            height = this._uiTrans.contentSize.height;
          }
          if (!this._forceUpdate && this._m00 === _mat4_temp$1.m00 && this._m01 === _mat4_temp$1.m01 && this._m04 === _mat4_temp$1.m04 && this._m05 === _mat4_temp$1.m05 && this._m12 === _mat4_temp$1.m12 && this._m13 === _mat4_temp$1.m13 && this._w === width && this._h === height) {
            return;
          }
          this._m00 = _mat4_temp$1.m00;
          this._m01 = _mat4_temp$1.m01;
          this._m04 = _mat4_temp$1.m04;
          this._m05 = _mat4_temp$1.m05;
          this._m12 = _mat4_temp$1.m12;
          this._m13 = _mat4_temp$1.m13;
          this._w = width;
          this._h = height;
          var dpr = screenAdapter.devicePixelRatio;
          var scaleX = 1 / dpr;
          var scaleY = 1 / dpr;
          var container = game.container;
          var sx = _mat4_temp$1.m00 * scaleX;
          var b = _mat4_temp$1.m01;
          var c = _mat4_temp$1.m04;
          var sy = _mat4_temp$1.m05 * scaleY;
          this._video.style.width = this._w + "px";
          this._video.style.height = this._h + "px";
          if (sys.browserType !== BrowserType.MOBILE_QQ) {
            this._video.style.objectFit = this._keepAspectRatio ? 'none' : 'fill';
          } else {
            warn('keepAspectRatio is not supported by the qq mobile browser.');
          }
          var w = this._w * scaleX;
          var h = this._h * scaleY;
          var _anchorPoint = this._uiTrans.anchorPoint,
            x = _anchorPoint.x,
            y = _anchorPoint.y;
          var appx = w * _mat4_temp$1.m00 * x;
          var appy = h * _mat4_temp$1.m05 * y;
          var offsetX = container && container.style.paddingLeft ? parseInt(container.style.paddingLeft) : 0;
          var offsetY = container && container.style.paddingBottom ? parseInt(container.style.paddingBottom) : 0;
          var tx = _mat4_temp$1.m12 * scaleX - appx + offsetX;
          var ty = _mat4_temp$1.m13 * scaleY - appy + offsetY;
          var matrix = "matrix(" + sx + "," + -b + "," + -c + "," + sy + "," + tx + "," + -ty + ")";
          this._video.style.transform = matrix;
          this._video.style['-webkit-transform'] = matrix;
          if (sys.browserType !== BrowserType.IE) {
            this._forceUpdate = false;
          }
        };
        return VideoPlayerImplWeb;
      }(VideoPlayerImpl);

      var VideoPlayerImplManager = function () {
        function VideoPlayerImplManager() {}
        VideoPlayerImplManager.getImpl = function getImpl(component) {
          return new VideoPlayerImplWeb(component);
        };
        return VideoPlayerImplManager;
      }();
      legacyCC.internal.VideoPlayerImplManager = VideoPlayerImplManager;

      var _dec$1, _dec2$1, _dec3$1, _dec4, _dec5, _dec6, _class$1, _class2$1, _initializer$1, _initializer2$1, _initializer3, _initializer4, _initializer5, _initializer6, _initializer7, _initializer8, _initializer9, _initializer10, _initializer11, _initializer12, _class3$1;
      var VideoPlayer = exports('hk', (_dec$1 = ccclass$M('cc.VideoPlayer'), _dec2$1 = requireComponent(UITransform), _dec3$1 = type$d(VideoClip), _dec4 = type$d(ResourceType), _dec5 = type$d(VideoClip), _dec6 = type$d([EventHandler]), _dec$1(_class$1 = _dec2$1(_class$1 = (_class2$1 = (_class3$1 = function (_Component) {
        _inheritsLoose(VideoPlayer, _Component);
        function VideoPlayer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._resourceType = _initializer$1 && _initializer$1();
          _this._remoteURL = _initializer2$1 && _initializer2$1();
          _this._clip = _initializer3 && _initializer3();
          _this._playOnAwake = _initializer4 && _initializer4();
          _this._volume = _initializer5 && _initializer5();
          _this._mute = _initializer6 && _initializer6();
          _this._playbackRate = _initializer7 && _initializer7();
          _this._loop = _initializer8 && _initializer8();
          _this._fullScreenOnAwake = _initializer9 && _initializer9();
          _this._stayOnBottom = _initializer10 && _initializer10();
          _this._keepAspectRatio = _initializer11 && _initializer11();
          _this._impl = null;
          _this._cachedCurrentTime = 0;
          _this.videoPlayerEvent = _initializer12 && _initializer12();
          return _this;
        }
        var _proto = VideoPlayer.prototype;
        _proto.syncSource = function syncSource() {
          if (!this._impl) {
            return;
          }
          if (this._resourceType === ResourceType.REMOTE) {
            this._impl.syncURL(this._remoteURL);
          } else {
            this._impl.syncClip(this._clip);
          }
          this._cachedCurrentTime = 0;
          this._impl.syncLoop(this._loop);
          this._impl.syncVolume(this._volume);
          this._impl.syncMute(this._mute);
          this._impl.seekTo(this._cachedCurrentTime);
          this._impl.syncPlaybackRate(this._playbackRate);
          this._impl.syncStayOnBottom(this._stayOnBottom);
          this._impl.syncKeepAspectRatio(this._keepAspectRatio);
          this._impl.syncFullScreenOnAwake(this._fullScreenOnAwake);
        };
        _proto.__preload = function __preload() {
          this._impl = VideoPlayerImplManager.getImpl(this);
          this.syncSource();
          this._impl.componentEventList.set(EventType$1.META_LOADED, this.onMetaLoaded.bind(this));
          this._impl.componentEventList.set(EventType$1.READY_TO_PLAY, this.onReadyToPlay.bind(this));
          this._impl.componentEventList.set(EventType$1.PLAYING, this.onPlaying.bind(this));
          this._impl.componentEventList.set(EventType$1.PAUSED, this.onPaused.bind(this));
          this._impl.componentEventList.set(EventType$1.STOPPED, this.onStopped.bind(this));
          this._impl.componentEventList.set(EventType$1.COMPLETED, this.onCompleted.bind(this));
          this._impl.componentEventList.set(EventType$1.ERROR, this.onError.bind(this));
          this._impl.componentEventList.set(EventType$1.CLICKED, this.onClicked.bind(this));
          if (this._playOnAwake && this._impl.loaded) {
            this.play();
          }
        };
        _proto.onEnable = function onEnable() {
          if (this._impl) {
            this._impl.enable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._impl) {
            this._impl.disable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._impl) {
            this._impl.destroy();
            this._impl = null;
          }
        };
        _proto.update = function update(dt) {
          if (this._impl) {
            this._impl.syncMatrix();
          }
        };
        _proto.onMetaLoaded = function onMetaLoaded() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$1.META_LOADED);
          this.node.emit('meta-loaded', this);
        };
        _proto.onReadyToPlay = function onReadyToPlay() {
          if (this._playOnAwake && !this.isPlaying) {
            this.play();
          }
          EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$1.READY_TO_PLAY);
          this.node.emit(EventType$1.READY_TO_PLAY, this);
        };
        _proto.onPlaying = function onPlaying() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$1.PLAYING);
          this.node.emit(EventType$1.PLAYING, this);
        };
        _proto.onPaused = function onPaused() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$1.PAUSED);
          this.node.emit(EventType$1.PAUSED, this);
        };
        _proto.onStopped = function onStopped() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$1.STOPPED);
          this.node.emit(EventType$1.STOPPED, this);
        };
        _proto.onCompleted = function onCompleted() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$1.COMPLETED);
          this.node.emit(EventType$1.COMPLETED, this);
        };
        _proto.onError = function onError() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$1.ERROR);
          this.node.emit(EventType$1.ERROR, this);
        };
        _proto.onClicked = function onClicked() {
          EventHandler.emitEvents(this.videoPlayerEvent, this, EventType$1.CLICKED);
          this.node.emit(EventType$1.CLICKED, this);
        };
        _proto.play = function play() {
          if (this._impl) {
            this._impl.play();
          }
        };
        _proto.resume = function resume() {
          if (this._impl) {
            this._impl.resume();
          }
        };
        _proto.pause = function pause() {
          if (this._impl) {
            this._impl.pause();
          }
        };
        _proto.stop = function stop() {
          if (this._impl) {
            this._impl.stop();
          }
        };
        _createClass(VideoPlayer, [{
          key: "resourceType",
          get: function get() {
            return this._resourceType;
          },
          set: function set(val) {
            if (this._resourceType !== val) {
              this._resourceType = val;
              this.syncSource();
            }
          }
        }, {
          key: "remoteURL",
          get: function get() {
            return this._remoteURL;
          },
          set: function set(val) {
            if (this._remoteURL !== val) {
              this._remoteURL = val;
              this.syncSource();
            }
          }
        }, {
          key: "clip",
          get: function get() {
            return this._clip;
          },
          set: function set(val) {
            if (this._clip !== val) {
              this._clip = val;
              this.syncSource();
            }
          }
        }, {
          key: "playOnAwake",
          get: function get() {
            return this._playOnAwake;
          },
          set: function set(value) {
            this._playOnAwake = value;
          }
        }, {
          key: "playbackRate",
          get: function get() {
            return this._playbackRate;
          },
          set: function set(value) {
            this._playbackRate = value;
            if (this._impl) {
              this._impl.syncPlaybackRate(value);
            }
          }
        }, {
          key: "volume",
          get: function get() {
            return this._volume;
          },
          set: function set(value) {
            this._volume = value;
            if (this._impl) {
              this._impl.syncVolume(value);
            }
          }
        }, {
          key: "mute",
          get: function get() {
            return this._mute;
          },
          set: function set(value) {
            this._mute = value;
            if (this._impl) {
              this._impl.syncMute(value);
            }
          }
        }, {
          key: "loop",
          get: function get() {
            return this._loop;
          },
          set: function set(value) {
            this._loop = value;
            if (this._impl) {
              this._impl.syncLoop(value);
            }
          }
        }, {
          key: "keepAspectRatio",
          get: function get() {
            return this._keepAspectRatio;
          },
          set: function set(value) {
            if (this._keepAspectRatio !== value) {
              this._keepAspectRatio = value;
              if (this._impl) {
                this._impl.syncKeepAspectRatio(value);
              }
            }
          }
        }, {
          key: "fullScreenOnAwake",
          get: function get() {
            {
              if (this._impl) {
                this._fullScreenOnAwake = this._impl.fullScreenOnAwake;
                return this._fullScreenOnAwake;
              }
            }
            return this._fullScreenOnAwake;
          },
          set: function set(value) {
            if (this._fullScreenOnAwake !== value) {
              this._fullScreenOnAwake = value;
              if (this._impl) {
                this._impl.syncFullScreenOnAwake(value);
              }
            }
          }
        }, {
          key: "stayOnBottom",
          get: function get() {
            return this._stayOnBottom;
          },
          set: function set(value) {
            if (this._stayOnBottom !== value) {
              this._stayOnBottom = value;
              if (this._impl) {
                this._impl.syncStayOnBottom(value);
              }
            }
          }
        }, {
          key: "nativeVideo",
          get: function get() {
            return this._impl && this._impl.video || null;
          }
        }, {
          key: "currentTime",
          get: function get() {
            if (!this._impl) {
              return this._cachedCurrentTime;
            }
            return this._impl.getCurrentTime();
          },
          set: function set(val) {
            if (Number.isNaN(val)) {
              warn("illegal video time! value:" + val);
              return;
            }
            val = clamp$1(val, 0, this.duration);
            this._cachedCurrentTime = val;
            if (this._impl) {
              this._impl.seekTo(val);
            }
          }
        }, {
          key: "duration",
          get: function get() {
            if (!this._impl) {
              return 0;
            }
            return this._impl.getDuration();
          }
        }, {
          key: "state",
          get: function get() {
            if (!this._impl) {
              return EventType$1.NONE;
            }
            return this._impl.state;
          }
        }, {
          key: "isPlaying",
          get: function get() {
            if (!this._impl) {
              return false;
            }
            return this._impl.isPlaying;
          }
        }]);
        return VideoPlayer;
      }(Component), _class3$1.EventType = EventType$1, _class3$1.ResourceType = ResourceType, _class3$1), (_initializer$1 = applyDecoratedInitializer(_class2$1.prototype, "_resourceType", [serializable$p], function () {
        return ResourceType.LOCAL;
      }), _initializer2$1 = applyDecoratedInitializer(_class2$1.prototype, "_remoteURL", [serializable$p], function () {
        return '';
      }), _initializer3 = applyDecoratedInitializer(_class2$1.prototype, "_clip", [_dec3$1, serializable$p], function () {
        return null;
      }), _initializer4 = applyDecoratedInitializer(_class2$1.prototype, "_playOnAwake", [serializable$p], function () {
        return true;
      }), _initializer5 = applyDecoratedInitializer(_class2$1.prototype, "_volume", [serializable$p], function () {
        return 1.0;
      }), _initializer6 = applyDecoratedInitializer(_class2$1.prototype, "_mute", [serializable$p], function () {
        return false;
      }), _initializer7 = applyDecoratedInitializer(_class2$1.prototype, "_playbackRate", [serializable$p], function () {
        return 1;
      }), _initializer8 = applyDecoratedInitializer(_class2$1.prototype, "_loop", [serializable$p], function () {
        return false;
      }), _initializer9 = applyDecoratedInitializer(_class2$1.prototype, "_fullScreenOnAwake", [serializable$p], function () {
        return false;
      }), _initializer10 = applyDecoratedInitializer(_class2$1.prototype, "_stayOnBottom", [serializable$p], function () {
        return false;
      }), _initializer11 = applyDecoratedInitializer(_class2$1.prototype, "_keepAspectRatio", [serializable$p], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$1.prototype, "resourceType", [_dec4], Object.getOwnPropertyDescriptor(_class2$1.prototype, "resourceType"), _class2$1.prototype), _applyDecoratedDescriptor(_class2$1.prototype, "clip", [_dec5], Object.getOwnPropertyDescriptor(_class2$1.prototype, "clip"), _class2$1.prototype), _initializer12 = applyDecoratedInitializer(_class2$1.prototype, "videoPlayerEvent", [serializable$p, _dec6], function () {
        return [];
      })), _class2$1)) || _class$1) || _class$1));
      legacyCC.internal.VideoPlayer = VideoPlayer;

      replaceProperty(VideoPlayer.prototype, 'VideoPlayer.prototype', [{
        name: 'onPasued',
        newName: 'onPaused'
      }]);

      var EventType;
      (function (EventType) {
        EventType["NONE"] = "none";
        EventType["LOADING"] = "loading";
        EventType["LOADED"] = "loaded";
        EventType["ERROR"] = "error";
      })(EventType || (EventType = {}));

      var WebViewImpl = function () {
        function WebViewImpl(component) {
          this._componentEventList = new Map();
          this._state = EventType.NONE;
          this._wrapper = void 0;
          this._webview = null;
          this._loaded = false;
          this._forceUpdate = false;
          this._component = null;
          this._uiTrans = null;
          this._node = null;
          this._w = 0;
          this._h = 0;
          this._m00 = 0;
          this._m01 = 0;
          this._m04 = 0;
          this._m05 = 0;
          this._m12 = 0;
          this._m13 = 0;
          this._component = component;
          this._node = component.node;
          this._uiTrans = component.node.getComponent(UITransform);
          this.reset();
          this.createWebView();
        }
        var _proto = WebViewImpl.prototype;
        _proto.reset = function reset() {
          this._wrapper = null;
          this._webview = null;
          this._loaded = false;
          this._w = 0;
          this._h = 0;
          this._m00 = 0;
          this._m01 = 0;
          this._m04 = 0;
          this._m05 = 0;
          this._m12 = 0;
          this._m13 = 0;
          this._state = EventType.NONE;
          this._forceUpdate = false;
        };
        _proto.dispatchEvent = function dispatchEvent(key) {
          var callback = this._componentEventList.get(key);
          if (callback) {
            this._state = key;
            for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
              args[_key - 1] = arguments[_key];
            }
            callback.call(this, args);
          }
        };
        _proto.destroy = function destroy() {
          this.removeWebView();
          this._wrapper = null;
          this._webview = null;
          this._loaded = false;
          this._component = null;
          this._uiTrans = null;
          this._forceUpdate = false;
          this._componentEventList.clear();
        };
        _createClass(WebViewImpl, [{
          key: "loaded",
          get: function get() {
            return this._loaded;
          }
        }, {
          key: "componentEventList",
          get: function get() {
            return this._componentEventList;
          }
        }, {
          key: "webview",
          get: function get() {
            return this._webview;
          }
        }, {
          key: "state",
          get: function get() {
            return this._state;
          }
        }, {
          key: "UICamera",
          get: function get() {
            return director.root.batcher2D.getFirstRenderCamera(this._node);
          }
        }]);
        return WebViewImpl;
      }();
      legacyCC.internal.WebViewImpl = WebViewImpl;

      var ccdocument = ccwindow.document;
      var _mat4_temp = mat4();
      var WebViewImplWeb = function (_WebViewImpl) {
        _inheritsLoose(WebViewImplWeb, _WebViewImpl);
        function WebViewImplWeb(component) {
          return _WebViewImpl.call(this, component) || this;
        }
        var _proto = WebViewImplWeb.prototype;
        _proto._bindDomEvent = function _bindDomEvent() {
          var _this = this;
          if (!this.webview) {
            return;
          }
          var onLoaded = function onLoaded(e) {
            _this._forceUpdate = true;
            _this.dispatchEvent(EventType.LOADED);
            var iframe = e.target;
            var body = iframe.contentDocument && iframe.contentDocument.body;
            if (body && body.innerHTML.includes('404')) {
              _this.dispatchEvent(EventType.ERROR, body.innerHTML);
            }
          };
          this.webview.addEventListener('load', onLoaded);
        };
        _proto.loadURL = function loadURL(url) {
          if (this.webview) {
            this.webview.src = url;
            this.dispatchEvent(EventType.LOADING);
          }
        };
        _proto.createWebView = function createWebView() {
          var wrapper = ccdocument.createElement('div');
          this._wrapper = wrapper;
          wrapper.id = 'webview-wrapper';
          wrapper.style['-webkit-overflow'] = 'auto';
          wrapper.style['-webkit-overflow-scrolling'] = 'touch';
          wrapper.style.position = 'absolute';
          wrapper.style.bottom = '0px';
          wrapper.style.left = '0px';
          wrapper.style.transformOrigin = '0px 100% 0px';
          wrapper.style['-webkit-transform-origin'] = '0px 100% 0px';
          game.container.appendChild(wrapper);
          var webview = ccdocument.createElement('iframe');
          this._webview = webview;
          webview.id = 'webview';
          webview.style.border = 'none';
          webview.style.width = '100%';
          webview.style.height = '100%';
          wrapper.appendChild(webview);
          this._bindDomEvent();
        };
        _proto.removeWebView = function removeWebView() {
          var wrapper = this._wrapper;
          if (contains$1(game.container, wrapper)) {
            game.container.removeChild(wrapper);
          }
          this.reset();
        };
        _proto.enable = function enable() {
          if (this._wrapper) {
            this._wrapper.style.visibility = 'visible';
          }
        };
        _proto.disable = function disable() {
          if (this._wrapper) {
            this._wrapper.style.visibility = 'hidden';
          }
        };
        _proto.evaluateJS = function evaluateJS(str) {
          if (this.webview) {
            var win = this.webview.contentWindow;
            if (win) {
              try {
                win.eval(str);
              } catch (e) {
                this.dispatchEvent(EventType.ERROR, e);
                error(e);
              }
            }
          }
        };
        _proto.setOnJSCallback = function setOnJSCallback(callback) {
          warn('The platform does not support');
        };
        _proto.setJavascriptInterfaceScheme = function setJavascriptInterfaceScheme(scheme) {
          warn('The platform does not support');
        };
        _proto.syncMatrix = function syncMatrix() {
          if (!this._wrapper || !this._uiTrans || !this._component || this._wrapper.style.visibility === 'hidden') return;
          var camera = this.UICamera;
          if (!camera) {
            return;
          }
          this._component.node.getWorldMatrix(_mat4_temp);
          camera.update(true);
          camera.worldMatrixToScreen(_mat4_temp, _mat4_temp, game.canvas.width, game.canvas.height);
          var _this$_uiTrans$conten = this._uiTrans.contentSize,
            width = _this$_uiTrans$conten.width,
            height = _this$_uiTrans$conten.height;
          if (!this._forceUpdate && this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 && this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 && this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 && this._w === width && this._h === height) {
            return;
          }
          this._m00 = _mat4_temp.m00;
          this._m01 = _mat4_temp.m01;
          this._m04 = _mat4_temp.m04;
          this._m05 = _mat4_temp.m05;
          this._m12 = _mat4_temp.m12;
          this._m13 = _mat4_temp.m13;
          this._w = width;
          this._h = height;
          var dpr = screenAdapter.devicePixelRatio;
          var scaleX = 1 / dpr;
          var scaleY = 1 / dpr;
          var container = game.container;
          var sx = _mat4_temp.m00 * scaleX;
          var b = _mat4_temp.m01;
          var c = _mat4_temp.m04;
          var sy = _mat4_temp.m05 * scaleY;
          this._wrapper.style.width = width + "px";
          this._wrapper.style.height = height + "px";
          var w = this._w * scaleX;
          var h = this._h * scaleY;
          var appx = w * _mat4_temp.m00 * this._uiTrans.anchorX;
          var appy = h * _mat4_temp.m05 * this._uiTrans.anchorY;
          var offsetX = container && container.style.paddingLeft ? parseInt(container.style.paddingLeft) : 0;
          var offsetY = container && container.style.paddingBottom ? parseInt(container.style.paddingBottom) : 0;
          var tx = _mat4_temp.m12 * scaleX - appx + offsetX;
          var ty = _mat4_temp.m13 * scaleY - appy + offsetY;
          var matrix = "matrix(" + sx + "," + -b + "," + -c + "," + sy + "," + tx + "," + -ty + ")";
          this._wrapper.style.transform = matrix;
          this._wrapper.style['-webkit-transform'] = matrix;
          this._forceUpdate = false;
        };
        return WebViewImplWeb;
      }(WebViewImpl);

      var WebViewImplManager = function () {
        function WebViewImplManager() {}
        WebViewImplManager.getImpl = function getImpl(component) {
          return new WebViewImplWeb(component);
        };
        return WebViewImplManager;
      }();
      legacyCC.internal.WebViewImplManager = WebViewImplManager;

      var _dec, _dec2, _dec3, _class, _class2, _initializer, _initializer2, _class3;
      var WebView = exports('hl', (_dec = ccclass$M('cc.WebView'), _dec2 = requireComponent(UITransform), _dec3 = type$d([EventHandler]), _dec(_class = _dec2(_class = (_class2 = (_class3 = function (_Component) {
        _inheritsLoose(WebView, _Component);
        function WebView() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._url = _initializer && _initializer();
          _this._impl = null;
          _this.webviewEvents = _initializer2 && _initializer2();
          return _this;
        }
        var _proto = WebView.prototype;
        _proto.setJavascriptInterfaceScheme = function setJavascriptInterfaceScheme(scheme) {
          if (this._impl) {
            this._impl.setJavascriptInterfaceScheme(scheme);
          }
        };
        _proto.setOnJSCallback = function setOnJSCallback(callback) {
          if (this._impl) {
            this._impl.setOnJSCallback(callback);
          }
        };
        _proto.evaluateJS = function evaluateJS(str) {
          if (this._impl) {
            this._impl.evaluateJS(str);
          }
        };
        _proto.__preload = function __preload() {
          this._impl = WebViewImplManager.getImpl(this);
          this._impl.componentEventList.set(EventType.LOADING, this.onLoading.bind(this));
          this._impl.componentEventList.set(EventType.LOADED, this.onLoaded.bind(this));
          this._impl.componentEventList.set(EventType.ERROR, this.onError.bind(this));
          this._impl.loadURL(this._url);
        };
        _proto.onLoading = function onLoading() {
          EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADING);
          this.node.emit(EventType.LOADING, this);
        };
        _proto.onLoaded = function onLoaded() {
          EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADED);
          this.node.emit(EventType.LOADED, this);
        };
        _proto.onError = function onError() {
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          EventHandler.emitEvents(this.webviewEvents, this, EventType.ERROR, args);
          this.node.emit(EventType.ERROR, this, args);
        };
        _proto.onEnable = function onEnable() {
          if (this._impl) {
            this._impl.enable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._impl) {
            this._impl.disable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._impl) {
            this._impl.destroy();
            this._impl = null;
          }
        };
        _proto.update = function update(dt) {
          if (this._impl) {
            this._impl.syncMatrix();
          }
        };
        _createClass(WebView, [{
          key: "url",
          get: function get() {
            return this._url;
          },
          set: function set(val) {
            this._url = val;
            if (this._impl) {
              this._impl.loadURL(val);
            }
          }
        }, {
          key: "nativeWebView",
          get: function get() {
            return this._impl && this._impl.webview || null;
          }
        }, {
          key: "state",
          get: function get() {
            if (!this._impl) {
              return EventType.NONE;
            }
            return this._impl.state;
          }
        }]);
        return WebView;
      }(Component), _class3.EventType = EventType, _class3), (_initializer = applyDecoratedInitializer(_class2.prototype, "_url", [serializable$p], function () {
        return 'https://cocos.com';
      }), _initializer2 = applyDecoratedInitializer(_class2.prototype, "webviewEvents", [serializable$p, _dec3], function () {
        return [];
      })), _class2)) || _class) || _class));
      legacyCC.internal.WebView = WebView;

      var WebGL2DescriptorSet = function (_DescriptorSet) {
        _inheritsLoose(WebGL2DescriptorSet, _DescriptorSet);
        function WebGL2DescriptorSet() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _DescriptorSet.call.apply(_DescriptorSet, [this].concat(args)) || this;
          _this._gpuDescriptorSet = null;
          return _this;
        }
        var _proto = WebGL2DescriptorSet.prototype;
        _proto.initialize = function initialize(info) {
          this._layout = info.layout;
          var _gpuDescriptorSetLayo = info.layout.gpuDescriptorSetLayout,
            bindings = _gpuDescriptorSetLayo.bindings,
            descriptorIndices = _gpuDescriptorSetLayo.descriptorIndices,
            descriptorCount = _gpuDescriptorSetLayo.descriptorCount;
          this._buffers = Array(descriptorCount).fill(null);
          this._textures = Array(descriptorCount).fill(null);
          this._samplers = Array(descriptorCount).fill(null);
          var gpuDescriptors = [];
          this._gpuDescriptorSet = {
            gpuDescriptors: gpuDescriptors,
            descriptorIndices: descriptorIndices
          };
          for (var i = 0; i < bindings.length; ++i) {
            var binding = bindings[i];
            for (var j = 0; j < binding.count; j++) {
              gpuDescriptors.push({
                type: binding.descriptorType,
                gpuBuffer: null,
                gpuTextureView: null,
                gpuSampler: null
              });
            }
          }
        };
        _proto.destroy = function destroy() {
          this._layout = null;
          this._gpuDescriptorSet = null;
        };
        _proto.update = function update() {
          if (this._isDirty && this._gpuDescriptorSet) {
            var descriptors = this._gpuDescriptorSet.gpuDescriptors;
            for (var i = 0; i < descriptors.length; ++i) {
              if (descriptors[i].type & DESCRIPTOR_BUFFER_TYPE) {
                if (this._buffers[i]) {
                  descriptors[i].gpuBuffer = this._buffers[i].gpuBuffer;
                }
              } else if (descriptors[i].type & DESCRIPTOR_SAMPLER_TYPE) {
                if (this._textures[i]) {
                  descriptors[i].gpuTextureView = this._textures[i].gpuTextureView;
                }
                if (this._samplers[i]) {
                  descriptors[i].gpuSampler = this._samplers[i].gpuSampler;
                }
              }
            }
            this._isDirty = false;
          }
        };
        _createClass(WebGL2DescriptorSet, [{
          key: "gpuDescriptorSet",
          get: function get() {
            return this._gpuDescriptorSet;
          }
        }]);
        return WebGL2DescriptorSet;
      }(DescriptorSet);

      var WebGL2EXT;
      (function (WebGL2EXT) {
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL";
        WebGL2EXT[WebGL2EXT["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_4x4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4x4_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_5x4_KHR"] = 37809] = "COMPRESSED_RGBA_ASTC_5x4_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_5x5_KHR"] = 37810] = "COMPRESSED_RGBA_ASTC_5x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_6x5_KHR"] = 37811] = "COMPRESSED_RGBA_ASTC_6x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_6x6_KHR"] = 37812] = "COMPRESSED_RGBA_ASTC_6x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_8x5_KHR"] = 37813] = "COMPRESSED_RGBA_ASTC_8x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_8x6_KHR"] = 37814] = "COMPRESSED_RGBA_ASTC_8x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_8x8_KHR"] = 37815] = "COMPRESSED_RGBA_ASTC_8x8_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_10x5_KHR"] = 37816] = "COMPRESSED_RGBA_ASTC_10x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_10x6_KHR"] = 37817] = "COMPRESSED_RGBA_ASTC_10x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_10x8_KHR"] = 37818] = "COMPRESSED_RGBA_ASTC_10x8_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_10x10_KHR"] = 37819] = "COMPRESSED_RGBA_ASTC_10x10_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_12x10_KHR"] = 37820] = "COMPRESSED_RGBA_ASTC_12x10_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_12x12_KHR"] = 37821] = "COMPRESSED_RGBA_ASTC_12x12_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR"] = 37840] = "COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR"] = 37841] = "COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR"] = 37842] = "COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR"] = 37843] = "COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR"] = 37844] = "COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR"] = 37845] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR"] = 37846] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR"] = 37847] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR"] = 37848] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR"] = 37849] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR"] = 37850] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR"] = 37851] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR"] = 37852] = "COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR"] = 37853] = "COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR";
      })(WebGL2EXT || (WebGL2EXT = {}));
      var WebGL2DeviceManager = function () {
        function WebGL2DeviceManager() {}
        WebGL2DeviceManager.setInstance = function setInstance(instance) {
          WebGL2DeviceManager._instance = instance;
        };
        _createClass(WebGL2DeviceManager, null, [{
          key: "instance",
          get: function get() {
            return WebGL2DeviceManager._instance;
          }
        }]);
        return WebGL2DeviceManager;
      }();
      WebGL2DeviceManager._instance = null;

      var WebGLWraps = [0x2901, 0x8370, 0x812F, 0x812F];
      var _f32v4 = new Float32Array(4);
      function GFXFormatToWebGLType(format, gl) {
        switch (format) {
          case Format.R8:
            return gl.UNSIGNED_BYTE;
          case Format.R8SN:
            return gl.BYTE;
          case Format.R8UI:
            return gl.UNSIGNED_BYTE;
          case Format.R8I:
            return gl.BYTE;
          case Format.R16F:
            return gl.HALF_FLOAT;
          case Format.R16UI:
            return gl.UNSIGNED_SHORT;
          case Format.R16I:
            return gl.SHORT;
          case Format.R32F:
            return gl.FLOAT;
          case Format.R32UI:
            return gl.UNSIGNED_INT;
          case Format.R32I:
            return gl.INT;
          case Format.RG8:
            return gl.UNSIGNED_BYTE;
          case Format.RG8SN:
            return gl.BYTE;
          case Format.RG8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RG8I:
            return gl.BYTE;
          case Format.RG16F:
            return gl.HALF_FLOAT;
          case Format.RG16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RG16I:
            return gl.SHORT;
          case Format.RG32F:
            return gl.FLOAT;
          case Format.RG32UI:
            return gl.UNSIGNED_INT;
          case Format.RG32I:
            return gl.INT;
          case Format.RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.SRGB8:
            return gl.UNSIGNED_BYTE;
          case Format.RGB8SN:
            return gl.BYTE;
          case Format.RGB8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RGB8I:
            return gl.BYTE;
          case Format.RGB16F:
            return gl.HALF_FLOAT;
          case Format.RGB16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RGB16I:
            return gl.SHORT;
          case Format.RGB32F:
            return gl.FLOAT;
          case Format.RGB32UI:
            return gl.UNSIGNED_INT;
          case Format.RGB32I:
            return gl.INT;
          case Format.BGRA8:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8:
            return gl.UNSIGNED_BYTE;
          case Format.SRGB8_A8:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8SN:
            return gl.BYTE;
          case Format.RGBA8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8I:
            return gl.BYTE;
          case Format.RGBA16F:
            return gl.HALF_FLOAT;
          case Format.RGBA16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RGBA16I:
            return gl.SHORT;
          case Format.RGBA32F:
            return gl.FLOAT;
          case Format.RGBA32UI:
            return gl.UNSIGNED_INT;
          case Format.RGBA32I:
            return gl.INT;
          case Format.R5G6B5:
            return gl.UNSIGNED_SHORT_5_6_5;
          case Format.R11G11B10F:
            return gl.UNSIGNED_INT_10F_11F_11F_REV;
          case Format.RGB5A1:
            return gl.UNSIGNED_SHORT_5_5_5_1;
          case Format.RGBA4:
            return gl.UNSIGNED_SHORT_4_4_4_4;
          case Format.RGB10A2:
            return gl.UNSIGNED_INT_2_10_10_10_REV;
          case Format.RGB10A2UI:
            return gl.UNSIGNED_INT_2_10_10_10_REV;
          case Format.RGB9E5:
            return gl.FLOAT;
          case Format.DEPTH:
            return gl.FLOAT;
          case Format.DEPTH_STENCIL:
            return gl.UNSIGNED_INT_24_8;
          case Format.BC1:
            return gl.UNSIGNED_BYTE;
          case Format.BC1_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC2:
            return gl.UNSIGNED_BYTE;
          case Format.BC2_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC3:
            return gl.UNSIGNED_BYTE;
          case Format.BC3_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC4:
            return gl.UNSIGNED_BYTE;
          case Format.BC4_SNORM:
            return gl.BYTE;
          case Format.BC5:
            return gl.UNSIGNED_BYTE;
          case Format.BC5_SNORM:
            return gl.BYTE;
          case Format.BC6H_SF16:
            return gl.FLOAT;
          case Format.BC6H_UF16:
            return gl.FLOAT;
          case Format.BC7:
            return gl.UNSIGNED_BYTE;
          case Format.BC7_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.ETC_RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_SRGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_RGB8_A1:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_SRGB8_A1:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_R11:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_R11SN:
            return gl.BYTE;
          case Format.EAC_RG11:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_RG11SN:
            return gl.BYTE;
          case Format.PVRTC_RGB2:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGBA2:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGB4:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGBA4:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC2_2BPP:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC2_4BPP:
            return gl.UNSIGNED_BYTE;
          case Format.ASTC_RGBA_4X4:
          case Format.ASTC_RGBA_5X4:
          case Format.ASTC_RGBA_5X5:
          case Format.ASTC_RGBA_6X5:
          case Format.ASTC_RGBA_6X6:
          case Format.ASTC_RGBA_8X5:
          case Format.ASTC_RGBA_8X6:
          case Format.ASTC_RGBA_8X8:
          case Format.ASTC_RGBA_10X5:
          case Format.ASTC_RGBA_10X6:
          case Format.ASTC_RGBA_10X8:
          case Format.ASTC_RGBA_10X10:
          case Format.ASTC_RGBA_12X10:
          case Format.ASTC_RGBA_12X12:
          case Format.ASTC_SRGBA_4X4:
          case Format.ASTC_SRGBA_5X4:
          case Format.ASTC_SRGBA_5X5:
          case Format.ASTC_SRGBA_6X5:
          case Format.ASTC_SRGBA_6X6:
          case Format.ASTC_SRGBA_8X5:
          case Format.ASTC_SRGBA_8X6:
          case Format.ASTC_SRGBA_8X8:
          case Format.ASTC_SRGBA_10X5:
          case Format.ASTC_SRGBA_10X6:
          case Format.ASTC_SRGBA_10X8:
          case Format.ASTC_SRGBA_10X10:
          case Format.ASTC_SRGBA_12X10:
          case Format.ASTC_SRGBA_12X12:
            return gl.UNSIGNED_BYTE;
          default:
            {
              return gl.UNSIGNED_BYTE;
            }
        }
      }
      function GFXFormatToWebGLInternalFormat(format, gl) {
        switch (format) {
          case Format.A8:
            return gl.ALPHA;
          case Format.L8:
            return gl.LUMINANCE;
          case Format.LA8:
            return gl.LUMINANCE_ALPHA;
          case Format.R8:
            return gl.R8;
          case Format.R8SN:
            return gl.R8_SNORM;
          case Format.R8UI:
            return gl.R8UI;
          case Format.R8I:
            return gl.R8I;
          case Format.RG8:
            return gl.RG8;
          case Format.RG8SN:
            return gl.RG8_SNORM;
          case Format.RG8UI:
            return gl.RG8UI;
          case Format.RG8I:
            return gl.RG8I;
          case Format.RGB8:
            return gl.RGB8;
          case Format.RGB8SN:
            return gl.RGB8_SNORM;
          case Format.RGB8UI:
            return gl.RGB8UI;
          case Format.RGB8I:
            return gl.RGB8I;
          case Format.BGRA8:
            return gl.RGBA8;
          case Format.RGBA8:
            return gl.RGBA8;
          case Format.RGBA8SN:
            return gl.RGBA8_SNORM;
          case Format.RGBA8UI:
            return gl.RGBA8UI;
          case Format.RGBA8I:
            return gl.RGBA8I;
          case Format.R16I:
            return gl.R16I;
          case Format.R16UI:
            return gl.R16UI;
          case Format.R16F:
            return gl.R16F;
          case Format.RG16I:
            return gl.RG16I;
          case Format.RG16UI:
            return gl.RG16UI;
          case Format.RG16F:
            return gl.RG16F;
          case Format.RGB16I:
            return gl.RGB16I;
          case Format.RGB16UI:
            return gl.RGB16UI;
          case Format.RGB16F:
            return gl.RGB16F;
          case Format.RGBA16I:
            return gl.RGBA16I;
          case Format.RGBA16UI:
            return gl.RGBA16UI;
          case Format.RGBA16F:
            return gl.RGBA16F;
          case Format.R32I:
            return gl.R32I;
          case Format.R32UI:
            return gl.R32UI;
          case Format.R32F:
            return gl.R32F;
          case Format.RG32I:
            return gl.RG32I;
          case Format.RG32UI:
            return gl.RG32UI;
          case Format.RG32F:
            return gl.RG32F;
          case Format.RGB32I:
            return gl.RGB32I;
          case Format.RGB32UI:
            return gl.RGB32UI;
          case Format.RGB32F:
            return gl.RGB32F;
          case Format.RGBA32I:
            return gl.RGBA32I;
          case Format.RGBA32UI:
            return gl.RGBA32UI;
          case Format.RGBA32F:
            return gl.RGBA32F;
          case Format.R5G6B5:
            return gl.RGB565;
          case Format.RGB5A1:
            return gl.RGB5_A1;
          case Format.RGBA4:
            return gl.RGBA4;
          case Format.SRGB8:
            return gl.SRGB8;
          case Format.SRGB8_A8:
            return gl.SRGB8_ALPHA8;
          case Format.RGB10A2:
            return gl.RGB10_A2;
          case Format.RGB10A2UI:
            return gl.RGB10_A2UI;
          case Format.R11G11B10F:
            return gl.R11F_G11F_B10F;
          case Format.DEPTH:
            return gl.DEPTH_COMPONENT32F;
          case Format.DEPTH_STENCIL:
            return gl.DEPTH24_STENCIL8;
          case Format.BC1:
            return WebGL2EXT.COMPRESSED_RGB_S3TC_DXT1_EXT;
          case Format.BC1_ALPHA:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT1_EXT;
          case Format.BC1_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_S3TC_DXT1_EXT;
          case Format.BC1_SRGB_ALPHA:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
          case Format.BC2:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT3_EXT;
          case Format.BC2_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
          case Format.BC3:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
          case Format.BC3_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
          case Format.ETC_RGB8:
            return WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL;
          case Format.ETC2_RGB8:
            return WebGL2EXT.COMPRESSED_RGB8_ETC2;
          case Format.ETC2_SRGB8:
            return WebGL2EXT.COMPRESSED_SRGB8_ETC2;
          case Format.ETC2_RGB8_A1:
            return WebGL2EXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_SRGB8_A1:
            return WebGL2EXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_RGBA8:
            return WebGL2EXT.COMPRESSED_RGBA8_ETC2_EAC;
          case Format.ETC2_SRGB8_A8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
          case Format.EAC_R11:
            return WebGL2EXT.COMPRESSED_R11_EAC;
          case Format.EAC_R11SN:
            return WebGL2EXT.COMPRESSED_SIGNED_R11_EAC;
          case Format.EAC_RG11:
            return WebGL2EXT.COMPRESSED_RG11_EAC;
          case Format.EAC_RG11SN:
            return WebGL2EXT.COMPRESSED_SIGNED_RG11_EAC;
          case Format.PVRTC_RGB2:
            return WebGL2EXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGBA2:
            return WebGL2EXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGB4:
            return WebGL2EXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
          case Format.PVRTC_RGBA4:
            return WebGL2EXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
          case Format.ASTC_RGBA_4X4:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_4x4_KHR;
          case Format.ASTC_RGBA_5X4:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_5x4_KHR;
          case Format.ASTC_RGBA_5X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_5x5_KHR;
          case Format.ASTC_RGBA_6X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_6x5_KHR;
          case Format.ASTC_RGBA_6X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_6x6_KHR;
          case Format.ASTC_RGBA_8X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x5_KHR;
          case Format.ASTC_RGBA_8X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x6_KHR;
          case Format.ASTC_RGBA_8X8:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x8_KHR;
          case Format.ASTC_RGBA_10X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x5_KHR;
          case Format.ASTC_RGBA_10X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x6_KHR;
          case Format.ASTC_RGBA_10X8:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x8_KHR;
          case Format.ASTC_RGBA_10X10:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x10_KHR;
          case Format.ASTC_RGBA_12X10:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_12x10_KHR;
          case Format.ASTC_RGBA_12X12:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_12x12_KHR;
          case Format.ASTC_SRGBA_4X4:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
          case Format.ASTC_SRGBA_5X4:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;
          case Format.ASTC_SRGBA_5X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;
          case Format.ASTC_SRGBA_6X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;
          case Format.ASTC_SRGBA_6X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;
          case Format.ASTC_SRGBA_8X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;
          case Format.ASTC_SRGBA_8X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;
          case Format.ASTC_SRGBA_8X8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;
          case Format.ASTC_SRGBA_10X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;
          case Format.ASTC_SRGBA_10X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;
          case Format.ASTC_SRGBA_10X8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;
          case Format.ASTC_SRGBA_10X10:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;
          case Format.ASTC_SRGBA_12X10:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;
          case Format.ASTC_SRGBA_12X12:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;
          default:
            {
              error('Unsupported Format, convert to WebGL internal format failed.');
              return gl.RGBA;
            }
        }
      }
      function GFXFormatToWebGLFormat(format, gl) {
        switch (format) {
          case Format.A8:
            return gl.ALPHA;
          case Format.L8:
            return gl.LUMINANCE;
          case Format.LA8:
            return gl.LUMINANCE_ALPHA;
          case Format.R8:
          case Format.R8SN:
            return gl.RED;
          case Format.R8UI:
          case Format.R8I:
            return gl.RED;
          case Format.RG8:
          case Format.RG8SN:
          case Format.RG8UI:
          case Format.RG8I:
            return gl.RG;
          case Format.RGB8:
          case Format.RGB8SN:
          case Format.RGB8UI:
          case Format.RGB8I:
            return gl.RGB;
          case Format.BGRA8:
          case Format.RGBA8:
          case Format.RGBA8SN:
          case Format.RGBA8UI:
          case Format.RGBA8I:
            return gl.RGBA;
          case Format.R16UI:
          case Format.R16I:
          case Format.R16F:
            return gl.RED;
          case Format.RG16UI:
          case Format.RG16I:
          case Format.RG16F:
            return gl.RG;
          case Format.RGB16UI:
          case Format.RGB16I:
          case Format.RGB16F:
            return gl.RGB;
          case Format.RGBA16UI:
          case Format.RGBA16I:
          case Format.RGBA16F:
            return gl.RGBA;
          case Format.R32UI:
          case Format.R32I:
          case Format.R32F:
            return gl.RED;
          case Format.RG32UI:
          case Format.RG32I:
          case Format.RG32F:
            return gl.RG;
          case Format.RGB32UI:
          case Format.RGB32I:
          case Format.RGB32F:
            return gl.RGB;
          case Format.RGBA32UI:
          case Format.RGBA32I:
          case Format.RGBA32F:
            return gl.RGBA;
          case Format.RGB10A2:
            return gl.RGBA;
          case Format.R11G11B10F:
            return gl.RGB;
          case Format.R5G6B5:
            return gl.RGB;
          case Format.RGB5A1:
            return gl.RGBA;
          case Format.RGBA4:
            return gl.RGBA;
          case Format.SRGB8:
            return gl.RGB;
          case Format.SRGB8_A8:
            return gl.RGBA;
          case Format.DEPTH:
            return gl.DEPTH_COMPONENT;
          case Format.DEPTH_STENCIL:
            return gl.DEPTH_STENCIL;
          case Format.BC1:
            return WebGL2EXT.COMPRESSED_RGB_S3TC_DXT1_EXT;
          case Format.BC1_ALPHA:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT1_EXT;
          case Format.BC1_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_S3TC_DXT1_EXT;
          case Format.BC1_SRGB_ALPHA:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
          case Format.BC2:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT3_EXT;
          case Format.BC2_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
          case Format.BC3:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
          case Format.BC3_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
          case Format.ETC_RGB8:
            return WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL;
          case Format.ETC2_RGB8:
            return WebGL2EXT.COMPRESSED_RGB8_ETC2;
          case Format.ETC2_SRGB8:
            return WebGL2EXT.COMPRESSED_SRGB8_ETC2;
          case Format.ETC2_RGB8_A1:
            return WebGL2EXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_SRGB8_A1:
            return WebGL2EXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_RGBA8:
            return WebGL2EXT.COMPRESSED_RGBA8_ETC2_EAC;
          case Format.ETC2_SRGB8_A8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
          case Format.EAC_R11:
            return WebGL2EXT.COMPRESSED_R11_EAC;
          case Format.EAC_R11SN:
            return WebGL2EXT.COMPRESSED_SIGNED_R11_EAC;
          case Format.EAC_RG11:
            return WebGL2EXT.COMPRESSED_RG11_EAC;
          case Format.EAC_RG11SN:
            return WebGL2EXT.COMPRESSED_SIGNED_RG11_EAC;
          case Format.PVRTC_RGB2:
            return WebGL2EXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGBA2:
            return WebGL2EXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGB4:
            return WebGL2EXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
          case Format.PVRTC_RGBA4:
            return WebGL2EXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
          case Format.ASTC_RGBA_4X4:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_4x4_KHR;
          case Format.ASTC_RGBA_5X4:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_5x4_KHR;
          case Format.ASTC_RGBA_5X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_5x5_KHR;
          case Format.ASTC_RGBA_6X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_6x5_KHR;
          case Format.ASTC_RGBA_6X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_6x6_KHR;
          case Format.ASTC_RGBA_8X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x5_KHR;
          case Format.ASTC_RGBA_8X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x6_KHR;
          case Format.ASTC_RGBA_8X8:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x8_KHR;
          case Format.ASTC_RGBA_10X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x5_KHR;
          case Format.ASTC_RGBA_10X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x6_KHR;
          case Format.ASTC_RGBA_10X8:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x8_KHR;
          case Format.ASTC_RGBA_10X10:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x10_KHR;
          case Format.ASTC_RGBA_12X10:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_12x10_KHR;
          case Format.ASTC_RGBA_12X12:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_12x12_KHR;
          case Format.ASTC_SRGBA_4X4:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
          case Format.ASTC_SRGBA_5X4:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;
          case Format.ASTC_SRGBA_5X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;
          case Format.ASTC_SRGBA_6X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;
          case Format.ASTC_SRGBA_6X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;
          case Format.ASTC_SRGBA_8X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;
          case Format.ASTC_SRGBA_8X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;
          case Format.ASTC_SRGBA_8X8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;
          case Format.ASTC_SRGBA_10X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;
          case Format.ASTC_SRGBA_10X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;
          case Format.ASTC_SRGBA_10X8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;
          case Format.ASTC_SRGBA_10X10:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;
          case Format.ASTC_SRGBA_12X10:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;
          case Format.ASTC_SRGBA_12X12:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;
          default:
            {
              error('Unsupported Format, convert to WebGL format failed.');
              return gl.RGBA;
            }
        }
      }
      function GFXTypeToWebGLType(type, gl) {
        switch (type) {
          case Type$1.BOOL:
            return gl.BOOL;
          case Type$1.BOOL2:
            return gl.BOOL_VEC2;
          case Type$1.BOOL3:
            return gl.BOOL_VEC3;
          case Type$1.BOOL4:
            return gl.BOOL_VEC4;
          case Type$1.INT:
            return gl.INT;
          case Type$1.INT2:
            return gl.INT_VEC2;
          case Type$1.INT3:
            return gl.INT_VEC3;
          case Type$1.INT4:
            return gl.INT_VEC4;
          case Type$1.UINT:
            return gl.UNSIGNED_INT;
          case Type$1.FLOAT:
            return gl.FLOAT;
          case Type$1.FLOAT2:
            return gl.FLOAT_VEC2;
          case Type$1.FLOAT3:
            return gl.FLOAT_VEC3;
          case Type$1.FLOAT4:
            return gl.FLOAT_VEC4;
          case Type$1.MAT2:
            return gl.FLOAT_MAT2;
          case Type$1.MAT2X3:
            return gl.FLOAT_MAT2x3;
          case Type$1.MAT2X4:
            return gl.FLOAT_MAT2x4;
          case Type$1.MAT3X2:
            return gl.FLOAT_MAT3x2;
          case Type$1.MAT3:
            return gl.FLOAT_MAT3;
          case Type$1.MAT3X4:
            return gl.FLOAT_MAT3x4;
          case Type$1.MAT4X2:
            return gl.FLOAT_MAT4x2;
          case Type$1.MAT4X3:
            return gl.FLOAT_MAT4x3;
          case Type$1.MAT4:
            return gl.FLOAT_MAT4;
          case Type$1.SAMPLER2D:
            return gl.SAMPLER_2D;
          case Type$1.SAMPLER2D_ARRAY:
            return gl.SAMPLER_2D_ARRAY;
          case Type$1.SAMPLER3D:
            return gl.SAMPLER_3D;
          case Type$1.SAMPLER_CUBE:
            return gl.SAMPLER_CUBE;
          default:
            {
              error('Unsupported GLType, convert to GL type failed.');
              return Type$1.UNKNOWN;
            }
        }
      }
      function WebGLTypeToGFXType(glType, gl) {
        switch (glType) {
          case gl.BOOL:
            return Type$1.BOOL;
          case gl.BOOL_VEC2:
            return Type$1.BOOL2;
          case gl.BOOL_VEC3:
            return Type$1.BOOL3;
          case gl.BOOL_VEC4:
            return Type$1.BOOL4;
          case gl.INT:
            return Type$1.INT;
          case gl.INT_VEC2:
            return Type$1.INT2;
          case gl.INT_VEC3:
            return Type$1.INT3;
          case gl.INT_VEC4:
            return Type$1.INT4;
          case gl.UNSIGNED_INT:
            return Type$1.UINT;
          case gl.UNSIGNED_INT_VEC2:
            return Type$1.UINT2;
          case gl.UNSIGNED_INT_VEC3:
            return Type$1.UINT3;
          case gl.UNSIGNED_INT_VEC4:
            return Type$1.UINT4;
          case gl.FLOAT:
            return Type$1.FLOAT;
          case gl.FLOAT_VEC2:
            return Type$1.FLOAT2;
          case gl.FLOAT_VEC3:
            return Type$1.FLOAT3;
          case gl.FLOAT_VEC4:
            return Type$1.FLOAT4;
          case gl.FLOAT_MAT2:
            return Type$1.MAT2;
          case gl.FLOAT_MAT2x3:
            return Type$1.MAT2X3;
          case gl.FLOAT_MAT2x4:
            return Type$1.MAT2X4;
          case gl.FLOAT_MAT3x2:
            return Type$1.MAT3X2;
          case gl.FLOAT_MAT3:
            return Type$1.MAT3;
          case gl.FLOAT_MAT3x4:
            return Type$1.MAT3X4;
          case gl.FLOAT_MAT4x2:
            return Type$1.MAT4X2;
          case gl.FLOAT_MAT4x3:
            return Type$1.MAT4X3;
          case gl.FLOAT_MAT4:
            return Type$1.MAT4;
          case gl.SAMPLER_2D:
            return Type$1.SAMPLER2D;
          case gl.SAMPLER_2D_ARRAY:
            return Type$1.SAMPLER2D_ARRAY;
          case gl.SAMPLER_3D:
            return Type$1.SAMPLER3D;
          case gl.SAMPLER_CUBE:
            return Type$1.SAMPLER_CUBE;
          default:
            {
              error('Unsupported GLType, convert to Type failed.');
              return Type$1.UNKNOWN;
            }
        }
      }
      function WebGLGetTypeSize(glType, gl) {
        switch (glType) {
          case gl.BOOL:
            return 4;
          case gl.BOOL_VEC2:
            return 8;
          case gl.BOOL_VEC3:
            return 12;
          case gl.BOOL_VEC4:
            return 16;
          case gl.INT:
            return 4;
          case gl.INT_VEC2:
            return 8;
          case gl.INT_VEC3:
            return 12;
          case gl.INT_VEC4:
            return 16;
          case gl.UNSIGNED_INT:
            return 4;
          case gl.UNSIGNED_INT_VEC2:
            return 8;
          case gl.UNSIGNED_INT_VEC3:
            return 12;
          case gl.UNSIGNED_INT_VEC4:
            return 16;
          case gl.FLOAT:
            return 4;
          case gl.FLOAT_VEC2:
            return 8;
          case gl.FLOAT_VEC3:
            return 12;
          case gl.FLOAT_VEC4:
            return 16;
          case gl.FLOAT_MAT2:
            return 16;
          case gl.FLOAT_MAT2x3:
            return 24;
          case gl.FLOAT_MAT2x4:
            return 32;
          case gl.FLOAT_MAT3x2:
            return 24;
          case gl.FLOAT_MAT3:
            return 36;
          case gl.FLOAT_MAT3x4:
            return 48;
          case gl.FLOAT_MAT4x2:
            return 32;
          case gl.FLOAT_MAT4x3:
            return 48;
          case gl.FLOAT_MAT4:
            return 64;
          case gl.SAMPLER_2D:
            return 4;
          case gl.SAMPLER_2D_ARRAY:
            return 4;
          case gl.SAMPLER_2D_ARRAY_SHADOW:
            return 4;
          case gl.SAMPLER_3D:
            return 4;
          case gl.SAMPLER_CUBE:
            return 4;
          case gl.INT_SAMPLER_2D:
            return 4;
          case gl.INT_SAMPLER_2D_ARRAY:
            return 4;
          case gl.INT_SAMPLER_3D:
            return 4;
          case gl.INT_SAMPLER_CUBE:
            return 4;
          case gl.UNSIGNED_INT_SAMPLER_2D:
            return 4;
          case gl.UNSIGNED_INT_SAMPLER_2D_ARRAY:
            return 4;
          case gl.UNSIGNED_INT_SAMPLER_3D:
            return 4;
          case gl.UNSIGNED_INT_SAMPLER_CUBE:
            return 4;
          default:
            {
              error('Unsupported GLType, get type failed.');
              return 0;
            }
        }
      }
      function WebGLGetComponentCount(glType, gl) {
        switch (glType) {
          case gl.FLOAT_MAT2:
            return 2;
          case gl.FLOAT_MAT2x3:
            return 2;
          case gl.FLOAT_MAT2x4:
            return 2;
          case gl.FLOAT_MAT3x2:
            return 3;
          case gl.FLOAT_MAT3:
            return 3;
          case gl.FLOAT_MAT3x4:
            return 3;
          case gl.FLOAT_MAT4x2:
            return 4;
          case gl.FLOAT_MAT4x3:
            return 4;
          case gl.FLOAT_MAT4:
            return 4;
          default:
            {
              return 1;
            }
        }
      }
      var WebGLCmpFuncs = [0x0200, 0x0201, 0x0202, 0x0203, 0x0204, 0x0205, 0x0206, 0x0207];
      var WebGLStencilOps = [0x0000, 0x1E00, 0x1E01, 0x1E02, 0x1E03, 0x150A, 0x8507, 0x8508];
      var WebGLBlendOps = [0x8006, 0x800A, 0x800B, 0x8007, 0x8008];
      var WebGLBlendFactors = [0x0000, 0x0001, 0x0302, 0x0304, 0x0303, 0x0305, 0x0300, 0x0306, 0x0301, 0x0307, 0x0308, 0x8001, 0x8002, 0x8003, 0x8004];
      var WebGL2Cmd;
      (function (WebGL2Cmd) {
        WebGL2Cmd[WebGL2Cmd["BEGIN_RENDER_PASS"] = 0] = "BEGIN_RENDER_PASS";
        WebGL2Cmd[WebGL2Cmd["END_RENDER_PASS"] = 1] = "END_RENDER_PASS";
        WebGL2Cmd[WebGL2Cmd["BIND_STATES"] = 2] = "BIND_STATES";
        WebGL2Cmd[WebGL2Cmd["DRAW"] = 3] = "DRAW";
        WebGL2Cmd[WebGL2Cmd["UPDATE_BUFFER"] = 4] = "UPDATE_BUFFER";
        WebGL2Cmd[WebGL2Cmd["COPY_BUFFER_TO_TEXTURE"] = 5] = "COPY_BUFFER_TO_TEXTURE";
        WebGL2Cmd[WebGL2Cmd["BLIT_TEXTURE"] = 6] = "BLIT_TEXTURE";
        WebGL2Cmd[WebGL2Cmd["COUNT"] = 7] = "COUNT";
      })(WebGL2Cmd || (WebGL2Cmd = {}));
      var WebGL2CmdObject = function WebGL2CmdObject(type) {
        this.cmdType = void 0;
        this.refCount = 0;
        this.cmdType = type;
      };
      var WebGL2CmdBeginRenderPass = function (_WebGL2CmdObject) {
        _inheritsLoose(WebGL2CmdBeginRenderPass, _WebGL2CmdObject);
        function WebGL2CmdBeginRenderPass() {
          var _this;
          _this = _WebGL2CmdObject.call(this, WebGL2Cmd.BEGIN_RENDER_PASS) || this;
          _this.gpuRenderPass = null;
          _this.gpuFramebuffer = null;
          _this.renderArea = new Rect();
          _this.clearColors = [];
          _this.clearDepth = 1.0;
          _this.clearStencil = 0;
          return _this;
        }
        var _proto = WebGL2CmdBeginRenderPass.prototype;
        _proto.clear = function clear() {
          this.gpuFramebuffer = null;
          this.clearColors.length = 0;
        };
        return WebGL2CmdBeginRenderPass;
      }(WebGL2CmdObject);
      var WebGL2CmdBindStates = function (_WebGL2CmdObject2) {
        _inheritsLoose(WebGL2CmdBindStates, _WebGL2CmdObject2);
        function WebGL2CmdBindStates() {
          var _this2;
          _this2 = _WebGL2CmdObject2.call(this, WebGL2Cmd.BIND_STATES) || this;
          _this2.gpuPipelineState = null;
          _this2.gpuInputAssembler = null;
          _this2.gpuDescriptorSets = [];
          _this2.dynamicOffsets = [];
          _this2.dynamicStates = new DynamicStates();
          return _this2;
        }
        var _proto2 = WebGL2CmdBindStates.prototype;
        _proto2.clear = function clear() {
          this.gpuPipelineState = null;
          this.gpuInputAssembler = null;
          this.gpuDescriptorSets.length = 0;
          this.dynamicOffsets.length = 0;
        };
        return WebGL2CmdBindStates;
      }(WebGL2CmdObject);
      var WebGL2CmdDraw = function (_WebGL2CmdObject3) {
        _inheritsLoose(WebGL2CmdDraw, _WebGL2CmdObject3);
        function WebGL2CmdDraw() {
          var _this3;
          _this3 = _WebGL2CmdObject3.call(this, WebGL2Cmd.DRAW) || this;
          _this3.drawInfo = new DrawInfo();
          return _this3;
        }
        var _proto3 = WebGL2CmdDraw.prototype;
        _proto3.clear = function clear() {};
        return WebGL2CmdDraw;
      }(WebGL2CmdObject);
      var WebGL2CmdUpdateBuffer = function (_WebGL2CmdObject4) {
        _inheritsLoose(WebGL2CmdUpdateBuffer, _WebGL2CmdObject4);
        function WebGL2CmdUpdateBuffer() {
          var _this4;
          _this4 = _WebGL2CmdObject4.call(this, WebGL2Cmd.UPDATE_BUFFER) || this;
          _this4.gpuBuffer = null;
          _this4.buffer = null;
          _this4.offset = 0;
          _this4.size = 0;
          return _this4;
        }
        var _proto4 = WebGL2CmdUpdateBuffer.prototype;
        _proto4.clear = function clear() {
          this.gpuBuffer = null;
          this.buffer = null;
        };
        return WebGL2CmdUpdateBuffer;
      }(WebGL2CmdObject);
      var WebGL2CmdCopyBufferToTexture = function (_WebGL2CmdObject5) {
        _inheritsLoose(WebGL2CmdCopyBufferToTexture, _WebGL2CmdObject5);
        function WebGL2CmdCopyBufferToTexture() {
          var _this5;
          _this5 = _WebGL2CmdObject5.call(this, WebGL2Cmd.COPY_BUFFER_TO_TEXTURE) || this;
          _this5.gpuTexture = null;
          _this5.buffers = [];
          _this5.regions = [];
          return _this5;
        }
        var _proto5 = WebGL2CmdCopyBufferToTexture.prototype;
        _proto5.clear = function clear() {
          this.gpuTexture = null;
          this.buffers.length = 0;
          this.regions.length = 0;
        };
        return WebGL2CmdCopyBufferToTexture;
      }(WebGL2CmdObject);
      var WebGL2CmdBlitTexture = function (_WebGL2CmdObject6) {
        _inheritsLoose(WebGL2CmdBlitTexture, _WebGL2CmdObject6);
        function WebGL2CmdBlitTexture() {
          var _this6;
          _this6 = _WebGL2CmdObject6.call(this, WebGL2Cmd.BLIT_TEXTURE) || this;
          _this6.srcTexture = null;
          _this6.dstTexture = null;
          _this6.regions = [];
          _this6.filter = Filter$1.LINEAR;
          return _this6;
        }
        var _proto6 = WebGL2CmdBlitTexture.prototype;
        _proto6.clear = function clear() {
          this.srcTexture = null;
          this.dstTexture = null;
          this.regions.length = 0;
        };
        return WebGL2CmdBlitTexture;
      }(WebGL2CmdObject);
      var WebGL2CmdPackage = function () {
        function WebGL2CmdPackage() {
          this.cmds = new CachedArray(1);
          this.beginRenderPassCmds = new CachedArray(1);
          this.bindStatesCmds = new CachedArray(1);
          this.drawCmds = new CachedArray(1);
          this.updateBufferCmds = new CachedArray(1);
          this.copyBufferToTextureCmds = new CachedArray(1);
          this.blitTextureCmds = new CachedArray(1);
        }
        var _proto7 = WebGL2CmdPackage.prototype;
        _proto7.clearCmds = function clearCmds(allocator) {
          if (this.beginRenderPassCmds.length) {
            allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds);
            this.beginRenderPassCmds.clear();
          }
          if (this.bindStatesCmds.length) {
            allocator.bindStatesCmdPool.freeCmds(this.bindStatesCmds);
            this.bindStatesCmds.clear();
          }
          if (this.drawCmds.length) {
            allocator.drawCmdPool.freeCmds(this.drawCmds);
            this.drawCmds.clear();
          }
          if (this.updateBufferCmds.length) {
            allocator.updateBufferCmdPool.freeCmds(this.updateBufferCmds);
            this.updateBufferCmds.clear();
          }
          if (this.copyBufferToTextureCmds.length) {
            allocator.copyBufferToTextureCmdPool.freeCmds(this.copyBufferToTextureCmds);
            this.copyBufferToTextureCmds.clear();
          }
          if (this.blitTextureCmds.length) {
            allocator.blitTextureCmdPool.freeCmds(this.blitTextureCmds);
            this.blitTextureCmds.clear();
          }
          this.cmds.clear();
        };
        return WebGL2CmdPackage;
      }();
      function WebGL2CmdFuncCreateBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        var glUsage = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
        if (gpuBuffer.usage & BufferUsageBit.VERTEX) {
          gpuBuffer.glTarget = gl.ARRAY_BUFFER;
          var glBuffer = gl.createBuffer();
          if (glBuffer) {
            gpuBuffer.glBuffer = glBuffer;
            if (gpuBuffer.size > 0) {
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  gl.bindVertexArray(null);
                  cache.glVAO = null;
                }
              }
              gfxStateCache.gpuInputAssembler = null;
              if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) {
                gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
                device.stateCache.glArrayBuffer = gpuBuffer.glBuffer;
              }
              gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.size, glUsage);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              device.stateCache.glArrayBuffer = null;
            }
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
          gpuBuffer.glTarget = gl.ELEMENT_ARRAY_BUFFER;
          var _glBuffer = gl.createBuffer();
          if (_glBuffer) {
            gpuBuffer.glBuffer = _glBuffer;
            if (gpuBuffer.size > 0) {
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  gl.bindVertexArray(null);
                  cache.glVAO = null;
                }
              }
              gfxStateCache.gpuInputAssembler = null;
              if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
                device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer;
              }
              gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              device.stateCache.glElementArrayBuffer = null;
            }
          }
        } else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
          gpuBuffer.glTarget = gl.UNIFORM_BUFFER;
          var _glBuffer2 = gl.createBuffer();
          if (_glBuffer2 && gpuBuffer.size > 0) {
            gpuBuffer.glBuffer = _glBuffer2;
            if (device.stateCache.glUniformBuffer !== gpuBuffer.glBuffer) {
              gl.bindBuffer(gl.UNIFORM_BUFFER, gpuBuffer.glBuffer);
              device.stateCache.glUniformBuffer = gpuBuffer.glBuffer;
            }
            gl.bufferData(gl.UNIFORM_BUFFER, gpuBuffer.size, glUsage);
            gl.bindBuffer(gl.UNIFORM_BUFFER, null);
            device.stateCache.glUniformBuffer = null;
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT) {
          gpuBuffer.glTarget = gl.NONE;
        } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_DST) {
          gpuBuffer.glTarget = gl.NONE;
        } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) {
          gpuBuffer.glTarget = gl.NONE;
        } else {
          error('Unsupported BufferType, create buffer failed.');
          gpuBuffer.glTarget = gl.NONE;
        }
      }
      function WebGL2CmdFuncDestroyBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        if (gpuBuffer.glBuffer) {
          switch (gpuBuffer.glTarget) {
            case gl.ARRAY_BUFFER:
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  gl.bindVertexArray(null);
                  device.stateCache.glVAO = null;
                }
              }
              gfxStateCache.gpuInputAssembler = null;
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              device.stateCache.glArrayBuffer = null;
              break;
            case gl.ELEMENT_ARRAY_BUFFER:
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  gl.bindVertexArray(null);
                  device.stateCache.glVAO = null;
                }
              }
              gfxStateCache.gpuInputAssembler = null;
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              device.stateCache.glElementArrayBuffer = null;
              break;
            case gl.UNIFORM_BUFFER:
              gl.bindBuffer(gl.UNIFORM_BUFFER, null);
              device.stateCache.glUniformBuffer = null;
              break;
          }
          gl.deleteBuffer(gpuBuffer.glBuffer);
          gpuBuffer.glBuffer = null;
        }
      }
      function WebGL2CmdFuncResizeBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        var glUsage = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
        if (gpuBuffer.usage & BufferUsageBit.VERTEX) {
          if (device.extensions.useVAO) {
            if (cache.glVAO) {
              gl.bindVertexArray(null);
              cache.glVAO = null;
            }
          }
          gfxStateCache.gpuInputAssembler = null;
          if (cache.glArrayBuffer !== gpuBuffer.glBuffer) {
            gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
          }
          if (gpuBuffer.buffer) {
            gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.buffer, glUsage);
          } else {
            gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.size, glUsage);
          }
          gl.bindBuffer(gl.ARRAY_BUFFER, null);
          cache.glArrayBuffer = null;
        } else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
          if (device.extensions.useVAO) {
            if (cache.glVAO) {
              gl.bindVertexArray(null);
              cache.glVAO = null;
            }
          }
          gfxStateCache.gpuInputAssembler = null;
          if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
          }
          if (gpuBuffer.buffer) {
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.buffer, glUsage);
          } else {
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
          }
          gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
          device.stateCache.glElementArrayBuffer = null;
        } else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
          if (device.stateCache.glUniformBuffer !== gpuBuffer.glBuffer) {
            gl.bindBuffer(gl.UNIFORM_BUFFER, gpuBuffer.glBuffer);
          }
          gl.bufferData(gl.UNIFORM_BUFFER, gpuBuffer.size, glUsage);
          gl.bindBuffer(gl.UNIFORM_BUFFER, null);
          device.stateCache.glUniformBuffer = null;
        } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT || gpuBuffer.usage & BufferUsageBit.TRANSFER_DST || gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) {
          gpuBuffer.glTarget = gl.NONE;
        } else {
          error('Unsupported BufferType, create buffer failed.');
          gpuBuffer.glTarget = gl.NONE;
        }
      }
      function WebGL2CmdFuncUpdateBuffer(device, gpuBuffer, buffer, offset, size) {
        if (gpuBuffer.usage & BufferUsageBit.INDIRECT) {
          gpuBuffer.indirects.clearDraws();
          var drawInfos = buffer.drawInfos;
          for (var i = 0; i < drawInfos.length; ++i) {
            gpuBuffer.indirects.setDrawInfo(offset + i, drawInfos[i]);
          }
        } else {
          var buff = buffer;
          var gl = device.gl;
          var cache = device.stateCache;
          switch (gpuBuffer.glTarget) {
            case gl.ARRAY_BUFFER:
              {
                if (device.extensions.useVAO) {
                  if (cache.glVAO) {
                    gl.bindVertexArray(null);
                    cache.glVAO = null;
                  }
                }
                gfxStateCache.gpuInputAssembler = null;
                if (cache.glArrayBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
                  cache.glArrayBuffer = gpuBuffer.glBuffer;
                }
                if (size === buff.byteLength) {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff);
                } else {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size));
                }
                break;
              }
            case gl.ELEMENT_ARRAY_BUFFER:
              {
                if (device.extensions.useVAO) {
                  if (cache.glVAO) {
                    gl.bindVertexArray(null);
                    cache.glVAO = null;
                  }
                }
                gfxStateCache.gpuInputAssembler = null;
                if (cache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
                  cache.glElementArrayBuffer = gpuBuffer.glBuffer;
                }
                if (size === buff.byteLength) {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff);
                } else {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size));
                }
                break;
              }
            case gl.UNIFORM_BUFFER:
              {
                if (cache.glUniformBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.UNIFORM_BUFFER, gpuBuffer.glBuffer);
                  cache.glUniformBuffer = gpuBuffer.glBuffer;
                }
                if (size === buff.byteLength) {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff);
                } else {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, new Float32Array(buff, 0, size / 4));
                }
                break;
              }
            default:
              {
                error('Unsupported BufferType, update buffer failed.');
              }
          }
        }
      }
      function WebGL2CmdFuncCreateTexture(device, gpuTexture) {
        var gl = device.gl;
        gpuTexture.glInternalFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format, gl);
        gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format, gl);
        gpuTexture.glType = GFXFormatToWebGLType(gpuTexture.format, gl);
        var w = gpuTexture.width;
        var h = gpuTexture.height;
        var d = gpuTexture.depth;
        var l = gpuTexture.arrayLayer;
        switch (gpuTexture.type) {
          case TextureType.TEX2D:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D;
              var maxSize = Math.max(w, h);
              if (maxSize > device.capabilities.maxTextureSize) {
                errorID(9100, maxSize, device.capabilities.maxTextureSize);
              }
              if (gpuTexture.samples === SampleCount.X1) {
                gpuTexture.glTexture = gl.createTexture();
                if (gpuTexture.size > 0) {
                  var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                  if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                    gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture);
                    glTexUnit.glTexture = gpuTexture.glTexture;
                  }
                  if (FormatInfos[gpuTexture.format].isCompressed) {
                    for (var i = 0; i < gpuTexture.mipLevel; ++i) {
                      var imgSize = FormatSize(gpuTexture.format, w, h, 1);
                      var view = new Uint8Array(imgSize);
                      gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view);
                      w = Math.max(1, w >> 1);
                      h = Math.max(1, h >> 1);
                    }
                  } else if (gpuTexture.flags & TextureFlagBit.MUTABLE_STORAGE) {
                    gl.texImage2D(gl.TEXTURE_2D, 0, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                  } else {
                    gl.texStorage2D(gl.TEXTURE_2D, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h);
                  }
                }
              } else {
                gpuTexture.glRenderbuffer = gl.createRenderbuffer();
                if (gpuTexture.size > 0) {
                  if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) {
                    gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
                    device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer;
                  }
                  gl.renderbufferStorageMultisample(gl.RENDERBUFFER, gpuTexture.samples, gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height);
                }
              }
              break;
            }
          case TextureType.TEX2D_ARRAY:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D_ARRAY;
              var _maxSize = Math.max(w, h);
              if (_maxSize > device.capabilities.maxTextureSize) {
                errorID(9100, _maxSize, device.capabilities.maxTextureSize);
              }
              if (l > device.capabilities.maxArrayTextureLayers) {
                errorID(9100, l, device.capabilities.maxArrayTextureLayers);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_2D_ARRAY, gpuTexture.glTexture);
                  _glTexUnit.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var _i = 0; _i < gpuTexture.mipLevel; ++_i) {
                    var _imgSize = FormatSize(gpuTexture.format, w, h, l);
                    var _view = new Uint8Array(_imgSize);
                    gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, _i, gpuTexture.glInternalFmt, w, h, l, 0, _view);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  gl.texStorage3D(gl.TEXTURE_2D_ARRAY, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h, l);
                }
              }
              break;
            }
          case TextureType.TEX3D:
            {
              gpuTexture.glTarget = gl.TEXTURE_3D;
              var _maxSize2 = Math.max(Math.max(w, h), d);
              if (_maxSize2 > device.capabilities.max3DTextureSize) {
                errorID(9100, _maxSize2, device.capabilities.max3DTextureSize);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit2 = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit2.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_3D, gpuTexture.glTexture);
                  _glTexUnit2.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var _i2 = 0; _i2 < gpuTexture.mipLevel; ++_i2) {
                    var _imgSize2 = FormatSize(gpuTexture.format, w, h, d);
                    var _view2 = new Uint8Array(_imgSize2);
                    gl.compressedTexImage3D(gl.TEXTURE_3D, _i2, gpuTexture.glInternalFmt, w, h, d, 0, _view2);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  gl.texStorage3D(gl.TEXTURE_3D, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h, d);
                }
              }
              break;
            }
          case TextureType.CUBE:
            {
              gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP;
              var _maxSize3 = Math.max(w, h);
              if (_maxSize3 > device.capabilities.maxCubeMapTextureSize) {
                errorID(9100, _maxSize3, device.capabilities.maxTextureSize);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit3 = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit3.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture);
                  _glTexUnit3.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var _i3 = 0; _i3 < gpuTexture.mipLevel; ++_i3) {
                    var _imgSize3 = FormatSize(gpuTexture.format, w, h, 1);
                    var _view3 = new Uint8Array(_imgSize3);
                    for (var f = 0; f < 6; ++f) {
                      gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _i3, gpuTexture.glInternalFmt, w, h, 0, _view3);
                    }
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  gl.texStorage2D(gl.TEXTURE_CUBE_MAP, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h);
                }
              }
              break;
            }
          default:
            {
              error('Unsupported TextureType, create texture failed.');
              gpuTexture.type = TextureType.TEX2D;
              gpuTexture.glTarget = gl.TEXTURE_2D;
            }
        }
      }
      function WebGL2CmdFuncDestroyTexture(device, gpuTexture) {
        var gl = device.gl;
        if (gpuTexture.glTexture) {
          var glTexUnits = device.stateCache.glTexUnits;
          var texUnit = device.stateCache.texUnit;
          gl.deleteTexture(gpuTexture.glTexture);
          for (var i = 0; i < glTexUnits.length; ++i) {
            if (glTexUnits[i].glTexture === gpuTexture.glTexture) {
              gl.activeTexture(gl.TEXTURE0 + i);
              texUnit = i;
              gl.bindTexture(gpuTexture.glTarget, null);
              glTexUnits[i].glTexture = null;
            }
          }
          device.stateCache.texUnit = texUnit;
          gpuTexture.glTexture = null;
        }
        if (gpuTexture.glRenderbuffer) {
          var glRenderbuffer = device.stateCache.glRenderbuffer;
          gl.deleteRenderbuffer(gpuTexture.glRenderbuffer);
          if (glRenderbuffer === gpuTexture.glRenderbuffer) {
            gl.bindRenderbuffer(gl.RENDERBUFFER, null);
            glRenderbuffer = null;
          }
          gpuTexture.glRenderbuffer = null;
        }
      }
      function WebGL2CmdFuncResizeTexture(device, gpuTexture) {
        if (!gpuTexture.size) return;
        var gl = device.gl;
        var w = gpuTexture.width;
        var h = gpuTexture.height;
        var d = gpuTexture.depth;
        var l = gpuTexture.arrayLayer;
        switch (gpuTexture.type) {
          case TextureType.TEX2D:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D;
              var maxSize = Math.max(w, h);
              if (maxSize > device.capabilities.maxTextureSize) {
                errorID(9100, maxSize, device.capabilities.maxTextureSize);
              }
              if (gpuTexture.samples === SampleCount.X1) {
                var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture);
                  glTexUnit.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var i = 0; i < gpuTexture.mipLevel; ++i) {
                    var imgSize = FormatSize(gpuTexture.format, w, h, 1);
                    var view = new Uint8Array(imgSize);
                    gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  WebGL2CmdFuncDestroyTexture(device, gpuTexture);
                  WebGL2CmdFuncCreateTexture(device, gpuTexture);
                }
              } else if (gpuTexture.glRenderbuffer) {
                if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) {
                  gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
                  device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer;
                }
                gl.renderbufferStorageMultisample(gl.RENDERBUFFER, gpuTexture.samples, gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height);
              }
              break;
            }
          case TextureType.TEX2D_ARRAY:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D_ARRAY;
              var _maxSize4 = Math.max(w, h);
              if (_maxSize4 > device.capabilities.maxTextureSize) {
                errorID(9100, _maxSize4, device.capabilities.maxTextureSize);
              }
              if (l > device.capabilities.maxArrayTextureLayers) {
                errorID(9100, l, device.capabilities.maxArrayTextureLayers);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit4 = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit4.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_2D_ARRAY, gpuTexture.glTexture);
                  _glTexUnit4.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var _i4 = 0; _i4 < gpuTexture.mipLevel; ++_i4) {
                    var _imgSize4 = FormatSize(gpuTexture.format, w, h, l);
                    var _view4 = new Uint8Array(_imgSize4);
                    gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, _i4, gpuTexture.glInternalFmt, w, h, l, 0, _view4);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  gl.texStorage3D(gl.TEXTURE_2D_ARRAY, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h, l);
                }
              }
              break;
            }
          case TextureType.TEX3D:
            {
              gpuTexture.glTarget = gl.TEXTURE_3D;
              var _maxSize5 = Math.max(Math.max(w, h), d);
              if (_maxSize5 > device.capabilities.max3DTextureSize) {
                errorID(9100, _maxSize5, device.capabilities.max3DTextureSize);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit5 = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit5.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_3D, gpuTexture.glTexture);
                  _glTexUnit5.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var _i5 = 0; _i5 < gpuTexture.mipLevel; ++_i5) {
                    var _imgSize5 = FormatSize(gpuTexture.format, w, h, d);
                    var _view5 = new Uint8Array(_imgSize5);
                    gl.compressedTexImage3D(gl.TEXTURE_3D, _i5, gpuTexture.glInternalFmt, w, h, d, 0, _view5);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  gl.texStorage3D(gl.TEXTURE_3D, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h, d);
                }
              }
              break;
            }
          case TextureType.CUBE:
            {
              gpuTexture.type = TextureType.CUBE;
              gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP;
              var _maxSize6 = Math.max(w, h);
              if (_maxSize6 > device.capabilities.maxCubeMapTextureSize) {
                errorID(9100, _maxSize6, device.capabilities.maxTextureSize);
              }
              var _glTexUnit6 = device.stateCache.glTexUnits[device.stateCache.texUnit];
              if (_glTexUnit6.glTexture !== gpuTexture.glTexture) {
                gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture);
                _glTexUnit6.glTexture = gpuTexture.glTexture;
              }
              if (FormatInfos[gpuTexture.format].isCompressed) {
                for (var f = 0; f < 6; ++f) {
                  w = gpuTexture.width;
                  h = gpuTexture.height;
                  for (var _i6 = 0; _i6 < gpuTexture.mipLevel; ++_i6) {
                    var _imgSize6 = FormatSize(gpuTexture.format, w, h, 1);
                    var _view6 = new Uint8Array(_imgSize6);
                    gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _i6, gpuTexture.glInternalFmt, w, h, 0, _view6);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                }
              } else {
                WebGL2CmdFuncDestroyTexture(device, gpuTexture);
                WebGL2CmdFuncCreateTexture(device, gpuTexture);
              }
              break;
            }
          default:
            {
              error('Unsupported TextureType, create texture failed.');
              gpuTexture.type = TextureType.TEX2D;
              gpuTexture.glTarget = gl.TEXTURE_2D;
            }
        }
      }
      function WebGL2CmdFuncPrepareSamplerInfo(device, gpuSampler) {
        var gl = device.gl;
        if (gpuSampler.minFilter === Filter$1.LINEAR || gpuSampler.minFilter === Filter$1.ANISOTROPIC) {
          if (gpuSampler.mipFilter === Filter$1.LINEAR || gpuSampler.mipFilter === Filter$1.ANISOTROPIC) {
            gpuSampler.glMinFilter = gl.LINEAR_MIPMAP_LINEAR;
          } else if (gpuSampler.mipFilter === Filter$1.POINT) {
            gpuSampler.glMinFilter = gl.LINEAR_MIPMAP_NEAREST;
          } else {
            gpuSampler.glMinFilter = gl.LINEAR;
          }
        } else if (gpuSampler.mipFilter === Filter$1.LINEAR || gpuSampler.mipFilter === Filter$1.ANISOTROPIC) {
          gpuSampler.glMinFilter = gl.NEAREST_MIPMAP_LINEAR;
        } else if (gpuSampler.mipFilter === Filter$1.POINT) {
          gpuSampler.glMinFilter = gl.NEAREST_MIPMAP_NEAREST;
        } else {
          gpuSampler.glMinFilter = gl.NEAREST;
        }
        if (gpuSampler.magFilter === Filter$1.LINEAR || gpuSampler.magFilter === Filter$1.ANISOTROPIC) {
          gpuSampler.glMagFilter = gl.LINEAR;
        } else {
          gpuSampler.glMagFilter = gl.NEAREST;
        }
        gpuSampler.glWrapS = WebGLWraps[gpuSampler.addressU];
        gpuSampler.glWrapT = WebGLWraps[gpuSampler.addressV];
        gpuSampler.glWrapR = WebGLWraps[gpuSampler.addressW];
      }
      function WebGL2CmdFuncDestroySampler(device, gpuSampler) {
        var gl = device.gl;
        var it = gpuSampler.glSamplers.values();
        var res = it.next();
        while (!res.done) {
          gl.deleteSampler(res.value);
          var glSamplerUnits = device.stateCache.glSamplerUnits;
          for (var i = 0; i < glSamplerUnits.length; ++i) {
            if (glSamplerUnits[i] === res.value) {
              gl.bindSampler(i, null);
              glSamplerUnits[i] = null;
            }
          }
        }
        gpuSampler.glSamplers.clear();
      }
      function WebGL2CmdFuncCreateFramebuffer(device, gpuFramebuffer) {
        for (var i = 0; i < gpuFramebuffer.gpuColorViews.length; ++i) {
          var tex = gpuFramebuffer.gpuColorViews[i].gpuTexture;
          if (tex.isSwapchainTexture) {
            gpuFramebuffer.isOffscreen = false;
            return;
          }
        }
        var gl = device.gl;
        var attachments = [];
        var glFramebuffer = gl.createFramebuffer();
        if (glFramebuffer) {
          gpuFramebuffer.glFramebuffer = glFramebuffer;
          if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer);
          }
          for (var _i7 = 0; _i7 < gpuFramebuffer.gpuColorViews.length; ++_i7) {
            var colorTextureView = gpuFramebuffer.gpuColorViews[_i7];
            var colorTexture = colorTextureView.gpuTexture;
            if (colorTexture) {
              if (colorTexture.glTexture) {
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + _i7, colorTexture.glTarget, colorTexture.glTexture, colorTextureView.baseLevel);
              } else {
                gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + _i7, gl.RENDERBUFFER, colorTexture.glRenderbuffer);
              }
              attachments.push(gl.COLOR_ATTACHMENT0 + _i7);
              gpuFramebuffer.width = Math.min(gpuFramebuffer.width, colorTexture.width >> colorTextureView.baseLevel);
              gpuFramebuffer.height = Math.min(gpuFramebuffer.height, colorTexture.height >> colorTextureView.baseLevel);
            }
          }
          var dstView = gpuFramebuffer.gpuDepthStencilView;
          if (dstView) {
            var dst = dstView.gpuTexture;
            var glAttachment = FormatInfos[dst.format].hasStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
            if (dst.glTexture) {
              gl.framebufferTexture2D(gl.FRAMEBUFFER, glAttachment, dst.glTarget, dst.glTexture, gpuFramebuffer.gpuDepthStencilView.baseLevel);
            } else {
              gl.framebufferRenderbuffer(gl.FRAMEBUFFER, glAttachment, gl.RENDERBUFFER, dst.glRenderbuffer);
            }
            gpuFramebuffer.width = Math.min(gpuFramebuffer.width, dst.width >> dstView.baseLevel);
            gpuFramebuffer.height = Math.min(gpuFramebuffer.height, dst.height >> dstView.baseLevel);
          }
          gl.drawBuffers(attachments);
          var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
          if (status !== gl.FRAMEBUFFER_COMPLETE) {
            switch (status) {
              case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT');
                  break;
                }
              case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT');
                  break;
                }
              case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS');
                  break;
                }
              case gl.FRAMEBUFFER_UNSUPPORTED:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED');
                  break;
                }
            }
          }
          if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, device.stateCache.glFramebuffer);
          }
        }
      }
      function WebGL2CmdFuncDestroyFramebuffer(device, gpuFramebuffer) {
        if (gpuFramebuffer.glFramebuffer) {
          device.gl.deleteFramebuffer(gpuFramebuffer.glFramebuffer);
          if (device.stateCache.glFramebuffer === gpuFramebuffer.glFramebuffer) {
            device.gl.bindFramebuffer(device.gl.FRAMEBUFFER, null);
            device.stateCache.glFramebuffer = null;
          }
          gpuFramebuffer.glFramebuffer = null;
        }
      }
      function WebGL2CmdFuncCreateShader(device, gpuShader) {
        var gl = device.gl;
        var _loop = function _loop() {
            var gpuStage = gpuShader.gpuStages[k];
            var glShaderType = 0;
            var shaderTypeStr = '';
            var lineNumber = 1;
            switch (gpuStage.type) {
              case ShaderStageFlagBit.VERTEX:
                {
                  shaderTypeStr = 'VertexShader';
                  glShaderType = gl.VERTEX_SHADER;
                  break;
                }
              case ShaderStageFlagBit.FRAGMENT:
                {
                  shaderTypeStr = 'FragmentShader';
                  glShaderType = gl.FRAGMENT_SHADER;
                  break;
                }
              default:
                {
                  error('Unsupported ShaderType.');
                  return {
                    v: void 0
                  };
                }
            }
            var glShader = gl.createShader(glShaderType);
            if (glShader) {
              gpuStage.glShader = glShader;
              gl.shaderSource(gpuStage.glShader, "#version 300 es\n" + gpuStage.source);
              gl.compileShader(gpuStage.glShader);
              if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) {
                error(shaderTypeStr + " in '" + gpuShader.name + "' compilation failed.");
                error('Shader source dump:', gpuStage.source.replace(/^|\n/g, function () {
                  return "\n" + lineNumber++ + " ";
                }));
                error(gl.getShaderInfoLog(gpuStage.glShader));
                for (var l = 0; l < gpuShader.gpuStages.length; l++) {
                  var stage = gpuShader.gpuStages[k];
                  if (stage.glShader) {
                    gl.deleteShader(stage.glShader);
                    stage.glShader = null;
                  }
                }
                return {
                  v: void 0
                };
              }
            }
          },
          _ret;
        for (var k = 0; k < gpuShader.gpuStages.length; k++) {
          _ret = _loop();
          if (_ret) return _ret.v;
        }
        var glProgram = gl.createProgram();
        if (!glProgram) {
          return;
        }
        gpuShader.glProgram = glProgram;
        var enableEffectImport = !!(legacyCC.rendering && legacyCC.rendering.enableEffectImport);
        for (var _k = 0; _k < gpuShader.gpuStages.length; _k++) {
          var gpuStage = gpuShader.gpuStages[_k];
          gl.attachShader(gpuShader.glProgram, gpuStage.glShader);
        }
        gl.linkProgram(gpuShader.glProgram);
        for (var _k2 = 0; _k2 < gpuShader.gpuStages.length; _k2++) {
          var _gpuStage = gpuShader.gpuStages[_k2];
          if (_gpuStage.glShader) {
            gl.detachShader(gpuShader.glProgram, _gpuStage.glShader);
            gl.deleteShader(_gpuStage.glShader);
            _gpuStage.glShader = null;
          }
        }
        if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) {
          debug("Shader '" + gpuShader.name + "' compilation succeeded.");
        } else {
          error("Failed to link shader '" + gpuShader.name + "'.");
          error(gl.getProgramInfoLog(gpuShader.glProgram));
          return;
        }
        var activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES);
        gpuShader.glInputs = new Array(activeAttribCount);
        for (var i = 0; i < activeAttribCount; ++i) {
          var attribInfo = gl.getActiveAttrib(gpuShader.glProgram, i);
          if (attribInfo) {
            var varName = void 0;
            var nameOffset = attribInfo.name.indexOf('[');
            if (nameOffset !== -1) {
              varName = attribInfo.name.substr(0, nameOffset);
            } else {
              varName = attribInfo.name;
            }
            var glLoc = gl.getAttribLocation(gpuShader.glProgram, varName);
            var type = WebGLTypeToGFXType(attribInfo.type, gl);
            var stride = WebGLGetTypeSize(attribInfo.type, gl);
            gpuShader.glInputs[i] = {
              name: varName,
              type: type,
              stride: stride,
              count: attribInfo.size,
              size: stride * attribInfo.size,
              glType: attribInfo.type,
              glLoc: glLoc
            };
          }
        }
        var activeBlockCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORM_BLOCKS);
        var blockName;
        var blockIdx;
        var blockSize;
        var block;
        if (activeBlockCount) {
          gpuShader.glBlocks = new Array(activeBlockCount);
          for (var b = 0; b < activeBlockCount; ++b) {
            blockName = gl.getActiveUniformBlockName(gpuShader.glProgram, b);
            var _nameOffset = blockName.indexOf('[');
            if (_nameOffset !== -1) {
              blockName = blockName.substr(0, _nameOffset);
            }
            block = null;
            for (var _k3 = 0; _k3 < gpuShader.blocks.length; _k3++) {
              if (gpuShader.blocks[_k3].name === blockName) {
                block = gpuShader.blocks[_k3];
                break;
              }
            }
            if (!block) {
              error("Block '" + blockName + "' does not bound");
            } else {
              blockIdx = b;
              blockSize = gl.getActiveUniformBlockParameter(gpuShader.glProgram, blockIdx, gl.UNIFORM_BLOCK_DATA_SIZE);
              var glBinding = enableEffectImport ? block.flattened : block.binding + (device.bindingMappings.blockOffsets[block.set] || 0);
              gl.uniformBlockBinding(gpuShader.glProgram, blockIdx, glBinding);
              gpuShader.glBlocks[b] = {
                set: block.set,
                binding: block.binding,
                idx: blockIdx,
                name: blockName,
                size: blockSize,
                glBinding: glBinding
              };
            }
          }
        }
        for (var _i8 = 0; _i8 < gpuShader.subpassInputs.length; ++_i8) {
          var subpassInput = gpuShader.subpassInputs[_i8];
          gpuShader.samplerTextures.push(new UniformSamplerTexture(subpassInput.set, subpassInput.binding, subpassInput.name, Type$1.SAMPLER2D, subpassInput.count));
        }
        if (gpuShader.samplerTextures.length > 0) {
          gpuShader.glSamplerTextures = new Array(gpuShader.samplerTextures.length);
          for (var _i9 = 0; _i9 < gpuShader.samplerTextures.length; ++_i9) {
            var sampler = gpuShader.samplerTextures[_i9];
            gpuShader.glSamplerTextures[_i9] = {
              set: sampler.set,
              binding: sampler.binding,
              name: sampler.name,
              type: sampler.type,
              count: sampler.count,
              units: [],
              glUnits: null,
              glType: GFXTypeToWebGLType(sampler.type, gl),
              glLoc: null
            };
          }
        }
        var glActiveSamplers = [];
        var glActiveSamplerLocations = [];
        var texUnitCacheMap = device.stateCache.texUnitCacheMap;
        if (!enableEffectImport) {
          var flexibleSetBaseOffset = 0;
          for (var _i10 = 0; _i10 < gpuShader.blocks.length; ++_i10) {
            if (gpuShader.blocks[_i10].set === device.bindingMappings.flexibleSet) {
              flexibleSetBaseOffset++;
            }
          }
          var arrayOffset = 0;
          for (var _i11 = 0; _i11 < gpuShader.samplerTextures.length; ++_i11) {
            var _sampler = gpuShader.samplerTextures[_i11];
            var _glLoc = gl.getUniformLocation(gpuShader.glProgram, _sampler.name);
            if (_glLoc && _glLoc.id !== -1) {
              glActiveSamplers.push(gpuShader.glSamplerTextures[_i11]);
              glActiveSamplerLocations.push(_glLoc);
            }
            if (texUnitCacheMap[_sampler.name] === undefined) {
              var binding = _sampler.binding + device.bindingMappings.samplerTextureOffsets[_sampler.set] + arrayOffset;
              if (_sampler.set === device.bindingMappings.flexibleSet) {
                binding -= flexibleSetBaseOffset;
              }
              texUnitCacheMap[_sampler.name] = binding % device.capabilities.maxTextureUnits;
              arrayOffset += _sampler.count - 1;
            }
          }
        } else {
          for (var _i12 = 0; _i12 < gpuShader.samplerTextures.length; ++_i12) {
            var _sampler2 = gpuShader.samplerTextures[_i12];
            var _glLoc2 = gl.getUniformLocation(gpuShader.glProgram, _sampler2.name);
            if (_glLoc2 && _glLoc2.id !== -1) {
              glActiveSamplers.push(gpuShader.glSamplerTextures[_i12]);
              glActiveSamplerLocations.push(_glLoc2);
            }
            if (texUnitCacheMap[_sampler2.name] === undefined) {
              texUnitCacheMap[_sampler2.name] = _sampler2.flattened % device.capabilities.maxTextureUnits;
            }
          }
        }
        if (glActiveSamplers.length) {
          var usedTexUnits = [];
          for (var _i13 = 0; _i13 < glActiveSamplers.length; ++_i13) {
            var glSampler = glActiveSamplers[_i13];
            var cachedUnit = texUnitCacheMap[glSampler.name];
            if (cachedUnit !== undefined) {
              glSampler.glLoc = glActiveSamplerLocations[_i13];
              for (var t = 0; t < glSampler.count; ++t) {
                while (usedTexUnits[cachedUnit]) {
                  cachedUnit = (cachedUnit + 1) % device.capabilities.maxTextureUnits;
                }
                glSampler.units.push(cachedUnit);
                usedTexUnits[cachedUnit] = true;
              }
            }
          }
          var unitIdx = 0;
          for (var _i14 = 0; _i14 < glActiveSamplers.length; ++_i14) {
            var _glSampler = glActiveSamplers[_i14];
            if (!_glSampler.glLoc) {
              _glSampler.glLoc = glActiveSamplerLocations[_i14];
              while (usedTexUnits[unitIdx]) {
                unitIdx++;
              }
              for (var _t = 0; _t < _glSampler.count; ++_t) {
                while (usedTexUnits[unitIdx]) {
                  unitIdx = (unitIdx + 1) % device.capabilities.maxTextureUnits;
                }
                if (texUnitCacheMap[_glSampler.name] === undefined) {
                  texUnitCacheMap[_glSampler.name] = unitIdx;
                }
                _glSampler.units.push(unitIdx);
                usedTexUnits[unitIdx] = true;
              }
            }
          }
          if (device.stateCache.glProgram !== gpuShader.glProgram) {
            gl.useProgram(gpuShader.glProgram);
          }
          for (var _k4 = 0; _k4 < glActiveSamplers.length; _k4++) {
            var _glSampler2 = glActiveSamplers[_k4];
            _glSampler2.glUnits = new Int32Array(_glSampler2.units);
            gl.uniform1iv(_glSampler2.glLoc, _glSampler2.glUnits);
          }
          if (device.stateCache.glProgram !== gpuShader.glProgram) {
            gl.useProgram(device.stateCache.glProgram);
          }
        }
        gpuShader.glSamplerTextures = glActiveSamplers;
      }
      function WebGL2CmdFuncDestroyShader(device, gpuShader) {
        if (gpuShader.glProgram) {
          device.gl.deleteProgram(gpuShader.glProgram);
          if (device.stateCache.glProgram === gpuShader.glProgram) {
            device.gl.useProgram(null);
            device.stateCache.glProgram = null;
          }
          gpuShader.glProgram = null;
        }
      }
      function WebGL2CmdFuncCreateInputAssember(device, gpuInputAssembler) {
        var gl = device.gl;
        gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length);
        var offsets = [0, 0, 0, 0, 0, 0, 0, 0];
        for (var i = 0; i < gpuInputAssembler.attributes.length; ++i) {
          var attrib = gpuInputAssembler.attributes[i];
          var stream = attrib.stream !== undefined ? attrib.stream : 0;
          var gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream];
          var glType = GFXFormatToWebGLType(attrib.format, gl);
          var size = FormatInfos[attrib.format].size;
          gpuInputAssembler.glAttribs[i] = {
            name: attrib.name,
            glBuffer: gpuBuffer.glBuffer,
            glType: glType,
            size: size,
            count: FormatInfos[attrib.format].count,
            stride: gpuBuffer.stride,
            componentCount: WebGLGetComponentCount(glType, gl),
            isNormalized: attrib.isNormalized !== undefined ? attrib.isNormalized : false,
            isInstanced: attrib.isInstanced !== undefined ? attrib.isInstanced : false,
            offset: offsets[stream]
          };
          offsets[stream] += size;
        }
      }
      function WebGL2CmdFuncDestroyInputAssembler(device, gpuInputAssembler) {
        var it = gpuInputAssembler.glVAOs.values();
        var res = it.next();
        var gl = device.gl;
        var glVAO = device.stateCache.glVAO;
        while (!res.done) {
          gl.deleteVertexArray(res.value);
          if (glVAO === res.value) {
            gl.bindVertexArray(null);
            glVAO = null;
          }
          res = it.next();
        }
        device.stateCache.glVAO = glVAO;
        gpuInputAssembler.glVAOs.clear();
      }
      var gfxStateCache = {
        gpuPipelineState: null,
        gpuInputAssembler: null,
        glPrimitive: 0,
        invalidateAttachments: []
      };
      function WebGL2CmdFuncBeginRenderPass(device, gpuRenderPass, gpuFramebuffer, renderArea, clearColors, clearDepth, clearStencil) {
        var gl = device.gl;
        var cache = device.stateCache;
        var clears = 0;
        if (gpuFramebuffer && gpuRenderPass) {
          if (cache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer);
            cache.glFramebuffer = gpuFramebuffer.glFramebuffer;
          }
          if (cache.viewport.left !== renderArea.x || cache.viewport.top !== renderArea.y || cache.viewport.width !== renderArea.width || cache.viewport.height !== renderArea.height) {
            gl.viewport(renderArea.x, renderArea.y, renderArea.width, renderArea.height);
            cache.viewport.left = renderArea.x;
            cache.viewport.top = renderArea.y;
            cache.viewport.width = renderArea.width;
            cache.viewport.height = renderArea.height;
          }
          if (cache.scissorRect.x !== renderArea.x || cache.scissorRect.y !== renderArea.y || cache.scissorRect.width !== renderArea.width || cache.scissorRect.height !== renderArea.height) {
            gl.scissor(renderArea.x, renderArea.y, renderArea.width, renderArea.height);
            cache.scissorRect.x = renderArea.x;
            cache.scissorRect.y = renderArea.y;
            cache.scissorRect.width = renderArea.width;
            cache.scissorRect.height = renderArea.height;
          }
          gfxStateCache.invalidateAttachments.length = 0;
          for (var j = 0; j < clearColors.length; ++j) {
            var colorAttachment = gpuRenderPass.colorAttachments[j];
            if (colorAttachment.format !== Format.UNKNOWN) {
              switch (colorAttachment.loadOp) {
                case LoadOp.LOAD:
                  break;
                case LoadOp.CLEAR:
                  {
                    if (cache.bs.targets[0].blendColorMask !== ColorMask.ALL) {
                      gl.colorMask(true, true, true, true);
                    }
                    if (gpuRenderPass.colorAttachments.length === 1) {
                      var clearColor = clearColors[0];
                      gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
                      clears |= gl.COLOR_BUFFER_BIT;
                    } else {
                      _f32v4[0] = clearColors[j].x;
                      _f32v4[1] = clearColors[j].y;
                      _f32v4[2] = clearColors[j].z;
                      _f32v4[3] = clearColors[j].w;
                      gl.clearBufferfv(gl.COLOR, j, _f32v4);
                    }
                    break;
                  }
                case LoadOp.DISCARD:
                  {
                    gfxStateCache.invalidateAttachments.push(gl.COLOR_ATTACHMENT0 + j);
                    break;
                  }
              }
            }
          }
          if (gpuRenderPass.depthStencilAttachment) {
            if (gpuRenderPass.depthStencilAttachment.format !== Format.UNKNOWN) {
              switch (gpuRenderPass.depthStencilAttachment.depthLoadOp) {
                case LoadOp.LOAD:
                  break;
                case LoadOp.CLEAR:
                  {
                    if (!cache.dss.depthWrite) {
                      gl.depthMask(true);
                    }
                    gl.clearDepth(clearDepth);
                    clears |= gl.DEPTH_BUFFER_BIT;
                    break;
                  }
                case LoadOp.DISCARD:
                  {
                    gfxStateCache.invalidateAttachments.push(gl.DEPTH_ATTACHMENT);
                    break;
                  }
              }
              if (FormatInfos[gpuRenderPass.depthStencilAttachment.format].hasStencil) {
                switch (gpuRenderPass.depthStencilAttachment.stencilLoadOp) {
                  case LoadOp.LOAD:
                    break;
                  case LoadOp.CLEAR:
                    {
                      if (!cache.dss.stencilWriteMaskFront) {
                        gl.stencilMaskSeparate(gl.FRONT, 0xffff);
                      }
                      if (!cache.dss.stencilWriteMaskBack) {
                        gl.stencilMaskSeparate(gl.BACK, 0xffff);
                      }
                      gl.clearStencil(clearStencil);
                      clears |= gl.STENCIL_BUFFER_BIT;
                      break;
                    }
                  case LoadOp.DISCARD:
                    {
                      gfxStateCache.invalidateAttachments.push(gl.STENCIL_ATTACHMENT);
                      break;
                    }
                }
              }
            }
          }
          if (gpuFramebuffer.glFramebuffer && gfxStateCache.invalidateAttachments.length) {
            gl.invalidateFramebuffer(gl.FRAMEBUFFER, gfxStateCache.invalidateAttachments);
          }
          if (clears) {
            gl.clear(clears);
          }
          if (clears & gl.COLOR_BUFFER_BIT) {
            var colorMask = cache.bs.targets[0].blendColorMask;
            if (colorMask !== ColorMask.ALL) {
              var r = (colorMask & ColorMask.R) !== ColorMask.NONE;
              var g = (colorMask & ColorMask.G) !== ColorMask.NONE;
              var b = (colorMask & ColorMask.B) !== ColorMask.NONE;
              var a = (colorMask & ColorMask.A) !== ColorMask.NONE;
              gl.colorMask(r, g, b, a);
            }
          }
          if (clears & gl.DEPTH_BUFFER_BIT && !cache.dss.depthWrite) {
            gl.depthMask(false);
          }
          if (clears & gl.STENCIL_BUFFER_BIT) {
            if (!cache.dss.stencilWriteMaskFront) {
              gl.stencilMaskSeparate(gl.FRONT, 0);
            }
            if (!cache.dss.stencilWriteMaskBack) {
              gl.stencilMaskSeparate(gl.BACK, 0);
            }
          }
        }
      }
      function WebGL2CmdFuncBindStates(device, gpuPipelineState, gpuInputAssembler, gpuDescriptorSets, dynamicOffsets, dynamicStates) {
        var gl = device.gl;
        var cache = device.stateCache;
        var gpuShader = gpuPipelineState && gpuPipelineState.gpuShader;
        var isShaderChanged = false;
        if (gpuPipelineState && gfxStateCache.gpuPipelineState !== gpuPipelineState) {
          gfxStateCache.gpuPipelineState = gpuPipelineState;
          gfxStateCache.glPrimitive = gpuPipelineState.glPrimitive;
          if (gpuShader) {
            var glProgram = gpuShader.glProgram;
            if (cache.glProgram !== glProgram) {
              gl.useProgram(glProgram);
              cache.glProgram = glProgram;
              isShaderChanged = true;
            }
          }
          var rs = gpuPipelineState.rs;
          if (rs) {
            if (cache.rs.cullMode !== rs.cullMode) {
              switch (rs.cullMode) {
                case CullMode.NONE:
                  {
                    gl.disable(gl.CULL_FACE);
                    break;
                  }
                case CullMode.FRONT:
                  {
                    gl.enable(gl.CULL_FACE);
                    gl.cullFace(gl.FRONT);
                    break;
                  }
                case CullMode.BACK:
                  {
                    gl.enable(gl.CULL_FACE);
                    gl.cullFace(gl.BACK);
                    break;
                  }
              }
              device.stateCache.rs.cullMode = rs.cullMode;
            }
            var isFrontFaceCCW = rs.isFrontFaceCCW;
            if (device.stateCache.rs.isFrontFaceCCW !== isFrontFaceCCW) {
              gl.frontFace(isFrontFaceCCW ? gl.CCW : gl.CW);
              device.stateCache.rs.isFrontFaceCCW = isFrontFaceCCW;
            }
            if (device.stateCache.rs.depthBias !== rs.depthBias || device.stateCache.rs.depthBiasSlop !== rs.depthBiasSlop) {
              gl.polygonOffset(rs.depthBias, rs.depthBiasSlop);
              device.stateCache.rs.depthBias = rs.depthBias;
              device.stateCache.rs.depthBiasSlop = rs.depthBiasSlop;
            }
            if (device.stateCache.rs.lineWidth !== rs.lineWidth) {
              gl.lineWidth(rs.lineWidth);
              device.stateCache.rs.lineWidth = rs.lineWidth;
            }
          }
          var dss = gpuPipelineState.dss;
          if (dss) {
            if (cache.dss.depthTest !== dss.depthTest) {
              if (dss.depthTest) {
                gl.enable(gl.DEPTH_TEST);
              } else {
                gl.disable(gl.DEPTH_TEST);
              }
              cache.dss.depthTest = dss.depthTest;
            }
            if (cache.dss.depthWrite !== dss.depthWrite) {
              gl.depthMask(dss.depthWrite);
              cache.dss.depthWrite = dss.depthWrite;
            }
            if (cache.dss.depthFunc !== dss.depthFunc) {
              gl.depthFunc(WebGLCmpFuncs[dss.depthFunc]);
              cache.dss.depthFunc = dss.depthFunc;
            }
            if (cache.dss.stencilTestFront !== dss.stencilTestFront || cache.dss.stencilTestBack !== dss.stencilTestBack) {
              if (dss.stencilTestFront || dss.stencilTestBack) {
                gl.enable(gl.STENCIL_TEST);
              } else {
                gl.disable(gl.STENCIL_TEST);
              }
              cache.dss.stencilTestFront = dss.stencilTestFront;
              cache.dss.stencilTestBack = dss.stencilTestBack;
            }
            if (cache.dss.stencilFuncFront !== dss.stencilFuncFront || cache.dss.stencilRefFront !== dss.stencilRefFront || cache.dss.stencilReadMaskFront !== dss.stencilReadMaskFront) {
              gl.stencilFuncSeparate(gl.FRONT, WebGLCmpFuncs[dss.stencilFuncFront], dss.stencilRefFront, dss.stencilReadMaskFront);
              cache.dss.stencilFuncFront = dss.stencilFuncFront;
              cache.dss.stencilRefFront = dss.stencilRefFront;
              cache.dss.stencilReadMaskFront = dss.stencilReadMaskFront;
            }
            if (cache.dss.stencilFailOpFront !== dss.stencilFailOpFront || cache.dss.stencilZFailOpFront !== dss.stencilZFailOpFront || cache.dss.stencilPassOpFront !== dss.stencilPassOpFront) {
              gl.stencilOpSeparate(gl.FRONT, WebGLStencilOps[dss.stencilFailOpFront], WebGLStencilOps[dss.stencilZFailOpFront], WebGLStencilOps[dss.stencilPassOpFront]);
              cache.dss.stencilFailOpFront = dss.stencilFailOpFront;
              cache.dss.stencilZFailOpFront = dss.stencilZFailOpFront;
              cache.dss.stencilPassOpFront = dss.stencilPassOpFront;
            }
            if (cache.dss.stencilWriteMaskFront !== dss.stencilWriteMaskFront) {
              gl.stencilMaskSeparate(gl.FRONT, dss.stencilWriteMaskFront);
              cache.dss.stencilWriteMaskFront = dss.stencilWriteMaskFront;
            }
            if (cache.dss.stencilFuncBack !== dss.stencilFuncBack || cache.dss.stencilRefBack !== dss.stencilRefBack || cache.dss.stencilReadMaskBack !== dss.stencilReadMaskBack) {
              gl.stencilFuncSeparate(gl.BACK, WebGLCmpFuncs[dss.stencilFuncBack], dss.stencilRefBack, dss.stencilReadMaskBack);
              cache.dss.stencilFuncBack = dss.stencilFuncBack;
              cache.dss.stencilRefBack = dss.stencilRefBack;
              cache.dss.stencilReadMaskBack = dss.stencilReadMaskBack;
            }
            if (cache.dss.stencilFailOpBack !== dss.stencilFailOpBack || cache.dss.stencilZFailOpBack !== dss.stencilZFailOpBack || cache.dss.stencilPassOpBack !== dss.stencilPassOpBack) {
              gl.stencilOpSeparate(gl.BACK, WebGLStencilOps[dss.stencilFailOpBack], WebGLStencilOps[dss.stencilZFailOpBack], WebGLStencilOps[dss.stencilPassOpBack]);
              cache.dss.stencilFailOpBack = dss.stencilFailOpBack;
              cache.dss.stencilZFailOpBack = dss.stencilZFailOpBack;
              cache.dss.stencilPassOpBack = dss.stencilPassOpBack;
            }
            if (cache.dss.stencilWriteMaskBack !== dss.stencilWriteMaskBack) {
              gl.stencilMaskSeparate(gl.BACK, dss.stencilWriteMaskBack);
              cache.dss.stencilWriteMaskBack = dss.stencilWriteMaskBack;
            }
          }
          var bs = gpuPipelineState.bs;
          if (bs) {
            if (cache.bs.isA2C !== bs.isA2C) {
              if (bs.isA2C) {
                gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE);
              } else {
                gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
              }
              cache.bs.isA2C = bs.isA2C;
            }
            if (cache.bs.blendColor.x !== bs.blendColor.x || cache.bs.blendColor.y !== bs.blendColor.y || cache.bs.blendColor.z !== bs.blendColor.z || cache.bs.blendColor.w !== bs.blendColor.w) {
              gl.blendColor(bs.blendColor.x, bs.blendColor.y, bs.blendColor.z, bs.blendColor.w);
              cache.bs.blendColor.x = bs.blendColor.x;
              cache.bs.blendColor.y = bs.blendColor.y;
              cache.bs.blendColor.z = bs.blendColor.z;
              cache.bs.blendColor.w = bs.blendColor.w;
            }
            var target0 = bs.targets[0];
            var target0Cache = cache.bs.targets[0];
            if (target0Cache.blend !== target0.blend) {
              if (target0.blend) {
                gl.enable(gl.BLEND);
              } else {
                gl.disable(gl.BLEND);
              }
              target0Cache.blend = target0.blend;
            }
            if (target0Cache.blendEq !== target0.blendEq || target0Cache.blendAlphaEq !== target0.blendAlphaEq) {
              gl.blendEquationSeparate(WebGLBlendOps[target0.blendEq], WebGLBlendOps[target0.blendAlphaEq]);
              target0Cache.blendEq = target0.blendEq;
              target0Cache.blendAlphaEq = target0.blendAlphaEq;
            }
            if (target0Cache.blendSrc !== target0.blendSrc || target0Cache.blendDst !== target0.blendDst || target0Cache.blendSrcAlpha !== target0.blendSrcAlpha || target0Cache.blendDstAlpha !== target0.blendDstAlpha) {
              gl.blendFuncSeparate(WebGLBlendFactors[target0.blendSrc], WebGLBlendFactors[target0.blendDst], WebGLBlendFactors[target0.blendSrcAlpha], WebGLBlendFactors[target0.blendDstAlpha]);
              target0Cache.blendSrc = target0.blendSrc;
              target0Cache.blendDst = target0.blendDst;
              target0Cache.blendSrcAlpha = target0.blendSrcAlpha;
              target0Cache.blendDstAlpha = target0.blendDstAlpha;
            }
            if (target0Cache.blendColorMask !== target0.blendColorMask) {
              gl.colorMask((target0.blendColorMask & ColorMask.R) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.G) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.B) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.A) !== ColorMask.NONE);
              target0Cache.blendColorMask = target0.blendColorMask;
            }
          }
        }
        if (gpuPipelineState && gpuPipelineState.gpuPipelineLayout && gpuShader) {
          var blockLen = gpuShader.glBlocks.length;
          var dynamicOffsetIndices = gpuPipelineState.gpuPipelineLayout.dynamicOffsetIndices;
          for (var j = 0; j < blockLen; j++) {
            var glBlock = gpuShader.glBlocks[j];
            var gpuDescriptorSet = gpuDescriptorSets[glBlock.set];
            var descriptorIndex = gpuDescriptorSet && gpuDescriptorSet.descriptorIndices[glBlock.binding];
            var gpuDescriptor = descriptorIndex >= 0 && gpuDescriptorSet.gpuDescriptors[descriptorIndex];
            if (!gpuDescriptor || !gpuDescriptor.gpuBuffer) {
              continue;
            }
            var dynamicOffsetIndexSet = dynamicOffsetIndices[glBlock.set];
            var dynamicOffsetIndex = dynamicOffsetIndexSet && dynamicOffsetIndexSet[glBlock.binding];
            var offset = gpuDescriptor.gpuBuffer.glOffset;
            if (dynamicOffsetIndex >= 0) {
              offset += dynamicOffsets[dynamicOffsetIndex];
            }
            if (cache.glBindUBOs[glBlock.glBinding] !== gpuDescriptor.gpuBuffer.glBuffer || cache.glBindUBOOffsets[glBlock.glBinding] !== offset) {
              if (offset) {
                gl.bindBufferRange(gl.UNIFORM_BUFFER, glBlock.glBinding, gpuDescriptor.gpuBuffer.glBuffer, offset, gpuDescriptor.gpuBuffer.size);
              } else {
                gl.bindBufferBase(gl.UNIFORM_BUFFER, glBlock.glBinding, gpuDescriptor.gpuBuffer.glBuffer);
              }
              cache.glUniformBuffer = cache.glBindUBOs[glBlock.glBinding] = gpuDescriptor.gpuBuffer.glBuffer;
              cache.glBindUBOOffsets[glBlock.glBinding] = offset;
            }
          }
          var samplerLen = gpuShader.glSamplerTextures.length;
          for (var i = 0; i < samplerLen; i++) {
            var glSampler = gpuShader.glSamplerTextures[i];
            var _gpuDescriptorSet = gpuDescriptorSets[glSampler.set];
            var _descriptorIndex = _gpuDescriptorSet && _gpuDescriptorSet.descriptorIndices[glSampler.binding];
            var _gpuDescriptor = _descriptorIndex >= 0 && _gpuDescriptorSet.gpuDescriptors[_descriptorIndex];
            for (var l = 0; l < glSampler.units.length; l++) {
              var texUnit = glSampler.units[l];
              var glTexUnit = cache.glTexUnits[texUnit];
              if (!_gpuDescriptor || !_gpuDescriptor.gpuTextureView || !_gpuDescriptor.gpuTextureView.gpuTexture || !_gpuDescriptor.gpuSampler) {
                continue;
              }
              var gpuTextureView = _gpuDescriptor.gpuTextureView;
              var gpuTexture = gpuTextureView.gpuTexture;
              var minLod = gpuTextureView.baseLevel;
              var maxLod = minLod + gpuTextureView.levelCount;
              if (gpuTexture.size > 0) {
                if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  if (gpuTexture.glTexture) {
                    gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
                  } else {
                    gl.bindTexture(gpuTexture.glTarget, device.nullTex2D.gpuTexture.glTexture);
                  }
                  glTexUnit.glTexture = gpuTexture.glTexture;
                }
                var _gpuDescriptor2 = _gpuDescriptor,
                  gpuSampler = _gpuDescriptor2.gpuSampler;
                var _glSampler3 = gpuSampler.getGLSampler(device, minLod, maxLod);
                if (cache.glSamplerUnits[texUnit] !== _glSampler3) {
                  gl.bindSampler(texUnit, _glSampler3);
                  cache.glSamplerUnits[texUnit] = _glSampler3;
                }
              }
              _gpuDescriptor = _gpuDescriptorSet.gpuDescriptors[++_descriptorIndex];
            }
          }
        }
        if (gpuInputAssembler && gpuShader && (isShaderChanged || gfxStateCache.gpuInputAssembler !== gpuInputAssembler)) {
          gfxStateCache.gpuInputAssembler = gpuInputAssembler;
          if (device.extensions.useVAO) {
            var glVAO = gpuInputAssembler.glVAOs.get(gpuShader.glProgram);
            if (!glVAO) {
              glVAO = gl.createVertexArray();
              gpuInputAssembler.glVAOs.set(gpuShader.glProgram, glVAO);
              gl.bindVertexArray(glVAO);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              cache.glArrayBuffer = null;
              cache.glElementArrayBuffer = null;
              var glAttrib;
              for (var _j = 0; _j < gpuShader.glInputs.length; _j++) {
                var glInput = gpuShader.glInputs[_j];
                glAttrib = null;
                for (var k = 0; k < gpuInputAssembler.glAttribs.length; k++) {
                  var attrib = gpuInputAssembler.glAttribs[k];
                  if (attrib.name === glInput.name) {
                    glAttrib = attrib;
                    break;
                  }
                }
                if (glAttrib) {
                  if (cache.glArrayBuffer !== glAttrib.glBuffer) {
                    gl.bindBuffer(gl.ARRAY_BUFFER, glAttrib.glBuffer);
                    cache.glArrayBuffer = glAttrib.glBuffer;
                  }
                  for (var c = 0; c < glAttrib.componentCount; ++c) {
                    var glLoc = glInput.glLoc + c;
                    var attribOffset = glAttrib.offset + glAttrib.size * c;
                    gl.enableVertexAttribArray(glLoc);
                    cache.glCurrentAttribLocs[glLoc] = true;
                    gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, glAttrib.isNormalized, glAttrib.stride, attribOffset);
                    gl.vertexAttribDivisor(glLoc, glAttrib.isInstanced ? 1 : 0);
                  }
                }
              }
              var gpuBuffer = gpuInputAssembler.gpuIndexBuffer;
              if (gpuBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
              }
              gl.bindVertexArray(null);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              cache.glArrayBuffer = null;
              cache.glElementArrayBuffer = null;
            }
            if (cache.glVAO !== glVAO) {
              gl.bindVertexArray(glVAO);
              cache.glVAO = glVAO;
            }
          } else {
            for (var a = 0; a < device.capabilities.maxVertexAttributes; ++a) {
              cache.glCurrentAttribLocs[a] = false;
            }
            for (var _j2 = 0; _j2 < gpuShader.glInputs.length; _j2++) {
              var _glInput = gpuShader.glInputs[_j2];
              var _glAttrib = null;
              for (var _k5 = 0; _k5 < gpuInputAssembler.glAttribs.length; _k5++) {
                var _attrib = gpuInputAssembler.glAttribs[_k5];
                if (_attrib.name === _glInput.name) {
                  _glAttrib = _attrib;
                  break;
                }
              }
              if (_glAttrib) {
                if (cache.glArrayBuffer !== _glAttrib.glBuffer) {
                  gl.bindBuffer(gl.ARRAY_BUFFER, _glAttrib.glBuffer);
                  cache.glArrayBuffer = _glAttrib.glBuffer;
                }
                for (var _c = 0; _c < _glAttrib.componentCount; ++_c) {
                  var _glLoc3 = _glInput.glLoc + _c;
                  var _attribOffset = _glAttrib.offset + _glAttrib.size * _c;
                  if (!cache.glEnabledAttribLocs[_glLoc3] && _glLoc3 >= 0) {
                    gl.enableVertexAttribArray(_glLoc3);
                    cache.glEnabledAttribLocs[_glLoc3] = true;
                  }
                  cache.glCurrentAttribLocs[_glLoc3] = true;
                  gl.vertexAttribPointer(_glLoc3, _glAttrib.count, _glAttrib.glType, _glAttrib.isNormalized, _glAttrib.stride, _attribOffset);
                  gl.vertexAttribDivisor(_glLoc3, _glAttrib.isInstanced ? 1 : 0);
                }
              }
            }
            var _gpuBuffer = gpuInputAssembler.gpuIndexBuffer;
            if (_gpuBuffer) {
              if (cache.glElementArrayBuffer !== _gpuBuffer.glBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _gpuBuffer.glBuffer);
                cache.glElementArrayBuffer = _gpuBuffer.glBuffer;
              }
            }
            for (var _a = 0; _a < device.capabilities.maxVertexAttributes; ++_a) {
              if (cache.glEnabledAttribLocs[_a] !== cache.glCurrentAttribLocs[_a]) {
                gl.disableVertexAttribArray(_a);
                cache.glEnabledAttribLocs[_a] = false;
              }
            }
          }
        }
        if (gpuPipelineState && gpuPipelineState.dynamicStates.length) {
          var dsLen = gpuPipelineState.dynamicStates.length;
          for (var _k6 = 0; _k6 < dsLen; _k6++) {
            var dynamicState = gpuPipelineState.dynamicStates[_k6];
            switch (dynamicState) {
              case DynamicStateFlagBit.LINE_WIDTH:
                {
                  if (cache.rs.lineWidth !== dynamicStates.lineWidth) {
                    gl.lineWidth(dynamicStates.lineWidth);
                    cache.rs.lineWidth = dynamicStates.lineWidth;
                  }
                  break;
                }
              case DynamicStateFlagBit.DEPTH_BIAS:
                {
                  if (cache.rs.depthBias !== dynamicStates.depthBiasConstant || cache.rs.depthBiasSlop !== dynamicStates.depthBiasSlope) {
                    gl.polygonOffset(dynamicStates.depthBiasConstant, dynamicStates.depthBiasSlope);
                    cache.rs.depthBias = dynamicStates.depthBiasConstant;
                    cache.rs.depthBiasSlop = dynamicStates.depthBiasSlope;
                  }
                  break;
                }
              case DynamicStateFlagBit.BLEND_CONSTANTS:
                {
                  var blendConstant = dynamicStates.blendConstant;
                  if (cache.bs.blendColor.x !== blendConstant.x || cache.bs.blendColor.y !== blendConstant.y || cache.bs.blendColor.z !== blendConstant.z || cache.bs.blendColor.w !== blendConstant.w) {
                    gl.blendColor(blendConstant.x, blendConstant.y, blendConstant.z, blendConstant.w);
                    cache.bs.blendColor.copy(blendConstant);
                  }
                  break;
                }
              case DynamicStateFlagBit.STENCIL_WRITE_MASK:
                {
                  var front = dynamicStates.stencilStatesFront;
                  var back = dynamicStates.stencilStatesBack;
                  if (cache.dss.stencilWriteMaskFront !== front.writeMask) {
                    gl.stencilMaskSeparate(gl.FRONT, front.writeMask);
                    cache.dss.stencilWriteMaskFront = front.writeMask;
                  }
                  if (cache.dss.stencilWriteMaskBack !== back.writeMask) {
                    gl.stencilMaskSeparate(gl.BACK, back.writeMask);
                    cache.dss.stencilWriteMaskBack = back.writeMask;
                  }
                  break;
                }
              case DynamicStateFlagBit.STENCIL_COMPARE_MASK:
                {
                  var _front = dynamicStates.stencilStatesFront;
                  var _back = dynamicStates.stencilStatesBack;
                  if (cache.dss.stencilRefFront !== _front.reference || cache.dss.stencilReadMaskFront !== _front.compareMask) {
                    gl.stencilFuncSeparate(gl.FRONT, WebGLCmpFuncs[cache.dss.stencilFuncFront], _front.reference, _front.compareMask);
                    cache.dss.stencilRefFront = _front.reference;
                    cache.dss.stencilReadMaskFront = _front.compareMask;
                  }
                  if (cache.dss.stencilRefBack !== _back.reference || cache.dss.stencilReadMaskBack !== _back.compareMask) {
                    gl.stencilFuncSeparate(gl.BACK, WebGLCmpFuncs[cache.dss.stencilFuncBack], _back.reference, _back.compareMask);
                    cache.dss.stencilRefBack = _back.reference;
                    cache.dss.stencilReadMaskBack = _back.compareMask;
                  }
                  break;
                }
            }
          }
        }
      }
      function WebGL2CmdFuncDraw(device, drawInfo) {
        var gl = device.gl;
        var gpuInputAssembler = gfxStateCache.gpuInputAssembler,
          glPrimitive = gfxStateCache.glPrimitive;
        var md = device.extensions.WEBGL_multi_draw;
        if (gpuInputAssembler) {
          var indexBuffer = gpuInputAssembler.gpuIndexBuffer;
          if (gpuInputAssembler.gpuIndirectBuffer) {
            var indirects = gpuInputAssembler.gpuIndirectBuffer.indirects;
            if (indirects.drawByIndex) {
              for (var j = 0; j < indirects.drawCount; j++) {
                indirects.byteOffsets[j] = indirects.offsets[j] * indexBuffer.stride;
              }
              if (md) {
                if (indirects.instancedDraw) {
                  md.multiDrawElementsInstancedWEBGL(glPrimitive, indirects.counts, 0, gpuInputAssembler.glIndexType, indirects.byteOffsets, 0, indirects.instances, 0, indirects.drawCount);
                } else {
                  md.multiDrawElementsWEBGL(glPrimitive, indirects.counts, 0, gpuInputAssembler.glIndexType, indirects.byteOffsets, 0, indirects.drawCount);
                }
              } else {
                for (var _j3 = 0; _j3 < indirects.drawCount; _j3++) {
                  if (indirects.instances[_j3]) {
                    gl.drawElementsInstanced(glPrimitive, indirects.counts[_j3], gpuInputAssembler.glIndexType, indirects.byteOffsets[_j3], indirects.instances[_j3]);
                  } else {
                    gl.drawElements(glPrimitive, indirects.counts[_j3], gpuInputAssembler.glIndexType, indirects.byteOffsets[_j3]);
                  }
                }
              }
            } else if (md) {
              if (indirects.instancedDraw) {
                md.multiDrawArraysInstancedWEBGL(glPrimitive, indirects.offsets, 0, indirects.counts, 0, indirects.instances, 0, indirects.drawCount);
              } else {
                md.multiDrawArraysWEBGL(glPrimitive, indirects.offsets, 0, indirects.counts, 0, indirects.drawCount);
              }
            } else {
              for (var _j4 = 0; _j4 < indirects.drawCount; _j4++) {
                if (indirects.instances[_j4]) {
                  gl.drawArraysInstanced(glPrimitive, indirects.offsets[_j4], indirects.counts[_j4], indirects.instances[_j4]);
                } else {
                  gl.drawArrays(glPrimitive, indirects.offsets[_j4], indirects.counts[_j4]);
                }
              }
            }
          } else if (drawInfo.instanceCount) {
            if (indexBuffer) {
              if (drawInfo.indexCount > 0) {
                var offset = drawInfo.firstIndex * indexBuffer.stride;
                gl.drawElementsInstanced(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset, drawInfo.instanceCount);
              }
            } else if (drawInfo.vertexCount > 0) {
              gl.drawArraysInstanced(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount);
            }
          } else if (indexBuffer) {
            if (drawInfo.indexCount > 0) {
              var _offset = drawInfo.firstIndex * indexBuffer.stride;
              gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, _offset);
            }
          } else if (drawInfo.vertexCount > 0) {
            gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount);
          }
        }
      }
      var cmdIds = new Array(WebGL2Cmd.COUNT);
      function WebGL2CmdFuncExecuteCmds(device, cmdPackage) {
        cmdIds.fill(0);
        for (var i = 0; i < cmdPackage.cmds.length; ++i) {
          var cmd = cmdPackage.cmds.array[i];
          var cmdId = cmdIds[cmd]++;
          switch (cmd) {
            case WebGL2Cmd.BEGIN_RENDER_PASS:
              {
                var cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId];
                WebGL2CmdFuncBeginRenderPass(device, cmd0.gpuRenderPass, cmd0.gpuFramebuffer, cmd0.renderArea, cmd0.clearColors, cmd0.clearDepth, cmd0.clearStencil);
                break;
              }
            case WebGL2Cmd.BIND_STATES:
              {
                var cmd2 = cmdPackage.bindStatesCmds.array[cmdId];
                WebGL2CmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, cmd2.dynamicStates);
                break;
              }
            case WebGL2Cmd.DRAW:
              {
                var cmd3 = cmdPackage.drawCmds.array[cmdId];
                WebGL2CmdFuncDraw(device, cmd3.drawInfo);
                break;
              }
            case WebGL2Cmd.UPDATE_BUFFER:
              {
                var cmd4 = cmdPackage.updateBufferCmds.array[cmdId];
                WebGL2CmdFuncUpdateBuffer(device, cmd4.gpuBuffer, cmd4.buffer, cmd4.offset, cmd4.size);
                break;
              }
            case WebGL2Cmd.COPY_BUFFER_TO_TEXTURE:
              {
                var cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId];
                WebGL2CmdFuncCopyBuffersToTexture(device, cmd5.buffers, cmd5.gpuTexture, cmd5.regions);
                break;
              }
            case WebGL2Cmd.BLIT_TEXTURE:
              {
                var cmd6 = cmdPackage.blitTextureCmds.array[cmdId];
                WebGL2CmdFuncBlitTexture(device, cmd6.srcTexture, cmd6.dstTexture, cmd6.regions, cmd6.filter);
                break;
              }
          }
        }
      }
      function toUseTexImage2D(texImages, regions) {
        if (texImages.length > 1 || regions.length > 1) return false;
        var isVideoElement = texImages[0] instanceof HTMLVideoElement;
        if (isVideoElement) {
          var videoElement = texImages[0];
          var isSameSize = regions[0].texOffset.x === 0 && regions[0].texOffset.y === 0 && regions[0].texExtent.width === videoElement.videoWidth && regions[0].texExtent.height === videoElement.videoHeight;
          return isSameSize;
        }
        return false;
      }
      function WebGL2CmdFuncCopyTexImagesToTexture(device, texImages, gpuTexture, regions) {
        var gl = device.gl;
        var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
        if (glTexUnit.glTexture !== gpuTexture.glTexture) {
          gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
          glTexUnit.glTexture = gpuTexture.glTexture;
        }
        var n = 0;
        var f = 0;
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              if (gpuTexture.flags & TextureFlagBit.MUTABLE_STORAGE || toUseTexImage2D(texImages, regions)) {
                gl.texImage2D(gl.TEXTURE_2D, regions[0].texSubres.mipLevel, gpuTexture.glInternalFmt, regions[0].texExtent.width, regions[0].texExtent.height, 0, gpuTexture.glFormat, gpuTexture.glType, texImages[0]);
              } else {
                for (var k = 0; k < regions.length; k++) {
                  var region = regions[k];
                  gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, region.texOffset.x, region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]);
                }
              }
              break;
            }
          case gl.TEXTURE_CUBE_MAP:
            {
              for (var _k7 = 0; _k7 < regions.length; _k7++) {
                var _region = regions[_k7];
                var fcount = _region.texSubres.baseArrayLayer + _region.texSubres.layerCount;
                for (f = _region.texSubres.baseArrayLayer; f < fcount; ++f) {
                  gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _region.texSubres.mipLevel, _region.texOffset.x, _region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]);
                }
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy buffer to texture failed.');
            }
        }
        if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) {
          gl.generateMipmap(gpuTexture.glTarget);
        }
      }
      var stagingBuffer = new Uint8Array(1);
      function pixelBufferPick(buffer, format, offset, stride, extent) {
        var blockHeight = formatAlignment(format).height;
        var bufferSize = FormatSize(format, extent.width, extent.height, extent.depth);
        var rowStrideSize = FormatSize(format, stride.width, 1, 1);
        var sliceStrideSize = FormatSize(format, stride.width, stride.height, 1);
        var destRowSize = FormatSize(format, extent.width, 1, 1);
        var ArrayBufferCtor = getTypedArrayConstructor(FormatInfos[format]);
        if (stagingBuffer.byteLength < bufferSize) {
          stagingBuffer = new Uint8Array(bufferSize);
        }
        var destOffset = 0;
        var bufferOffset = offset;
        for (var i = 0; i < extent.depth; i++) {
          bufferOffset = offset + sliceStrideSize * i;
          for (var j = 0; j < extent.height; j += blockHeight) {
            stagingBuffer.subarray(destOffset, destOffset + destRowSize).set(new Uint8Array(buffer.buffer, buffer.byteOffset + bufferOffset, destRowSize));
            destOffset += destRowSize;
            bufferOffset += rowStrideSize;
          }
        }
        var length = bufferSize / ArrayBufferCtor.BYTES_PER_ELEMENT;
        assertID(Number.isInteger(length), 9101);
        return new ArrayBufferCtor(stagingBuffer.buffer, 0, length);
      }
      function WebGL2CmdFuncCopyBuffersToTexture(device, buffers, gpuTexture, regions) {
        var gl = device.gl;
        var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
        if (glTexUnit.glTexture !== gpuTexture.glTexture) {
          gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
          glTexUnit.glTexture = gpuTexture.glTexture;
        }
        var n = 0;
        var f = 0;
        var fmtInfo = FormatInfos[gpuTexture.format];
        var ArrayBufferCtor = getTypedArrayConstructor(fmtInfo);
        var isCompressed = fmtInfo.isCompressed;
        var blockSize = formatAlignment(gpuTexture.format);
        var extent = new Extent();
        var offset = new Offset();
        var stride = new Extent();
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              for (var k = 0; k < regions.length; k++) {
                var region = regions[k];
                var mipLevel = region.texSubres.mipLevel;
                offset.x = region.texOffset.x === 0 ? 0 : alignTo(region.texOffset.x, blockSize.width);
                offset.y = region.texOffset.y === 0 ? 0 : alignTo(region.texOffset.y, blockSize.height);
                extent.width = region.texExtent.width < blockSize.width ? region.texExtent.width : alignTo(region.texExtent.width, blockSize.width);
                extent.height = region.texExtent.height < blockSize.height ? region.texExtent.width : alignTo(region.texExtent.height, blockSize.height);
                stride.width = region.buffStride > 0 ? region.buffStride : extent.width;
                stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
                var destWidth = region.texExtent.width + offset.x === gpuTexture.width >> mipLevel ? region.texExtent.width : extent.width;
                var destHeight = region.texExtent.height + offset.y === gpuTexture.height >> mipLevel ? region.texExtent.height : extent.height;
                var pixels = void 0;
                var buffer = buffers[n++];
                if (stride.width === extent.width && stride.height === extent.height) {
                  var length = FormatSize(gpuTexture.format, destWidth, destHeight, 1) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                  assertID(Number.isInteger(length), 9101);
                  pixels = new ArrayBufferCtor(buffer.buffer, buffer.byteOffset + region.buffOffset, length);
                } else {
                  pixels = pixelBufferPick(buffer, gpuTexture.format, region.buffOffset, stride, extent);
                }
                if (!isCompressed) {
                  gl.texSubImage2D(gl.TEXTURE_2D, mipLevel, offset.x, offset.y, destWidth, destHeight, gpuTexture.glFormat, gpuTexture.glType, pixels);
                } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) {
                  gl.compressedTexSubImage2D(gl.TEXTURE_2D, mipLevel, offset.x, offset.y, destWidth, destHeight, gpuTexture.glFormat, pixels);
                } else {
                  gl.compressedTexImage2D(gl.TEXTURE_2D, mipLevel, gpuTexture.glInternalFmt, destWidth, destHeight, 0, pixels);
                }
              }
              break;
            }
          case gl.TEXTURE_2D_ARRAY:
            {
              for (var _k8 = 0; _k8 < regions.length; _k8++) {
                var _region2 = regions[_k8];
                var _mipLevel = _region2.texSubres.mipLevel;
                offset.x = _region2.texOffset.x === 0 ? 0 : alignTo(_region2.texOffset.x, blockSize.width);
                offset.y = _region2.texOffset.y === 0 ? 0 : alignTo(_region2.texOffset.y, blockSize.height);
                extent.width = _region2.texExtent.width < blockSize.width ? _region2.texExtent.width : alignTo(_region2.texExtent.width, blockSize.width);
                extent.height = _region2.texExtent.height < blockSize.height ? _region2.texExtent.width : alignTo(_region2.texExtent.height, blockSize.height);
                extent.depth = 1;
                stride.width = _region2.buffStride > 0 ? _region2.buffStride : extent.width;
                stride.height = _region2.buffTexHeight > 0 ? _region2.buffTexHeight : extent.height;
                var _destWidth = _region2.texExtent.width + offset.x === gpuTexture.width >> _mipLevel ? _region2.texExtent.width : extent.width;
                var _destHeight = _region2.texExtent.height + offset.y === gpuTexture.height >> _mipLevel ? _region2.texExtent.height : extent.height;
                var fcount = _region2.texSubres.baseArrayLayer + _region2.texSubres.layerCount;
                for (f = _region2.texSubres.baseArrayLayer; f < fcount; ++f) {
                  offset.z = f;
                  var _pixels = void 0;
                  var _buffer = buffers[n++];
                  if (stride.width === extent.width && stride.height === extent.height) {
                    var _length = FormatSize(gpuTexture.format, _destWidth, _destHeight, 1) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                    assertID(Number.isInteger(_length), 9101);
                    _pixels = new ArrayBufferCtor(_buffer.buffer, _buffer.byteOffset + _region2.buffOffset, _length);
                  } else {
                    _pixels = pixelBufferPick(_buffer, gpuTexture.format, _region2.buffOffset, stride, extent);
                  }
                  if (!isCompressed) {
                    gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel, offset.x, offset.y, offset.z, _destWidth, _destHeight, extent.depth, gpuTexture.glFormat, gpuTexture.glType, _pixels);
                  } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) {
                    gl.compressedTexSubImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel, offset.x, offset.y, offset.z, _destWidth, _destHeight, extent.depth, gpuTexture.glFormat, _pixels);
                  } else {
                    gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel, gpuTexture.glInternalFmt, _destWidth, _destHeight, extent.depth, 0, _pixels);
                  }
                }
              }
              break;
            }
          case gl.TEXTURE_3D:
            {
              for (var _k9 = 0; _k9 < regions.length; _k9++) {
                var _region3 = regions[_k9];
                var _mipLevel2 = _region3.texSubres.mipLevel;
                offset.x = _region3.texOffset.x === 0 ? 0 : alignTo(_region3.texOffset.x, blockSize.width);
                offset.y = _region3.texOffset.y === 0 ? 0 : alignTo(_region3.texOffset.y, blockSize.height);
                offset.z = _region3.texOffset.z;
                extent.width = _region3.texExtent.width < blockSize.width ? _region3.texExtent.width : alignTo(_region3.texExtent.width, blockSize.width);
                extent.height = _region3.texExtent.height < blockSize.height ? _region3.texExtent.width : alignTo(_region3.texExtent.height, blockSize.height);
                extent.depth = _region3.texExtent.depth;
                stride.width = _region3.buffStride > 0 ? _region3.buffStride : extent.width;
                stride.height = _region3.buffTexHeight > 0 ? _region3.buffTexHeight : extent.height;
                var _destWidth2 = _region3.texExtent.width + offset.x === gpuTexture.width >> _mipLevel2 ? _region3.texExtent.width : extent.width;
                var _destHeight2 = _region3.texExtent.height + offset.y === gpuTexture.height >> _mipLevel2 ? _region3.texExtent.height : extent.height;
                var _pixels2 = void 0;
                var _buffer2 = buffers[n++];
                if (stride.width === extent.width && stride.height === extent.height) {
                  var _length2 = FormatSize(gpuTexture.format, _destWidth2, _destHeight2, extent.depth) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                  assertID(Number.isInteger(_length2), 9101);
                  _pixels2 = new ArrayBufferCtor(_buffer2.buffer, _buffer2.byteOffset + _region3.buffOffset, _length2);
                } else {
                  _pixels2 = pixelBufferPick(_buffer2, gpuTexture.format, _region3.buffOffset, stride, extent);
                }
                if (!isCompressed) {
                  gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel2, offset.x, offset.y, offset.z, _destWidth2, _destHeight2, extent.depth, gpuTexture.glFormat, gpuTexture.glType, _pixels2);
                } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) {
                  gl.compressedTexSubImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel2, offset.x, offset.y, offset.z, _destWidth2, _destHeight2, extent.depth, gpuTexture.glFormat, _pixels2);
                } else {
                  gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel2, gpuTexture.glInternalFmt, _destWidth2, _destHeight2, extent.depth, 0, _pixels2);
                }
              }
              break;
            }
          case gl.TEXTURE_CUBE_MAP:
            {
              for (var _k10 = 0; _k10 < regions.length; _k10++) {
                var _region4 = regions[_k10];
                var _mipLevel3 = _region4.texSubres.mipLevel;
                offset.x = _region4.texOffset.x === 0 ? 0 : alignTo(_region4.texOffset.x, blockSize.width);
                offset.y = _region4.texOffset.y === 0 ? 0 : alignTo(_region4.texOffset.y, blockSize.height);
                extent.width = _region4.texExtent.width < blockSize.width ? _region4.texExtent.width : alignTo(_region4.texExtent.width, blockSize.width);
                extent.height = _region4.texExtent.height < blockSize.height ? _region4.texExtent.width : alignTo(_region4.texExtent.height, blockSize.height);
                stride.width = _region4.buffStride > 0 ? _region4.buffStride : extent.width;
                stride.height = _region4.buffTexHeight > 0 ? _region4.buffTexHeight : extent.height;
                var _destWidth3 = _region4.texExtent.width + offset.x === gpuTexture.width >> _mipLevel3 ? _region4.texExtent.width : extent.width;
                var _destHeight3 = _region4.texExtent.height + offset.y === gpuTexture.height >> _mipLevel3 ? _region4.texExtent.height : extent.height;
                var _fcount = _region4.texSubres.baseArrayLayer + _region4.texSubres.layerCount;
                for (f = _region4.texSubres.baseArrayLayer; f < _fcount; ++f) {
                  var _pixels3 = void 0;
                  var _buffer3 = buffers[n++];
                  if (stride.width === extent.width && stride.height === extent.height) {
                    var _length3 = FormatSize(gpuTexture.format, _destWidth3, _destHeight3, 1) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                    assertID(Number.isInteger(_length3), 9101);
                    _pixels3 = new ArrayBufferCtor(_buffer3.buffer, _buffer3.byteOffset + _region4.buffOffset, _length3);
                  } else {
                    _pixels3 = pixelBufferPick(_buffer3, gpuTexture.format, _region4.buffOffset, stride, extent);
                  }
                  if (!isCompressed) {
                    gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel3, offset.x, offset.y, _destWidth3, _destHeight3, gpuTexture.glFormat, gpuTexture.glType, _pixels3);
                  } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) {
                    gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel3, offset.x, offset.y, _destWidth3, _destHeight3, gpuTexture.glFormat, _pixels3);
                  } else {
                    gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel3, gpuTexture.glInternalFmt, _destWidth3, _destHeight3, 0, _pixels3);
                  }
                }
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy buffer to texture failed.');
            }
        }
        if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) {
          gl.generateMipmap(gpuTexture.glTarget);
        }
      }
      function WebGL2CmdFuncCopyTextureToBuffers(device, gpuTexture, buffers, regions) {
        var gl = device.gl;
        var cache = device.stateCache;
        var framebuffer = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
        var x = 0;
        var y = 0;
        var w = 1;
        var h = 1;
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              for (var k = 0; k < regions.length; k++) {
                var region = regions[k];
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gpuTexture.glTarget, gpuTexture.glTexture, region.texSubres.mipLevel);
                x = region.texOffset.x;
                y = region.texOffset.y;
                w = region.texExtent.width;
                h = region.texExtent.height;
                gl.readPixels(x, y, w, h, gpuTexture.glFormat, gpuTexture.glType, buffers[k]);
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy texture to buffers failed.');
            }
        }
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        cache.glFramebuffer = null;
        gl.deleteFramebuffer(framebuffer);
      }
      function WebGL2CmdFuncBlitTexture(device, src, dst, regions, filter) {
        var gl = device.gl;
        var cache = device.stateCache;
        var blitManager = device.blitManager;
        if (!blitManager) {
          return;
        }
        var glFilter = filter === Filter$1.LINEAR || filter === Filter$1.ANISOTROPIC ? gl.LINEAR : gl.NEAREST;
        var srcFramebuffer = blitManager.srcFramebuffer;
        var dstFramebuffer = blitManager.dstFramebuffer;
        var origReadFBO = cache.glReadFramebuffer;
        var origDrawFBO = cache.glFramebuffer;
        var srcMip = regions[0].srcSubres.mipLevel;
        var dstMip = regions[0].dstSubres.mipLevel;
        var blitInfo = function blitInfo(formatInfo) {
          var mask = 0;
          var attachment = gl.COLOR_ATTACHMENT0;
          if (formatInfo.hasStencil) {
            attachment = gl.DEPTH_STENCIL_ATTACHMENT;
          } else if (formatInfo.hasDepth) {
            attachment = gl.DEPTH_ATTACHMENT;
          }
          if (formatInfo.hasDepth || formatInfo.hasStencil) {
            if (formatInfo.hasDepth) {
              mask |= gl.DEPTH_BUFFER_BIT;
            }
            if (formatInfo.hasStencil) {
              mask |= gl.STENCIL_BUFFER_BIT;
            }
          } else {
            mask |= gl.COLOR_BUFFER_BIT;
          }
          return {
            mask: mask,
            attachment: attachment
          };
        };
        var regionIndices = regions.map(function (_, i) {
          return i;
        });
        regionIndices.sort(function (a, b) {
          return regions[a].srcSubres.mipLevel - regions[b].srcSubres.mipLevel;
        });
        var _blitInfo = blitInfo(FormatInfos[src.format]),
          srcMask = _blitInfo.mask,
          srcAttachment = _blitInfo.attachment;
        var _blitInfo2 = blitInfo(FormatInfos[dst.format]),
          dstAttachment = _blitInfo2.attachment;
        if (cache.glReadFramebuffer !== srcFramebuffer) {
          gl.bindFramebuffer(gl.READ_FRAMEBUFFER, srcFramebuffer);
          cache.glReadFramebuffer = srcFramebuffer;
        }
        if (cache.glFramebuffer !== dstFramebuffer) {
          gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, dstFramebuffer);
          cache.glFramebuffer = dstFramebuffer;
        }
        if (src.glTexture) {
          gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, srcAttachment, src.glTarget, src.glTexture, srcMip);
        } else {
          gl.framebufferRenderbuffer(gl.READ_FRAMEBUFFER, srcAttachment, gl.RENDERBUFFER, src.glRenderbuffer);
        }
        if (dst.glTexture) {
          gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, dstAttachment, dst.glTarget, dst.glTexture, dstMip);
        } else {
          gl.framebufferRenderbuffer(gl.DRAW_FRAMEBUFFER, dstAttachment, gl.RENDERBUFFER, dst.glRenderbuffer);
        }
        for (var i = 0; i < regionIndices.length; i++) {
          var region = regions[regionIndices[i]];
          if (src.glTexture && srcMip !== region.srcSubres.mipLevel) {
            srcMip = region.srcSubres.mipLevel;
            gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, srcAttachment, src.glTarget, src.glTexture, srcMip);
          }
          if (dst.glTexture && dstMip !== region.dstSubres.mipLevel) {
            dstMip = region.dstSubres.mipLevel;
            gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, dstAttachment, dst.glTarget, dst.glTexture, dstMip);
          }
          gl.blitFramebuffer(region.srcOffset.x, region.srcOffset.y, region.srcOffset.x + region.srcExtent.width, region.srcOffset.y + region.srcExtent.height, region.dstOffset.x, region.dstOffset.y, region.dstOffset.x + region.dstExtent.width, region.dstOffset.y + region.dstExtent.height, srcMask, glFilter);
        }
        if (cache.glReadFramebuffer !== origReadFBO) {
          gl.bindFramebuffer(gl.READ_FRAMEBUFFER, origReadFBO);
          cache.glReadFramebuffer = origReadFBO;
        }
        if (cache.glFramebuffer !== origDrawFBO) {
          gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, origDrawFBO);
          cache.glFramebuffer = origDrawFBO;
        }
      }

      var WebGL2IndirectDrawInfos = function () {
        function WebGL2IndirectDrawInfos() {
          this.counts = void 0;
          this.offsets = void 0;
          this.instances = void 0;
          this.drawCount = 0;
          this.drawByIndex = false;
          this.instancedDraw = false;
          this.byteOffsets = void 0;
          this._capacity = 4;
          this.counts = new Int32Array(this._capacity);
          this.offsets = new Int32Array(this._capacity);
          this.instances = new Int32Array(this._capacity);
          this.byteOffsets = new Int32Array(this._capacity);
        }
        var _proto = WebGL2IndirectDrawInfos.prototype;
        _proto.clearDraws = function clearDraws() {
          this.drawCount = 0;
          this.drawByIndex = false;
          this.instancedDraw = false;
        };
        _proto.setDrawInfo = function setDrawInfo(idx, info) {
          this._ensureCapacity(idx);
          this.drawByIndex = info.indexCount > 0;
          this.instancedDraw = !!info.instanceCount;
          this.drawCount = Math.max(idx + 1, this.drawCount);
          if (this.drawByIndex) {
            this.counts[idx] = info.indexCount;
            this.offsets[idx] = info.firstIndex;
          } else {
            this.counts[idx] = info.vertexCount;
            this.offsets[idx] = info.firstVertex;
          }
          this.instances[idx] = Math.max(1, info.instanceCount);
        };
        _proto._ensureCapacity = function _ensureCapacity(target) {
          if (this._capacity > target) return;
          this._capacity = nextPow2(target);
          var counts = new Int32Array(this._capacity);
          var offsets = new Int32Array(this._capacity);
          var instances = new Int32Array(this._capacity);
          this.byteOffsets = new Int32Array(this._capacity);
          counts.set(this.counts);
          offsets.set(this.offsets);
          instances.set(this.instances);
          this.counts = counts;
          this.offsets = offsets;
          this.instances = instances;
        };
        return WebGL2IndirectDrawInfos;
      }();
      var IWebGL2BlitManager = function () {
        function IWebGL2BlitManager() {
          this._srcFramebuffer = void 0;
          this._dstFramebuffer = void 0;
          var gl = WebGL2DeviceManager.instance.gl;
          this._srcFramebuffer = gl.createFramebuffer();
          this._dstFramebuffer = gl.createFramebuffer();
        }
        var _proto2 = IWebGL2BlitManager.prototype;
        _proto2.destroy = function destroy() {
          var gl = WebGL2DeviceManager.instance.gl;
          gl.deleteFramebuffer(this._srcFramebuffer);
          gl.deleteFramebuffer(this._dstFramebuffer);
        };
        _createClass(IWebGL2BlitManager, [{
          key: "srcFramebuffer",
          get: function get() {
            return this._srcFramebuffer;
          }
        }, {
          key: "dstFramebuffer",
          get: function get() {
            return this._dstFramebuffer;
          }
        }]);
        return IWebGL2BlitManager;
      }();

      var WebGL2Buffer = function (_Buffer) {
        _inheritsLoose(WebGL2Buffer, _Buffer);
        function WebGL2Buffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Buffer.call.apply(_Buffer, [this].concat(args)) || this;
          _this._gpuBuffer = null;
          return _this;
        }
        var _proto = WebGL2Buffer.prototype;
        _proto.initialize = function initialize(info) {
          if ('buffer' in info) {
            this._isBufferView = true;
            var buffer = info.buffer;
            this._usage = buffer.usage;
            this._memUsage = buffer.memUsage;
            this._size = this._stride = info.range;
            this._count = 1;
            this._flags = buffer.flags;
            this._gpuBuffer = {
              usage: this._usage,
              memUsage: this._memUsage,
              size: this._size,
              stride: this._stride,
              buffer: null,
              indirects: buffer.gpuBuffer.indirects,
              glTarget: buffer.gpuBuffer.glTarget,
              glBuffer: buffer.gpuBuffer.glBuffer,
              glOffset: info.offset
            };
          } else {
            this._usage = info.usage;
            this._memUsage = info.memUsage;
            this._size = info.size;
            this._stride = Math.max(info.stride || this._size, 1);
            this._count = this._size / this._stride;
            this._flags = info.flags;
            this._gpuBuffer = {
              usage: this._usage,
              memUsage: this._memUsage,
              size: this._size,
              stride: this._stride,
              buffer: null,
              indirects: new WebGL2IndirectDrawInfos(),
              glTarget: 0,
              glBuffer: null,
              glOffset: 0
            };
            WebGL2CmdFuncCreateBuffer(WebGL2DeviceManager.instance, this._gpuBuffer);
            WebGL2DeviceManager.instance.memoryStatus.bufferSize += this._size;
          }
        };
        _proto.destroy = function destroy() {
          if (this._gpuBuffer) {
            if (!this._isBufferView) {
              WebGL2CmdFuncDestroyBuffer(WebGL2DeviceManager.instance, this._gpuBuffer);
              WebGL2DeviceManager.instance.memoryStatus.bufferSize -= this._size;
            }
            this._gpuBuffer = null;
          }
        };
        _proto.resize = function resize(size) {
          if (this._isBufferView) {
            console.warn('cannot resize buffer views!');
            return;
          }
          var oldSize = this._size;
          if (oldSize === size) {
            return;
          }
          this._size = size;
          this._count = this._size / this._stride;
          if (this._gpuBuffer) {
            this._gpuBuffer.size = size;
            if (size > 0) {
              WebGL2CmdFuncResizeBuffer(WebGL2DeviceManager.instance, this._gpuBuffer);
              WebGL2DeviceManager.instance.memoryStatus.bufferSize -= oldSize;
              WebGL2DeviceManager.instance.memoryStatus.bufferSize += size;
            }
          }
        };
        _proto.update = function update(buffer, size) {
          if (this._isBufferView) {
            console.warn('cannot update through buffer views!');
            return;
          }
          var buffSize;
          if (size !== undefined) {
            buffSize = size;
          } else if (this._usage & BufferUsageBit.INDIRECT) {
            buffSize = 0;
          } else {
            buffSize = buffer.byteLength;
          }
          WebGL2CmdFuncUpdateBuffer(WebGL2DeviceManager.instance, this._gpuBuffer, buffer, 0, buffSize);
        };
        _createClass(WebGL2Buffer, [{
          key: "gpuBuffer",
          get: function get() {
            return this._gpuBuffer;
          }
        }]);
        return WebGL2Buffer;
      }(Buffer);

      var WebGL2CommandPool = function () {
        function WebGL2CommandPool(Clazz, count) {
          this._frees = void 0;
          this._freeIdx = 0;
          this._freeCmds = void 0;
          this._frees = new Array(count);
          this._freeCmds = new CachedArray(count);
          for (var i = 0; i < count; ++i) {
            this._frees[i] = new Clazz();
          }
          this._freeIdx = count - 1;
        }
        var _proto = WebGL2CommandPool.prototype;
        _proto.alloc = function alloc(Clazz) {
          if (this._freeIdx < 0) {
            var size = this._frees.length * 2;
            var temp = this._frees;
            this._frees = new Array(size);
            var increase = size - temp.length;
            for (var i = 0; i < increase; ++i) {
              this._frees[i] = new Clazz();
            }
            for (var _i = increase, j = 0; _i < size; ++_i, ++j) {
              this._frees[_i] = temp[j];
            }
            this._freeIdx += increase;
          }
          var cmd = this._frees[this._freeIdx];
          this._frees[this._freeIdx--] = null;
          ++cmd.refCount;
          return cmd;
        };
        _proto.free = function free(cmd) {
          if (--cmd.refCount === 0) {
            this._freeCmds.push(cmd);
          }
        };
        _proto.freeCmds = function freeCmds(cmds) {
          for (var i = 0; i < cmds.length; ++i) {
            if (--cmds.array[i].refCount === 0) {
              this._freeCmds.push(cmds.array[i]);
            }
          }
        };
        _proto.release = function release() {
          for (var i = 0; i < this._freeCmds.length; ++i) {
            var cmd = this._freeCmds.array[i];
            cmd.clear();
            this._frees[++this._freeIdx] = cmd;
          }
          this._freeCmds.clear();
        };
        return WebGL2CommandPool;
      }();
      var WebGL2CommandAllocator = function () {
        function WebGL2CommandAllocator() {
          this.beginRenderPassCmdPool = void 0;
          this.bindStatesCmdPool = void 0;
          this.drawCmdPool = void 0;
          this.updateBufferCmdPool = void 0;
          this.copyBufferToTextureCmdPool = void 0;
          this.blitTextureCmdPool = void 0;
          this.beginRenderPassCmdPool = new WebGL2CommandPool(WebGL2CmdBeginRenderPass, 1);
          this.bindStatesCmdPool = new WebGL2CommandPool(WebGL2CmdBindStates, 1);
          this.drawCmdPool = new WebGL2CommandPool(WebGL2CmdDraw, 1);
          this.updateBufferCmdPool = new WebGL2CommandPool(WebGL2CmdUpdateBuffer, 1);
          this.copyBufferToTextureCmdPool = new WebGL2CommandPool(WebGL2CmdCopyBufferToTexture, 1);
          this.blitTextureCmdPool = new WebGL2CommandPool(WebGL2CmdBlitTexture, 1);
        }
        var _proto2 = WebGL2CommandAllocator.prototype;
        _proto2.clearCmds = function clearCmds(cmdPackage) {
          if (cmdPackage.beginRenderPassCmds.length) {
            this.beginRenderPassCmdPool.freeCmds(cmdPackage.beginRenderPassCmds);
            cmdPackage.beginRenderPassCmds.clear();
          }
          if (cmdPackage.bindStatesCmds.length) {
            this.bindStatesCmdPool.freeCmds(cmdPackage.bindStatesCmds);
            cmdPackage.bindStatesCmds.clear();
          }
          if (cmdPackage.drawCmds.length) {
            this.drawCmdPool.freeCmds(cmdPackage.drawCmds);
            cmdPackage.drawCmds.clear();
          }
          if (cmdPackage.updateBufferCmds.length) {
            this.updateBufferCmdPool.freeCmds(cmdPackage.updateBufferCmds);
            cmdPackage.updateBufferCmds.clear();
          }
          if (cmdPackage.copyBufferToTextureCmds.length) {
            this.copyBufferToTextureCmdPool.freeCmds(cmdPackage.copyBufferToTextureCmds);
            cmdPackage.copyBufferToTextureCmds.clear();
          }
          if (cmdPackage.blitTextureCmds.length) {
            this.blitTextureCmdPool.freeCmds(cmdPackage.blitTextureCmds);
            cmdPackage.blitTextureCmds.clear();
          }
          cmdPackage.cmds.clear();
        };
        _proto2.releaseCmds = function releaseCmds() {
          this.beginRenderPassCmdPool.release();
          this.bindStatesCmdPool.release();
          this.drawCmdPool.release();
          this.updateBufferCmdPool.release();
          this.copyBufferToTextureCmdPool.release();
          this.blitTextureCmdPool.release();
        };
        return WebGL2CommandAllocator;
      }();

      var WebGL2CommandBuffer = function (_CommandBuffer) {
        _inheritsLoose(WebGL2CommandBuffer, _CommandBuffer);
        function WebGL2CommandBuffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _CommandBuffer.call.apply(_CommandBuffer, [this].concat(args)) || this;
          _this.cmdPackage = new WebGL2CmdPackage();
          _this._cmdAllocator = new WebGL2CommandAllocator();
          _this._isInRenderPass = false;
          _this._curGPUPipelineState = null;
          _this._curGPUDescriptorSets = [];
          _this._curGPUInputAssembler = null;
          _this._curDynamicOffsets = Array(8).fill(0);
          _this._curDynamicStates = new DynamicStates();
          _this._isStateInvalied = false;
          return _this;
        }
        var _proto = WebGL2CommandBuffer.prototype;
        _proto.initialize = function initialize(info) {
          this._type = info.type;
          this._queue = info.queue;
          var setCount = WebGL2DeviceManager.instance.bindingMappings.blockOffsets.length;
          for (var i = 0; i < setCount; i++) {
            this._curGPUDescriptorSets.push(null);
          }
        };
        _proto.destroy = function destroy() {
          this._cmdAllocator.clearCmds(this.cmdPackage);
        };
        _proto.begin = function begin(renderPass, subpass, frameBuffer) {
          this._cmdAllocator.clearCmds(this.cmdPackage);
          this._curGPUPipelineState = null;
          this._curGPUInputAssembler = null;
          this._curGPUDescriptorSets.length = 0;
          this._numDrawCalls = 0;
          this._numInstances = 0;
          this._numTris = 0;
        };
        _proto.end = function end() {
          if (this._isStateInvalied) {
            this.bindStates();
          }
          this._isInRenderPass = false;
        };
        _proto.beginRenderPass = function beginRenderPass(renderPass, framebuffer, renderArea, clearColors, clearDepth, clearStencil) {
          var cmd = this._cmdAllocator.beginRenderPassCmdPool.alloc(WebGL2CmdBeginRenderPass);
          cmd.gpuRenderPass = renderPass.gpuRenderPass;
          cmd.gpuFramebuffer = framebuffer.gpuFramebuffer;
          cmd.renderArea.copy(renderArea);
          for (var i = 0; i < clearColors.length; ++i) {
            cmd.clearColors[i] = clearColors[i];
          }
          cmd.clearDepth = clearDepth;
          cmd.clearStencil = clearStencil;
          this.cmdPackage.beginRenderPassCmds.push(cmd);
          this.cmdPackage.cmds.push(WebGL2Cmd.BEGIN_RENDER_PASS);
          this._isInRenderPass = true;
        };
        _proto.endRenderPass = function endRenderPass() {
          this._isInRenderPass = false;
        };
        _proto.bindPipelineState = function bindPipelineState(pipelineState) {
          var gpuPipelineState = pipelineState.gpuPipelineState;
          if (gpuPipelineState !== this._curGPUPipelineState) {
            this._curGPUPipelineState = gpuPipelineState;
            this._isStateInvalied = true;
          }
        };
        _proto.bindDescriptorSet = function bindDescriptorSet(set, descriptorSet, dynamicOffsets) {
          var gpuDescriptorSets = descriptorSet.gpuDescriptorSet;
          if (gpuDescriptorSets !== this._curGPUDescriptorSets[set]) {
            this._curGPUDescriptorSets[set] = gpuDescriptorSets;
            this._isStateInvalied = true;
          }
          if (dynamicOffsets) {
            var _this$_curGPUPipeline;
            var gpuPipelineLayout = (_this$_curGPUPipeline = this._curGPUPipelineState) === null || _this$_curGPUPipeline === void 0 ? void 0 : _this$_curGPUPipeline.gpuPipelineLayout;
            if (gpuPipelineLayout) {
              var offsets = this._curDynamicOffsets;
              var idx = gpuPipelineLayout.dynamicOffsetOffsets[set];
              for (var i = 0; i < dynamicOffsets.length; i++) offsets[idx + i] = dynamicOffsets[i];
              this._isStateInvalied = true;
            }
          }
        };
        _proto.bindInputAssembler = function bindInputAssembler(inputAssembler) {
          var gpuInputAssembler = inputAssembler.gpuInputAssembler;
          this._curGPUInputAssembler = gpuInputAssembler;
          this._isStateInvalied = true;
        };
        _proto.setViewport = function setViewport(viewport) {
          var cache = this._curDynamicStates.viewport;
          if (cache.left !== viewport.left || cache.top !== viewport.top || cache.width !== viewport.width || cache.height !== viewport.height || cache.minDepth !== viewport.minDepth || cache.maxDepth !== viewport.maxDepth) {
            cache.left = viewport.left;
            cache.top = viewport.top;
            cache.width = viewport.width;
            cache.height = viewport.height;
            cache.minDepth = viewport.minDepth;
            cache.maxDepth = viewport.maxDepth;
            this._isStateInvalied = true;
          }
        };
        _proto.setScissor = function setScissor(scissor) {
          var cache = this._curDynamicStates.scissor;
          if (cache.x !== scissor.x || cache.y !== scissor.y || cache.width !== scissor.width || cache.height !== scissor.height) {
            cache.x = scissor.x;
            cache.y = scissor.y;
            cache.width = scissor.width;
            cache.height = scissor.height;
            this._isStateInvalied = true;
          }
        };
        _proto.setLineWidth = function setLineWidth(lineWidth) {
          if (this._curDynamicStates.lineWidth !== lineWidth) {
            this._curDynamicStates.lineWidth = lineWidth;
            this._isStateInvalied = true;
          }
        };
        _proto.setDepthBias = function setDepthBias(depthBiasConstantFactor, depthBiasClamp, depthBiasSlopeFactor) {
          var cache = this._curDynamicStates;
          if (cache.depthBiasConstant !== depthBiasConstantFactor || cache.depthBiasClamp !== depthBiasClamp || cache.depthBiasSlope !== depthBiasSlopeFactor) {
            cache.depthBiasConstant = depthBiasConstantFactor;
            cache.depthBiasClamp = depthBiasClamp;
            cache.depthBiasSlope = depthBiasSlopeFactor;
            this._isStateInvalied = true;
          }
        };
        _proto.setBlendConstants = function setBlendConstants(blendConstants) {
          var cache = this._curDynamicStates.blendConstant;
          if (cache.x !== blendConstants.x || cache.y !== blendConstants.y || cache.z !== blendConstants.z || cache.w !== blendConstants.w) {
            cache.copy(blendConstants);
            this._isStateInvalied = true;
          }
        };
        _proto.setDepthBound = function setDepthBound(minDepthBounds, maxDepthBounds) {
          var cache = this._curDynamicStates;
          if (cache.depthMinBounds !== minDepthBounds || cache.depthMaxBounds !== maxDepthBounds) {
            cache.depthMinBounds = minDepthBounds;
            cache.depthMaxBounds = maxDepthBounds;
            this._isStateInvalied = true;
          }
        };
        _proto.setStencilWriteMask = function setStencilWriteMask(face, writeMask) {
          var front = this._curDynamicStates.stencilStatesFront;
          var back = this._curDynamicStates.stencilStatesBack;
          if (face & StencilFace.FRONT) {
            if (front.writeMask !== writeMask) {
              front.writeMask = writeMask;
              this._isStateInvalied = true;
            }
          }
          if (face & StencilFace.BACK) {
            if (back.writeMask !== writeMask) {
              back.writeMask = writeMask;
              this._isStateInvalied = true;
            }
          }
        };
        _proto.setStencilCompareMask = function setStencilCompareMask(face, reference, compareMask) {
          var front = this._curDynamicStates.stencilStatesFront;
          var back = this._curDynamicStates.stencilStatesBack;
          if (face & StencilFace.FRONT) {
            if (front.compareMask !== compareMask || front.reference !== reference) {
              front.reference = reference;
              front.compareMask = compareMask;
              this._isStateInvalied = true;
            }
          }
          if (face & StencilFace.BACK) {
            if (back.compareMask !== compareMask || back.reference !== reference) {
              back.reference = reference;
              back.compareMask = compareMask;
              this._isStateInvalied = true;
            }
          }
        };
        _proto.draw = function draw(infoOrAssembler) {
          if (this._type === CommandBufferType.PRIMARY && this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            if (this._isStateInvalied) {
              this.bindStates();
            }
            var info = 'drawInfo' in infoOrAssembler ? infoOrAssembler.drawInfo : infoOrAssembler;
            var cmd = this._cmdAllocator.drawCmdPool.alloc(WebGL2CmdDraw);
            cmd.drawInfo.copy(info);
            this.cmdPackage.drawCmds.push(cmd);
            this.cmdPackage.cmds.push(WebGL2Cmd.DRAW);
            ++this._numDrawCalls;
            this._numInstances += info.instanceCount;
            var indexCount = info.indexCount || info.vertexCount;
            if (this._curGPUPipelineState) {
              var glPrimitive = this._curGPUPipelineState.glPrimitive;
              switch (glPrimitive) {
                case 0x0004:
                  {
                    this._numTris += indexCount / 3 * Math.max(info.instanceCount, 1);
                    break;
                  }
                case 0x0005:
                case 0x0006:
                  {
                    this._numTris += (indexCount - 2) * Math.max(info.instanceCount, 1);
                    break;
                  }
              }
            }
          } else {
            console.error('Command \'draw\' must be recorded inside a render pass.');
          }
        };
        _proto.updateBuffer = function updateBuffer(buffer, data, size) {
          if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            var gpuBuffer = buffer.gpuBuffer;
            if (gpuBuffer) {
              var cmd = this._cmdAllocator.updateBufferCmdPool.alloc(WebGL2CmdUpdateBuffer);
              var buffSize = 0;
              var buff = null;
              if (buffer.usage & BufferUsageBit.INDIRECT) {
                buff = data;
              } else {
                if (size !== undefined) {
                  buffSize = size;
                } else {
                  buffSize = data.byteLength;
                }
                buff = data;
              }
              cmd.gpuBuffer = gpuBuffer;
              cmd.buffer = buff;
              cmd.offset = 0;
              cmd.size = buffSize;
              this.cmdPackage.updateBufferCmds.push(cmd);
              this.cmdPackage.cmds.push(WebGL2Cmd.UPDATE_BUFFER);
            }
          } else {
            console.error('Command \'updateBuffer\' must be recorded outside a render pass.');
          }
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            var gpuTexture = texture.gpuTexture;
            if (gpuTexture) {
              var cmd = this._cmdAllocator.copyBufferToTextureCmdPool.alloc(WebGL2CmdCopyBufferToTexture);
              cmd.gpuTexture = gpuTexture;
              cmd.regions = regions;
              cmd.buffers = buffers;
              this.cmdPackage.copyBufferToTextureCmds.push(cmd);
              this.cmdPackage.cmds.push(WebGL2Cmd.COPY_BUFFER_TO_TEXTURE);
            }
          } else {
            console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.');
          }
        };
        _proto.execute = function execute(cmdBuffs, count) {
          for (var i = 0; i < count; ++i) {
            var webGL2CmdBuff = cmdBuffs[i];
            for (var c = 0; c < webGL2CmdBuff.cmdPackage.beginRenderPassCmds.length; ++c) {
              var cmd = webGL2CmdBuff.cmdPackage.beginRenderPassCmds.array[c];
              ++cmd.refCount;
              this.cmdPackage.beginRenderPassCmds.push(cmd);
            }
            for (var _c = 0; _c < webGL2CmdBuff.cmdPackage.bindStatesCmds.length; ++_c) {
              var _cmd = webGL2CmdBuff.cmdPackage.bindStatesCmds.array[_c];
              ++_cmd.refCount;
              this.cmdPackage.bindStatesCmds.push(_cmd);
            }
            for (var _c2 = 0; _c2 < webGL2CmdBuff.cmdPackage.drawCmds.length; ++_c2) {
              var _cmd2 = webGL2CmdBuff.cmdPackage.drawCmds.array[_c2];
              ++_cmd2.refCount;
              this.cmdPackage.drawCmds.push(_cmd2);
            }
            for (var _c3 = 0; _c3 < webGL2CmdBuff.cmdPackage.updateBufferCmds.length; ++_c3) {
              var _cmd3 = webGL2CmdBuff.cmdPackage.updateBufferCmds.array[_c3];
              ++_cmd3.refCount;
              this.cmdPackage.updateBufferCmds.push(_cmd3);
            }
            for (var _c4 = 0; _c4 < webGL2CmdBuff.cmdPackage.copyBufferToTextureCmds.length; ++_c4) {
              var _cmd4 = webGL2CmdBuff.cmdPackage.copyBufferToTextureCmds.array[_c4];
              ++_cmd4.refCount;
              this.cmdPackage.copyBufferToTextureCmds.push(_cmd4);
            }
            for (var _c5 = 0; _c5 < webGL2CmdBuff.cmdPackage.blitTextureCmds.length; ++_c5) {
              var _cmd5 = webGL2CmdBuff.cmdPackage.blitTextureCmds.array[_c5];
              ++_cmd5.refCount;
              this.cmdPackage.blitTextureCmds.push(_cmd5);
            }
            this.cmdPackage.cmds.concat(webGL2CmdBuff.cmdPackage.cmds.array);
            this._numDrawCalls += webGL2CmdBuff._numDrawCalls;
            this._numInstances += webGL2CmdBuff._numInstances;
            this._numTris += webGL2CmdBuff._numTris;
          }
        };
        _proto.pipelineBarrier = function pipelineBarrier(GeneralBarrier, bufferBarriers, buffers, textureBarriers, textures) {};
        _proto.bindStates = function bindStates() {
          var bindStatesCmd = this._cmdAllocator.bindStatesCmdPool.alloc(WebGL2CmdBindStates);
          bindStatesCmd.gpuPipelineState = this._curGPUPipelineState;
          Array.prototype.push.apply(bindStatesCmd.gpuDescriptorSets, this._curGPUDescriptorSets);
          Array.prototype.push.apply(bindStatesCmd.dynamicOffsets, this._curDynamicOffsets);
          bindStatesCmd.gpuInputAssembler = this._curGPUInputAssembler;
          bindStatesCmd.dynamicStates = this._curDynamicStates;
          this.cmdPackage.bindStatesCmds.push(bindStatesCmd);
          this.cmdPackage.cmds.push(WebGL2Cmd.BIND_STATES);
          this._isStateInvalied = false;
        };
        _proto.blitTexture = function blitTexture(srcTexture, dstTexture, regions, filter) {
          var blitTextureCmd = this._cmdAllocator.blitTextureCmdPool.alloc(WebGL2CmdBlitTexture);
          blitTextureCmd.srcTexture = srcTexture.gpuTexture;
          blitTextureCmd.dstTexture = dstTexture.gpuTexture;
          blitTextureCmd.regions = regions;
          blitTextureCmd.filter = filter;
          ++this._numDrawCalls;
          this.cmdPackage.blitTextureCmds.push(blitTextureCmd);
          this.cmdPackage.cmds.push(WebGL2Cmd.BLIT_TEXTURE);
        };
        return WebGL2CommandBuffer;
      }(CommandBuffer);

      var WebGL2Framebuffer = function (_Framebuffer) {
        _inheritsLoose(WebGL2Framebuffer, _Framebuffer);
        function WebGL2Framebuffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Framebuffer.call.apply(_Framebuffer, [this].concat(args)) || this;
          _this._gpuFramebuffer = null;
          return _this;
        }
        var _proto = WebGL2Framebuffer.prototype;
        _proto.initialize = function initialize(info) {
          this._renderPass = info.renderPass;
          this._colorTextures = info.colorTextures || [];
          this._depthStencilTexture = info.depthStencilTexture || null;
          var gpuColorViews = [];
          for (var i = 0; i < info.colorTextures.length; i++) {
            var colorTexture = info.colorTextures[i];
            if (colorTexture) {
              gpuColorViews.push(colorTexture.gpuTextureView);
            }
          }
          var gpuDepthStencilView = null;
          if (info.depthStencilTexture) {
            gpuDepthStencilView = info.depthStencilTexture.gpuTextureView;
          }
          var width = Number.MAX_SAFE_INTEGER;
          var height = Number.MAX_SAFE_INTEGER;
          this._gpuFramebuffer = {
            gpuRenderPass: info.renderPass.gpuRenderPass,
            gpuColorViews: gpuColorViews,
            gpuDepthStencilView: gpuDepthStencilView,
            glFramebuffer: null,
            isOffscreen: true,
            get width() {
              if (this.gpuColorViews.length > 0) {
                return this.gpuColorViews[0].gpuTexture.width;
              } else if (this.gpuDepthStencilView) {
                return this.gpuDepthStencilView.gpuTexture.width;
              }
              return width;
            },
            set width(val) {
              width = val;
            },
            get height() {
              if (this.gpuColorViews.length > 0) {
                return this.gpuColorViews[0].gpuTexture.height;
              } else if (this.gpuDepthStencilView) {
                return this.gpuDepthStencilView.gpuTexture.height;
              }
              return height;
            },
            set height(val) {
              height = val;
            }
          };
          WebGL2CmdFuncCreateFramebuffer(WebGL2DeviceManager.instance, this._gpuFramebuffer);
          this._width = this._gpuFramebuffer.width;
          this._height = this._gpuFramebuffer.height;
        };
        _proto.destroy = function destroy() {
          if (this._gpuFramebuffer) {
            WebGL2CmdFuncDestroyFramebuffer(WebGL2DeviceManager.instance, this._gpuFramebuffer);
            this._gpuFramebuffer = null;
          }
        };
        _createClass(WebGL2Framebuffer, [{
          key: "gpuFramebuffer",
          get: function get() {
            return this._gpuFramebuffer;
          }
        }]);
        return WebGL2Framebuffer;
      }(Framebuffer);

      var WebGL2InputAssembler = function (_InputAssembler) {
        _inheritsLoose(WebGL2InputAssembler, _InputAssembler);
        function WebGL2InputAssembler() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _InputAssembler.call.apply(_InputAssembler, [this].concat(args)) || this;
          _this._gpuInputAssembler = null;
          return _this;
        }
        var _proto = WebGL2InputAssembler.prototype;
        _proto.initialize = function initialize(info) {
          if (info.vertexBuffers.length === 0) {
            console.error('InputAssemblerInfo.vertexBuffers is null.');
            return;
          }
          this._attributes = info.attributes;
          this._attributesHash = this.computeAttributesHash();
          this._vertexBuffers = info.vertexBuffers;
          if (info.indexBuffer) {
            this._indexBuffer = info.indexBuffer;
            this._drawInfo.indexCount = this._indexBuffer.size / this._indexBuffer.stride;
            this._drawInfo.firstIndex = 0;
          } else {
            var vertBuff = this._vertexBuffers[0];
            this._drawInfo.vertexCount = vertBuff.size / vertBuff.stride;
            this._drawInfo.firstVertex = 0;
            this._drawInfo.vertexOffset = 0;
          }
          this._drawInfo.instanceCount = 0;
          this._drawInfo.firstInstance = 0;
          this._indirectBuffer = info.indirectBuffer || null;
          var gpuVertexBuffers = new Array(info.vertexBuffers.length);
          for (var i = 0; i < info.vertexBuffers.length; ++i) {
            var vb = info.vertexBuffers[i];
            if (vb.gpuBuffer) {
              gpuVertexBuffers[i] = vb.gpuBuffer;
            }
          }
          var gpuIndexBuffer = null;
          var glIndexType = 0;
          if (info.indexBuffer) {
            gpuIndexBuffer = info.indexBuffer.gpuBuffer;
            if (gpuIndexBuffer) {
              switch (gpuIndexBuffer.stride) {
                case 1:
                  glIndexType = 0x1401;
                  break;
                case 2:
                  glIndexType = 0x1403;
                  break;
                case 4:
                  glIndexType = 0x1405;
                  break;
                default:
                  {
                    console.error('Illegal index buffer stride.');
                  }
              }
            }
          }
          var gpuIndirectBuffer = null;
          if (info.indirectBuffer) {
            gpuIndirectBuffer = info.indirectBuffer.gpuBuffer;
          }
          this._gpuInputAssembler = {
            attributes: info.attributes,
            gpuVertexBuffers: gpuVertexBuffers,
            gpuIndexBuffer: gpuIndexBuffer,
            gpuIndirectBuffer: gpuIndirectBuffer,
            glAttribs: [],
            glIndexType: glIndexType,
            glVAOs: new Map()
          };
          WebGL2CmdFuncCreateInputAssember(WebGL2DeviceManager.instance, this._gpuInputAssembler);
        };
        _proto.destroy = function destroy() {
          var device = WebGL2DeviceManager.instance;
          if (this._gpuInputAssembler && device.extensions.useVAO) {
            WebGL2CmdFuncDestroyInputAssembler(device, this._gpuInputAssembler);
          }
          this._gpuInputAssembler = null;
        };
        _createClass(WebGL2InputAssembler, [{
          key: "gpuInputAssembler",
          get: function get() {
            return this._gpuInputAssembler;
          }
        }]);
        return WebGL2InputAssembler;
      }(InputAssembler);

      var WebGL2DescriptorSetLayout = function (_DescriptorSetLayout) {
        _inheritsLoose(WebGL2DescriptorSetLayout, _DescriptorSetLayout);
        function WebGL2DescriptorSetLayout() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _DescriptorSetLayout.call.apply(_DescriptorSetLayout, [this].concat(args)) || this;
          _this._gpuDescriptorSetLayout = null;
          return _this;
        }
        var _proto = WebGL2DescriptorSetLayout.prototype;
        _proto.initialize = function initialize(info) {
          Array.prototype.push.apply(this._bindings, info.bindings);
          var descriptorCount = 0;
          var maxBinding = -1;
          var flattenedIndices = [];
          for (var i = 0; i < this._bindings.length; i++) {
            var binding = this._bindings[i];
            flattenedIndices.push(descriptorCount);
            descriptorCount += binding.count;
            if (binding.binding > maxBinding) maxBinding = binding.binding;
          }
          this._bindingIndices = Array(maxBinding + 1).fill(-1);
          var descriptorIndices = this._descriptorIndices = Array(maxBinding + 1).fill(-1);
          for (var _i = 0; _i < this._bindings.length; _i++) {
            var _binding = this._bindings[_i];
            this._bindingIndices[_binding.binding] = _i;
            descriptorIndices[_binding.binding] = flattenedIndices[_i];
          }
          var dynamicBindings = [];
          for (var _i2 = 0; _i2 < this._bindings.length; _i2++) {
            var _binding2 = this._bindings[_i2];
            if (_binding2.descriptorType & DESCRIPTOR_DYNAMIC_TYPE) {
              for (var j = 0; j < _binding2.count; j++) {
                dynamicBindings.push(_binding2.binding);
              }
            }
          }
          this._gpuDescriptorSetLayout = {
            bindings: this._bindings,
            dynamicBindings: dynamicBindings,
            descriptorIndices: descriptorIndices,
            descriptorCount: descriptorCount
          };
        };
        _proto.destroy = function destroy() {
          this._bindings.length = 0;
        };
        _createClass(WebGL2DescriptorSetLayout, [{
          key: "gpuDescriptorSetLayout",
          get: function get() {
            return this._gpuDescriptorSetLayout;
          }
        }]);
        return WebGL2DescriptorSetLayout;
      }(DescriptorSetLayout);

      var WebGL2PipelineLayout = function (_PipelineLayout) {
        _inheritsLoose(WebGL2PipelineLayout, _PipelineLayout);
        function WebGL2PipelineLayout() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineLayout.call.apply(_PipelineLayout, [this].concat(args)) || this;
          _this._gpuPipelineLayout = null;
          return _this;
        }
        var _proto = WebGL2PipelineLayout.prototype;
        _proto.initialize = function initialize(info) {
          Array.prototype.push.apply(this._setLayouts, info.setLayouts);
          var dynamicOffsetIndices = [];
          var gpuSetLayouts = [];
          var dynamicOffsetCount = 0;
          var dynamicOffsetOffsets = [];
          for (var i = 0; i < this._setLayouts.length; i++) {
            var setLayout = this._setLayouts[i];
            var dynamicBindings = setLayout.gpuDescriptorSetLayout.dynamicBindings;
            var indices = Array(setLayout.bindingIndices.length).fill(-1);
            for (var j = 0; j < dynamicBindings.length; j++) {
              var binding = dynamicBindings[j];
              if (indices[binding] < 0) indices[binding] = dynamicOffsetCount + j;
            }
            gpuSetLayouts.push(setLayout.gpuDescriptorSetLayout);
            dynamicOffsetIndices.push(indices);
            dynamicOffsetOffsets.push(dynamicOffsetCount);
            dynamicOffsetCount += dynamicBindings.length;
          }
          this._gpuPipelineLayout = {
            gpuSetLayouts: gpuSetLayouts,
            dynamicOffsetIndices: dynamicOffsetIndices,
            dynamicOffsetCount: dynamicOffsetCount,
            dynamicOffsetOffsets: dynamicOffsetOffsets
          };
        };
        _proto.destroy = function destroy() {
          this._setLayouts.length = 0;
        };
        _createClass(WebGL2PipelineLayout, [{
          key: "gpuPipelineLayout",
          get: function get() {
            return this._gpuPipelineLayout;
          }
        }]);
        return WebGL2PipelineLayout;
      }(PipelineLayout);

      var WebGLPrimitives = [0x0000, 0x0001, 0x0003, 0x0002, 0x0000, 0x0000, 0x0000, 0x0004, 0x0005, 0x0006, 0x0000, 0x0000, 0x0000, 0x0000];
      var WebGL2PipelineState = function (_PipelineState) {
        _inheritsLoose(WebGL2PipelineState, _PipelineState);
        function WebGL2PipelineState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineState.call.apply(_PipelineState, [this].concat(args)) || this;
          _this._gpuPipelineState = null;
          return _this;
        }
        var _proto = WebGL2PipelineState.prototype;
        _proto.initialize = function initialize(info) {
          this._primitive = info.primitive;
          this._shader = info.shader;
          this._pipelineLayout = info.pipelineLayout;
          var bs = this._bs;
          if (info.blendState) {
            var bsInfo = info.blendState;
            var targets = bsInfo.targets;
            if (targets) {
              targets.forEach(function (t, i) {
                bs.setTarget(i, t);
              });
            }
            if (bsInfo.isA2C !== undefined) {
              bs.isA2C = bsInfo.isA2C;
            }
            if (bsInfo.isIndepend !== undefined) {
              bs.isIndepend = bsInfo.isIndepend;
            }
            if (bsInfo.blendColor !== undefined) {
              bs.blendColor = bsInfo.blendColor;
            }
          }
          Object.assign(this._rs, info.rasterizerState);
          Object.assign(this._dss, info.depthStencilState);
          this._is = info.inputState;
          this._renderPass = info.renderPass;
          this._dynamicStates = info.dynamicStates;
          var dynamicStates = [];
          for (var i = 0; i < 31; i++) {
            if (this._dynamicStates & 1 << i) {
              dynamicStates.push(1 << i);
            }
          }
          this._gpuPipelineState = {
            glPrimitive: WebGLPrimitives[info.primitive],
            gpuShader: info.shader.gpuShader,
            gpuPipelineLayout: info.pipelineLayout.gpuPipelineLayout,
            rs: info.rasterizerState,
            dss: info.depthStencilState,
            bs: info.blendState,
            gpuRenderPass: info.renderPass.gpuRenderPass,
            dynamicStates: dynamicStates
          };
        };
        _proto.destroy = function destroy() {
          this._gpuPipelineState = null;
        };
        _createClass(WebGL2PipelineState, [{
          key: "gpuPipelineState",
          get: function get() {
            return this._gpuPipelineState;
          }
        }]);
        return WebGL2PipelineState;
      }(PipelineState);

      var WebGL2PrimaryCommandBuffer = function (_WebGL2CommandBuffer) {
        _inheritsLoose(WebGL2PrimaryCommandBuffer, _WebGL2CommandBuffer);
        function WebGL2PrimaryCommandBuffer() {
          return _WebGL2CommandBuffer.apply(this, arguments) || this;
        }
        var _proto = WebGL2PrimaryCommandBuffer.prototype;
        _proto.beginRenderPass = function beginRenderPass(renderPass, framebuffer, renderArea, clearColors, clearDepth, clearStencil) {
          WebGL2CmdFuncBeginRenderPass(WebGL2DeviceManager.instance, renderPass.gpuRenderPass, framebuffer.gpuFramebuffer, renderArea, clearColors, clearDepth, clearStencil);
          this._isInRenderPass = true;
        };
        _proto.draw = function draw(infoOrAssembler) {
          if (this._isInRenderPass) {
            if (this._isStateInvalied) {
              this.bindStates();
            }
            var info = 'drawInfo' in infoOrAssembler ? infoOrAssembler.drawInfo : infoOrAssembler;
            WebGL2CmdFuncDraw(WebGL2DeviceManager.instance, info);
            ++this._numDrawCalls;
            this._numInstances += info.instanceCount;
            var indexCount = info.indexCount || info.vertexCount;
            if (this._curGPUPipelineState) {
              var glPrimitive = this._curGPUPipelineState.glPrimitive;
              switch (glPrimitive) {
                case 0x0004:
                  {
                    this._numTris += indexCount / 3 * Math.max(info.instanceCount, 1);
                    break;
                  }
                case 0x0005:
                case 0x0006:
                  {
                    this._numTris += (indexCount - 2) * Math.max(info.instanceCount, 1);
                    break;
                  }
              }
            }
          } else {
            console.error('Command \'draw\' must be recorded inside a render pass.');
          }
        };
        _proto.setViewport = function setViewport(viewport) {
          var _WebGL2DeviceManager$ = WebGL2DeviceManager.instance,
            cache = _WebGL2DeviceManager$.stateCache,
            gl = _WebGL2DeviceManager$.gl;
          if (cache.viewport.left !== viewport.left || cache.viewport.top !== viewport.top || cache.viewport.width !== viewport.width || cache.viewport.height !== viewport.height) {
            gl.viewport(viewport.left, viewport.top, viewport.width, viewport.height);
            cache.viewport.left = viewport.left;
            cache.viewport.top = viewport.top;
            cache.viewport.width = viewport.width;
            cache.viewport.height = viewport.height;
          }
        };
        _proto.setScissor = function setScissor(scissor) {
          var _WebGL2DeviceManager$2 = WebGL2DeviceManager.instance,
            cache = _WebGL2DeviceManager$2.stateCache,
            gl = _WebGL2DeviceManager$2.gl;
          if (cache.scissorRect.x !== scissor.x || cache.scissorRect.y !== scissor.y || cache.scissorRect.width !== scissor.width || cache.scissorRect.height !== scissor.height) {
            gl.scissor(scissor.x, scissor.y, scissor.width, scissor.height);
            cache.scissorRect.x = scissor.x;
            cache.scissorRect.y = scissor.y;
            cache.scissorRect.width = scissor.width;
            cache.scissorRect.height = scissor.height;
          }
        };
        _proto.updateBuffer = function updateBuffer(buffer, data, size) {
          if (!this._isInRenderPass) {
            var gpuBuffer = buffer.gpuBuffer;
            if (gpuBuffer) {
              var buffSize;
              if (size !== undefined) {
                buffSize = size;
              } else if (buffer.usage & BufferUsageBit.INDIRECT) {
                buffSize = 0;
              } else {
                buffSize = data.byteLength;
              }
              WebGL2CmdFuncUpdateBuffer(WebGL2DeviceManager.instance, gpuBuffer, data, 0, buffSize);
            }
          } else {
            console.error('Command \'updateBuffer\' must be recorded outside a render pass.');
          }
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          if (!this._isInRenderPass) {
            var gpuTexture = texture.gpuTexture;
            if (gpuTexture) {
              WebGL2CmdFuncCopyBuffersToTexture(WebGL2DeviceManager.instance, buffers, gpuTexture, regions);
            }
          } else {
            console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.');
          }
        };
        _proto.execute = function execute(cmdBuffs, count) {
          for (var i = 0; i < count; ++i) {
            var webGL2CmdBuff = cmdBuffs[i];
            WebGL2CmdFuncExecuteCmds(WebGL2DeviceManager.instance, webGL2CmdBuff.cmdPackage);
            this._numDrawCalls += webGL2CmdBuff._numDrawCalls;
            this._numInstances += webGL2CmdBuff._numInstances;
            this._numTris += webGL2CmdBuff._numTris;
          }
        };
        _proto.bindStates = function bindStates() {
          WebGL2CmdFuncBindStates(WebGL2DeviceManager.instance, this._curGPUPipelineState, this._curGPUInputAssembler, this._curGPUDescriptorSets, this._curDynamicOffsets, this._curDynamicStates);
          this._isStateInvalied = false;
        };
        _proto.blitTexture = function blitTexture(srcTexture, dstTexture, regions, filter) {
          var gpuTextureSrc = srcTexture.gpuTexture;
          var gpuTextureDst = dstTexture.gpuTexture;
          WebGL2CmdFuncBlitTexture(WebGL2DeviceManager.instance, gpuTextureSrc, gpuTextureDst, regions, filter);
        };
        return WebGL2PrimaryCommandBuffer;
      }(WebGL2CommandBuffer);

      var WebGL2Queue = function (_Queue) {
        _inheritsLoose(WebGL2Queue, _Queue);
        function WebGL2Queue() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Queue.call.apply(_Queue, [this].concat(args)) || this;
          _this.numDrawCalls = 0;
          _this.numInstances = 0;
          _this.numTris = 0;
          return _this;
        }
        var _proto = WebGL2Queue.prototype;
        _proto.initialize = function initialize(info) {
          this._type = info.type;
        };
        _proto.destroy = function destroy() {};
        _proto.submit = function submit(cmdBuffs) {
          for (var i = 0; i < cmdBuffs.length; i++) {
            var cmdBuff = cmdBuffs[i];
            this.numDrawCalls += cmdBuff.numDrawCalls;
            this.numInstances += cmdBuff.numInstances;
            this.numTris += cmdBuff.numTris;
          }
        };
        _proto.clear = function clear() {
          this.numDrawCalls = 0;
          this.numInstances = 0;
          this.numTris = 0;
        };
        return WebGL2Queue;
      }(Queue);

      var WebGL2RenderPass = function (_RenderPass) {
        _inheritsLoose(WebGL2RenderPass, _RenderPass);
        function WebGL2RenderPass() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderPass.call.apply(_RenderPass, [this].concat(args)) || this;
          _this._gpuRenderPass = null;
          return _this;
        }
        var _proto = WebGL2RenderPass.prototype;
        _proto.initialize = function initialize(info) {
          this._colorInfos = info.colorAttachments;
          this._depthStencilInfo = info.depthStencilAttachment;
          this._subpasses = info.subpasses;
          this._gpuRenderPass = {
            colorAttachments: this._colorInfos,
            depthStencilAttachment: this._depthStencilInfo
          };
          this._hash = this.computeHash();
        };
        _proto.destroy = function destroy() {
          this._gpuRenderPass = null;
        };
        _createClass(WebGL2RenderPass, [{
          key: "gpuRenderPass",
          get: function get() {
            return this._gpuRenderPass;
          }
        }]);
        return WebGL2RenderPass;
      }(RenderPass);

      var WebGL2Sampler = function (_Sampler) {
        _inheritsLoose(WebGL2Sampler, _Sampler);
        function WebGL2Sampler(info, hash) {
          var _this;
          _this = _Sampler.call(this, info, hash) || this;
          _this._gpuSampler = null;
          _this._gpuSampler = {
            glSamplers: new Map(),
            minFilter: _this._info.minFilter,
            magFilter: _this._info.magFilter,
            mipFilter: _this._info.mipFilter,
            addressU: _this._info.addressU,
            addressV: _this._info.addressV,
            addressW: _this._info.addressW,
            glMinFilter: 0,
            glMagFilter: 0,
            glWrapS: 0,
            glWrapT: 0,
            glWrapR: 0,
            getGLSampler: function getGLSampler(device, minLod, maxLod) {
              var gl = device.gl;
              var samplerHash = minLod << 16 | maxLod;
              if (!this.glSamplers.has(samplerHash)) {
                var glSampler = gl.createSampler();
                if (glSampler) {
                  this.glSamplers.set(samplerHash, glSampler);
                  gl.samplerParameteri(glSampler, gl.TEXTURE_MIN_FILTER, this.glMinFilter);
                  gl.samplerParameteri(glSampler, gl.TEXTURE_MAG_FILTER, this.glMagFilter);
                  gl.samplerParameteri(glSampler, gl.TEXTURE_WRAP_S, this.glWrapS);
                  gl.samplerParameteri(glSampler, gl.TEXTURE_WRAP_T, this.glWrapT);
                  gl.samplerParameteri(glSampler, gl.TEXTURE_WRAP_R, this.glWrapR);
                  gl.samplerParameterf(glSampler, gl.TEXTURE_MIN_LOD, minLod);
                  gl.samplerParameterf(glSampler, gl.TEXTURE_MAX_LOD, maxLod);
                }
              }
              var sampler = this.glSamplers.get(samplerHash);
              return sampler;
            }
          };
          WebGL2CmdFuncPrepareSamplerInfo(WebGL2DeviceManager.instance, _this._gpuSampler);
          return _this;
        }
        var _proto = WebGL2Sampler.prototype;
        _proto.destroy = function destroy() {
          if (this._gpuSampler) {
            WebGL2CmdFuncDestroySampler(WebGL2DeviceManager.instance, this._gpuSampler);
            this._gpuSampler = null;
          }
        };
        _createClass(WebGL2Sampler, [{
          key: "gpuSampler",
          get: function get() {
            return this._gpuSampler;
          }
        }]);
        return WebGL2Sampler;
      }(Sampler);

      var WebGL2Shader = function (_Shader) {
        _inheritsLoose(WebGL2Shader, _Shader);
        function WebGL2Shader() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Shader.call.apply(_Shader, [this].concat(args)) || this;
          _this._gpuShader = null;
          return _this;
        }
        var _proto = WebGL2Shader.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name;
          this._stages = info.stages;
          this._attributes = info.attributes;
          this._blocks = info.blocks;
          this._samplers = info.samplers;
          this._gpuShader = {
            name: info.name,
            blocks: info.blocks.slice(),
            samplerTextures: info.samplerTextures.slice(),
            subpassInputs: info.subpassInputs.slice(),
            gpuStages: new Array(info.stages.length),
            glProgram: null,
            glInputs: [],
            glUniforms: [],
            glBlocks: [],
            glSamplerTextures: []
          };
          for (var i = 0; i < info.stages.length; ++i) {
            var stage = info.stages[i];
            this._gpuShader.gpuStages[i] = {
              type: stage.stage,
              source: stage.source,
              glShader: null
            };
          }
        };
        _proto.destroy = function destroy() {
          if (this._gpuShader) {
            WebGL2CmdFuncDestroyShader(WebGL2DeviceManager.instance, this._gpuShader);
            this._gpuShader = null;
          }
        };
        _createClass(WebGL2Shader, [{
          key: "gpuShader",
          get: function get() {
            if (this._gpuShader.glProgram === null) {
              WebGL2CmdFuncCreateShader(WebGL2DeviceManager.instance, this._gpuShader);
            }
            return this._gpuShader;
          }
        }]);
        return WebGL2Shader;
      }(Shader);

      var WebGL2StateCache = function () {
        function WebGL2StateCache() {
          this.glArrayBuffer = null;
          this.glElementArrayBuffer = null;
          this.glUniformBuffer = null;
          this.glBindUBOs = [];
          this.glBindUBOOffsets = [];
          this.glVAO = null;
          this.texUnit = 0;
          this.glTexUnits = [];
          this.glSamplerUnits = [];
          this.glRenderbuffer = null;
          this.glFramebuffer = null;
          this.glReadFramebuffer = null;
          this.viewport = new Viewport();
          this.scissorRect = new Rect(0, 0, 0, 0);
          this.rs = new RasterizerState();
          this.dss = new DepthStencilState();
          this.bs = new BlendState$1();
          this.glProgram = null;
          this.glEnabledAttribLocs = [];
          this.glCurrentAttribLocs = [];
          this.texUnitCacheMap = {};
        }
        var _proto = WebGL2StateCache.prototype;
        _proto.initialize = function initialize(texUnit, bufferBindings, vertexAttributes) {
          for (var i = 0; i < texUnit; ++i) this.glTexUnits.push({
            glTexture: null
          });
          this.glSamplerUnits.length = texUnit;
          this.glSamplerUnits.fill(null);
          this.glBindUBOs.length = bufferBindings;
          this.glBindUBOs.fill(null);
          this.glBindUBOOffsets.length = bufferBindings;
          this.glBindUBOOffsets.fill(0);
          this.glEnabledAttribLocs.length = vertexAttributes;
          this.glEnabledAttribLocs.fill(false);
          this.glCurrentAttribLocs.length = vertexAttributes;
          this.glCurrentAttribLocs.fill(false);
        };
        return WebGL2StateCache;
      }();

      var WebGL2Texture = function (_Texture) {
        _inheritsLoose(WebGL2Texture, _Texture);
        function WebGL2Texture() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Texture.call.apply(_Texture, [this].concat(args)) || this;
          _this._gpuTexture = null;
          _this._gpuTextureView = null;
          return _this;
        }
        var _proto = WebGL2Texture.prototype;
        _proto.initialize = function initialize(info, isSwapchainTexture) {
          var texInfo = info;
          var viewInfo = info;
          if ('texture' in info) {
            texInfo = viewInfo.texture.info;
            this._isTextureView = true;
          }
          this._info.copy(texInfo);
          this._isPowerOf2 = IsPowerOf2(this._info.width) && IsPowerOf2(this._info.height);
          this._size = FormatSurfaceSize(this._info.format, this.width, this.height, this.depth, this._info.levelCount) * this._info.layerCount;
          if (!this._isTextureView) {
            this._gpuTexture = {
              type: texInfo.type,
              format: texInfo.format,
              usage: texInfo.usage,
              width: texInfo.width,
              height: texInfo.height,
              depth: texInfo.depth,
              size: this._size,
              arrayLayer: texInfo.layerCount,
              mipLevel: texInfo.levelCount,
              samples: texInfo.samples,
              flags: texInfo.flags,
              isPowerOf2: this._isPowerOf2,
              glTarget: 0,
              glInternalFmt: 0,
              glFormat: 0,
              glType: 0,
              glUsage: 0,
              glTexture: null,
              glRenderbuffer: null,
              glWrapS: 0,
              glWrapT: 0,
              glMinFilter: 0,
              glMagFilter: 0,
              isSwapchainTexture: isSwapchainTexture || false
            };
            if (!this._gpuTexture.isSwapchainTexture && this._gpuTexture) {
              WebGL2CmdFuncCreateTexture(WebGL2DeviceManager.instance, this._gpuTexture);
              WebGL2DeviceManager.instance.memoryStatus.textureSize += this._size;
            }
            this._viewInfo.texture = this;
            this._viewInfo.type = info.type;
            this._viewInfo.format = info.format;
            this._viewInfo.baseLevel = 0;
            this._viewInfo.levelCount = info.levelCount;
            this._viewInfo.baseLayer = 0;
            this._viewInfo.layerCount = info.layerCount;
            this._gpuTextureView = {
              gpuTexture: this._gpuTexture,
              type: this._viewInfo.type,
              format: this._viewInfo.format,
              baseLevel: this._viewInfo.baseLevel,
              levelCount: this._viewInfo.levelCount
            };
          } else {
            var _this$_gpuTexture;
            this._viewInfo.copy(viewInfo);
            this._gpuTexture = viewInfo.texture._gpuTexture;
            if (((_this$_gpuTexture = this._gpuTexture) === null || _this$_gpuTexture === void 0 ? void 0 : _this$_gpuTexture.format) !== texInfo.format) {
              console.log('GPU memory alias is not supported');
              return;
            }
            this._gpuTextureView = {
              gpuTexture: this._gpuTexture,
              type: viewInfo.type,
              format: viewInfo.format,
              baseLevel: viewInfo.baseLevel,
              levelCount: viewInfo.levelCount
            };
          }
        };
        _proto.destroy = function destroy() {
          if (!this._isTextureView && this._gpuTexture) {
            WebGL2CmdFuncDestroyTexture(WebGL2DeviceManager.instance, this._gpuTexture);
            WebGL2DeviceManager.instance.memoryStatus.textureSize -= this._size;
            this._gpuTexture = null;
          }
        };
        _proto.getGLTextureHandle = function getGLTextureHandle() {
          var gpuTexture = this._gpuTexture;
          if (!gpuTexture) {
            return 0;
          }
          if (gpuTexture.glTexture) {
            return gpuTexture.glTexture;
          } else if (gpuTexture.glRenderbuffer) {
            return gpuTexture.glRenderbuffer;
          }
          return 0;
        };
        _proto.resize = function resize(width, height) {
          if (this._info.width === width && this._info.height === height) {
            return;
          }
          if (this._info.levelCount === WebGL2Texture.getLevelCount(this._info.width, this._info.height)) {
            this._info.levelCount = WebGL2Texture.getLevelCount(width, height);
          } else if (this._info.levelCount > 1) {
            this._info.levelCount = Math.min(this._info.levelCount, WebGL2Texture.getLevelCount(width, height));
          }
          var oldSize = this._size;
          this._info.width = width;
          this._info.height = height;
          this._size = FormatSurfaceSize(this._info.format, this.width, this.height, this.depth, this._info.levelCount) * this._info.layerCount;
          if (!this._isTextureView && this._gpuTexture) {
            this._gpuTexture.width = width;
            this._gpuTexture.height = height;
            this._gpuTexture.size = this._size;
            if (!this._gpuTexture.isSwapchainTexture) {
              WebGL2CmdFuncResizeTexture(WebGL2DeviceManager.instance, this._gpuTexture);
              WebGL2DeviceManager.instance.memoryStatus.textureSize -= oldSize;
              WebGL2DeviceManager.instance.memoryStatus.textureSize += this._size;
            }
          }
        };
        _proto.initAsSwapchainTexture = function initAsSwapchainTexture(info) {
          var texInfo = new TextureInfo();
          texInfo.format = info.format;
          texInfo.usage = FormatInfos[info.format].hasDepth ? TextureUsageBit.DEPTH_STENCIL_ATTACHMENT : TextureUsageBit.COLOR_ATTACHMENT;
          texInfo.width = info.width;
          texInfo.height = info.height;
          this.initialize(texInfo, true);
        };
        _createClass(WebGL2Texture, [{
          key: "gpuTexture",
          get: function get() {
            return this._gpuTexture;
          }
        }, {
          key: "gpuTextureView",
          get: function get() {
            return this._gpuTextureView;
          }
        }]);
        return WebGL2Texture;
      }(Texture);

      var eventWebGLContextLost = 'webglcontextlost';
      function initStates(gl) {
        gl.activeTexture(gl.TEXTURE0);
        gl.pixelStorei(gl.PACK_ALIGNMENT, 1);
        gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        gl.enable(gl.SCISSOR_TEST);
        gl.enable(gl.CULL_FACE);
        gl.cullFace(gl.BACK);
        gl.frontFace(gl.CCW);
        gl.polygonOffset(0.0, 0.0);
        gl.enable(gl.DEPTH_TEST);
        gl.depthMask(true);
        gl.depthFunc(gl.LESS);
        gl.stencilFuncSeparate(gl.FRONT, gl.ALWAYS, 1, 0xffff);
        gl.stencilOpSeparate(gl.FRONT, gl.KEEP, gl.KEEP, gl.KEEP);
        gl.stencilMaskSeparate(gl.FRONT, 0xffff);
        gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 1, 0xffff);
        gl.stencilOpSeparate(gl.BACK, gl.KEEP, gl.KEEP, gl.KEEP);
        gl.stencilMaskSeparate(gl.BACK, 0xffff);
        gl.disable(gl.STENCIL_TEST);
        gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
        gl.disable(gl.BLEND);
        gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
        gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
        gl.colorMask(true, true, true, true);
        gl.blendColor(0.0, 0.0, 0.0, 0.0);
      }
      function getExtension(gl, ext) {
        var prefixes = ['', 'WEBKIT_', 'MOZ_'];
        for (var i = 0; i < prefixes.length; ++i) {
          var _ext = gl.getExtension(prefixes[i] + ext);
          if (_ext) {
            return _ext;
          }
        }
        return null;
      }
      function getExtensions(gl) {
        var res = {
          EXT_texture_filter_anisotropic: getExtension(gl, 'EXT_texture_filter_anisotropic'),
          EXT_color_buffer_half_float: getExtension(gl, 'EXT_color_buffer_half_float'),
          EXT_color_buffer_float: getExtension(gl, 'EXT_color_buffer_float'),
          WEBGL_compressed_texture_etc1: getExtension(gl, 'WEBGL_compressed_texture_etc1'),
          WEBGL_compressed_texture_etc: getExtension(gl, 'WEBGL_compressed_texture_etc'),
          WEBGL_compressed_texture_pvrtc: getExtension(gl, 'WEBGL_compressed_texture_pvrtc'),
          WEBGL_compressed_texture_astc: getExtension(gl, 'WEBGL_compressed_texture_astc'),
          WEBGL_compressed_texture_s3tc: getExtension(gl, 'WEBGL_compressed_texture_s3tc'),
          WEBGL_compressed_texture_s3tc_srgb: getExtension(gl, 'WEBGL_compressed_texture_s3tc_srgb'),
          WEBGL_debug_shaders: getExtension(gl, 'WEBGL_debug_shaders'),
          WEBGL_lose_context: getExtension(gl, 'WEBGL_lose_context'),
          WEBGL_debug_renderer_info: getExtension(gl, 'WEBGL_debug_renderer_info'),
          OES_texture_half_float_linear: getExtension(gl, 'OES_texture_half_float_linear'),
          OES_texture_float_linear: getExtension(gl, 'OES_texture_float_linear'),
          WEBGL_multi_draw: null,
          useVAO: true
        };
        {
          if (systemInfo.os !== OS.ANDROID && systemInfo.os !== OS.IOS) {
            res.WEBGL_multi_draw = getExtension(gl, 'WEBGL_multi_draw');
          }
        }
        return res;
      }
      function getContext(canvas) {
        var context = null;
        try {
          var _globalThis$__globalX;
          if ((_globalThis$__globalX = globalThis.__globalXR) !== null && _globalThis$__globalX !== void 0 && _globalThis$__globalX.webxrCompatible) {
            var glAttribs = {
              alpha: macro.ENABLE_TRANSPARENT_CANVAS,
              antialias: EDITOR || macro.ENABLE_WEBGL_ANTIALIAS,
              depth: true,
              stencil: true,
              premultipliedAlpha: false,
              preserveDrawingBuffer: false,
              powerPreference: 'default',
              failIfMajorPerformanceCaveat: false,
              xrCompatible: true
            };
            context = canvas.getContext('webgl2', glAttribs);
            return context;
          }
          var webGLCtxAttribs = {
            alpha: macro.ENABLE_TRANSPARENT_CANVAS,
            antialias: EDITOR || macro.ENABLE_WEBGL_ANTIALIAS,
            depth: true,
            stencil: true,
            premultipliedAlpha: false,
            preserveDrawingBuffer: false,
            powerPreference: 'default',
            failIfMajorPerformanceCaveat: false
          };
          context = canvas.getContext('webgl2', webGLCtxAttribs);
        } catch (err) {
          return null;
        }
        return context;
      }
      var WebGL2Swapchain = function (_Swapchain) {
        _inheritsLoose(WebGL2Swapchain, _Swapchain);
        function WebGL2Swapchain() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Swapchain.call.apply(_Swapchain, [this].concat(args)) || this;
          _this.stateCache = new WebGL2StateCache();
          _this.nullTex2D = null;
          _this.nullTexCube = null;
          _this._canvas = null;
          _this._webGL2ContextLostHandler = null;
          _this._extensions = null;
          _this._blitManager = null;
          return _this;
        }
        var _proto = WebGL2Swapchain.prototype;
        _proto.initialize = function initialize(info) {
          this._canvas = info.windowHandle;
          this._webGL2ContextLostHandler = this._onWebGLContextLost.bind(this);
          this._canvas.addEventListener(eventWebGLContextLost, this._onWebGLContextLost);
          var gl = WebGL2DeviceManager.instance.gl;
          this.stateCache.initialize(WebGL2DeviceManager.instance.capabilities.maxTextureUnits, WebGL2DeviceManager.instance.capabilities.maxUniformBufferBindings, WebGL2DeviceManager.instance.capabilities.maxVertexAttributes);
          this._extensions = getExtensions(gl);
          initStates(gl);
          var colorFmt = Format.RGBA8;
          var depthStencilFmt = Format.DEPTH_STENCIL;
          var depthBits = gl.getParameter(gl.DEPTH_BITS);
          var stencilBits = gl.getParameter(gl.STENCIL_BITS);
          if (depthBits && stencilBits) depthStencilFmt = Format.DEPTH_STENCIL;else if (depthBits) depthStencilFmt = Format.DEPTH;
          this._colorTexture = new WebGL2Texture();
          this._colorTexture.initAsSwapchainTexture({
            swapchain: this,
            format: colorFmt,
            width: info.width,
            height: info.height
          });
          this._depthStencilTexture = new WebGL2Texture();
          this._depthStencilTexture.initAsSwapchainTexture({
            swapchain: this,
            format: depthStencilFmt,
            width: info.width,
            height: info.height
          });
          this.nullTex2D = WebGL2DeviceManager.instance.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE));
          this.nullTexCube = WebGL2DeviceManager.instance.createTexture(new TextureInfo(TextureType.CUBE, TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE, 6));
          var nullTexRegion = new BufferTextureCopy();
          nullTexRegion.texExtent.width = 2;
          nullTexRegion.texExtent.height = 2;
          var nullTexBuff = new Uint8Array(this.nullTex2D.size);
          nullTexBuff.fill(0);
          WebGL2DeviceManager.instance.copyBuffersToTexture([nullTexBuff], this.nullTex2D, [nullTexRegion]);
          nullTexRegion.texSubres.layerCount = 6;
          WebGL2DeviceManager.instance.copyBuffersToTexture([nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff], this.nullTexCube, [nullTexRegion]);
          this._blitManager = new IWebGL2BlitManager();
        };
        _proto.destroy = function destroy() {
          if (this._canvas && this._webGL2ContextLostHandler) {
            this._canvas.removeEventListener(eventWebGLContextLost, this._webGL2ContextLostHandler);
            this._webGL2ContextLostHandler = null;
          }
          if (this.nullTex2D) {
            this.nullTex2D.destroy();
            this.nullTex2D = null;
          }
          if (this.nullTexCube) {
            this.nullTexCube.destroy();
            this.nullTexCube = null;
          }
          if (this._blitManager) {
            this._blitManager.destroy();
            this._blitManager = null;
          }
          this._extensions = null;
          this._canvas = null;
        };
        _proto.resize = function resize(width, height, surfaceTransform) {
          if (this._colorTexture.width !== width || this._colorTexture.height !== height) {
            debug("Resizing swapchain: " + width + "x" + height);
            this._canvas.width = width;
            this._canvas.height = height;
            this._colorTexture.resize(width, height);
            this._depthStencilTexture.resize(width, height);
          }
        };
        _proto._onWebGLContextLost = function _onWebGLContextLost(event) {
          warnID(11000);
          warn(event);
        };
        _createClass(WebGL2Swapchain, [{
          key: "extensions",
          get: function get() {
            return this._extensions;
          }
        }, {
          key: "blitManager",
          get: function get() {
            return this._blitManager;
          }
        }]);
        return WebGL2Swapchain;
      }(Swapchain);

      var WebGL2Device = exports('hm', function (_Device) {
        _inheritsLoose(WebGL2Device, _Device);
        function WebGL2Device() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Device.call.apply(_Device, [this].concat(args)) || this;
          _this._swapchain = null;
          _this._context = null;
          _this._bindingMappings = null;
          _this._textureExclusive = new Array(Format.COUNT);
          return _this;
        }
        var _proto = WebGL2Device.prototype;
        _proto.initialize = function initialize(info) {
          WebGL2DeviceManager.setInstance(this);
          this._gfxAPI = API.WEBGL2;
          var mapping = this._bindingMappingInfo = info.bindingMappingInfo;
          var blockOffsets = [];
          var samplerTextureOffsets = [];
          var firstSet = mapping.setIndices[0];
          blockOffsets[firstSet] = 0;
          samplerTextureOffsets[firstSet] = 0;
          for (var i = 1; i < mapping.setIndices.length; ++i) {
            var curSet = mapping.setIndices[i];
            var prevSet = mapping.setIndices[i - 1];
            blockOffsets[curSet] = mapping.maxBlockCounts[prevSet] + blockOffsets[prevSet];
            samplerTextureOffsets[curSet] = mapping.maxSamplerTextureCounts[prevSet] + samplerTextureOffsets[prevSet];
          }
          for (var _i = 0; _i < mapping.setIndices.length; ++_i) {
            var _curSet = mapping.setIndices[_i];
            samplerTextureOffsets[_curSet] -= mapping.maxBlockCounts[_curSet];
          }
          this._bindingMappings = {
            blockOffsets: blockOffsets,
            samplerTextureOffsets: samplerTextureOffsets,
            flexibleSet: mapping.setIndices[mapping.setIndices.length - 1]
          };
          var gl = this._context = getContext(Device.canvas);
          if (!gl) {
            console.error('This device does not support WebGL2.');
            return false;
          }
          this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
          this._cmdBuff = this.createCommandBuffer(new CommandBufferInfo(this._queue));
          this._caps.maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
          this._caps.maxVertexUniformVectors = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
          if (systemInfo.os === OS.IOS) {
            var maxVertexUniformVectors = this._caps.maxVertexUniformVectors;
            if (sys.browserType === BrowserType.WECHAT) {
              this._caps.maxVertexUniformVectors = maxVertexUniformVectors < 256 ? maxVertexUniformVectors : 256;
            } else if (sys.browserType === BrowserType.SAFARI) {
              this._caps.maxVertexUniformVectors = maxVertexUniformVectors < 512 ? maxVertexUniformVectors : 512;
            }
          }
          this._caps.maxFragmentUniformVectors = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
          this._caps.maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
          this._caps.maxVertexTextureUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
          this._caps.maxUniformBufferBindings = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS);
          this._caps.maxUniformBlockSize = gl.getParameter(gl.MAX_UNIFORM_BLOCK_SIZE);
          this._caps.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
          this._caps.maxCubeMapTextureSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
          this._caps.maxArrayTextureLayers = gl.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS);
          this._caps.max3DTextureSize = gl.getParameter(gl.MAX_3D_TEXTURE_SIZE);
          this._caps.uboOffsetAlignment = gl.getParameter(gl.UNIFORM_BUFFER_OFFSET_ALIGNMENT);
          var extensions = gl.getSupportedExtensions();
          var extStr = '';
          if (extensions) {
            for (var _iterator = _createForOfIteratorHelperLoose(extensions), _step; !(_step = _iterator()).done;) {
              var ext = _step.value;
              extStr += ext + " ";
            }
          }
          var exts = getExtensions(gl);
          if (exts.WEBGL_debug_renderer_info) {
            this._renderer = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL);
            this._vendor = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL);
          } else {
            this._renderer = gl.getParameter(gl.RENDERER);
            this._vendor = gl.getParameter(gl.VENDOR);
          }
          var version = gl.getParameter(gl.VERSION);
          this._features.fill(false);
          this.initFormatFeatures(exts);
          this._features[Feature.ELEMENT_INDEX_UINT] = true;
          this._features[Feature.INSTANCED_ARRAYS] = true;
          this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
          this._features[Feature.BLEND_MINMAX] = true;
          var compressedFormat = '';
          if (this.getFormatFeatures(Format.ETC_RGB8)) {
            compressedFormat += 'etc1 ';
          }
          if (this.getFormatFeatures(Format.ETC2_RGB8)) {
            compressedFormat += 'etc2 ';
          }
          if (this.getFormatFeatures(Format.BC1)) {
            compressedFormat += 'dxt ';
          }
          if (this.getFormatFeatures(Format.PVRTC_RGB2)) {
            compressedFormat += 'pvrtc ';
          }
          if (this.getFormatFeatures(Format.ASTC_RGBA_4X4)) {
            compressedFormat += 'astc ';
          }
          debug('WebGL2 device initialized.');
          debug("RENDERER: " + this._renderer);
          debug("VENDOR: " + this._vendor);
          debug("VERSION: " + version);
          debug("COMPRESSED_FORMAT: " + compressedFormat);
          debug("EXTENSIONS: " + extStr);
          return true;
        };
        _proto.destroy = function destroy() {
          if (this._queue) {
            this._queue.destroy();
            this._queue = null;
          }
          if (this._cmdBuff) {
            this._cmdBuff.destroy();
            this._cmdBuff = null;
          }
          var it = this._samplers.values();
          var res = it.next();
          while (!res.done) {
            res.value.destroy();
            res = it.next();
          }
          this._swapchain = null;
        };
        _proto.flushCommands = function flushCommands(cmdBuffs) {};
        _proto.acquire = function acquire(swapchains) {};
        _proto.present = function present() {
          var queue = this._queue;
          this._numDrawCalls = queue.numDrawCalls;
          this._numInstances = queue.numInstances;
          this._numTris = queue.numTris;
          queue.clear();
        };
        _proto.initFormatFeatures = function initFormatFeatures(exts) {
          this._formatFeatures.fill(FormatFeatureBit.NONE);
          this._textureExclusive.fill(true);
          var tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.LINEAR_FILTER | FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R8] = tempFeature;
          this._formatFeatures[Format.RG8] = tempFeature;
          this._formatFeatures[Format.RGB8] = tempFeature;
          this._formatFeatures[Format.RGBA8] = tempFeature;
          tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          this._formatFeatures[Format.R8SN] = tempFeature;
          this._formatFeatures[Format.RG8SN] = tempFeature;
          this._formatFeatures[Format.RGB8SN] = tempFeature;
          this._formatFeatures[Format.RGBA8SN] = tempFeature;
          this._formatFeatures[Format.R5G6B5] = tempFeature;
          this._formatFeatures[Format.RGBA4] = tempFeature;
          this._formatFeatures[Format.RGB5A1] = tempFeature;
          this._formatFeatures[Format.RGB10A2] = tempFeature;
          this._formatFeatures[Format.SRGB8] = tempFeature;
          this._formatFeatures[Format.SRGB8_A8] = tempFeature;
          this._formatFeatures[Format.R11G11B10F] = tempFeature;
          this._formatFeatures[Format.RGB9E5] = tempFeature;
          this._formatFeatures[Format.DEPTH] = tempFeature;
          this._formatFeatures[Format.DEPTH_STENCIL] = tempFeature;
          this._formatFeatures[Format.RGB10A2UI] = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R16F] = tempFeature;
          this._formatFeatures[Format.RG16F] = tempFeature;
          this._formatFeatures[Format.RGB16F] = tempFeature;
          this._formatFeatures[Format.RGBA16F] = tempFeature;
          tempFeature = FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R32F] = tempFeature;
          this._formatFeatures[Format.RG32F] = tempFeature;
          this._formatFeatures[Format.RGB32F] = tempFeature;
          this._formatFeatures[Format.RGBA32F] = tempFeature;
          this._formatFeatures[Format.RGB10A2UI] = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER | FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R8I] = tempFeature;
          this._formatFeatures[Format.R8UI] = tempFeature;
          this._formatFeatures[Format.R16I] = tempFeature;
          this._formatFeatures[Format.R16UI] = tempFeature;
          this._formatFeatures[Format.R32I] = tempFeature;
          this._formatFeatures[Format.R32UI] = tempFeature;
          this._formatFeatures[Format.RG8I] = tempFeature;
          this._formatFeatures[Format.RG8UI] = tempFeature;
          this._formatFeatures[Format.RG16I] = tempFeature;
          this._formatFeatures[Format.RG16UI] = tempFeature;
          this._formatFeatures[Format.RG32I] = tempFeature;
          this._formatFeatures[Format.RG32UI] = tempFeature;
          this._formatFeatures[Format.RGB8I] = tempFeature;
          this._formatFeatures[Format.RGB8UI] = tempFeature;
          this._formatFeatures[Format.RGB16I] = tempFeature;
          this._formatFeatures[Format.RGB16UI] = tempFeature;
          this._formatFeatures[Format.RGB32I] = tempFeature;
          this._formatFeatures[Format.RGB32UI] = tempFeature;
          this._formatFeatures[Format.RGBA8I] = tempFeature;
          this._formatFeatures[Format.RGBA8UI] = tempFeature;
          this._formatFeatures[Format.RGBA16I] = tempFeature;
          this._formatFeatures[Format.RGBA16UI] = tempFeature;
          this._formatFeatures[Format.RGBA32I] = tempFeature;
          this._formatFeatures[Format.RGBA32UI] = tempFeature;
          this._textureExclusive[Format.R8] = false;
          this._textureExclusive[Format.RG8] = false;
          this._textureExclusive[Format.RGB8] = false;
          this._textureExclusive[Format.R5G6B5] = false;
          this._textureExclusive[Format.RGBA4] = false;
          this._textureExclusive[Format.RGB5A1] = false;
          this._textureExclusive[Format.RGBA8] = false;
          this._textureExclusive[Format.RGB10A2] = false;
          this._textureExclusive[Format.RGB10A2UI] = false;
          this._textureExclusive[Format.SRGB8_A8] = false;
          this._textureExclusive[Format.R8I] = false;
          this._textureExclusive[Format.R8UI] = false;
          this._textureExclusive[Format.R16I] = false;
          this._textureExclusive[Format.R16UI] = false;
          this._textureExclusive[Format.R32I] = false;
          this._textureExclusive[Format.R32UI] = false;
          this._textureExclusive[Format.RG8I] = false;
          this._textureExclusive[Format.RG8UI] = false;
          this._textureExclusive[Format.RG16I] = false;
          this._textureExclusive[Format.RG16UI] = false;
          this._textureExclusive[Format.RG32I] = false;
          this._textureExclusive[Format.RG32UI] = false;
          this._textureExclusive[Format.RGBA8I] = false;
          this._textureExclusive[Format.RGBA8UI] = false;
          this._textureExclusive[Format.RGBA16I] = false;
          this._textureExclusive[Format.RGBA16UI] = false;
          this._textureExclusive[Format.RGBA32I] = false;
          this._textureExclusive[Format.RGBA32UI] = false;
          this._textureExclusive[Format.DEPTH] = false;
          this._textureExclusive[Format.DEPTH_STENCIL] = false;
          if (exts.EXT_color_buffer_float) {
            this._formatFeatures[Format.R32F] |= FormatFeatureBit.RENDER_TARGET;
            this._formatFeatures[Format.RG32F] |= FormatFeatureBit.RENDER_TARGET;
            this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.RENDER_TARGET;
            this._textureExclusive[Format.R32F] = false;
            this._textureExclusive[Format.RG32F] = false;
            this._textureExclusive[Format.RGBA32F] = false;
          }
          if (exts.EXT_color_buffer_half_float) {
            this._textureExclusive[Format.R16F] = false;
            this._textureExclusive[Format.RG16F] = false;
            this._textureExclusive[Format.RGBA16F] = false;
          }
          if (exts.OES_texture_float_linear) {
            this._formatFeatures[Format.RGB32F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.R32F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RG32F] |= FormatFeatureBit.LINEAR_FILTER;
          }
          if (exts.OES_texture_half_float_linear) {
            this._formatFeatures[Format.RGB16F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RGBA16F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.R16F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RG16F] |= FormatFeatureBit.LINEAR_FILTER;
          }
          var compressedFeature = FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          if (exts.WEBGL_compressed_texture_etc1) {
            this._formatFeatures[Format.ETC_RGB8] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_etc) {
            this._formatFeatures[Format.ETC2_RGB8] = compressedFeature;
            this._formatFeatures[Format.ETC2_RGBA8] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8_A8] = compressedFeature;
            this._formatFeatures[Format.ETC2_RGB8_A1] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8_A1] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_s3tc) {
            this._formatFeatures[Format.BC1] = compressedFeature;
            this._formatFeatures[Format.BC1_ALPHA] = compressedFeature;
            this._formatFeatures[Format.BC1_SRGB] = compressedFeature;
            this._formatFeatures[Format.BC1_SRGB_ALPHA] = compressedFeature;
            this._formatFeatures[Format.BC2] = compressedFeature;
            this._formatFeatures[Format.BC2_SRGB] = compressedFeature;
            this._formatFeatures[Format.BC3] = compressedFeature;
            this._formatFeatures[Format.BC3_SRGB] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_pvrtc) {
            this._formatFeatures[Format.PVRTC_RGB2] = compressedFeature;
            this._formatFeatures[Format.PVRTC_RGBA2] = compressedFeature;
            this._formatFeatures[Format.PVRTC_RGB4] = compressedFeature;
            this._formatFeatures[Format.PVRTC_RGBA4] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_astc) {
            this._formatFeatures[Format.ASTC_RGBA_4X4] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_5X4] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_5X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_6X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_6X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X8] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X8] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X10] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_12X10] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_12X12] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_4X4] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_5X4] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_5X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_6X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_6X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X8] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X8] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X10] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_12X10] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_12X12] = compressedFeature;
          }
        };
        _proto.createCommandBuffer = function createCommandBuffer(info) {
          var Ctor = info.type === CommandBufferType.PRIMARY ? WebGL2PrimaryCommandBuffer : WebGL2CommandBuffer;
          var cmdBuff = new Ctor();
          cmdBuff.initialize(info);
          return cmdBuff;
        };
        _proto.createSwapchain = function createSwapchain(info) {
          var swapchain = new WebGL2Swapchain();
          this._swapchain = swapchain;
          swapchain.initialize(info);
          return swapchain;
        };
        _proto.createBuffer = function createBuffer(info) {
          var buffer = new WebGL2Buffer();
          buffer.initialize(info);
          return buffer;
        };
        _proto.createTexture = function createTexture(info) {
          var texture = new WebGL2Texture();
          texture.initialize(info);
          return texture;
        };
        _proto.createDescriptorSet = function createDescriptorSet(info) {
          var descriptorSet = new WebGL2DescriptorSet();
          descriptorSet.initialize(info);
          return descriptorSet;
        };
        _proto.createShader = function createShader(info) {
          var shader = new WebGL2Shader();
          shader.initialize(info);
          return shader;
        };
        _proto.createInputAssembler = function createInputAssembler(info) {
          var inputAssembler = new WebGL2InputAssembler();
          inputAssembler.initialize(info);
          return inputAssembler;
        };
        _proto.createRenderPass = function createRenderPass(info) {
          var renderPass = new WebGL2RenderPass();
          renderPass.initialize(info);
          return renderPass;
        };
        _proto.createFramebuffer = function createFramebuffer(info) {
          var framebuffer = new WebGL2Framebuffer();
          framebuffer.initialize(info);
          return framebuffer;
        };
        _proto.createDescriptorSetLayout = function createDescriptorSetLayout(info) {
          var descriptorSetLayout = new WebGL2DescriptorSetLayout();
          descriptorSetLayout.initialize(info);
          return descriptorSetLayout;
        };
        _proto.createPipelineLayout = function createPipelineLayout(info) {
          var pipelineLayout = new WebGL2PipelineLayout();
          pipelineLayout.initialize(info);
          return pipelineLayout;
        };
        _proto.createPipelineState = function createPipelineState(info) {
          var pipelineState = new WebGL2PipelineState();
          pipelineState.initialize(info);
          return pipelineState;
        };
        _proto.createQueue = function createQueue(info) {
          var queue = new WebGL2Queue();
          queue.initialize(info);
          return queue;
        };
        _proto.getSampler = function getSampler(info) {
          var hash = Sampler.computeHash(info);
          if (!this._samplers.has(hash)) {
            this._samplers.set(hash, new WebGL2Sampler(info, hash));
          }
          return this._samplers.get(hash);
        };
        _proto.getSwapchains = function getSwapchains() {
          return [this._swapchain];
        };
        _proto.getGeneralBarrier = function getGeneralBarrier(info) {
          var hash = GeneralBarrier.computeHash(info);
          if (!this._generalBarrierss.has(hash)) {
            this._generalBarrierss.set(hash, new GeneralBarrier(info, hash));
          }
          return this._generalBarrierss.get(hash);
        };
        _proto.getTextureBarrier = function getTextureBarrier(info) {
          var hash = TextureBarrier.computeHash(info);
          if (!this._textureBarriers.has(hash)) {
            this._textureBarriers.set(hash, new TextureBarrier(info, hash));
          }
          return this._textureBarriers.get(hash);
        };
        _proto.getBufferBarrier = function getBufferBarrier(info) {
          var hash = BufferBarrier.computeHash(info);
          if (!this._bufferBarriers.has(hash)) {
            this._bufferBarriers.set(hash, new BufferBarrier(info, hash));
          }
          return this._bufferBarriers.get(hash);
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          WebGL2CmdFuncCopyBuffersToTexture(this, buffers, texture.gpuTexture, regions);
        };
        _proto.copyTextureToBuffers = function copyTextureToBuffers(texture, buffers, regions) {
          WebGL2CmdFuncCopyTextureToBuffers(this, texture.gpuTexture, buffers, regions);
        };
        _proto.copyTexImagesToTexture = function copyTexImagesToTexture(texImages, texture, regions) {
          WebGL2CmdFuncCopyTexImagesToTexture(this, texImages, texture.gpuTexture, regions);
        };
        _createClass(WebGL2Device, [{
          key: "gl",
          get: function get() {
            return this._context;
          }
        }, {
          key: "extensions",
          get: function get() {
            return this._swapchain.extensions;
          }
        }, {
          key: "stateCache",
          get: function get() {
            return this._swapchain.stateCache;
          }
        }, {
          key: "nullTex2D",
          get: function get() {
            return this._swapchain.nullTex2D;
          }
        }, {
          key: "nullTexCube",
          get: function get() {
            return this._swapchain.nullTexCube;
          }
        }, {
          key: "textureExclusive",
          get: function get() {
            return this._textureExclusive;
          }
        }, {
          key: "bindingMappings",
          get: function get() {
            return this._bindingMappings;
          }
        }, {
          key: "blitManager",
          get: function get() {
            return this._swapchain.blitManager;
          }
        }]);
        return WebGL2Device;
      }(Device));

      legacyCC.WebGL2Device = WebGL2Device;

    })
  };
}));
